httplib.h 883 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.67.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x004300"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. #if defined(__SANITIZE_THREAD__)
  18. #define CPPHTTPLIB_THREAD_SANITIZER
  19. #elif defined(__has_feature)
  20. #if __has_feature(thread_sanitizer)
  21. #define CPPHTTPLIB_THREAD_SANITIZER
  22. #endif
  23. #endif
  24. /*
  25. * Configuration
  26. */
  27. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  28. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  29. #endif
  30. // Whether a Server starts with set_keep_alive_parking(true).
  31. #ifndef CPPHTTPLIB_KEEPALIVE_PARKING
  32. #define CPPHTTPLIB_KEEPALIVE_PARKING false
  33. #endif
  34. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  35. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  36. #endif
  37. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  38. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  39. #endif
  40. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  41. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  42. #endif
  43. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  44. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  45. #endif
  46. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  47. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  48. #endif
  49. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  50. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  51. #endif
  52. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  53. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  54. #endif
  55. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  56. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  57. #endif
  58. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  59. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  60. #endif
  61. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  62. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  63. #endif
  64. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  65. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  66. #endif
  67. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  68. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  69. #endif
  70. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  71. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  72. #endif
  73. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  74. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  75. #endif
  76. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  77. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  78. #endif
  79. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  80. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  81. #endif
  82. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  83. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  84. #endif
  85. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  86. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  87. #endif
  88. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  89. #ifdef _WIN32
  90. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  91. #else
  92. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  93. #endif
  94. #endif
  95. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  96. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  97. #endif
  98. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  99. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  100. #endif
  101. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  102. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  103. #endif
  104. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  105. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  106. #endif
  107. #ifndef CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT
  108. #define CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT 100
  109. #endif
  110. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  111. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  112. #endif
  113. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  114. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  115. #endif
  116. // How much of an unread request body the server skips to reuse the connection,
  117. // 0 for no limit
  118. #ifndef CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH
  119. #define CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH (256 * 1024) // 256KB
  120. #endif
  121. #ifndef CPPHTTPLIB_SSE_MAX_EVENT_LENGTH
  122. #define CPPHTTPLIB_SSE_MAX_EVENT_LENGTH (16 * 1024 * 1024) // 16MB
  123. #endif
  124. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  125. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  126. #endif
  127. #ifndef CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH
  128. // 1400 rather than a round number: a body that already fits in one 1500-byte
  129. // MTU gains nothing from being made smaller.
  130. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH 1400
  131. #endif
  132. #ifndef CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH
  133. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH (4 * 1024 * 1024) // 4MB
  134. #endif
  135. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  136. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  137. #endif
  138. // std::regex_match's backtracking implementation (most acutely on libstdc++)
  139. // recurses roughly once per matched character for quantified patterns such
  140. // as "(.*)", so a long enough path can exhaust the calling thread's stack; on
  141. // a default ~8MB thread stack that has been observed to take on the order of
  142. // a couple thousand characters for a simple pattern. 256 leaves a wide safety
  143. // margin below that (well under the 8192-byte request URI limit) while still
  144. // fitting any realistic route segment; raise it if a route legitimately needs
  145. // longer paths. Regex routes are never applied to paths longer than this.
  146. #ifndef CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH
  147. #define CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH 256
  148. #endif
  149. #ifndef CPPHTTPLIB_TCP_NODELAY
  150. #define CPPHTTPLIB_TCP_NODELAY false
  151. #endif
  152. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  153. #define CPPHTTPLIB_IPV6_V6ONLY false
  154. #endif
  155. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  156. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  157. #endif
  158. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  159. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  160. #endif
  161. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  162. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  163. #endif
  164. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  165. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  166. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  167. ? std::thread::hardware_concurrency() - 1 \
  168. : 0))
  169. #endif
  170. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  171. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  172. #endif
  173. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  174. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  175. #endif
  176. #ifndef CPPHTTPLIB_RECV_FLAGS
  177. #define CPPHTTPLIB_RECV_FLAGS 0
  178. #endif
  179. #ifndef CPPHTTPLIB_SEND_FLAGS
  180. #define CPPHTTPLIB_SEND_FLAGS 0
  181. #endif
  182. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  183. #define CPPHTTPLIB_LISTEN_BACKLOG 128
  184. #endif
  185. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  186. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  187. #endif
  188. // These bound the parsing of every request, so 0 cannot lift them.
  189. static_assert(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH > 0,
  190. "CPPHTTPLIB_REQUEST_URI_MAX_LENGTH must be positive");
  191. static_assert(CPPHTTPLIB_HEADER_MAX_LENGTH > 0,
  192. "CPPHTTPLIB_HEADER_MAX_LENGTH must be positive");
  193. static_assert(CPPHTTPLIB_HEADER_MAX_COUNT > 0,
  194. "CPPHTTPLIB_HEADER_MAX_COUNT must be positive");
  195. static_assert(CPPHTTPLIB_MAX_LINE_LENGTH > 0,
  196. "CPPHTTPLIB_MAX_LINE_LENGTH must be positive");
  197. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  198. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  199. #endif
  200. // One macro used to set the read timeout for both sides. They want different
  201. // defaults: a client's read timeout is the caller's own tool (it waits forever
  202. // until asked not to), while a server keeps a ceiling that reclaims a worker
  203. // from a peer that has gone quiet. The old name still works and sets both.
  204. #ifdef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  205. #pragma message( \
  206. "CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND is deprecated; define " \
  207. "CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND and/or " \
  208. "CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND instead")
  209. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  210. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND \
  211. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  212. #endif
  213. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  214. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND \
  215. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  216. #endif
  217. #endif
  218. // 0 waits forever. A read timeout is how a caller gets control back to send on
  219. // the same connection; it is not a liveness check (that is ping/pong). Only a
  220. // timeout set at runtime through set_read_timeout() is reported as
  221. // ws::Timeout; when one of these compile-time defaults elapses, read() returns
  222. // ws::Fail and closes the connection.
  223. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  224. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND 0
  225. #endif
  226. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  227. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND 300
  228. #endif
  229. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  230. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  231. #endif
  232. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  233. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  234. #endif
  235. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  236. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  237. #endif
  238. // A WebSocket connection carries small messages each way, which Nagle's
  239. // algorithm would hold back for the peer's delayed ACK (tens of milliseconds
  240. // on Linux), so it sets TCP_NODELAY unless this is false.
  241. #ifndef CPPHTTPLIB_WEBSOCKET_TCP_NODELAY
  242. #define CPPHTTPLIB_WEBSOCKET_TCP_NODELAY true
  243. #endif
  244. /*
  245. * Headers
  246. */
  247. #ifdef _WIN32
  248. #ifndef _CRT_SECURE_NO_WARNINGS
  249. #define _CRT_SECURE_NO_WARNINGS
  250. #endif //_CRT_SECURE_NO_WARNINGS
  251. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  252. #define _CRT_NONSTDC_NO_DEPRECATE
  253. #endif //_CRT_NONSTDC_NO_DEPRECATE
  254. #if defined(_MSC_VER)
  255. #if _MSC_VER < 1900
  256. #error Sorry, Visual Studio versions prior to 2015 are not supported
  257. #endif
  258. #pragma comment(lib, "ws2_32.lib")
  259. #ifndef _SSIZE_T_DEFINED
  260. using ssize_t = __int64;
  261. #define _SSIZE_T_DEFINED
  262. #endif
  263. #endif // _MSC_VER
  264. #ifndef S_ISREG
  265. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  266. #endif // S_ISREG
  267. #ifndef S_ISDIR
  268. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  269. #endif // S_ISDIR
  270. #ifndef NOMINMAX
  271. #define NOMINMAX
  272. #endif // NOMINMAX
  273. #include <io.h>
  274. #include <winsock2.h>
  275. #include <ws2tcpip.h>
  276. #if defined(__has_include)
  277. #if __has_include(<afunix.h>)
  278. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  279. #include <afunix.h>
  280. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  281. #endif
  282. #endif
  283. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  284. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  285. #endif
  286. using nfds_t = unsigned long;
  287. using socket_t = SOCKET;
  288. using socklen_t = int;
  289. #else // not _WIN32
  290. #include <arpa/inet.h>
  291. #if !defined(_AIX) && !defined(__MVS__)
  292. #include <ifaddrs.h>
  293. #endif
  294. #ifdef __MVS__
  295. #include <strings.h>
  296. #ifndef NI_MAXHOST
  297. #define NI_MAXHOST 1025
  298. #endif
  299. #endif
  300. #include <net/if.h>
  301. #include <netdb.h>
  302. #include <netinet/in.h>
  303. #ifdef __linux__
  304. #include <resolv.h>
  305. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  306. #include <sys/epoll.h>
  307. #include <sys/eventfd.h>
  308. #endif
  309. #include <csignal>
  310. #include <netinet/tcp.h>
  311. #include <poll.h>
  312. #include <pthread.h>
  313. #include <sys/socket.h>
  314. #include <sys/un.h>
  315. #include <unistd.h>
  316. using socket_t = int;
  317. #ifndef INVALID_SOCKET
  318. #define INVALID_SOCKET (-1)
  319. #endif
  320. #endif //_WIN32
  321. #if defined(__APPLE__)
  322. #include <TargetConditionals.h>
  323. #endif
  324. #if defined(__APPLE__) || defined(__FreeBSD__)
  325. #define CPPHTTPLIB_KQUEUE_POLLER
  326. #include <sys/event.h>
  327. #endif
  328. #include <algorithm>
  329. #include <array>
  330. #include <atomic>
  331. #include <cassert>
  332. #include <chrono>
  333. #include <climits>
  334. #include <condition_variable>
  335. #include <cstdlib>
  336. #include <cstring>
  337. #include <errno.h>
  338. #include <exception>
  339. #include <fcntl.h>
  340. #include <fstream>
  341. #include <functional>
  342. #include <iomanip>
  343. #include <iostream>
  344. #include <iterator>
  345. #include <list>
  346. #include <map>
  347. #include <memory>
  348. #include <mutex>
  349. #include <random>
  350. #include <regex>
  351. #include <set>
  352. #include <sstream>
  353. #include <string>
  354. #include <sys/stat.h>
  355. #include <system_error>
  356. #include <thread>
  357. #include <type_traits>
  358. #include <unordered_map>
  359. #include <unordered_set>
  360. #include <utility>
  361. #include <vector>
  362. // On macOS with a TLS backend, enable Keychain root certificates by default
  363. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  364. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  365. // only; on those platforms the user must provide a CA bundle explicitly.
  366. #if defined(__APPLE__) && defined(__clang__) && \
  367. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  368. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  369. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  370. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  371. #if TARGET_OS_OSX
  372. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  373. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  374. #endif
  375. #endif
  376. #endif
  377. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  378. defined(__APPLE__) && !TARGET_OS_OSX
  379. #error \
  380. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  381. #endif
  382. // On Windows, enable Schannel certificate verification by default
  383. // unless the user explicitly opts out.
  384. #if defined(_WIN32) && \
  385. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  386. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  387. #endif
  388. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  389. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  390. #if TARGET_OS_MAC && defined(__clang__)
  391. #include <CFNetwork/CFHost.h>
  392. #include <CoreFoundation/CoreFoundation.h>
  393. #endif
  394. #endif
  395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  396. #ifdef _WIN32
  397. #include <wincrypt.h>
  398. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  399. // used
  400. #undef X509_NAME
  401. #undef X509_CERT_PAIR
  402. #undef X509_EXTENSIONS
  403. #undef PKCS7_SIGNER_INFO
  404. #ifdef _MSC_VER
  405. #pragma comment(lib, "crypt32.lib")
  406. #endif
  407. #endif // _WIN32
  408. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  409. #if TARGET_OS_OSX
  410. #include <Security/Security.h>
  411. #endif
  412. #endif
  413. #include <openssl/err.h>
  414. #include <openssl/evp.h>
  415. #include <openssl/rand.h>
  416. #include <openssl/ssl.h>
  417. #include <openssl/x509v3.h>
  418. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  419. #include <openssl/applink.c>
  420. #endif
  421. #include <iostream>
  422. #include <sstream>
  423. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  424. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  425. #error Please use OpenSSL or a current version of BoringSSL
  426. #endif
  427. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  428. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  429. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  430. #endif
  431. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  432. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  433. // version.h defines MBEDTLS_VERSION_MAJOR (on 2.x/3.x/4.x alike); it is pulled
  434. // in with this first include group so the version gating below can use it.
  435. #include <mbedtls/error.h>
  436. #include <mbedtls/net_sockets.h>
  437. #include <mbedtls/oid.h>
  438. #include <mbedtls/pk.h>
  439. #include <mbedtls/ssl.h>
  440. #include <mbedtls/version.h>
  441. #include <mbedtls/x509_crt.h>
  442. #if MBEDTLS_VERSION_MAJOR >= 4
  443. // Mbed TLS 4.x moved hashing/RNG to PSA Crypto and removed these headers.
  444. #include <psa/crypto.h>
  445. #else
  446. #include <mbedtls/ctr_drbg.h>
  447. #include <mbedtls/entropy.h>
  448. #include <mbedtls/md5.h>
  449. #include <mbedtls/sha1.h>
  450. #include <mbedtls/sha256.h>
  451. #include <mbedtls/sha512.h>
  452. #endif
  453. #ifdef _WIN32
  454. #include <wincrypt.h>
  455. #ifdef _MSC_VER
  456. #pragma comment(lib, "crypt32.lib")
  457. #endif
  458. #endif // _WIN32
  459. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  460. #if TARGET_OS_OSX
  461. #include <Security/Security.h>
  462. #endif
  463. #endif
  464. // Mbed TLS version API compatibility. Note: V4 implies V3 (both defined on
  465. // 4.x), so version-specific 3.x-only code must check V3 && !V4.
  466. #if MBEDTLS_VERSION_MAJOR >= 4
  467. #define CPPHTTPLIB_MBEDTLS_V4
  468. #endif
  469. #if MBEDTLS_VERSION_MAJOR >= 3
  470. #define CPPHTTPLIB_MBEDTLS_V3
  471. #endif
  472. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  473. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  474. #include <wolfssl/options.h>
  475. #include <wolfssl/openssl/x509v3.h>
  476. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  477. #ifndef WOLFSSL_GEN_EMAIL
  478. #define WOLFSSL_GEN_EMAIL 1
  479. #endif
  480. #ifndef WOLFSSL_GEN_DNS
  481. #define WOLFSSL_GEN_DNS 2
  482. #endif
  483. #ifndef WOLFSSL_GEN_URI
  484. #define WOLFSSL_GEN_URI 6
  485. #endif
  486. #ifndef WOLFSSL_GEN_IPADD
  487. #define WOLFSSL_GEN_IPADD 7
  488. #endif
  489. #include <wolfssl/ssl.h>
  490. #include <wolfssl/wolfcrypt/hash.h>
  491. #include <wolfssl/wolfcrypt/md5.h>
  492. #include <wolfssl/wolfcrypt/sha256.h>
  493. #include <wolfssl/wolfcrypt/sha512.h>
  494. #ifdef _WIN32
  495. #include <wincrypt.h>
  496. #ifdef _MSC_VER
  497. #pragma comment(lib, "crypt32.lib")
  498. #endif
  499. #endif // _WIN32
  500. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  501. #if TARGET_OS_OSX
  502. #include <Security/Security.h>
  503. #endif
  504. #endif
  505. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  506. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  507. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  508. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  509. #define CPPHTTPLIB_SSL_ENABLED
  510. #endif
  511. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  512. #include <zlib.h>
  513. #endif
  514. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  515. #include <brotli/decode.h>
  516. #include <brotli/encode.h>
  517. #endif
  518. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  519. #include <zstd.h>
  520. #endif
  521. /*
  522. * Declaration
  523. */
  524. namespace httplib {
  525. namespace ws {
  526. class WebSocket;
  527. } // namespace ws
  528. namespace sse {
  529. class SSEClient;
  530. } // namespace sse
  531. namespace detail {
  532. /*
  533. * Backport std::make_unique from C++14.
  534. *
  535. * NOTE: This code came up with the following stackoverflow post:
  536. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  537. *
  538. */
  539. template <class T, class... Args>
  540. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  541. make_unique(Args &&...args) {
  542. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  543. }
  544. template <class T>
  545. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  546. make_unique(std::size_t n) {
  547. typedef typename std::remove_extent<T>::type RT;
  548. return std::unique_ptr<T>(new RT[n]);
  549. }
  550. // Locale-independent ASCII character classification. The <cctype>
  551. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  552. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  553. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  554. // classified without regard to the locale.
  555. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  556. inline bool is_ascii_alpha(char c) {
  557. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  558. }
  559. inline bool is_ascii_alnum(char c) {
  560. return is_ascii_digit(c) || is_ascii_alpha(c);
  561. }
  562. namespace case_ignore {
  563. inline unsigned char to_lower(int c) {
  564. const static unsigned char table[256] = {
  565. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  566. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  567. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  568. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  569. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  570. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  571. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  572. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  573. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  574. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  575. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  576. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  577. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  578. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  579. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  580. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  581. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  582. 255,
  583. };
  584. return table[(unsigned char)(char)c];
  585. }
  586. inline std::string to_lower(const std::string &s) {
  587. std::string result = s;
  588. std::transform(
  589. result.begin(), result.end(), result.begin(),
  590. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  591. return result;
  592. }
  593. inline bool equal(const std::string &a, const std::string &b) {
  594. return a.size() == b.size() &&
  595. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  596. return to_lower(ca) == to_lower(cb);
  597. });
  598. }
  599. // For a literal, without building a std::string from it.
  600. template <size_t N>
  601. inline bool equal(const std::string &a, const char (&b)[N]) {
  602. return a.size() == N - 1 &&
  603. std::equal(a.begin(), a.end(), b, [](char ca, char cb) {
  604. return to_lower(ca) == to_lower(cb);
  605. });
  606. }
  607. struct equal_to {
  608. bool operator()(const std::string &a, const std::string &b) const {
  609. return equal(a, b);
  610. }
  611. };
  612. struct hash {
  613. size_t operator()(const std::string &key) const {
  614. size_t h = 0;
  615. for (auto c : key) {
  616. // Unsets the 6 high bits of h, therefore no overflow happens
  617. h = (((std::numeric_limits<size_t>::max)() >> 6) & h * 33) ^
  618. static_cast<unsigned char>(to_lower(c));
  619. }
  620. return h;
  621. }
  622. };
  623. template <typename T>
  624. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  625. detail::case_ignore::equal_to>;
  626. } // namespace case_ignore
  627. // This is based on
  628. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  629. struct scope_exit {
  630. explicit scope_exit(std::function<void(void)> &&f)
  631. : exit_function(std::move(f)), execute_on_destruction{true} {}
  632. scope_exit(scope_exit &&rhs) noexcept
  633. : exit_function(std::move(rhs.exit_function)),
  634. execute_on_destruction{rhs.execute_on_destruction} {
  635. rhs.release();
  636. }
  637. ~scope_exit() {
  638. if (execute_on_destruction) { this->exit_function(); }
  639. }
  640. void release() { this->execute_on_destruction = false; }
  641. private:
  642. scope_exit(const scope_exit &) = delete;
  643. void operator=(const scope_exit &) = delete;
  644. scope_exit &operator=(scope_exit &&) = delete;
  645. std::function<void(void)> exit_function;
  646. bool execute_on_destruction;
  647. };
  648. // Simple from_chars implementation for integer and double types (C++17
  649. // substitute)
  650. template <typename T> struct from_chars_result {
  651. const char *ptr;
  652. std::errc ec;
  653. };
  654. template <typename T>
  655. inline from_chars_result<T> from_chars(const char *first, const char *last,
  656. T &value, int base = 10) {
  657. value = 0;
  658. const char *p = first;
  659. bool negative = false;
  660. if (p != last && *p == '-') {
  661. negative = true;
  662. ++p;
  663. }
  664. if (p == last) { return {first, std::errc::invalid_argument}; }
  665. auto radix = static_cast<T>(base);
  666. T result = 0;
  667. for (; p != last; ++p) {
  668. char c = *p;
  669. int digit = -1;
  670. if (is_ascii_digit(c)) {
  671. digit = c - '0';
  672. } else if ('a' <= c && c <= 'z') {
  673. digit = c - 'a' + 10;
  674. } else if ('A' <= c && c <= 'Z') {
  675. digit = c - 'A' + 10;
  676. } else {
  677. break;
  678. }
  679. if (digit < 0 || digit >= base) { break; }
  680. auto d = static_cast<T>(digit);
  681. if (result > ((std::numeric_limits<T>::max)() - d) / radix) {
  682. return {p, std::errc::result_out_of_range};
  683. }
  684. result = result * radix + d;
  685. }
  686. if (p == first || (negative && p == first + 1)) {
  687. return {first, std::errc::invalid_argument};
  688. }
  689. value = negative ? T(0) - result : result;
  690. return {p, std::errc{}};
  691. }
  692. // from_chars for double (hand-written, locale-independent)
  693. //
  694. // The only double consumed by this library is the HTTP quality value, whose
  695. // grammar is (RFC 9110 12.4.2):
  696. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  697. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  698. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  699. // '.' always the decimal separator (std::strtod would instead read it from the
  700. // global C locale, mis-parsing q-values once an embedder calls
  701. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  702. // the result to [0, 1], so inputs outside that range need not be distinguished
  703. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  704. // cases that exponent and wide-range handling would introduce.
  705. inline from_chars_result<double> from_chars(const char *first, const char *last,
  706. double &value) {
  707. value = 0.0;
  708. const char *p = first;
  709. // Each 1eN is exactly representable, so a single final division by the
  710. // matching entry yields a correctly-rounded result.
  711. static const double powers_of_ten[] = {
  712. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  713. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  714. const int max_frac_digits =
  715. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  716. // Accumulate digits into a 64-bit integer and remember how many were
  717. // fractional. Two independent caps keep this bounded and safe:
  718. // * accumulation saturates before mantissa could overflow uint64_t, and
  719. // * frac_digits is capped at max_frac_digits so it is always a valid index
  720. // into powers_of_ten (without this an input like "0.000...0" would never
  721. // grow mantissa, so the saturation cap alone would not bound it).
  722. // Both caps only drop digits far beyond the precision a q-value needs; any
  723. // value they would change is well outside [0, 1] and rejected by the caller.
  724. uint64_t mantissa = 0;
  725. int frac_digits = 0;
  726. bool seen_digit = false;
  727. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  728. auto accumulate = [&](char c) {
  729. if (mantissa <= limit) {
  730. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  731. return true;
  732. }
  733. return false;
  734. };
  735. for (; p != last && is_ascii_digit(*p); ++p) {
  736. seen_digit = true;
  737. accumulate(*p);
  738. }
  739. if (p != last && *p == '.') {
  740. ++p;
  741. for (; p != last && is_ascii_digit(*p); ++p) {
  742. seen_digit = true;
  743. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  744. }
  745. }
  746. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  747. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  748. return {p, std::errc{}};
  749. }
  750. inline bool parse_int_in_range(const char *s, size_t len, int lo, int hi,
  751. int &out) {
  752. int val = 0;
  753. auto r = from_chars(s, s + len, val);
  754. if (r.ec != std::errc{} || r.ptr != s + len || val < lo || val > hi) {
  755. return false;
  756. }
  757. out = val;
  758. return true;
  759. }
  760. inline bool parse_port(const char *s, size_t len, int &port) {
  761. return parse_int_in_range(s, len, 1, 65535, port);
  762. }
  763. inline bool parse_port(const std::string &s, int &port) {
  764. return parse_port(s.data(), s.size(), port);
  765. }
  766. struct UrlComponents {
  767. std::string scheme;
  768. std::string host;
  769. std::string port;
  770. std::string path;
  771. std::string query;
  772. };
  773. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  774. uc = {};
  775. size_t pos = 0;
  776. auto sep = url.find("://");
  777. if (sep != std::string::npos) {
  778. // Schemes are case-insensitive (RFC 3986 3.1)
  779. uc.scheme = case_ignore::to_lower(url.substr(0, sep));
  780. // Scheme must be [a-z]+ only
  781. if (uc.scheme.empty()) { return false; }
  782. for (auto c : uc.scheme) {
  783. if (c < 'a' || c > 'z') { return false; }
  784. }
  785. pos = sep + 3;
  786. } else if (url.compare(0, 2, "//") == 0) {
  787. pos = 2;
  788. }
  789. auto has_authority_prefix = pos > 0;
  790. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  791. url[0] != '?' && url[0] != '#');
  792. if (has_authority) {
  793. // userinfo is not supported, and a backslash that some parsers take for
  794. // '/' would leave them seeing another host than this one.
  795. if (url.find_first_of("@\\", pos) < url.find_first_of("/?#", pos)) {
  796. return false;
  797. }
  798. if (pos < url.size() && url[pos] == '[') {
  799. auto close = url.find(']', pos);
  800. if (close == std::string::npos) { return false; }
  801. uc.host = url.substr(pos + 1, close - pos - 1);
  802. // IPv6 host must be [a-fA-F0-9:]+ only
  803. if (uc.host.empty()) { return false; }
  804. for (auto c : uc.host) {
  805. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  806. (c >= 'A' && c <= 'F') || c == ':')) {
  807. return false;
  808. }
  809. }
  810. pos = close + 1;
  811. // The IPv6 literal is the whole host, so ']' must be followed by a port,
  812. // path, query or fragment delimiter (or the end of input). Otherwise the
  813. // trailing bytes would be folded into the path while the connection
  814. // still targets the bracketed address.
  815. if (pos < url.size()) {
  816. auto c = url[pos];
  817. if (c != ':' && c != '/' && c != '?' && c != '#') { return false; }
  818. }
  819. } else {
  820. auto end = url.find_first_of(":/?#", pos);
  821. if (end == std::string::npos) { end = url.size(); }
  822. uc.host = url.substr(pos, end - pos);
  823. pos = end;
  824. }
  825. if (pos < url.size() && url[pos] == ':') {
  826. ++pos;
  827. auto end = url.find_first_of("/?#", pos);
  828. if (end == std::string::npos) { end = url.size(); }
  829. uc.port = url.substr(pos, end - pos);
  830. pos = end;
  831. }
  832. // Without :// or //, the entire input must be consumed as host[:port].
  833. // If there is leftover (path, query, etc.), this is not a valid
  834. // host[:port] string — clear and reparse as a plain path.
  835. if (!has_authority_prefix && pos < url.size()) {
  836. uc.host.clear();
  837. uc.port.clear();
  838. pos = 0;
  839. }
  840. }
  841. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  842. auto end = url.find_first_of("?#", pos);
  843. if (end == std::string::npos) { end = url.size(); }
  844. uc.path = url.substr(pos, end - pos);
  845. pos = end;
  846. }
  847. if (pos < url.size() && url[pos] == '?') {
  848. auto end = url.find('#', pos);
  849. if (end == std::string::npos) { end = url.size(); }
  850. uc.query = url.substr(pos, end - pos);
  851. }
  852. return true;
  853. }
  854. // Removes "." and ".." segments from a path that starts with '/' (RFC 3986
  855. // section 5.2.4).
  856. inline std::string remove_dot_segments(const std::string &path) {
  857. std::string out;
  858. size_t i = 0;
  859. while (i < path.size()) {
  860. auto next = (std::min)(path.find('/', i + 1), path.size());
  861. auto segment = path.substr(i + 1, next - i - 1);
  862. auto is_last = next == path.size();
  863. if (segment == "." || segment == "..") {
  864. if (segment == "..") {
  865. out.erase((std::min)(out.rfind('/'), out.size()));
  866. }
  867. if (is_last) { out += '/'; }
  868. } else {
  869. out += '/';
  870. out += segment;
  871. }
  872. i = next;
  873. }
  874. if (out.empty()) { out = "/"; }
  875. return out;
  876. }
  877. // Resolves a relative-path or query-only Location value against the path of
  878. // the request being redirected (RFC 3986 section 5.2). Absolute URIs and
  879. // references starting with '/' are returned unchanged.
  880. inline std::string resolve_relative_location(const std::string &location,
  881. const std::string &base) {
  882. if (location.empty() || location[0] == '/') { return location; }
  883. // A ':' in the first segment means the value has a scheme.
  884. if (location.find(':') < location.find_first_of("/?#")) { return location; }
  885. // A path starting with "//" would be re-parsed as an authority. Prefix "/."
  886. // (as the URL Standard does); remove_dot_segments strips it later.
  887. auto on_this_host = [](std::string path) -> std::string {
  888. if (path.compare(0, 2, "//") == 0) { path.insert(0, "/."); }
  889. return path;
  890. };
  891. if (location[0] == '#') {
  892. return on_this_host(base.substr(0, base.find('#')) + location);
  893. }
  894. auto base_path = base.substr(0, base.find_first_of("?#"));
  895. if (location[0] == '?') { return on_this_host(base_path + location); }
  896. if (base_path.empty() || base_path[0] != '/') { base_path = "/"; }
  897. auto merged = base_path.substr(0, base_path.rfind('/') + 1) + location;
  898. // Remove "." and ".." segments from the merged path.
  899. auto path_end = (std::min)(merged.find_first_of("?#"), merged.size());
  900. return on_this_host(remove_dot_segments(merged.substr(0, path_end)) +
  901. merged.substr(path_end));
  902. }
  903. } // namespace detail
  904. enum class SSLVerifierResponse {
  905. // no decision has been made, use the built-in certificate verifier
  906. NoDecisionMade,
  907. // connection certificate is verified and accepted
  908. CertificateAccepted,
  909. // connection certificate was processed but is rejected
  910. CertificateRejected
  911. };
  912. // System CA loading policy for SSL clients. Auto (the default) loads system
  913. // CA certs only when no custom CA is configured; enable_system_ca() switches
  914. // to an explicit policy.
  915. enum class SystemCAMode { Auto, Enabled, Disabled };
  916. enum StatusCode {
  917. // Information responses
  918. Continue_100 = 100,
  919. SwitchingProtocol_101 = 101,
  920. Processing_102 = 102,
  921. EarlyHints_103 = 103,
  922. // Successful responses
  923. OK_200 = 200,
  924. Created_201 = 201,
  925. Accepted_202 = 202,
  926. NonAuthoritativeInformation_203 = 203,
  927. NoContent_204 = 204,
  928. ResetContent_205 = 205,
  929. PartialContent_206 = 206,
  930. MultiStatus_207 = 207,
  931. AlreadyReported_208 = 208,
  932. IMUsed_226 = 226,
  933. // Redirection messages
  934. MultipleChoices_300 = 300,
  935. MovedPermanently_301 = 301,
  936. Found_302 = 302,
  937. SeeOther_303 = 303,
  938. NotModified_304 = 304,
  939. UseProxy_305 = 305,
  940. unused_306 = 306,
  941. TemporaryRedirect_307 = 307,
  942. PermanentRedirect_308 = 308,
  943. // Client error responses
  944. BadRequest_400 = 400,
  945. Unauthorized_401 = 401,
  946. PaymentRequired_402 = 402,
  947. Forbidden_403 = 403,
  948. NotFound_404 = 404,
  949. MethodNotAllowed_405 = 405,
  950. NotAcceptable_406 = 406,
  951. ProxyAuthenticationRequired_407 = 407,
  952. RequestTimeout_408 = 408,
  953. Conflict_409 = 409,
  954. Gone_410 = 410,
  955. LengthRequired_411 = 411,
  956. PreconditionFailed_412 = 412,
  957. PayloadTooLarge_413 = 413,
  958. UriTooLong_414 = 414,
  959. UnsupportedMediaType_415 = 415,
  960. RangeNotSatisfiable_416 = 416,
  961. ExpectationFailed_417 = 417,
  962. ImATeapot_418 = 418,
  963. MisdirectedRequest_421 = 421,
  964. UnprocessableContent_422 = 422,
  965. Locked_423 = 423,
  966. FailedDependency_424 = 424,
  967. TooEarly_425 = 425,
  968. UpgradeRequired_426 = 426,
  969. PreconditionRequired_428 = 428,
  970. TooManyRequests_429 = 429,
  971. RequestHeaderFieldsTooLarge_431 = 431,
  972. UnavailableForLegalReasons_451 = 451,
  973. // Server error responses
  974. InternalServerError_500 = 500,
  975. NotImplemented_501 = 501,
  976. BadGateway_502 = 502,
  977. ServiceUnavailable_503 = 503,
  978. GatewayTimeout_504 = 504,
  979. HttpVersionNotSupported_505 = 505,
  980. VariantAlsoNegotiates_506 = 506,
  981. InsufficientStorage_507 = 507,
  982. LoopDetected_508 = 508,
  983. NotExtended_510 = 510,
  984. NetworkAuthenticationRequired_511 = 511,
  985. };
  986. namespace detail {
  987. // A multimap that keeps its entries in the order they were inserted.
  988. //
  989. // HTTP needs that order in two places. RFC 9110 5.3 makes the order of header
  990. // fields sharing a field name significant and forbids a proxy from reordering
  991. // them, and a query string's parameters are meaningful in the order the caller
  992. // wrote them. Neither standard container expresses it: std::unordered_multimap
  993. // gives no ordering guarantee at all for equivalent keys (libstdc++ yields
  994. // reverse insertion order, libc++ insertion order), and std::multimap sorts by
  995. // key, which would drop control data such as Host behind whatever else the
  996. // message carries and alphabetise a query string.
  997. //
  998. // Entries are therefore kept in a flat vector, in order. Lookup is a linear
  999. // scan, which beats hashing for the handful of entries a message carries
  1000. // (headers are capped at CPPHTTPLIB_HEADER_MAX_COUNT).
  1001. //
  1002. // KeyEqual compares keys; it is what makes Headers case-insensitive and
  1003. // Params, whose parameter names are case-sensitive, not.
  1004. template <typename Mapped, typename KeyEqual> class insertion_ordered_multimap {
  1005. public:
  1006. using key_type = std::string;
  1007. using mapped_type = Mapped;
  1008. using value_type = std::pair<std::string, Mapped>;
  1009. using size_type = std::size_t;
  1010. using difference_type = std::ptrdiff_t;
  1011. using reference = value_type &;
  1012. using const_reference = const value_type &;
  1013. private:
  1014. static size_type npos() { return static_cast<size_type>(-1); }
  1015. static bool keys_equal(const std::string &a, const std::string &b) {
  1016. return KeyEqual()(a, b);
  1017. }
  1018. // Iterating yields every entry in insertion order, but equal_range() and
  1019. // find() have to walk only the entries sharing one key, which are not
  1020. // adjacent. Both are the same iterator type: key_idx_ selects between the
  1021. // two traversals, and since equality compares only the position, an iterator
  1022. // restricted to one key still compares equal to end().
  1023. template <typename V> class iterator_t {
  1024. public:
  1025. using iterator_category = std::bidirectional_iterator_tag;
  1026. using value_type = insertion_ordered_multimap::value_type;
  1027. using difference_type = insertion_ordered_multimap::difference_type;
  1028. using pointer = V *;
  1029. using reference = V &;
  1030. iterator_t() : data_(nullptr), idx_(0), size_(0), key_idx_(npos()) {}
  1031. template <typename U,
  1032. typename std::enable_if<std::is_convertible<U *, V *>::value,
  1033. int>::type = 0>
  1034. iterator_t(const iterator_t<U> &rhs)
  1035. : data_(rhs.data_), idx_(rhs.idx_), size_(rhs.size_),
  1036. key_idx_(rhs.key_idx_) {}
  1037. reference operator*() const { return data_[idx_]; }
  1038. pointer operator->() const { return data_ + idx_; }
  1039. iterator_t &operator++() {
  1040. // Saturating, so that advancing past the last entry of a key stays at
  1041. // end() instead of running off the container.
  1042. if (idx_ >= size_) { return *this; }
  1043. ++idx_;
  1044. if (key_idx_ != npos()) {
  1045. while (idx_ < size_ && !matches(idx_)) {
  1046. ++idx_;
  1047. }
  1048. }
  1049. return *this;
  1050. }
  1051. iterator_t operator++(int) {
  1052. auto tmp = *this;
  1053. ++*this;
  1054. return tmp;
  1055. }
  1056. iterator_t &operator--() {
  1057. if (idx_ == 0) { return *this; }
  1058. --idx_;
  1059. if (key_idx_ != npos()) {
  1060. while (idx_ > 0 && !matches(idx_)) {
  1061. --idx_;
  1062. }
  1063. }
  1064. return *this;
  1065. }
  1066. iterator_t operator--(int) {
  1067. auto tmp = *this;
  1068. --*this;
  1069. return tmp;
  1070. }
  1071. template <typename U> bool operator==(const iterator_t<U> &rhs) const {
  1072. return idx_ == rhs.idx_;
  1073. }
  1074. template <typename U> bool operator!=(const iterator_t<U> &rhs) const {
  1075. return idx_ != rhs.idx_;
  1076. }
  1077. private:
  1078. friend class insertion_ordered_multimap;
  1079. template <typename> friend class iterator_t;
  1080. iterator_t(V *data, size_type idx, size_type size, size_type key_idx)
  1081. : data_(data), idx_(idx), size_(size), key_idx_(key_idx) {}
  1082. bool matches(size_type i) const {
  1083. return keys_equal(data_[i].first, data_[key_idx_].first);
  1084. }
  1085. V *data_;
  1086. size_type idx_;
  1087. size_type size_;
  1088. size_type key_idx_;
  1089. };
  1090. public:
  1091. using iterator = iterator_t<value_type>;
  1092. using const_iterator = iterator_t<const value_type>;
  1093. insertion_ordered_multimap() = default;
  1094. insertion_ordered_multimap(std::initializer_list<value_type> il)
  1095. : entries_(il) {}
  1096. template <typename InputIt>
  1097. insertion_ordered_multimap(InputIt first, InputIt last)
  1098. : entries_(first, last) {}
  1099. iterator begin() { return make_iter(0, npos()); }
  1100. iterator end() { return make_iter(entries_.size(), npos()); }
  1101. const_iterator begin() const { return make_citer(0, npos()); }
  1102. const_iterator end() const { return make_citer(entries_.size(), npos()); }
  1103. const_iterator cbegin() const { return begin(); }
  1104. const_iterator cend() const { return end(); }
  1105. bool empty() const { return entries_.empty(); }
  1106. size_type size() const { return entries_.size(); }
  1107. void clear() { entries_.clear(); }
  1108. void swap(insertion_ordered_multimap &rhs) { entries_.swap(rhs.entries_); }
  1109. iterator insert(const value_type &val) {
  1110. entries_.push_back(val);
  1111. return make_iter(entries_.size() - 1, npos());
  1112. }
  1113. iterator insert(value_type &&val) {
  1114. entries_.push_back(std::move(val));
  1115. return make_iter(entries_.size() - 1, npos());
  1116. }
  1117. template <typename... Args> iterator emplace(Args &&...args) {
  1118. entries_.emplace_back(std::forward<Args>(args)...);
  1119. return make_iter(entries_.size() - 1, npos());
  1120. }
  1121. // For entries that have to lead the message, such as the Host header field
  1122. // (RFC 9110 5.3 recommends sending control data first).
  1123. template <typename... Args> iterator emplace_front(Args &&...args) {
  1124. entries_.emplace(entries_.begin(), std::forward<Args>(args)...);
  1125. return make_iter(0, npos());
  1126. }
  1127. iterator find(const std::string &key) {
  1128. auto i = index_of(key);
  1129. return i == npos() ? end() : make_iter(i, i);
  1130. }
  1131. const_iterator find(const std::string &key) const {
  1132. auto i = index_of(key);
  1133. return i == npos() ? end() : make_citer(i, i);
  1134. }
  1135. size_type count(const std::string &key) const {
  1136. size_type n = 0;
  1137. for (const auto &entry : entries_) {
  1138. if (keys_equal(entry.first, key)) { n++; }
  1139. }
  1140. return n;
  1141. }
  1142. std::pair<iterator, iterator> equal_range(const std::string &key) {
  1143. auto i = index_of(key);
  1144. return i == npos() ? std::make_pair(end(), end())
  1145. : std::make_pair(make_iter(i, i), end());
  1146. }
  1147. std::pair<const_iterator, const_iterator>
  1148. equal_range(const std::string &key) const {
  1149. auto i = index_of(key);
  1150. return i == npos() ? std::make_pair(end(), end())
  1151. : std::make_pair(make_citer(i, i), end());
  1152. }
  1153. size_type erase(const std::string &key) {
  1154. auto before = entries_.size();
  1155. entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
  1156. [key](const value_type &entry) {
  1157. return keys_equal(entry.first, key);
  1158. }),
  1159. entries_.end());
  1160. return before - entries_.size();
  1161. }
  1162. iterator erase(const_iterator pos) {
  1163. entries_.erase(entries_.begin() + static_cast<difference_type>(pos.idx_));
  1164. return make_iter(pos.idx_, npos());
  1165. }
  1166. // Erases what iterating [first, last) would actually visit, so erasing an
  1167. // equal_range() removes only the entries with that key, not everything
  1168. // positioned between them.
  1169. iterator erase(const_iterator first, const_iterator last) {
  1170. auto from = first.idx_;
  1171. auto to = last.idx_;
  1172. if (from >= to) { return make_iter(from, npos()); }
  1173. auto begin_it = entries_.begin();
  1174. auto from_it = begin_it + static_cast<difference_type>(from);
  1175. auto to_it = begin_it + static_cast<difference_type>(to);
  1176. if (first.key_idx_ == npos()) {
  1177. entries_.erase(from_it, to_it);
  1178. } else {
  1179. auto key = entries_[first.key_idx_].first;
  1180. auto keep = from_it;
  1181. for (auto it = from_it; it != to_it; ++it) {
  1182. if (!keys_equal(it->first, key)) {
  1183. if (keep != it) { *keep = std::move(*it); }
  1184. ++keep;
  1185. }
  1186. }
  1187. if (keep != to_it) {
  1188. keep = std::move(to_it, entries_.end(), keep);
  1189. } else {
  1190. keep = entries_.end();
  1191. }
  1192. entries_.erase(keep, entries_.end());
  1193. }
  1194. return make_iter(from, npos());
  1195. }
  1196. friend bool operator==(const insertion_ordered_multimap &lhs,
  1197. const insertion_ordered_multimap &rhs) {
  1198. return lhs.entries_ == rhs.entries_;
  1199. }
  1200. friend bool operator!=(const insertion_ordered_multimap &lhs,
  1201. const insertion_ordered_multimap &rhs) {
  1202. return !(lhs == rhs);
  1203. }
  1204. private:
  1205. size_type index_of(const std::string &key) const {
  1206. for (size_type i = 0; i < entries_.size(); i++) {
  1207. if (keys_equal(entries_[i].first, key)) { return i; }
  1208. }
  1209. return npos();
  1210. }
  1211. iterator make_iter(size_type idx, size_type key_idx) {
  1212. return iterator(entries_.data(), idx, entries_.size(), key_idx);
  1213. }
  1214. const_iterator make_citer(size_type idx, size_type key_idx) const {
  1215. return const_iterator(entries_.data(), idx, entries_.size(), key_idx);
  1216. }
  1217. std::vector<value_type> entries_;
  1218. };
  1219. } // namespace detail
  1220. using Headers =
  1221. detail::insertion_ordered_multimap<std::string,
  1222. detail::case_ignore::equal_to>;
  1223. // Query parameter names are case-sensitive, unlike header field names.
  1224. using Params =
  1225. detail::insertion_ordered_multimap<std::string, std::equal_to<std::string>>;
  1226. using Match = std::smatch;
  1227. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  1228. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  1229. /*
  1230. * detail: type-erased storage used by UserData.
  1231. * ABI-stable regardless of C++ standard — always uses this custom
  1232. * implementation instead of std::any.
  1233. */
  1234. namespace detail {
  1235. using any_type_id = const void *;
  1236. template <typename T> any_type_id any_typeid() noexcept {
  1237. static const char id = 0;
  1238. return &id;
  1239. }
  1240. struct any_storage {
  1241. virtual ~any_storage() = default;
  1242. virtual std::unique_ptr<any_storage> clone() const = 0;
  1243. virtual any_type_id type_id() const noexcept = 0;
  1244. };
  1245. template <typename T> struct any_value final : any_storage {
  1246. T value;
  1247. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  1248. std::unique_ptr<any_storage> clone() const override {
  1249. return std::unique_ptr<any_storage>(new any_value<T>(value));
  1250. }
  1251. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  1252. };
  1253. } // namespace detail
  1254. class UserData {
  1255. public:
  1256. UserData() = default;
  1257. UserData(UserData &&) noexcept = default;
  1258. UserData &operator=(UserData &&) noexcept = default;
  1259. UserData(const UserData &o) {
  1260. for (const auto &e : o.entries_) {
  1261. if (e.second) { entries_[e.first] = e.second->clone(); }
  1262. }
  1263. }
  1264. UserData &operator=(const UserData &o) {
  1265. if (this != &o) {
  1266. entries_.clear();
  1267. for (const auto &e : o.entries_) {
  1268. if (e.second) { entries_[e.first] = e.second->clone(); }
  1269. }
  1270. }
  1271. return *this;
  1272. }
  1273. template <typename T> void set(const std::string &key, T &&value) {
  1274. using D = typename std::decay<T>::type;
  1275. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  1276. }
  1277. template <typename T> T *get(const std::string &key) noexcept {
  1278. auto it = entries_.find(key);
  1279. if (it == entries_.end() || !it->second) { return nullptr; }
  1280. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1281. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  1282. }
  1283. template <typename T> const T *get(const std::string &key) const noexcept {
  1284. auto it = entries_.find(key);
  1285. if (it == entries_.end() || !it->second) { return nullptr; }
  1286. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1287. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  1288. }
  1289. bool has(const std::string &key) const noexcept {
  1290. return entries_.find(key) != entries_.end();
  1291. }
  1292. void erase(const std::string &key) { entries_.erase(key); }
  1293. void clear() noexcept { entries_.clear(); }
  1294. private:
  1295. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  1296. entries_;
  1297. };
  1298. struct Response;
  1299. using ResponseHandler = std::function<bool(const Response &response)>;
  1300. struct FormData {
  1301. std::string name;
  1302. std::string content;
  1303. std::string filename;
  1304. std::string content_type;
  1305. Headers headers;
  1306. };
  1307. struct FormField {
  1308. std::string name;
  1309. std::string content;
  1310. Headers headers;
  1311. };
  1312. // RFC 7578 5.2: a form processor "SHOULD send back results in order" and
  1313. // "Intermediaries MUST NOT reorder the results", so a handler walking these
  1314. // should see the parts as they were sent. A std::multimap sorts by field name
  1315. // and loses that. Field names are case-sensitive, hence std::equal_to rather
  1316. // than the case-insensitive predicate Headers uses.
  1317. using FormFields =
  1318. detail::insertion_ordered_multimap<FormField, std::equal_to<std::string>>;
  1319. using FormFiles =
  1320. detail::insertion_ordered_multimap<FormData, std::equal_to<std::string>>;
  1321. struct MultipartFormData {
  1322. FormFields fields; // Text fields from multipart
  1323. FormFiles files; // Files from multipart
  1324. // Text field access
  1325. std::string get_field(const std::string &key, size_t id = 0) const;
  1326. std::vector<std::string> get_fields(const std::string &key) const;
  1327. bool has_field(const std::string &key) const;
  1328. size_t get_field_count(const std::string &key) const;
  1329. // File access
  1330. FormData get_file(const std::string &key, size_t id = 0) const;
  1331. std::vector<FormData> get_files(const std::string &key) const;
  1332. bool has_file(const std::string &key) const;
  1333. size_t get_file_count(const std::string &key) const;
  1334. };
  1335. struct UploadFormData {
  1336. std::string name;
  1337. std::string content;
  1338. std::string filename;
  1339. std::string content_type;
  1340. };
  1341. using UploadFormDataItems = std::vector<UploadFormData>;
  1342. class DataSink {
  1343. public:
  1344. DataSink() : os(&sb_), sb_(*this) {}
  1345. DataSink(const DataSink &) = delete;
  1346. DataSink &operator=(const DataSink &) = delete;
  1347. DataSink(DataSink &&) = delete;
  1348. DataSink &operator=(DataSink &&) = delete;
  1349. std::function<bool(const char *data, size_t data_len)> write;
  1350. // Only `write` is mandatory. The rest are defaulted so that a provider
  1351. // calling one on a writer that does not set it gets sensible behaviour
  1352. // rather than std::bad_function_call thrown from a worker thread. Capturing
  1353. // `this` is safe: DataSink is neither copyable nor movable.
  1354. std::function<bool()> is_writable = []() { return true; };
  1355. std::function<void()> done = []() {};
  1356. std::function<void(const Headers &trailer)> done_with_trailer =
  1357. [this](const Headers & /*trailer*/) { done(); };
  1358. std::ostream os;
  1359. private:
  1360. class data_sink_streambuf final : public std::streambuf {
  1361. public:
  1362. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  1363. protected:
  1364. std::streamsize xsputn(const char *s, std::streamsize n) override {
  1365. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  1366. return 0;
  1367. }
  1368. private:
  1369. DataSink &sink_;
  1370. };
  1371. data_sink_streambuf sb_;
  1372. };
  1373. using ContentProvider =
  1374. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  1375. using ContentProviderWithoutLength =
  1376. std::function<bool(size_t offset, DataSink &sink)>;
  1377. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  1378. struct FormDataProvider {
  1379. std::string name;
  1380. ContentProviderWithoutLength provider;
  1381. std::string filename;
  1382. std::string content_type;
  1383. };
  1384. using FormDataProviderItems = std::vector<FormDataProvider>;
  1385. inline FormDataProvider
  1386. make_file_provider(const std::string &name, const std::string &filepath,
  1387. const std::string &filename = std::string(),
  1388. const std::string &content_type = std::string()) {
  1389. FormDataProvider fdp;
  1390. fdp.name = name;
  1391. fdp.filename = filename.empty() ? filepath : filename;
  1392. fdp.content_type = content_type;
  1393. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  1394. std::ifstream f(filepath, std::ios::binary);
  1395. if (!f) { return false; }
  1396. if (offset > 0) {
  1397. f.seekg(static_cast<std::streamoff>(offset));
  1398. if (!f.good()) {
  1399. sink.done();
  1400. return true;
  1401. }
  1402. }
  1403. char buf[8192];
  1404. f.read(buf, sizeof(buf));
  1405. auto n = static_cast<size_t>(f.gcount());
  1406. if (n > 0) { return sink.write(buf, n); }
  1407. sink.done(); // EOF
  1408. return true;
  1409. };
  1410. return fdp;
  1411. }
  1412. inline std::pair<size_t, ContentProvider>
  1413. make_file_body(const std::string &filepath) {
  1414. size_t size = 0;
  1415. {
  1416. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  1417. if (!f) { return {0, ContentProvider{}}; }
  1418. size = static_cast<size_t>(f.tellg());
  1419. }
  1420. ContentProvider provider = [filepath](size_t offset, size_t length,
  1421. DataSink &sink) -> bool {
  1422. std::ifstream f(filepath, std::ios::binary);
  1423. if (!f) { return false; }
  1424. f.seekg(static_cast<std::streamoff>(offset));
  1425. if (!f.good()) { return false; }
  1426. char buf[8192];
  1427. while (length > 0) {
  1428. auto to_read = (std::min)(sizeof(buf), length);
  1429. f.read(buf, static_cast<std::streamsize>(to_read));
  1430. auto n = static_cast<size_t>(f.gcount());
  1431. // The file is shorter than the size make_file_body() measured, which the
  1432. // caller has already committed to as Content-Length. The body cannot be
  1433. // completed, so fail as every other error here does.
  1434. if (n == 0) { return false; }
  1435. if (!sink.write(buf, n)) { return false; }
  1436. length -= n;
  1437. }
  1438. return true;
  1439. };
  1440. return {size, std::move(provider)};
  1441. }
  1442. using ContentReceiverWithProgress = std::function<bool(
  1443. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1444. using ContentReceiver =
  1445. std::function<bool(const char *data, size_t data_length)>;
  1446. using FormDataHeader = std::function<bool(const FormData &file)>;
  1447. class ContentReader {
  1448. public:
  1449. using Reader = std::function<bool(ContentReceiver receiver)>;
  1450. using FormDataReader =
  1451. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1452. ContentReader(Reader reader, FormDataReader multipart_reader)
  1453. : reader_(std::move(reader)),
  1454. formdata_reader_(std::move(multipart_reader)) {}
  1455. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1456. return formdata_reader_(std::move(header), std::move(receiver));
  1457. }
  1458. bool operator()(ContentReceiver receiver) const {
  1459. return reader_(std::move(receiver));
  1460. }
  1461. Reader reader_;
  1462. FormDataReader formdata_reader_;
  1463. };
  1464. using Range = std::pair<ssize_t, ssize_t>;
  1465. using Ranges = std::vector<Range>;
  1466. #ifdef CPPHTTPLIB_SSL_ENABLED
  1467. // TLS abstraction layer - public type definitions and API
  1468. namespace tls {
  1469. // Opaque handles (defined as void* for abstraction)
  1470. using ctx_t = void *;
  1471. using session_t = void *;
  1472. using const_session_t = const void *; // For read-only session access
  1473. using cert_t = void *;
  1474. using ca_store_t = void *;
  1475. // TLS versions
  1476. enum class Version {
  1477. TLS1_2 = 0x0303,
  1478. TLS1_3 = 0x0304,
  1479. };
  1480. // Subject Alternative Names (SAN) entry types
  1481. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1482. // SAN entry structure
  1483. struct SanEntry {
  1484. SanType type;
  1485. std::string value;
  1486. };
  1487. // Verification context for certificate verification callback
  1488. struct VerifyContext {
  1489. session_t session; // TLS session handle
  1490. cert_t cert; // Current certificate being verified
  1491. int depth; // Certificate chain depth (0 = leaf)
  1492. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1493. long error_code; // Backend-specific error code (0 = no error)
  1494. const char *error_string; // Human-readable error description
  1495. // Certificate introspection methods
  1496. std::string subject_cn() const;
  1497. std::string issuer_name() const;
  1498. bool check_hostname(const char *hostname) const;
  1499. std::vector<SanEntry> sans() const;
  1500. bool validity(time_t &not_before, time_t &not_after) const;
  1501. std::string serial() const;
  1502. };
  1503. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1504. // TlsError codes for TLS operations (backend-independent)
  1505. enum class ErrorCode : int {
  1506. Success = 0,
  1507. WantRead, // Non-blocking: need to wait for read
  1508. WantWrite, // Non-blocking: need to wait for write
  1509. PeerClosed, // Peer closed the connection
  1510. Fatal, // Unrecoverable error
  1511. SyscallError, // System call error (check sys_errno)
  1512. CertVerifyFailed, // Certificate verification failed
  1513. HostnameMismatch, // Hostname verification failed
  1514. };
  1515. // TLS error information
  1516. struct TlsError {
  1517. ErrorCode code = ErrorCode::Fatal;
  1518. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1519. int sys_errno = 0; // errno when SyscallError
  1520. // Convert verification error code to human-readable string
  1521. static std::string verify_error_to_string(long error_code);
  1522. };
  1523. // RAII wrapper for peer certificate
  1524. class PeerCert {
  1525. public:
  1526. PeerCert();
  1527. PeerCert(PeerCert &&other) noexcept;
  1528. PeerCert &operator=(PeerCert &&other) noexcept;
  1529. ~PeerCert();
  1530. PeerCert(const PeerCert &) = delete;
  1531. PeerCert &operator=(const PeerCert &) = delete;
  1532. explicit operator bool() const;
  1533. std::string subject_cn() const;
  1534. std::string issuer_name() const;
  1535. bool check_hostname(const char *hostname) const;
  1536. std::vector<SanEntry> sans() const;
  1537. bool validity(time_t &not_before, time_t &not_after) const;
  1538. std::string serial() const;
  1539. private:
  1540. explicit PeerCert(cert_t cert);
  1541. cert_t cert_ = nullptr;
  1542. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1543. };
  1544. // Callback for TLS context setup (used by SSLServer constructor)
  1545. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1546. } // namespace tls
  1547. #endif
  1548. struct Request {
  1549. std::string method;
  1550. std::string path;
  1551. std::string matched_route;
  1552. Params params;
  1553. Headers headers;
  1554. Headers trailers;
  1555. std::string body;
  1556. std::string remote_addr;
  1557. int remote_port = -1;
  1558. std::string local_addr;
  1559. int local_port = -1;
  1560. // for server
  1561. std::string version;
  1562. std::string target;
  1563. MultipartFormData form;
  1564. Ranges ranges;
  1565. Match matches;
  1566. std::unordered_map<std::string, std::string> path_params;
  1567. std::function<bool()> is_connection_closed = []() { return true; };
  1568. // for client
  1569. std::vector<std::string> accept_content_types;
  1570. ResponseHandler response_handler;
  1571. ContentReceiverWithProgress content_receiver;
  1572. DownloadProgress download_progress;
  1573. UploadProgress upload_progress;
  1574. bool has_header(const std::string &key) const;
  1575. std::string get_header_value(const std::string &key, const char *def = "",
  1576. size_t id = 0) const;
  1577. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1578. size_t id = 0) const;
  1579. size_t get_header_value_count(const std::string &key) const;
  1580. void set_header(const std::string &key, const std::string &val);
  1581. bool has_trailer(const std::string &key) const;
  1582. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1583. size_t get_trailer_value_count(const std::string &key) const;
  1584. bool has_param(const std::string &key) const;
  1585. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1586. std::vector<std::string> get_param_values(const std::string &key) const;
  1587. size_t get_param_value_count(const std::string &key) const;
  1588. bool is_multipart_form_data() const;
  1589. // private members...
  1590. bool body_read_started_ = false;
  1591. bool body_consumed_ = false;
  1592. bool expect_100_continue_pending_ = false;
  1593. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1594. size_t content_length_ = 0;
  1595. ContentProvider content_provider_;
  1596. bool is_chunked_content_provider_ = false;
  1597. size_t authorization_count_ = 0;
  1598. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1599. (std::chrono::steady_clock::time_point::min)();
  1600. #ifdef CPPHTTPLIB_SSL_ENABLED
  1601. tls::const_session_t ssl = nullptr;
  1602. tls::PeerCert peer_cert() const;
  1603. std::string sni() const;
  1604. #endif
  1605. };
  1606. namespace detail {
  1607. // Declared up here, away from the rest of the compression helpers, because
  1608. // `Response` stores one.
  1609. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1610. } // namespace detail
  1611. struct Response {
  1612. std::string version;
  1613. int status = -1;
  1614. std::string reason;
  1615. Headers headers;
  1616. Headers trailers;
  1617. std::string body;
  1618. std::string location; // Redirect location
  1619. // User-defined context — set by pre-routing/pre-request handlers and read
  1620. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1621. UserData user_data;
  1622. bool has_header(const std::string &key) const;
  1623. std::string get_header_value(const std::string &key, const char *def = "",
  1624. size_t id = 0) const;
  1625. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1626. size_t id = 0) const;
  1627. size_t get_header_value_count(const std::string &key) const;
  1628. void set_header(const std::string &key, const std::string &val);
  1629. bool has_trailer(const std::string &key) const;
  1630. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1631. size_t get_trailer_value_count(const std::string &key) const;
  1632. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1633. void set_content(const char *s, size_t n, const std::string &content_type);
  1634. void set_content(const std::string &s, const std::string &content_type);
  1635. void set_content(std::string &&s, const std::string &content_type);
  1636. void set_content_provider(
  1637. size_t length, const std::string &content_type, ContentProvider provider,
  1638. ContentProviderResourceReleaser resource_releaser = nullptr);
  1639. void set_content_provider(
  1640. const std::string &content_type, ContentProviderWithoutLength provider,
  1641. ContentProviderResourceReleaser resource_releaser = nullptr);
  1642. void set_chunked_content_provider(
  1643. const std::string &content_type, ContentProviderWithoutLength provider,
  1644. ContentProviderResourceReleaser resource_releaser = nullptr);
  1645. void set_file_content(const std::string &path,
  1646. const std::string &content_type);
  1647. void set_file_content(const std::string &path);
  1648. Response() = default;
  1649. Response(const Response &) = default;
  1650. Response &operator=(const Response &) = default;
  1651. Response(Response &&) = default;
  1652. Response &operator=(Response &&) = default;
  1653. ~Response() {
  1654. if (content_provider_resource_releaser_) {
  1655. content_provider_resource_releaser_(content_provider_success_);
  1656. }
  1657. }
  1658. // private members...
  1659. size_t content_length_ = 0;
  1660. ContentProvider content_provider_;
  1661. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1662. bool is_chunked_content_provider_ = false;
  1663. bool is_file_content_provider_ = false;
  1664. bool content_provider_success_ = false;
  1665. std::string file_content_path_;
  1666. std::string file_content_content_type_;
  1667. // Content coding chosen for the response body, decided once so that the
  1668. // headers and the body cannot disagree: where the file is opened for a
  1669. // file-backed content provider (keeping the ETag honest), and in
  1670. // `apply_ranges()` for a chunked content provider. `EncodingType::None`
  1671. // for every other kind of response.
  1672. detail::EncodingType content_coding_ = detail::EncodingType::None;
  1673. };
  1674. enum class Error {
  1675. Success = 0,
  1676. Unknown,
  1677. Connection,
  1678. BindIPAddress,
  1679. Read,
  1680. Write,
  1681. ExceedRedirectCount,
  1682. Canceled,
  1683. SSLConnection,
  1684. SSLLoadingCerts,
  1685. SSLServerVerification,
  1686. SSLServerHostnameVerification,
  1687. UnsupportedMultipartBoundaryChars,
  1688. Compression,
  1689. ConnectionTimeout,
  1690. ProxyConnection,
  1691. ConnectionClosed,
  1692. Timeout,
  1693. ResourceExhaustion,
  1694. TooManyFormDataFiles,
  1695. ExceedMaxPayloadSize,
  1696. ExceedUriMaxLength,
  1697. ExceedMaxSocketDescriptorCount,
  1698. InvalidRequestLine,
  1699. InvalidHTTPMethod,
  1700. InvalidHTTPVersion,
  1701. InvalidHeaders,
  1702. MultipartParsing,
  1703. OpenFile,
  1704. Listen,
  1705. GetSockName,
  1706. UnsupportedAddressFamily,
  1707. HTTPParsing,
  1708. InvalidRangeHeader,
  1709. UnsupportedContentEncoding,
  1710. WebSocketHandshake,
  1711. UserCallbackException,
  1712. // For internal use only
  1713. SSLPeerCouldBeClosed_,
  1714. };
  1715. std::string to_string(Error error);
  1716. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1717. class Stream {
  1718. public:
  1719. virtual ~Stream() = default;
  1720. virtual bool is_readable() const = 0;
  1721. virtual bool wait_readable() const = 0;
  1722. virtual bool wait_writable() const = 0;
  1723. virtual bool is_peer_alive() const { return wait_writable(); }
  1724. virtual ssize_t read(char *ptr, size_t size) = 0;
  1725. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1726. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1727. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1728. virtual socket_t socket() const = 0;
  1729. virtual time_t duration() const = 0;
  1730. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1731. (void)sec;
  1732. (void)usec;
  1733. }
  1734. // Bounds the reads from now on to `msec` in total, on top of the timeout of
  1735. // each one. 0 lifts the bound.
  1736. virtual void set_max_timeout(time_t msec) { (void)msec; }
  1737. // Lets a wait for data end early once `interrupted` returns true, so that
  1738. // another thread can stop a blocked read on every platform.
  1739. virtual void set_read_interrupt(std::function<bool()> interrupted) {
  1740. (void)interrupted;
  1741. }
  1742. // Bytes already pulled off the socket and sitting in this stream's own
  1743. // buffer. Exposing them lets a line reader scan for a terminator in one
  1744. // pass instead of asking for a byte at a time. A stream that does no
  1745. // buffering of its own reports none, and readers fall back to read().
  1746. virtual const char *buffered_data(size_t &size) const {
  1747. size = 0;
  1748. return nullptr;
  1749. }
  1750. // Discards `size` bytes previously returned by buffered_data().
  1751. virtual void consume_buffered(size_t size) { (void)size; }
  1752. ssize_t write(const char *ptr);
  1753. ssize_t write(const std::string &s);
  1754. Error get_error() const { return error_; }
  1755. protected:
  1756. Error error_ = Error::Success;
  1757. };
  1758. class TaskQueue {
  1759. public:
  1760. TaskQueue() = default;
  1761. virtual ~TaskQueue() = default;
  1762. virtual bool enqueue(std::function<void()> fn) = 0;
  1763. virtual void shutdown() = 0;
  1764. virtual void on_idle() {}
  1765. };
  1766. class ThreadPool final : public TaskQueue {
  1767. public:
  1768. explicit ThreadPool(
  1769. size_t n, size_t max_n = 0, size_t mqr = 0,
  1770. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1771. ThreadPool(const ThreadPool &) = delete;
  1772. ~ThreadPool() override = default;
  1773. bool enqueue(std::function<void()> fn) override;
  1774. void shutdown() override;
  1775. private:
  1776. void worker(bool is_dynamic);
  1777. void move_to_finished(std::thread::id id);
  1778. void cleanup_finished_threads();
  1779. size_t base_thread_count_;
  1780. size_t max_thread_count_;
  1781. size_t max_queued_requests_;
  1782. time_t idle_timeout_sec_;
  1783. size_t idle_thread_count_;
  1784. bool shutdown_;
  1785. std::list<std::function<void()>> jobs_;
  1786. std::vector<std::thread> threads_; // base threads
  1787. std::list<std::thread> dynamic_threads_; // dynamic threads
  1788. std::vector<std::thread>
  1789. finished_threads_; // exited dynamic threads awaiting join
  1790. std::condition_variable cond_;
  1791. std::mutex mutex_;
  1792. };
  1793. using Logger = std::function<void(const Request &, const Response &)>;
  1794. // Forward declaration for Error type
  1795. enum class Error;
  1796. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1797. using SocketOptions = std::function<void(socket_t sock)>;
  1798. void default_socket_options(socket_t sock);
  1799. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1800. const char *status_message(int status);
  1801. std::string to_string(Error error);
  1802. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1803. std::string get_bearer_token_auth(const Request &req);
  1804. namespace detail {
  1805. class MatcherBase {
  1806. public:
  1807. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1808. virtual ~MatcherBase() = default;
  1809. const std::string &pattern() const { return pattern_; }
  1810. // Match request path and populate its matches and
  1811. virtual bool match(Request &request) const = 0;
  1812. private:
  1813. std::string pattern_;
  1814. };
  1815. /**
  1816. * Captures parameters in request path and stores them in Request::path_params
  1817. *
  1818. * Capture name is a substring of a pattern from : to /.
  1819. * The rest of the pattern is matched against the request path directly
  1820. * Parameters are captured starting from the next character after
  1821. * the end of the last matched static pattern fragment until the next /.
  1822. *
  1823. * Example pattern:
  1824. * "/path/fragments/:capture/more/fragments/:second_capture"
  1825. * Static fragments:
  1826. * "/path/fragments/", "more/fragments/"
  1827. *
  1828. * Given the following request path:
  1829. * "/path/fragments/:1/more/fragments/:2"
  1830. * the resulting capture will be
  1831. * {{"capture", "1"}, {"second_capture", "2"}}
  1832. */
  1833. class PathParamsMatcher final : public MatcherBase {
  1834. public:
  1835. PathParamsMatcher(const std::string &pattern);
  1836. bool match(Request &request) const override;
  1837. private:
  1838. // Treat segment separators as the end of path parameter capture
  1839. // Does not need to handle query parameters as they are parsed before path
  1840. // matching
  1841. static constexpr char separator = '/';
  1842. // Contains static path fragments to match against, excluding the '/' after
  1843. // path params
  1844. // Fragments are separated by path params
  1845. std::vector<std::string> static_fragments_;
  1846. // Stores the names of the path parameters to be used as keys in the
  1847. // Request::path_params map
  1848. std::vector<std::string> param_names_;
  1849. };
  1850. /**
  1851. * Performs std::regex_match on request path
  1852. * and stores the result in Request::matches
  1853. *
  1854. * Note that regex match is performed directly on the whole request.
  1855. * This means that wildcard patterns may match multiple path segments with /:
  1856. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1857. */
  1858. class RegexMatcher final : public MatcherBase {
  1859. public:
  1860. RegexMatcher(const std::string &pattern)
  1861. : MatcherBase(pattern), regex_(pattern) {}
  1862. bool match(Request &request) const override;
  1863. private:
  1864. std::regex regex_;
  1865. };
  1866. int close_socket(socket_t sock) noexcept;
  1867. bool is_accept_resource_error();
  1868. bool is_accept_transient_error();
  1869. ssize_t write_headers(Stream &strm, const Headers &headers);
  1870. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1871. time_t usec);
  1872. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1873. const std::string &boundary);
  1874. ContentProvider
  1875. make_multipart_content_provider(const UploadFormDataItems &items,
  1876. const std::string &boundary);
  1877. } // namespace detail
  1878. bool is_valid_multipart_boundary(const std::string &boundary);
  1879. // Serializer for multipart/form-data request bodies. The boundary is owned
  1880. // by the writer so that per-part framing and the final terminator always
  1881. // agree. Field names and filenames are escaped following the WHATWG HTML
  1882. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1883. // in content types.
  1884. class MultipartFormDataWriter {
  1885. public:
  1886. MultipartFormDataWriter();
  1887. // precondition: is_valid_multipart_boundary(boundary)
  1888. explicit MultipartFormDataWriter(std::string boundary);
  1889. const std::string &boundary() const;
  1890. std::string content_type() const;
  1891. // In-memory items -> whole body (known length)
  1892. std::string serialize(const UploadFormDataItems &items) const;
  1893. size_t content_length(const UploadFormDataItems &items) const;
  1894. // Per-part framing for streaming via a content provider
  1895. std::string item_begin(const UploadFormData &item) const;
  1896. static std::string item_end();
  1897. std::string finish() const;
  1898. private:
  1899. std::string boundary_;
  1900. };
  1901. class Server {
  1902. public:
  1903. using Handler = std::function<void(const Request &, Response &)>;
  1904. using ExceptionHandler =
  1905. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1906. enum class HandlerResponse {
  1907. Handled,
  1908. Unhandled,
  1909. };
  1910. using HandlerWithResponse =
  1911. std::function<HandlerResponse(const Request &, Response &)>;
  1912. using HandlerWithContentReader = std::function<void(
  1913. const Request &, Response &, const ContentReader &content_reader)>;
  1914. using Expect100ContinueHandler =
  1915. std::function<int(const Request &, Response &)>;
  1916. using StartHandler = std::function<void()>;
  1917. using WebSocketHandler =
  1918. std::function<void(const Request &, ws::WebSocket &)>;
  1919. using SubProtocolSelector =
  1920. std::function<std::string(const std::vector<std::string> &protocols)>;
  1921. Server();
  1922. virtual ~Server();
  1923. virtual bool is_valid() const;
  1924. Server &Get(const std::string &pattern, Handler handler);
  1925. Server &Post(const std::string &pattern, Handler handler);
  1926. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1927. Server &Put(const std::string &pattern, Handler handler);
  1928. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1929. Server &Patch(const std::string &pattern, Handler handler);
  1930. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1931. Server &Delete(const std::string &pattern, Handler handler);
  1932. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1933. Server &Options(const std::string &pattern, Handler handler);
  1934. // Register a handler for an HTTP method outside the built-in set (e.g. the
  1935. // WebDAV methods from RFC 4918). Registering a method here is what makes the
  1936. // server accept it; an unregistered method is still rejected with 400.
  1937. // `method` must be a valid HTTP method token and must not be one of the
  1938. // built-in methods, which have their own registration functions above. A
  1939. // rejected registration makes is_valid() return false, so listen() fails.
  1940. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1941. Handler handler);
  1942. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1943. HandlerWithContentReader handler);
  1944. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1945. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1946. SubProtocolSelector sub_protocol_selector);
  1947. bool set_base_dir(const std::string &dir,
  1948. const std::string &mount_point = std::string());
  1949. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1950. Headers headers = Headers());
  1951. bool remove_mount_point(const std::string &mount_point);
  1952. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1953. const std::string &mime);
  1954. Server &set_default_file_mimetype(const std::string &mime);
  1955. Server &set_file_request_handler(Handler handler);
  1956. template <class ErrorHandlerFunc>
  1957. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1958. return set_error_handler_core(
  1959. std::forward<ErrorHandlerFunc>(handler),
  1960. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1961. }
  1962. Server &set_exception_handler(ExceptionHandler handler);
  1963. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1964. Server &set_post_routing_handler(Handler handler);
  1965. Server &set_pre_request_handler(HandlerWithResponse handler);
  1966. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1967. Server &set_start_handler(StartHandler handler);
  1968. Server &set_logger(Logger logger);
  1969. Server &set_pre_compression_logger(Logger logger);
  1970. Server &set_error_logger(ErrorLogger error_logger);
  1971. Server &set_address_family(int family);
  1972. Server &set_tcp_nodelay(bool on);
  1973. Server &set_ipv6_v6only(bool on);
  1974. Server &set_socket_options(SocketOptions socket_options);
  1975. Server &set_default_headers(Headers headers);
  1976. Server &
  1977. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1978. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1979. Server &set_keep_alive_max_count(size_t count);
  1980. Server &set_keep_alive_timeout(time_t sec);
  1981. template <class Rep, class Period>
  1982. Server &
  1983. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1984. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1985. template <class Rep, class Period>
  1986. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1987. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1988. template <class Rep, class Period>
  1989. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1990. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1991. template <class Rep, class Period>
  1992. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1993. // Keeps idle keep-alive connections in an event loop instead of a worker
  1994. // thread each. Call it before listen(). See README for what changes.
  1995. Server &set_keep_alive_parking(bool on);
  1996. Server &set_payload_max_length(size_t length);
  1997. Server &set_compress(bool on);
  1998. Server &set_static_file_compression(bool on);
  1999. Server &set_static_file_compression_min_length(size_t length);
  2000. Server &set_static_file_compression_max_length(size_t length);
  2001. Server &set_websocket_ping_interval(time_t sec);
  2002. template <class Rep, class Period>
  2003. Server &set_websocket_ping_interval(
  2004. const std::chrono::duration<Rep, Period> &duration);
  2005. Server &set_websocket_max_missed_pongs(int count);
  2006. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  2007. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  2008. bool listen_after_bind();
  2009. bool listen(const std::string &host, int port, int socket_flags = 0);
  2010. bool is_running() const;
  2011. void wait_until_ready() const;
  2012. void stop() noexcept;
  2013. void decommission();
  2014. std::function<TaskQueue *(void)> new_task_queue;
  2015. protected:
  2016. bool process_request(Stream &strm, const std::string &remote_addr,
  2017. int remote_port, const std::string &local_addr,
  2018. int local_port, bool close_connection,
  2019. bool &connection_closed,
  2020. const std::function<void(Request &)> &setup_request,
  2021. bool *websocket_upgraded = nullptr);
  2022. // Runs the per-connection serving loop and stops an exception thrown by a
  2023. // user callback from escaping the worker thread.
  2024. //
  2025. // process_request() wraps only routing() and the hooks before a WebSocket
  2026. // upgrade in a try/catch. Content providers, the post-routing, error,
  2027. // logging and expect-100 handlers and WebSocket handlers all run outside
  2028. // it, and the task queue calls the job without a catch, so an exception
  2029. // from any of those would terminate the process.
  2030. //
  2031. // No 500 is possible here: by the time a content provider runs, the status
  2032. // line and headers are already on the wire. Report it through the error
  2033. // logger and drop the connection, which is what the peer observes either
  2034. // way. Other connections are unaffected.
  2035. template <typename Serve> bool serve_guarded(Serve &&serve) const {
  2036. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  2037. return serve();
  2038. #else
  2039. try {
  2040. return serve();
  2041. } catch (...) {
  2042. // The error logger is a user callback too, so it must not be able to
  2043. // throw the guard back open.
  2044. try {
  2045. output_error_log(Error::UserCallbackException, nullptr);
  2046. } catch (...) {}
  2047. return false;
  2048. }
  2049. #endif
  2050. }
  2051. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  2052. // stop() takes the listening socket away; listen() then waits for handlers
  2053. bool is_stopping() const { return svr_sock_ == INVALID_SOCKET; }
  2054. // See set_keep_alive_parking(). Defined in the implementation part.
  2055. struct KeepAliveConnection;
  2056. struct ParkingState;
  2057. std::unique_ptr<ParkingState> parking_;
  2058. bool keep_alive_parking_ = false;
  2059. bool idle_interval_set_ = false;
  2060. std::vector<std::string> trusted_proxies_;
  2061. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  2062. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  2063. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  2064. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  2065. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  2066. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  2067. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  2068. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  2069. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2070. bool compress_ = true;
  2071. bool static_file_compression_ = false;
  2072. size_t static_file_compression_min_length_ =
  2073. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH;
  2074. size_t static_file_compression_max_length_ =
  2075. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH;
  2076. time_t websocket_ping_interval_sec_ =
  2077. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  2078. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  2079. private:
  2080. using Handlers =
  2081. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  2082. using HandlersForContentReader =
  2083. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  2084. HandlerWithContentReader>>;
  2085. // Both handler tables for one custom method live in a single entry, so that
  2086. // routing() needs only one map lookup per request to reach either of them.
  2087. struct CustomHandlerEntry {
  2088. Handlers handlers;
  2089. HandlersForContentReader handlers_for_content_reader;
  2090. };
  2091. using CustomHandlers = std::map<std::string, CustomHandlerEntry>;
  2092. static std::unique_ptr<detail::MatcherBase>
  2093. make_matcher(const std::string &pattern);
  2094. static const std::set<std::string> &builtin_methods();
  2095. CustomHandlerEntry *custom_entry_for_registration(const std::string &method);
  2096. const CustomHandlerEntry *find_custom_entry(const std::string &method) const;
  2097. template <typename H>
  2098. Server &add_handler(
  2099. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  2100. const std::string &pattern, H handler) {
  2101. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  2102. return *this;
  2103. }
  2104. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  2105. Server &set_error_handler_core(Handler handler, std::false_type);
  2106. socket_t create_server_socket(const std::string &host, int port,
  2107. int socket_flags,
  2108. SocketOptions socket_options) const;
  2109. int bind_internal(const std::string &host, int port, int socket_flags);
  2110. bool listen_internal();
  2111. bool accept_loop(TaskQueue &task_queue);
  2112. bool parking_loop(TaskQueue &task_queue);
  2113. void prepare_accepted_socket(socket_t sock) const;
  2114. struct PlainConnection;
  2115. void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
  2116. bool abandon_listen_socket();
  2117. bool routing(Request &req, Response &res, Stream &strm,
  2118. bool skip_pre_routing);
  2119. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2120. bool handle_exception(Request &req, Response &res);
  2121. #endif
  2122. bool handle_file_request(Request &req, Response &res);
  2123. bool check_if_not_modified(const Request &req, Response &res,
  2124. const std::string &etag, time_t mtime) const;
  2125. bool check_if_range(Request &req, const std::string &etag,
  2126. time_t mtime) const;
  2127. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  2128. Stream &strm);
  2129. bool dispatch_request_for_content_reader(
  2130. Request &req, Response &res, ContentReader content_reader,
  2131. const HandlersForContentReader &handlers) const;
  2132. bool parse_request_line(const char *s, Request &req) const;
  2133. detail::EncodingType static_file_encoding(const Request &req,
  2134. const Response &res,
  2135. const std::string &content_type,
  2136. size_t length) const;
  2137. bool apply_static_file_compression(const Request &req, Response &res) const;
  2138. void apply_ranges(const Request &req, Response &res,
  2139. std::string &content_type, std::string &boundary) const;
  2140. bool write_response(Stream &strm, bool close_connection, Request &req,
  2141. Response &res);
  2142. bool write_response_with_content(Stream &strm, bool close_connection,
  2143. const Request &req, Response &res);
  2144. bool write_response_core(Stream &strm, bool close_connection,
  2145. const Request &req, Response &res,
  2146. bool need_apply_ranges);
  2147. bool write_content_with_provider(Stream &strm, const Request &req,
  2148. Response &res, const std::string &boundary,
  2149. const std::string &content_type);
  2150. bool read_content(Stream &strm, Request &req, Response &res);
  2151. bool read_content_with_content_receiver(Stream &strm, Request &req,
  2152. Response &res,
  2153. ContentReceiver receiver,
  2154. FormDataHeader multipart_header,
  2155. ContentReceiver multipart_receiver);
  2156. bool read_content_core(Stream &strm, Request &req, Response &res,
  2157. ContentReceiver receiver,
  2158. FormDataHeader multipart_header,
  2159. ContentReceiver multipart_receiver) const;
  2160. virtual bool process_and_close_socket(socket_t sock);
  2161. // The connection that parking_loop() keeps for a socket it has accepted.
  2162. virtual std::shared_ptr<KeepAliveConnection>
  2163. new_keep_alive_connection(socket_t sock);
  2164. void output_log(const Request &req, const Response &res) const;
  2165. void output_pre_compression_log(const Request &req,
  2166. const Response &res) const;
  2167. void output_error_log(const Error &err, const Request *req) const;
  2168. std::atomic<bool> is_running_{false};
  2169. std::atomic<bool> is_decommissioned{false};
  2170. // Set when CustomRoute() refuses a registration. Written before listen(),
  2171. // read by is_valid() on the same thread, so it needs no synchronization.
  2172. bool has_invalid_registration_ = false;
  2173. struct MountPointEntry {
  2174. std::string mount_point;
  2175. std::string base_dir;
  2176. std::string resolved_base_dir;
  2177. Headers headers;
  2178. };
  2179. std::vector<MountPointEntry> base_dirs_;
  2180. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  2181. std::string default_file_mimetype_ = "application/octet-stream";
  2182. Handler file_request_handler_;
  2183. Handlers get_handlers_;
  2184. Handlers post_handlers_;
  2185. HandlersForContentReader post_handlers_for_content_reader_;
  2186. Handlers put_handlers_;
  2187. HandlersForContentReader put_handlers_for_content_reader_;
  2188. Handlers patch_handlers_;
  2189. HandlersForContentReader patch_handlers_for_content_reader_;
  2190. Handlers delete_handlers_;
  2191. HandlersForContentReader delete_handlers_for_content_reader_;
  2192. Handlers options_handlers_;
  2193. CustomHandlers custom_handlers_;
  2194. struct WebSocketHandlerEntry {
  2195. std::unique_ptr<detail::MatcherBase> matcher;
  2196. WebSocketHandler handler;
  2197. SubProtocolSelector sub_protocol_selector;
  2198. };
  2199. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  2200. WebSocketHandlers websocket_handlers_;
  2201. HandlerWithResponse error_handler_;
  2202. ExceptionHandler exception_handler_;
  2203. HandlerWithResponse pre_routing_handler_;
  2204. Handler post_routing_handler_;
  2205. HandlerWithResponse pre_request_handler_;
  2206. Expect100ContinueHandler expect_100_continue_handler_;
  2207. StartHandler start_handler_;
  2208. mutable std::mutex logger_mutex_;
  2209. Logger logger_;
  2210. Logger pre_compression_logger_;
  2211. ErrorLogger error_logger_;
  2212. int address_family_ = AF_UNSPEC;
  2213. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2214. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2215. SocketOptions socket_options_ = default_socket_options;
  2216. Headers default_headers_;
  2217. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2218. detail::write_headers;
  2219. };
  2220. class Result {
  2221. public:
  2222. Result() = default;
  2223. Result(std::unique_ptr<Response> &&res, Error err,
  2224. Headers &&request_headers = Headers{})
  2225. : res_(std::move(res)), err_(err),
  2226. request_headers_(std::move(request_headers)) {}
  2227. // Response
  2228. operator bool() const { return res_ != nullptr; }
  2229. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  2230. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  2231. const Response &value() const { return *res_; }
  2232. Response &value() { return *res_; }
  2233. const Response &operator*() const { return *res_; }
  2234. Response &operator*() { return *res_; }
  2235. const Response *operator->() const { return res_.get(); }
  2236. Response *operator->() { return res_.get(); }
  2237. // Error
  2238. Error error() const { return err_; }
  2239. // Request Headers
  2240. bool has_request_header(const std::string &key) const;
  2241. std::string get_request_header_value(const std::string &key,
  2242. const char *def = "",
  2243. size_t id = 0) const;
  2244. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  2245. size_t id = 0) const;
  2246. size_t get_request_header_value_count(const std::string &key) const;
  2247. private:
  2248. std::unique_ptr<Response> res_;
  2249. Error err_ = Error::Unknown;
  2250. Headers request_headers_;
  2251. #ifdef CPPHTTPLIB_SSL_ENABLED
  2252. public:
  2253. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2254. int ssl_error)
  2255. : res_(std::move(res)), err_(err),
  2256. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  2257. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2258. int ssl_error, uint64_t ssl_backend_error)
  2259. : res_(std::move(res)), err_(err),
  2260. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  2261. ssl_backend_error_(ssl_backend_error) {}
  2262. int ssl_error() const { return ssl_error_; }
  2263. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  2264. private:
  2265. int ssl_error_ = 0;
  2266. uint64_t ssl_backend_error_ = 0;
  2267. #endif
  2268. };
  2269. struct ClientConnection {
  2270. socket_t sock = INVALID_SOCKET;
  2271. bool is_open() const { return sock != INVALID_SOCKET; }
  2272. ClientConnection() = default;
  2273. ~ClientConnection();
  2274. ClientConnection(const ClientConnection &) = delete;
  2275. ClientConnection &operator=(const ClientConnection &) = delete;
  2276. ClientConnection(ClientConnection &&other) noexcept
  2277. : sock(other.sock)
  2278. #ifdef CPPHTTPLIB_SSL_ENABLED
  2279. ,
  2280. session(other.session)
  2281. #endif
  2282. {
  2283. other.sock = INVALID_SOCKET;
  2284. #ifdef CPPHTTPLIB_SSL_ENABLED
  2285. other.session = nullptr;
  2286. #endif
  2287. }
  2288. ClientConnection &operator=(ClientConnection &&other) noexcept {
  2289. if (this != &other) {
  2290. sock = other.sock;
  2291. other.sock = INVALID_SOCKET;
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. session = other.session;
  2294. other.session = nullptr;
  2295. #endif
  2296. }
  2297. return *this;
  2298. }
  2299. #ifdef CPPHTTPLIB_SSL_ENABLED
  2300. tls::session_t session = nullptr;
  2301. #endif
  2302. };
  2303. namespace detail {
  2304. struct ChunkedDecoder;
  2305. struct BodyReader {
  2306. Stream *stream = nullptr;
  2307. bool has_content_length = false;
  2308. size_t content_length = 0;
  2309. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2310. size_t bytes_read = 0;
  2311. bool chunked = false;
  2312. bool eof = false;
  2313. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  2314. Error last_error = Error::Success;
  2315. ssize_t read(char *buf, size_t len);
  2316. bool has_error() const { return last_error != Error::Success; }
  2317. };
  2318. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  2319. size_t len) {
  2320. (void)stream;
  2321. return br.read(buf, len);
  2322. }
  2323. class decompressor;
  2324. enum class NoProxyKind {
  2325. Wildcard, // "*"
  2326. HostnameSuffix, // "example.com" or ".example.com"
  2327. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  2328. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  2329. };
  2330. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  2331. // Lets one CIDR matcher cover both families.
  2332. using IPBytes = std::array<uint8_t, 16>;
  2333. struct NoProxyEntry {
  2334. NoProxyKind kind = NoProxyKind::Wildcard;
  2335. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  2336. IPBytes net{};
  2337. int prefix_bits = 0;
  2338. };
  2339. struct NormalizedTarget {
  2340. std::string hostname; // lowercase; brackets and trailing dot removed
  2341. bool is_ipv4 = false;
  2342. bool is_ipv6 = false;
  2343. IPBytes ip{};
  2344. };
  2345. } // namespace detail
  2346. class ClientImpl {
  2347. public:
  2348. explicit ClientImpl(const std::string &host);
  2349. explicit ClientImpl(const std::string &host, int port);
  2350. explicit ClientImpl(const std::string &host, int port,
  2351. const std::string &client_cert_path,
  2352. const std::string &client_key_path);
  2353. virtual ~ClientImpl();
  2354. virtual bool is_valid() const;
  2355. struct StreamHandle {
  2356. std::unique_ptr<Response> response;
  2357. Error error = Error::Success;
  2358. StreamHandle() = default;
  2359. StreamHandle(const StreamHandle &) = delete;
  2360. StreamHandle &operator=(const StreamHandle &) = delete;
  2361. StreamHandle(StreamHandle &&) = default;
  2362. StreamHandle &operator=(StreamHandle &&) = default;
  2363. ~StreamHandle() = default;
  2364. bool is_valid() const {
  2365. return response != nullptr && error == Error::Success;
  2366. }
  2367. ssize_t read(char *buf, size_t len);
  2368. void parse_trailers_if_needed();
  2369. Error get_read_error() const { return body_reader_.last_error; }
  2370. bool has_read_error() const { return body_reader_.has_error(); }
  2371. bool trailers_parsed_ = false;
  2372. private:
  2373. friend class ClientImpl;
  2374. friend class sse::SSEClient;
  2375. ssize_t read_with_decompression(char *buf, size_t len);
  2376. std::unique_ptr<ClientConnection> connection_;
  2377. std::unique_ptr<Stream> socket_stream_;
  2378. Stream *stream_ = nullptr;
  2379. detail::BodyReader body_reader_;
  2380. std::unique_ptr<detail::decompressor> decompressor_;
  2381. std::string decompress_buffer_;
  2382. size_t decompress_offset_ = 0;
  2383. size_t decompressed_bytes_read_ = 0;
  2384. };
  2385. // clang-format off
  2386. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2387. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2388. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2389. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2390. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2391. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2392. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2393. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2394. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2395. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2396. Result Head(const std::string &path);
  2397. Result Head(const std::string &path, const Headers &headers);
  2398. Result Post(const std::string &path);
  2399. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2400. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2401. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2402. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2403. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2404. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2405. Result Post(const std::string &path, const Params &params);
  2406. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2407. Result Post(const std::string &path, const Headers &headers);
  2408. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2409. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2410. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2411. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2412. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2413. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2414. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2415. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2416. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2417. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2418. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2419. Result Put(const std::string &path);
  2420. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2421. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2422. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2423. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2424. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2425. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2426. Result Put(const std::string &path, const Params &params);
  2427. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2428. Result Put(const std::string &path, const Headers &headers);
  2429. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2430. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2431. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2432. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2433. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2434. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2435. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2436. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2437. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2438. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2439. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2440. Result Patch(const std::string &path);
  2441. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2442. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2443. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2444. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2445. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2446. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2447. Result Patch(const std::string &path, const Params &params);
  2448. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2449. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  2450. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2451. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2452. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2453. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2454. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2455. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2456. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2457. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2458. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2459. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2460. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2461. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2462. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2463. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2464. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2465. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2466. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2467. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2468. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2469. Result Options(const std::string &path);
  2470. Result Options(const std::string &path, const Headers &headers);
  2471. // clang-format on
  2472. // Streaming API: Open a stream for reading response body incrementally
  2473. // Socket ownership is transferred to StreamHandle for true streaming
  2474. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2475. StreamHandle open_stream(const std::string &method, const std::string &path,
  2476. const Params &params = {},
  2477. const Headers &headers = {},
  2478. const std::string &body = {},
  2479. const std::string &content_type = {});
  2480. bool send(Request &req, Response &res, Error &error);
  2481. Result send(const Request &req);
  2482. void stop();
  2483. std::string host() const;
  2484. int port() const;
  2485. size_t is_socket_open() const;
  2486. socket_t socket() const;
  2487. [[deprecated("Use set_direct_hostname_addr_map() instead.")]]
  2488. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2489. void
  2490. set_direct_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2491. void
  2492. set_tunnel_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2493. void set_default_headers(Headers headers);
  2494. void
  2495. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2496. void set_address_family(int family);
  2497. void set_tcp_nodelay(bool on);
  2498. void set_ipv6_v6only(bool on);
  2499. void set_socket_options(SocketOptions socket_options);
  2500. void set_connection_timeout(time_t sec, time_t usec = 0);
  2501. template <class Rep, class Period>
  2502. void
  2503. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2504. void set_read_timeout(time_t sec, time_t usec = 0);
  2505. template <class Rep, class Period>
  2506. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2507. void set_write_timeout(time_t sec, time_t usec = 0);
  2508. template <class Rep, class Period>
  2509. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2510. void set_max_timeout(time_t msec);
  2511. template <class Rep, class Period>
  2512. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2513. void set_basic_auth(const std::string &username, const std::string &password);
  2514. void set_bearer_token_auth(const std::string &token);
  2515. void set_keep_alive(bool on);
  2516. void set_follow_location(bool on);
  2517. void set_path_encode(bool on);
  2518. void set_compress(bool on);
  2519. void set_decompress(bool on);
  2520. void set_payload_max_length(size_t length);
  2521. void set_interface(const std::string &intf);
  2522. void set_proxy(const std::string &host, int port);
  2523. void set_proxy_basic_auth(const std::string &username,
  2524. const std::string &password);
  2525. void set_proxy_bearer_token_auth(const std::string &token);
  2526. void set_no_proxy(const std::vector<std::string> &patterns);
  2527. void set_logger(Logger logger);
  2528. void set_error_logger(ErrorLogger error_logger);
  2529. protected:
  2530. struct Socket {
  2531. socket_t sock = INVALID_SOCKET;
  2532. // For Mbed TLS compatibility: start_time for request timeout tracking
  2533. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2534. bool is_open() const { return sock != INVALID_SOCKET; }
  2535. #ifdef CPPHTTPLIB_SSL_ENABLED
  2536. tls::session_t ssl = nullptr;
  2537. #endif
  2538. };
  2539. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  2540. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  2541. virtual bool setup_proxy_connection(
  2542. Socket &socket,
  2543. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2544. Response &res, bool &success, Error &error);
  2545. bool is_proxy_enabled_for_host(const std::string &host) const;
  2546. // All of:
  2547. // shutdown_ssl
  2548. // shutdown_socket
  2549. // close_socket
  2550. // disconnect
  2551. // should ONLY be called on socket_ with socket_mutex_ locked, or on a
  2552. // connection being opened, and only when no other thread is using it.
  2553. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  2554. void shutdown_socket(Socket &socket) const;
  2555. void close_socket(Socket &socket);
  2556. void disconnect(bool gracefully);
  2557. // Under socket_mutex_: whether the connection kept alive can take another
  2558. // request. One with anything to read, or one set up under TLS settings
  2559. // changed since, is closed instead.
  2560. bool socket_reusable();
  2561. // Makes socket_ ready for a request, with socket_mutex_ held by guard. A new
  2562. // connection is opened without the lock, so that stop() can end it.
  2563. bool
  2564. prepare_socket(std::unique_lock<std::mutex> &guard,
  2565. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2566. Response &res, bool &success, Error &error);
  2567. // TLS settings apply as a connection is set up, so a change makes the
  2568. // connection kept alive unfit for the next request.
  2569. void tls_settings_changed() { tls_settings_version_++; }
  2570. std::string make_request_target(const Request &req) const;
  2571. bool process_request(Stream &strm, Request &req, Response &res,
  2572. bool close_connection, Error &error);
  2573. bool write_content_with_provider(Stream &strm, const Request &req,
  2574. Error &error) const;
  2575. void output_log(const Request &req, const Response &res) const;
  2576. void output_error_log(const Error &err, const Request *req) const;
  2577. // Socket endpoint information
  2578. const std::string host_;
  2579. const int port_;
  2580. // Current open socket
  2581. Socket socket_;
  2582. mutable std::mutex socket_mutex_;
  2583. std::recursive_mutex request_mutex_;
  2584. // How many send() calls are running on this client, guarded by
  2585. // request_mutex_
  2586. size_t send_depth_ = 0;
  2587. // Also guarded by request_mutex_
  2588. size_t socket_tls_settings_version_ = 0;
  2589. // These are all protected under socket_mutex
  2590. size_t socket_requests_in_flight_ = 0;
  2591. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2592. bool socket_should_be_closed_when_request_is_done_ = false;
  2593. // Set by stop(), cleared as a send() or an open_stream() starts. Its waits
  2594. // poll it: shutdown() does not reach a connection being opened, nor wake a
  2595. // read on Windows.
  2596. std::atomic<bool> stop_requested_{false};
  2597. std::function<bool()> stop_interrupt() const {
  2598. return [this] { return stop_requested_.load(); };
  2599. }
  2600. std::atomic<size_t> tls_settings_version_{0};
  2601. // Hostname to connection target map. The value is an IP literal or another
  2602. // hostname; only the connection target changes, never the identity.
  2603. std::map<std::string, std::string> addr_map_;
  2604. // Hostname to CONNECT target map, used only through a proxy.
  2605. std::map<std::string, std::string> tunnel_addr_map_;
  2606. // Default headers
  2607. Headers default_headers_;
  2608. // Header writer
  2609. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2610. detail::write_headers;
  2611. // Settings
  2612. std::string client_cert_path_;
  2613. std::string client_key_path_;
  2614. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2615. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2616. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2617. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2618. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2619. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2620. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2621. std::string basic_auth_username_;
  2622. std::string basic_auth_password_;
  2623. std::string bearer_token_auth_token_;
  2624. bool keep_alive_ = false;
  2625. bool follow_location_ = false;
  2626. bool path_encode_ = true;
  2627. int address_family_ = AF_UNSPEC;
  2628. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2629. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2630. SocketOptions socket_options_ = nullptr;
  2631. bool compress_ = false;
  2632. bool decompress_ = true;
  2633. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2634. bool has_payload_max_length_ = false;
  2635. std::string interface_;
  2636. std::string proxy_host_;
  2637. int proxy_port_ = -1;
  2638. std::string proxy_basic_auth_username_;
  2639. std::string proxy_basic_auth_password_;
  2640. std::string proxy_bearer_token_auth_token_;
  2641. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2642. mutable detail::NormalizedTarget host_normalized_;
  2643. mutable bool host_normalized_valid_ = false;
  2644. mutable std::mutex logger_mutex_;
  2645. Logger logger_;
  2646. ErrorLogger error_logger_;
  2647. private:
  2648. bool send_(Request &req, Response &res, Error &error);
  2649. Result send_(Request &&req);
  2650. socket_t create_client_socket(Error &error) const;
  2651. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2652. bool skip_100_continue = true) const;
  2653. bool write_request(Stream &strm, Request &req, bool close_connection,
  2654. Error &error, bool skip_body, bool &rejected_locally);
  2655. bool write_request_body(Stream &strm, Request &req, Error &error);
  2656. void prepare_default_headers(Request &r, bool for_stream,
  2657. const std::string &ct);
  2658. bool redirect(Request &req, Response &res, Error &error);
  2659. bool create_redirect_client(const std::string &scheme,
  2660. const std::string &host, int port, Request &req,
  2661. Response &res, const std::string &path,
  2662. const std::string &location, Error &error);
  2663. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2664. bool handle_request(Stream &strm, Request &req, Response &res,
  2665. bool close_connection, Error &error);
  2666. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2667. Request &req, const char *body, size_t content_length,
  2668. ContentProvider content_provider,
  2669. ContentProviderWithoutLength content_provider_without_length,
  2670. const std::string &content_type, ContentReceiver content_receiver,
  2671. Error &error);
  2672. Result send_with_content_provider_and_receiver(
  2673. const std::string &method, const std::string &path,
  2674. const Headers &headers, const char *body, size_t content_length,
  2675. ContentProvider content_provider,
  2676. ContentProviderWithoutLength content_provider_without_length,
  2677. const std::string &content_type, ContentReceiver content_receiver,
  2678. UploadProgress progress);
  2679. ContentProviderWithoutLength get_multipart_content_provider(
  2680. const std::string &boundary, const UploadFormDataItems &items,
  2681. const FormDataProviderItems &provider_items) const;
  2682. virtual bool
  2683. process_socket(const Socket &socket,
  2684. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2685. std::function<bool(Stream &strm)> callback);
  2686. virtual bool is_ssl() const;
  2687. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2688. StreamHandle open_stream_(Request &req);
  2689. void add_credential_headers(Request &req);
  2690. std::string proxy_target_prefix() const;
  2691. #ifdef CPPHTTPLIB_SSL_ENABLED
  2692. public:
  2693. void set_digest_auth(const std::string &username,
  2694. const std::string &password);
  2695. void set_proxy_digest_auth(const std::string &username,
  2696. const std::string &password);
  2697. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2698. const std::string &ca_cert_dir_path = std::string());
  2699. void enable_server_certificate_verification(bool enabled);
  2700. void enable_server_hostname_verification(bool enabled);
  2701. void enable_system_ca(bool enabled);
  2702. protected:
  2703. std::string digest_auth_username_;
  2704. std::string digest_auth_password_;
  2705. std::string proxy_digest_auth_username_;
  2706. std::string proxy_digest_auth_password_;
  2707. std::string ca_cert_file_path_;
  2708. std::string ca_cert_dir_path_;
  2709. bool server_certificate_verification_ = true;
  2710. bool server_hostname_verification_ = true;
  2711. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2712. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2713. int last_ssl_error_ = 0;
  2714. uint64_t last_backend_error_ = 0;
  2715. #endif
  2716. };
  2717. namespace detail {
  2718. // Stands in for a client that Client could not make from its arguments, so a
  2719. // request fails rather than going through a null pointer.
  2720. class InvalidClientImpl final : public ClientImpl {
  2721. public:
  2722. InvalidClientImpl() : ClientImpl(std::string(), 0) {}
  2723. bool is_valid() const override { return false; }
  2724. private:
  2725. bool create_and_connect_socket(Socket &, Error &error) override {
  2726. error = Error::Connection;
  2727. return false;
  2728. }
  2729. };
  2730. } // namespace detail
  2731. class Client {
  2732. public:
  2733. // Universal interface
  2734. explicit Client(const std::string &scheme_host_port);
  2735. explicit Client(const std::string &scheme_host_port,
  2736. const std::string &client_cert_path,
  2737. const std::string &client_key_path);
  2738. // HTTP only interface
  2739. explicit Client(const std::string &host, int port);
  2740. explicit Client(const std::string &host, int port,
  2741. const std::string &client_cert_path,
  2742. const std::string &client_key_path);
  2743. Client(Client &&) = default;
  2744. Client &operator=(Client &&) = default;
  2745. ~Client();
  2746. bool is_valid() const;
  2747. // clang-format off
  2748. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2749. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2750. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2751. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2752. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2753. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2754. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2755. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2756. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2757. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2758. Result Head(const std::string &path);
  2759. Result Head(const std::string &path, const Headers &headers);
  2760. Result Post(const std::string &path);
  2761. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2762. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2763. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2764. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2765. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2766. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2767. Result Post(const std::string &path, const Params &params);
  2768. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2769. Result Post(const std::string &path, const Headers &headers);
  2770. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2771. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2772. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2773. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2774. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2775. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2776. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2777. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2778. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2779. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2780. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2781. Result Put(const std::string &path);
  2782. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2783. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2784. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2785. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2786. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2787. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2788. Result Put(const std::string &path, const Params &params);
  2789. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2790. Result Put(const std::string &path, const Headers &headers);
  2791. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2792. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2793. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2794. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2795. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2796. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2797. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2798. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2799. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2800. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2801. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2802. Result Patch(const std::string &path);
  2803. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2804. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2805. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2806. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2807. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2808. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2809. Result Patch(const std::string &path, const Params &params);
  2810. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2811. Result Patch(const std::string &path, const Headers &headers);
  2812. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2813. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2814. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2815. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2816. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2817. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2818. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2819. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2820. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2821. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2822. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2823. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2824. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2825. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2826. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2827. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2828. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2829. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2830. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2831. Result Options(const std::string &path);
  2832. Result Options(const std::string &path, const Headers &headers);
  2833. // clang-format on
  2834. // Streaming API: Open a stream for reading response body incrementally
  2835. // Socket ownership is transferred to StreamHandle for true streaming
  2836. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2837. ClientImpl::StreamHandle open_stream(const std::string &method,
  2838. const std::string &path,
  2839. const Params &params = {},
  2840. const Headers &headers = {},
  2841. const std::string &body = {},
  2842. const std::string &content_type = {});
  2843. bool send(Request &req, Response &res, Error &error);
  2844. Result send(const Request &req);
  2845. void stop();
  2846. std::string host() const;
  2847. int port() const;
  2848. size_t is_socket_open() const;
  2849. socket_t socket() const;
  2850. [[deprecated("Use set_direct_hostname_addr_map() instead.")]]
  2851. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2852. void
  2853. set_direct_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2854. void
  2855. set_tunnel_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2856. void set_default_headers(Headers headers);
  2857. void
  2858. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2859. void set_address_family(int family);
  2860. void set_tcp_nodelay(bool on);
  2861. void set_socket_options(SocketOptions socket_options);
  2862. void set_connection_timeout(time_t sec, time_t usec = 0);
  2863. template <class Rep, class Period>
  2864. void
  2865. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2866. void set_read_timeout(time_t sec, time_t usec = 0);
  2867. template <class Rep, class Period>
  2868. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2869. void set_write_timeout(time_t sec, time_t usec = 0);
  2870. template <class Rep, class Period>
  2871. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2872. void set_max_timeout(time_t msec);
  2873. template <class Rep, class Period>
  2874. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2875. void set_basic_auth(const std::string &username, const std::string &password);
  2876. void set_bearer_token_auth(const std::string &token);
  2877. void set_keep_alive(bool on);
  2878. void set_follow_location(bool on);
  2879. void set_path_encode(bool on);
  2880. void set_compress(bool on);
  2881. void set_decompress(bool on);
  2882. void set_payload_max_length(size_t length);
  2883. void set_interface(const std::string &intf);
  2884. void set_proxy(const std::string &host, int port);
  2885. void set_proxy_basic_auth(const std::string &username,
  2886. const std::string &password);
  2887. void set_proxy_bearer_token_auth(const std::string &token);
  2888. void set_no_proxy(const std::vector<std::string> &patterns);
  2889. void set_logger(Logger logger);
  2890. void set_error_logger(ErrorLogger error_logger);
  2891. private:
  2892. std::unique_ptr<ClientImpl> cli_;
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. public:
  2895. void set_digest_auth(const std::string &username,
  2896. const std::string &password);
  2897. void set_proxy_digest_auth(const std::string &username,
  2898. const std::string &password);
  2899. void enable_server_certificate_verification(bool enabled);
  2900. void enable_server_hostname_verification(bool enabled);
  2901. void enable_system_ca(bool enabled);
  2902. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2903. const std::string &ca_cert_dir_path = std::string());
  2904. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2905. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2906. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2907. void set_session_verifier(
  2908. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2909. tls::ctx_t tls_context() const;
  2910. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2911. void enable_windows_certificate_verification(bool enabled);
  2912. #endif
  2913. private:
  2914. bool is_ssl_ = false;
  2915. #endif
  2916. };
  2917. #ifdef CPPHTTPLIB_SSL_ENABLED
  2918. class SSLServer : public Server {
  2919. public:
  2920. SSLServer(const char *cert_path, const char *private_key_path,
  2921. const char *client_ca_cert_file_path = nullptr,
  2922. const char *client_ca_cert_dir_path = nullptr,
  2923. const char *private_key_password = nullptr);
  2924. struct PemMemory {
  2925. const char *cert_pem;
  2926. size_t cert_pem_len;
  2927. const char *key_pem;
  2928. size_t key_pem_len;
  2929. const char *client_ca_pem;
  2930. size_t client_ca_pem_len;
  2931. const char *private_key_password;
  2932. };
  2933. explicit SSLServer(const PemMemory &pem);
  2934. // The callback receives the ctx_t handle which can be cast to the
  2935. // appropriate backend type (SSL_CTX* for OpenSSL,
  2936. // tls::impl::MbedTlsContext* for Mbed TLS)
  2937. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2938. ~SSLServer() override;
  2939. bool is_valid() const override;
  2940. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2941. const char *client_ca_pem = nullptr,
  2942. const char *password = nullptr);
  2943. tls::ctx_t tls_context() const { return ctx_; }
  2944. int ssl_last_error() const { return last_ssl_error_; }
  2945. private:
  2946. bool process_and_close_socket(socket_t sock) override;
  2947. std::shared_ptr<KeepAliveConnection>
  2948. new_keep_alive_connection(socket_t sock) override;
  2949. struct TlsConnection;
  2950. // Creates a session and runs the handshake. Null on failure, which sets
  2951. // last_ssl_error_.
  2952. tls::session_t start_session(socket_t sock);
  2953. tls::ctx_t ctx_ = nullptr;
  2954. // update_certs_pem() replaces the certificates and CAs that handshakes read
  2955. // from ctx_, so it waits for the handshakes in progress, which their timeout
  2956. // bounds, and new ones wait while it is pending so that they cannot keep it
  2957. // waiting.
  2958. std::mutex ctx_mutex_;
  2959. std::condition_variable ctx_cv_;
  2960. size_t handshakes_in_progress_ = 0;
  2961. size_t updates_pending_ = 0;
  2962. int last_ssl_error_ = 0;
  2963. };
  2964. class SSLClient final : public ClientImpl {
  2965. public:
  2966. explicit SSLClient(const std::string &host);
  2967. explicit SSLClient(const std::string &host, int port);
  2968. explicit SSLClient(const std::string &host, int port,
  2969. const std::string &client_cert_path,
  2970. const std::string &client_key_path,
  2971. const std::string &private_key_password = std::string());
  2972. struct PemMemory {
  2973. const char *cert_pem;
  2974. size_t cert_pem_len;
  2975. const char *key_pem;
  2976. size_t key_pem_len;
  2977. const char *private_key_password;
  2978. };
  2979. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2980. ~SSLClient() override;
  2981. bool is_valid() const override;
  2982. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2983. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2984. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2985. // Post-handshake session verifier (backend-independent)
  2986. void set_session_verifier(
  2987. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2988. tls::ctx_t tls_context() const { return ctx_; }
  2989. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2990. void enable_windows_certificate_verification(bool enabled);
  2991. #endif
  2992. private:
  2993. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2994. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2995. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2996. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2997. bool
  2998. process_socket(const Socket &socket,
  2999. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3000. std::function<bool(Stream &strm)> callback) override;
  3001. bool is_ssl() const override;
  3002. bool setup_proxy_connection(
  3003. Socket &socket,
  3004. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3005. Response &res, bool &success, Error &error) override;
  3006. bool connect_with_proxy(
  3007. Socket &sock,
  3008. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3009. Response &res, bool &success, Error &error);
  3010. bool initialize_ssl(Socket &socket, Error &error);
  3011. void init_ctx();
  3012. void reset_ctx_on_error();
  3013. bool load_certs();
  3014. tls::ctx_t ctx_ = nullptr;
  3015. std::mutex ctx_mutex_;
  3016. std::once_flag initialize_cert_;
  3017. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  3018. // since the store handle itself is owned by ctx_ and leaves no other trace.
  3019. bool ca_cert_store_set_ = false;
  3020. // Set by set_ca_cert_store() and load_ca_cert_store() even when they bring
  3021. // no certificate, so that a CA that failed to come through fails
  3022. // verification instead of letting the system CAs in.
  3023. bool custom_ca_loaded_ = false;
  3024. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  3025. // Like ca_cert_store_set_, keeps what ctx_ cannot report back: the verifier
  3026. // set_server_certificate_verifier() installed there.
  3027. tls::VerifyCallback server_certificate_verifier_;
  3028. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  3029. bool enable_windows_cert_verification_ = true;
  3030. #endif
  3031. friend class ClientImpl;
  3032. };
  3033. #endif // CPPHTTPLIB_SSL_ENABLED
  3034. namespace detail {
  3035. template <typename T, typename U>
  3036. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  3037. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  3038. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  3039. duration - std::chrono::seconds(sec))
  3040. .count();
  3041. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  3042. }
  3043. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  3044. return N - 1;
  3045. }
  3046. inline bool is_numeric(const std::string &str) {
  3047. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  3048. }
  3049. // std::ranges::next(first, n, last) for C++11
  3050. template <typename It> inline It bounded_next(It first, size_t n, It last) {
  3051. for (; n > 0 && first != last; --n) {
  3052. ++first;
  3053. }
  3054. return first;
  3055. }
  3056. inline size_t get_header_value_u64(const Headers &headers,
  3057. const std::string &key, size_t def,
  3058. size_t id, bool &is_invalid_value) {
  3059. is_invalid_value = false;
  3060. auto rng = headers.equal_range(key);
  3061. auto it = bounded_next(rng.first, id, rng.second);
  3062. if (it != rng.second) {
  3063. if (is_numeric(it->second)) {
  3064. // Parse at size_t width so an out-of-range Content-Length is reported
  3065. // rather than silently saturated/truncated (a value above 2^32 would
  3066. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  3067. // and return SIZE_MAX so the existing oversized-value guards reject it.
  3068. size_t val = 0;
  3069. const auto &s = it->second;
  3070. auto r = from_chars(s.data(), s.data() + s.size(), val);
  3071. if (r.ec == std::errc::result_out_of_range) {
  3072. is_invalid_value = true;
  3073. return (std::numeric_limits<size_t>::max)();
  3074. }
  3075. return val;
  3076. } else {
  3077. is_invalid_value = true;
  3078. }
  3079. }
  3080. return def;
  3081. }
  3082. inline size_t get_header_value_u64(const Headers &headers,
  3083. const std::string &key, size_t def,
  3084. size_t id) {
  3085. auto dummy = false;
  3086. return get_header_value_u64(headers, key, def, id, dummy);
  3087. }
  3088. } // namespace detail
  3089. template <class Rep, class Period>
  3090. inline Server &
  3091. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3092. detail::duration_to_sec_and_usec(
  3093. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3094. return *this;
  3095. }
  3096. template <class Rep, class Period>
  3097. inline Server &
  3098. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3099. detail::duration_to_sec_and_usec(
  3100. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3101. return *this;
  3102. }
  3103. template <class Rep, class Period>
  3104. inline Server &
  3105. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  3106. detail::duration_to_sec_and_usec(
  3107. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  3108. return *this;
  3109. }
  3110. template <class Rep, class Period>
  3111. inline void ClientImpl::set_connection_timeout(
  3112. const std::chrono::duration<Rep, Period> &duration) {
  3113. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  3114. set_connection_timeout(sec, usec);
  3115. });
  3116. }
  3117. template <class Rep, class Period>
  3118. inline void ClientImpl::set_read_timeout(
  3119. const std::chrono::duration<Rep, Period> &duration) {
  3120. detail::duration_to_sec_and_usec(
  3121. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3122. }
  3123. template <class Rep, class Period>
  3124. inline void ClientImpl::set_write_timeout(
  3125. const std::chrono::duration<Rep, Period> &duration) {
  3126. detail::duration_to_sec_and_usec(
  3127. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3128. }
  3129. template <class Rep, class Period>
  3130. inline void ClientImpl::set_max_timeout(
  3131. const std::chrono::duration<Rep, Period> &duration) {
  3132. auto msec =
  3133. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  3134. set_max_timeout(static_cast<time_t>(msec));
  3135. }
  3136. template <class Rep, class Period>
  3137. inline void Client::set_connection_timeout(
  3138. const std::chrono::duration<Rep, Period> &duration) {
  3139. cli_->set_connection_timeout(duration);
  3140. }
  3141. template <class Rep, class Period>
  3142. inline void
  3143. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3144. cli_->set_read_timeout(duration);
  3145. }
  3146. template <class Rep, class Period>
  3147. inline void
  3148. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3149. cli_->set_write_timeout(duration);
  3150. }
  3151. inline void Client::set_max_timeout(time_t msec) {
  3152. cli_->set_max_timeout(msec);
  3153. }
  3154. template <class Rep, class Period>
  3155. inline void
  3156. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  3157. cli_->set_max_timeout(duration);
  3158. }
  3159. /*
  3160. * Forward declarations and types that will be part of the .h file if split into
  3161. * .h + .cc.
  3162. */
  3163. std::string hosted_at(const std::string &hostname);
  3164. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  3165. // JavaScript-style URL encoding/decoding functions
  3166. std::string encode_uri_component(const std::string &value);
  3167. std::string encode_uri(const std::string &value);
  3168. std::string decode_uri_component(const std::string &value);
  3169. std::string decode_uri(const std::string &value);
  3170. // RFC 3986 compliant URL component encoding/decoding functions
  3171. std::string encode_path_component(const std::string &component);
  3172. std::string decode_path_component(const std::string &component);
  3173. std::string encode_query_component(const std::string &component,
  3174. bool space_as_plus = true);
  3175. std::string decode_query_component(const std::string &component,
  3176. bool plus_as_space = true);
  3177. std::string sanitize_filename(const std::string &filename);
  3178. std::string append_query_params(const std::string &path, const Params &params);
  3179. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  3180. std::pair<std::string, std::string>
  3181. make_basic_authentication_header(const std::string &username,
  3182. const std::string &password,
  3183. bool is_proxy = false);
  3184. namespace detail {
  3185. #if defined(_WIN32)
  3186. inline std::wstring u8string_to_wstring(const char *s) {
  3187. if (!s) { return std::wstring(); }
  3188. auto len = static_cast<int>(strlen(s));
  3189. if (!len) { return std::wstring(); }
  3190. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  3191. if (!wlen) { return std::wstring(); }
  3192. std::wstring ws;
  3193. ws.resize(wlen);
  3194. wlen = ::MultiByteToWideChar(
  3195. CP_UTF8, 0, s, len,
  3196. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  3197. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  3198. return ws;
  3199. }
  3200. #endif
  3201. struct FileStat {
  3202. FileStat(const std::string &path);
  3203. bool is_file() const;
  3204. bool is_dir() const;
  3205. time_t mtime() const;
  3206. size_t size() const;
  3207. private:
  3208. #if defined(_WIN32)
  3209. struct _stat st_;
  3210. #else
  3211. struct stat st_;
  3212. #endif
  3213. int ret_ = -1;
  3214. };
  3215. std::string make_host_and_port_string(const std::string &host, int port,
  3216. bool is_ssl);
  3217. template <typename T>
  3218. bool check_and_write_headers(Stream &strm, Headers &headers, T header_writer,
  3219. Error &error);
  3220. bool write_data(Stream &strm, const char *d, size_t l);
  3221. std::string trim_copy(const std::string &s);
  3222. void divide(
  3223. const char *data, std::size_t size, char d,
  3224. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3225. fn);
  3226. void divide(
  3227. const std::string &str, char d,
  3228. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3229. fn);
  3230. void split(const char *b, const char *e, char d,
  3231. std::function<void(const char *, const char *)> fn);
  3232. void split(const char *b, const char *e, char d, size_t m,
  3233. std::function<void(const char *, const char *)> fn);
  3234. bool split_find(const char *b, const char *e, char d,
  3235. std::function<bool(const char *, const char *)> fn);
  3236. bool has_header_token(const Headers &headers, const std::string &key,
  3237. const std::string &token);
  3238. std::string websocket_accept_key(const std::string &client_key);
  3239. bool is_websocket_upgrade(const Request &req);
  3240. bool process_client_socket(
  3241. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3242. time_t write_timeout_sec, time_t write_timeout_usec,
  3243. time_t max_timeout_msec,
  3244. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3245. std::function<bool(Stream &)> callback);
  3246. socket_t create_client_socket(
  3247. const std::string &host, const std::string &ip, int port,
  3248. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  3249. SocketOptions socket_options, time_t connection_timeout_sec,
  3250. time_t connection_timeout_usec, time_t read_timeout_sec,
  3251. time_t read_timeout_usec, time_t write_timeout_sec,
  3252. time_t write_timeout_usec, const std::string &intf, Error &error,
  3253. const std::function<bool()> &interrupted = nullptr);
  3254. const char *get_header_value(const Headers &headers, const std::string &key,
  3255. const char *def, size_t id);
  3256. std::string get_combined_header_value(const Headers &headers,
  3257. const std::string &key);
  3258. std::string params_to_query_str(const Params &params);
  3259. void parse_query_text(const char *data, std::size_t size, Params &params);
  3260. void parse_query_text(const std::string &s, Params &params);
  3261. bool parse_multipart_boundary(const std::string &content_type,
  3262. std::string &boundary);
  3263. bool parse_range_header(const std::string &s, Ranges &ranges);
  3264. bool parse_accept_header(const std::string &s,
  3265. std::vector<std::string> &content_types);
  3266. void parse_disposition_params(const std::string &s, Params &params);
  3267. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  3268. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  3269. EncodingType encoding_type(const Request &req, const std::string &content_type);
  3270. EncodingType encoding_type(const Request &req, const Response &res,
  3271. const std::string &content_type);
  3272. EncodingType encoding_type(const Request &req, const Response &res);
  3273. // Creates a connected pair of stream sockets that child processes do not
  3274. // inherit. Windows has no socketpair(), so it is emulated there.
  3275. bool create_socket_pair(socket_t sv[2]);
  3276. // Ends a Poller's wait() from another thread. The poller watches fd() for
  3277. // readability, level-triggered, and calls drain() when it is reported.
  3278. class PollerWaker {
  3279. public:
  3280. ~PollerWaker();
  3281. // An eventfd on Linux, a socket pair elsewhere.
  3282. bool open();
  3283. socket_t fd() const { return fd_; }
  3284. // An address inside the poller, which no caller's token can be.
  3285. uintptr_t token() const { return reinterpret_cast<uintptr_t>(this); }
  3286. // From any thread. While one is pending, later calls make no syscall.
  3287. void wake() noexcept;
  3288. void drain() noexcept;
  3289. private:
  3290. socket_t fd_ = INVALID_SOCKET;
  3291. socket_t pair_fd_ = INVALID_SOCKET; // the end wake() writes; none on Linux
  3292. std::atomic<bool> pending_{false};
  3293. };
  3294. // One-shot readiness notification for a reactor:
  3295. // - A delivered event disarms the descriptor; arm() it again to wait again.
  3296. // - A hang-up or an error counts as readable.
  3297. // - Only an unarmed descriptor may be armed, and an armed one must be
  3298. // disarmed before it is closed.
  3299. // - wake() may be called from any thread; the rest belongs to one thread.
  3300. class Poller {
  3301. public:
  3302. using Token = uintptr_t;
  3303. virtual ~Poller() = default;
  3304. virtual bool arm(socket_t fd, Token token) = 0;
  3305. virtual void disarm(socket_t fd) = 0;
  3306. // Fills `ready` in no particular order and returns whether wake() was
  3307. // called. A negative timeout waits until either happens.
  3308. virtual bool wait(int timeout_ms, std::vector<Token> &ready) = 0;
  3309. virtual void wake() noexcept = 0;
  3310. };
  3311. // poll() on POSIX, WSAPoll() on Windows. Works everywhere.
  3312. class PollPoller final : public Poller {
  3313. public:
  3314. // nullptr when the descriptors cannot be created.
  3315. static std::unique_ptr<Poller> create();
  3316. bool arm(socket_t fd, Token token) override;
  3317. void disarm(socket_t fd) override;
  3318. bool wait(int timeout_ms, std::vector<Token> &ready) override;
  3319. void wake() noexcept override { waker_.wake(); }
  3320. private:
  3321. PollPoller() = default;
  3322. void remove_at(size_t index);
  3323. PollerWaker waker_;
  3324. // fds_[0] is the waker's, which is always armed; tokens_[i] belongs to
  3325. // fds_[i].
  3326. std::vector<struct pollfd> fds_;
  3327. std::vector<Token> tokens_;
  3328. std::unordered_map<socket_t, size_t> index_;
  3329. };
  3330. #ifdef __linux__
  3331. // epoll with EPOLLONESHOT. Waits in O(ready) instead of O(armed).
  3332. class EpollPoller final : public Poller {
  3333. public:
  3334. // nullptr when the descriptors cannot be created.
  3335. static std::unique_ptr<Poller> create();
  3336. ~EpollPoller() override;
  3337. bool arm(socket_t fd, Token token) override;
  3338. void disarm(socket_t fd) override;
  3339. bool wait(int timeout_ms, std::vector<Token> &ready) override;
  3340. void wake() noexcept override { waker_.wake(); }
  3341. private:
  3342. EpollPoller() = default;
  3343. int epfd_ = -1;
  3344. PollerWaker waker_; // always armed
  3345. std::vector<struct epoll_event> events_;
  3346. };
  3347. #endif
  3348. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  3349. // kqueue with EV_ONESHOT. Waits in O(ready) instead of O(armed).
  3350. class KqueuePoller final : public Poller {
  3351. public:
  3352. // nullptr when the descriptors cannot be created.
  3353. static std::unique_ptr<Poller> create();
  3354. ~KqueuePoller() override;
  3355. bool arm(socket_t fd, Token token) override;
  3356. void disarm(socket_t fd) override;
  3357. bool wait(int timeout_ms, std::vector<Token> &ready) override;
  3358. void wake() noexcept override { waker_.wake(); }
  3359. private:
  3360. KqueuePoller() = default;
  3361. int kq_ = -1;
  3362. PollerWaker waker_; // always armed
  3363. std::vector<struct kevent> events_;
  3364. };
  3365. #endif
  3366. // The best poller for this platform, or nullptr when it cannot be created.
  3367. std::unique_ptr<Poller> make_poller();
  3368. class BufferStream final : public Stream {
  3369. public:
  3370. BufferStream() = default;
  3371. ~BufferStream() override = default;
  3372. bool is_readable() const override;
  3373. bool wait_readable() const override;
  3374. bool wait_writable() const override;
  3375. ssize_t read(char *ptr, size_t size) override;
  3376. ssize_t write(const char *ptr, size_t size) override;
  3377. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3378. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3379. socket_t socket() const override;
  3380. time_t duration() const override;
  3381. const std::string &get_buffer() const;
  3382. private:
  3383. std::string buffer;
  3384. size_t position = 0;
  3385. };
  3386. class compressor {
  3387. public:
  3388. virtual ~compressor() = default;
  3389. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3390. virtual bool compress(const char *data, size_t data_length, bool last,
  3391. Callback callback) = 0;
  3392. };
  3393. class decompressor {
  3394. public:
  3395. virtual ~decompressor() = default;
  3396. virtual bool is_valid() const = 0;
  3397. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3398. virtual bool decompress(const char *data, size_t data_length,
  3399. Callback callback) = 0;
  3400. };
  3401. class nocompressor final : public compressor {
  3402. public:
  3403. ~nocompressor() override = default;
  3404. bool compress(const char *data, size_t data_length, bool /*last*/,
  3405. Callback callback) override;
  3406. };
  3407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3408. class gzip_compressor final : public compressor {
  3409. public:
  3410. gzip_compressor();
  3411. ~gzip_compressor() override;
  3412. bool compress(const char *data, size_t data_length, bool last,
  3413. Callback callback) override;
  3414. private:
  3415. bool is_valid_ = false;
  3416. z_stream strm_;
  3417. };
  3418. class gzip_decompressor final : public decompressor {
  3419. public:
  3420. gzip_decompressor();
  3421. ~gzip_decompressor() override;
  3422. bool is_valid() const override;
  3423. bool decompress(const char *data, size_t data_length,
  3424. Callback callback) override;
  3425. private:
  3426. bool is_valid_ = false;
  3427. z_stream strm_;
  3428. };
  3429. #endif
  3430. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3431. class brotli_compressor final : public compressor {
  3432. public:
  3433. brotli_compressor();
  3434. ~brotli_compressor();
  3435. bool compress(const char *data, size_t data_length, bool last,
  3436. Callback callback) override;
  3437. private:
  3438. BrotliEncoderState *state_ = nullptr;
  3439. };
  3440. class brotli_decompressor final : public decompressor {
  3441. public:
  3442. brotli_decompressor();
  3443. ~brotli_decompressor();
  3444. bool is_valid() const override;
  3445. bool decompress(const char *data, size_t data_length,
  3446. Callback callback) override;
  3447. private:
  3448. BrotliDecoderResult decoder_r;
  3449. BrotliDecoderState *decoder_s = nullptr;
  3450. };
  3451. #endif
  3452. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3453. class zstd_compressor : public compressor {
  3454. public:
  3455. zstd_compressor();
  3456. ~zstd_compressor();
  3457. bool compress(const char *data, size_t data_length, bool last,
  3458. Callback callback) override;
  3459. private:
  3460. ZSTD_CCtx *ctx_ = nullptr;
  3461. };
  3462. class zstd_decompressor : public decompressor {
  3463. public:
  3464. zstd_decompressor();
  3465. ~zstd_decompressor();
  3466. bool is_valid() const override;
  3467. bool decompress(const char *data, size_t data_length,
  3468. Callback callback) override;
  3469. private:
  3470. ZSTD_DCtx *ctx_ = nullptr;
  3471. };
  3472. #endif
  3473. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  3474. // to store data. The call can set memory on stack for performance.
  3475. class stream_line_reader {
  3476. public:
  3477. stream_line_reader(Stream &strm, char *fixed_buffer,
  3478. size_t fixed_buffer_size);
  3479. const char *ptr() const;
  3480. size_t size() const;
  3481. bool end_with_crlf() const;
  3482. bool getline();
  3483. private:
  3484. void append(char c);
  3485. void append(const char *data, size_t size);
  3486. Stream &strm_;
  3487. char *fixed_buffer_;
  3488. const size_t fixed_buffer_size_;
  3489. size_t fixed_buffer_used_size_ = 0;
  3490. std::string growable_buffer_;
  3491. };
  3492. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3493. const Headers &src_headers);
  3494. struct ChunkedDecoder {
  3495. Stream &strm;
  3496. size_t chunk_remaining = 0;
  3497. bool finished = false;
  3498. char line_buf[64];
  3499. size_t last_chunk_total = 0;
  3500. size_t last_chunk_offset = 0;
  3501. size_t overhead = 0;
  3502. explicit ChunkedDecoder(Stream &s);
  3503. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  3504. size_t &out_chunk_total);
  3505. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  3506. };
  3507. // A regular file opened to be served: mapped on Windows, read with pread()
  3508. // elsewhere.
  3509. class mmap {
  3510. public:
  3511. mmap(const char *path);
  3512. ~mmap();
  3513. bool open(const char *path);
  3514. void close();
  3515. bool is_open() const;
  3516. size_t size() const;
  3517. // Copies up to len bytes from offset into buf and returns how many: fewer,
  3518. // down to 0, if the file has shrunk since it was opened.
  3519. size_t read(size_t offset, char *buf, size_t len) const;
  3520. private:
  3521. #if defined(_WIN32)
  3522. HANDLE hFile_ = NULL;
  3523. HANDLE hMapping_ = NULL;
  3524. void *addr_ = nullptr;
  3525. bool is_open_empty_file = false;
  3526. #else
  3527. int fd_ = -1;
  3528. #endif
  3529. size_t size_ = 0;
  3530. };
  3531. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  3532. namespace fields {
  3533. bool is_token_char(char c);
  3534. bool is_token(const std::string &s);
  3535. bool is_field_name(const std::string &s);
  3536. bool is_vchar(char c);
  3537. bool is_obs_text(char c);
  3538. bool is_field_vchar(char c);
  3539. bool is_field_content(const std::string &s);
  3540. bool is_field_value(const std::string &s);
  3541. bool is_field_valid(const std::string &name, const std::string &value);
  3542. bool is_request_target(const std::string &s);
  3543. bool is_host(const std::string &s);
  3544. } // namespace fields
  3545. } // namespace detail
  3546. /*
  3547. * TLS Abstraction Layer Declarations
  3548. */
  3549. #ifdef CPPHTTPLIB_SSL_ENABLED
  3550. // TLS abstraction layer - backend-specific type declarations
  3551. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  3552. namespace tls {
  3553. namespace impl {
  3554. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  3555. // cert/key). This struct is accessible via tls::impl for use in SSL context
  3556. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  3557. struct MbedTlsContext {
  3558. mbedtls_ssl_config conf;
  3559. #ifndef CPPHTTPLIB_MBEDTLS_V4
  3560. // Mbed TLS 4.x uses PSA Crypto's internal RNG; no explicit entropy/DRBG.
  3561. mbedtls_entropy_context entropy;
  3562. mbedtls_ctr_drbg_context ctr_drbg;
  3563. #endif
  3564. mbedtls_x509_crt ca_chain;
  3565. mbedtls_x509_crt own_cert;
  3566. mbedtls_pk_context own_key;
  3567. bool is_server = false;
  3568. // Peer certificate required (set_verify_client()); a client defaults to true
  3569. bool verify_client = false;
  3570. // Set by tls::set_verify_callback().
  3571. VerifyCallback verify_callback;
  3572. MbedTlsContext();
  3573. ~MbedTlsContext();
  3574. MbedTlsContext(const MbedTlsContext &) = delete;
  3575. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  3576. };
  3577. } // namespace impl
  3578. } // namespace tls
  3579. #endif
  3580. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  3581. namespace tls {
  3582. namespace impl {
  3583. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  3584. // This struct is accessible via tls::impl for use in SSL context
  3585. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  3586. struct WolfSSLContext {
  3587. WOLFSSL_CTX *ctx = nullptr;
  3588. bool is_server = false;
  3589. // Peer certificate required (set_verify_client()); a client defaults to true
  3590. bool verify_client = false;
  3591. // Replaced under verify_callback_mutex()
  3592. std::shared_ptr<VerifyCallback> verify_callback;
  3593. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  3594. WolfSSLContext();
  3595. ~WolfSSLContext();
  3596. WolfSSLContext(const WolfSSLContext &) = delete;
  3597. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  3598. };
  3599. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  3600. struct WolfSSLCAStore {
  3601. std::string pem_data;
  3602. };
  3603. } // namespace impl
  3604. } // namespace tls
  3605. #endif
  3606. #endif // CPPHTTPLIB_SSL_ENABLED
  3607. namespace stream {
  3608. class Result {
  3609. public:
  3610. Result();
  3611. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  3612. Result(Result &&other) noexcept;
  3613. Result &operator=(Result &&other) noexcept;
  3614. Result(const Result &) = delete;
  3615. Result &operator=(const Result &) = delete;
  3616. // Response info
  3617. bool is_valid() const;
  3618. explicit operator bool() const;
  3619. int status() const;
  3620. const Headers &headers() const;
  3621. std::string get_header_value(const std::string &key,
  3622. const char *def = "") const;
  3623. bool has_header(const std::string &key) const;
  3624. Error error() const;
  3625. Error read_error() const;
  3626. bool has_read_error() const;
  3627. // Stream reading
  3628. bool next();
  3629. const char *data() const;
  3630. size_t size() const;
  3631. std::string read_all();
  3632. private:
  3633. ClientImpl::StreamHandle handle_;
  3634. std::string buffer_;
  3635. size_t current_size_ = 0;
  3636. size_t chunk_size_;
  3637. bool finished_ = false;
  3638. };
  3639. // GET
  3640. template <typename ClientType>
  3641. inline Result Get(ClientType &cli, const std::string &path,
  3642. size_t chunk_size = 8192) {
  3643. return Result{cli.open_stream("GET", path), chunk_size};
  3644. }
  3645. template <typename ClientType>
  3646. inline Result Get(ClientType &cli, const std::string &path,
  3647. const Headers &headers, size_t chunk_size = 8192) {
  3648. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  3649. }
  3650. template <typename ClientType>
  3651. inline Result Get(ClientType &cli, const std::string &path,
  3652. const Params &params, size_t chunk_size = 8192) {
  3653. return Result{cli.open_stream("GET", path, params), chunk_size};
  3654. }
  3655. template <typename ClientType>
  3656. inline Result Get(ClientType &cli, const std::string &path,
  3657. const Params &params, const Headers &headers,
  3658. size_t chunk_size = 8192) {
  3659. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  3660. }
  3661. // POST
  3662. template <typename ClientType>
  3663. inline Result Post(ClientType &cli, const std::string &path,
  3664. const std::string &body, const std::string &content_type,
  3665. size_t chunk_size = 8192) {
  3666. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  3667. chunk_size};
  3668. }
  3669. template <typename ClientType>
  3670. inline Result Post(ClientType &cli, const std::string &path,
  3671. const Headers &headers, const std::string &body,
  3672. const std::string &content_type, size_t chunk_size = 8192) {
  3673. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  3674. chunk_size};
  3675. }
  3676. template <typename ClientType>
  3677. inline Result Post(ClientType &cli, const std::string &path,
  3678. const Params &params, const std::string &body,
  3679. const std::string &content_type, size_t chunk_size = 8192) {
  3680. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  3681. chunk_size};
  3682. }
  3683. template <typename ClientType>
  3684. inline Result Post(ClientType &cli, const std::string &path,
  3685. const Params &params, const Headers &headers,
  3686. const std::string &body, const std::string &content_type,
  3687. size_t chunk_size = 8192) {
  3688. return Result{
  3689. cli.open_stream("POST", path, params, headers, body, content_type),
  3690. chunk_size};
  3691. }
  3692. // PUT
  3693. template <typename ClientType>
  3694. inline Result Put(ClientType &cli, const std::string &path,
  3695. const std::string &body, const std::string &content_type,
  3696. size_t chunk_size = 8192) {
  3697. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  3698. chunk_size};
  3699. }
  3700. template <typename ClientType>
  3701. inline Result Put(ClientType &cli, const std::string &path,
  3702. const Headers &headers, const std::string &body,
  3703. const std::string &content_type, size_t chunk_size = 8192) {
  3704. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  3705. chunk_size};
  3706. }
  3707. template <typename ClientType>
  3708. inline Result Put(ClientType &cli, const std::string &path,
  3709. const Params &params, const std::string &body,
  3710. const std::string &content_type, size_t chunk_size = 8192) {
  3711. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  3712. chunk_size};
  3713. }
  3714. template <typename ClientType>
  3715. inline Result Put(ClientType &cli, const std::string &path,
  3716. const Params &params, const Headers &headers,
  3717. const std::string &body, const std::string &content_type,
  3718. size_t chunk_size = 8192) {
  3719. return Result{
  3720. cli.open_stream("PUT", path, params, headers, body, content_type),
  3721. chunk_size};
  3722. }
  3723. // PATCH
  3724. template <typename ClientType>
  3725. inline Result Patch(ClientType &cli, const std::string &path,
  3726. const std::string &body, const std::string &content_type,
  3727. size_t chunk_size = 8192) {
  3728. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  3729. chunk_size};
  3730. }
  3731. template <typename ClientType>
  3732. inline Result Patch(ClientType &cli, const std::string &path,
  3733. const Headers &headers, const std::string &body,
  3734. const std::string &content_type, size_t chunk_size = 8192) {
  3735. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  3736. chunk_size};
  3737. }
  3738. template <typename ClientType>
  3739. inline Result Patch(ClientType &cli, const std::string &path,
  3740. const Params &params, const std::string &body,
  3741. const std::string &content_type, size_t chunk_size = 8192) {
  3742. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  3743. chunk_size};
  3744. }
  3745. template <typename ClientType>
  3746. inline Result Patch(ClientType &cli, const std::string &path,
  3747. const Params &params, const Headers &headers,
  3748. const std::string &body, const std::string &content_type,
  3749. size_t chunk_size = 8192) {
  3750. return Result{
  3751. cli.open_stream("PATCH", path, params, headers, body, content_type),
  3752. chunk_size};
  3753. }
  3754. // DELETE
  3755. template <typename ClientType>
  3756. inline Result Delete(ClientType &cli, const std::string &path,
  3757. size_t chunk_size = 8192) {
  3758. return Result{cli.open_stream("DELETE", path), chunk_size};
  3759. }
  3760. template <typename ClientType>
  3761. inline Result Delete(ClientType &cli, const std::string &path,
  3762. const Headers &headers, size_t chunk_size = 8192) {
  3763. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  3764. }
  3765. template <typename ClientType>
  3766. inline Result Delete(ClientType &cli, const std::string &path,
  3767. const std::string &body, const std::string &content_type,
  3768. size_t chunk_size = 8192) {
  3769. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3770. chunk_size};
  3771. }
  3772. template <typename ClientType>
  3773. inline Result Delete(ClientType &cli, const std::string &path,
  3774. const Headers &headers, const std::string &body,
  3775. const std::string &content_type,
  3776. size_t chunk_size = 8192) {
  3777. return Result{
  3778. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3779. chunk_size};
  3780. }
  3781. template <typename ClientType>
  3782. inline Result Delete(ClientType &cli, const std::string &path,
  3783. const Params &params, size_t chunk_size = 8192) {
  3784. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3785. }
  3786. template <typename ClientType>
  3787. inline Result Delete(ClientType &cli, const std::string &path,
  3788. const Params &params, const Headers &headers,
  3789. size_t chunk_size = 8192) {
  3790. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3791. }
  3792. template <typename ClientType>
  3793. inline Result Delete(ClientType &cli, const std::string &path,
  3794. const Params &params, const std::string &body,
  3795. const std::string &content_type,
  3796. size_t chunk_size = 8192) {
  3797. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3798. chunk_size};
  3799. }
  3800. template <typename ClientType>
  3801. inline Result Delete(ClientType &cli, const std::string &path,
  3802. const Params &params, const Headers &headers,
  3803. const std::string &body, const std::string &content_type,
  3804. size_t chunk_size = 8192) {
  3805. return Result{
  3806. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3807. chunk_size};
  3808. }
  3809. // HEAD
  3810. template <typename ClientType>
  3811. inline Result Head(ClientType &cli, const std::string &path,
  3812. size_t chunk_size = 8192) {
  3813. return Result{cli.open_stream("HEAD", path), chunk_size};
  3814. }
  3815. template <typename ClientType>
  3816. inline Result Head(ClientType &cli, const std::string &path,
  3817. const Headers &headers, size_t chunk_size = 8192) {
  3818. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3819. }
  3820. template <typename ClientType>
  3821. inline Result Head(ClientType &cli, const std::string &path,
  3822. const Params &params, size_t chunk_size = 8192) {
  3823. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3824. }
  3825. template <typename ClientType>
  3826. inline Result Head(ClientType &cli, const std::string &path,
  3827. const Params &params, const Headers &headers,
  3828. size_t chunk_size = 8192) {
  3829. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3830. }
  3831. // OPTIONS
  3832. template <typename ClientType>
  3833. inline Result Options(ClientType &cli, const std::string &path,
  3834. size_t chunk_size = 8192) {
  3835. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3836. }
  3837. template <typename ClientType>
  3838. inline Result Options(ClientType &cli, const std::string &path,
  3839. const Headers &headers, size_t chunk_size = 8192) {
  3840. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3841. }
  3842. template <typename ClientType>
  3843. inline Result Options(ClientType &cli, const std::string &path,
  3844. const Params &params, size_t chunk_size = 8192) {
  3845. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3846. }
  3847. template <typename ClientType>
  3848. inline Result Options(ClientType &cli, const std::string &path,
  3849. const Params &params, const Headers &headers,
  3850. size_t chunk_size = 8192) {
  3851. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3852. }
  3853. } // namespace stream
  3854. namespace sse {
  3855. struct SSEMessage {
  3856. std::string event; // Event type (default: "message")
  3857. std::string data; // Event payload
  3858. std::string id; // Event ID for Last-Event-ID header
  3859. SSEMessage();
  3860. void clear();
  3861. };
  3862. class SSEClient {
  3863. public:
  3864. using MessageHandler = std::function<void(const SSEMessage &)>;
  3865. using ErrorHandler = std::function<void(Error)>;
  3866. using OpenHandler = std::function<void()>;
  3867. SSEClient(Client &client, const std::string &path);
  3868. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3869. ~SSEClient();
  3870. SSEClient(const SSEClient &) = delete;
  3871. SSEClient &operator=(const SSEClient &) = delete;
  3872. // Event handlers
  3873. SSEClient &on_message(MessageHandler handler);
  3874. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3875. SSEClient &on_open(OpenHandler handler);
  3876. SSEClient &on_error(ErrorHandler handler);
  3877. SSEClient &set_reconnect_interval(int ms);
  3878. SSEClient &set_max_reconnect_attempts(int n);
  3879. // Update headers (thread-safe)
  3880. SSEClient &set_headers(const Headers &headers);
  3881. // State accessors
  3882. bool is_connected() const;
  3883. std::string last_event_id() const;
  3884. // Blocking start - runs event loop with auto-reconnect
  3885. void start();
  3886. // Non-blocking start - runs in background thread
  3887. void start_async();
  3888. // Stop the client (thread-safe)
  3889. void stop();
  3890. private:
  3891. void run_event_loop();
  3892. void dispatch_event(const SSEMessage &msg);
  3893. bool should_reconnect(int count) const;
  3894. void wait_for_reconnect();
  3895. // Client and path
  3896. Client &client_;
  3897. std::string path_;
  3898. Headers headers_;
  3899. mutable std::mutex headers_mutex_;
  3900. // Callbacks
  3901. MessageHandler on_message_;
  3902. std::map<std::string, MessageHandler> event_handlers_;
  3903. OpenHandler on_open_;
  3904. ErrorHandler on_error_;
  3905. // Configuration
  3906. int reconnect_interval_ms_ = 3000;
  3907. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3908. // State
  3909. std::atomic<bool> running_{false};
  3910. std::atomic<bool> connected_{false};
  3911. // Written by the event loop, which start_async() runs on its own thread
  3912. std::string last_event_id_;
  3913. mutable std::mutex last_event_id_mutex_;
  3914. // Async support
  3915. std::thread async_thread_;
  3916. };
  3917. } // namespace sse
  3918. namespace detail {
  3919. // Interprets an event stream fed in chunks of any size
  3920. class SSEParser {
  3921. public:
  3922. using EventHandler = std::function<void(const sse::SSEMessage &msg)>;
  3923. using IdHandler = std::function<void(const std::string &id)>;
  3924. using RetryHandler = std::function<void(int retry_ms)>;
  3925. SSEParser(EventHandler on_event, IdHandler on_id, RetryHandler on_retry,
  3926. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH);
  3927. // Returns false once the line and the event still waiting for their end
  3928. // exceed max_event_length. 0 means no limit.
  3929. bool parse(const char *buf, size_t n);
  3930. private:
  3931. void parse_line(const std::string &line);
  3932. EventHandler on_event_;
  3933. IdHandler on_id_;
  3934. RetryHandler on_retry_;
  3935. size_t max_event_length_;
  3936. std::string buffer_;
  3937. sse::SSEMessage msg_;
  3938. bool has_data_ = false;
  3939. bool has_id_ = false;
  3940. bool first_line_ = true;
  3941. bool after_cr_ = false;
  3942. };
  3943. } // namespace detail
  3944. namespace ws {
  3945. class WebSocketClient;
  3946. enum class Opcode : uint8_t {
  3947. Continuation = 0x0,
  3948. Text = 0x1,
  3949. Binary = 0x2,
  3950. Close = 0x8,
  3951. Ping = 0x9,
  3952. Pong = 0xA,
  3953. };
  3954. enum class CloseStatus : uint16_t {
  3955. Normal = 1000,
  3956. GoingAway = 1001,
  3957. ProtocolError = 1002,
  3958. UnsupportedData = 1003,
  3959. NoStatus = 1005,
  3960. Abnormal = 1006,
  3961. InvalidPayload = 1007,
  3962. PolicyViolation = 1008,
  3963. MessageTooBig = 1009,
  3964. MandatoryExtension = 1010,
  3965. InternalError = 1011,
  3966. };
  3967. // Timeout is returned only when a read timeout was set and it elapsed before
  3968. // any byte of a frame arrived: nothing was consumed and the connection is
  3969. // still open, so the caller can send on it and read again. `msg` is left
  3970. // untouched, so a `while (ws.read(msg))` loop must not treat it as a message.
  3971. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2, Timeout = 3 };
  3972. // Result of WebSocketClient::connect(). Truthy only when the WebSocket
  3973. // upgrade handshake fully succeeded. On failure error() identifies the
  3974. // failing layer; status()/headers() expose the server's upgrade response
  3975. // when one was received (status() is -1 otherwise), or the proxy's reply to
  3976. // CONNECT when error() is ProxyConnection.
  3977. class Result {
  3978. public:
  3979. Result() = default;
  3980. Result(Error err, int status, Headers &&headers)
  3981. : err_(err), status_(status), headers_(std::move(headers)) {}
  3982. explicit operator bool() const { return err_ == Error::Success; }
  3983. Error error() const { return err_; }
  3984. // Upgrade response info
  3985. int status() const { return status_; }
  3986. const Headers &headers() const { return headers_; }
  3987. std::string get_header_value(const std::string &key,
  3988. const char *def = "") const {
  3989. return detail::get_header_value(headers_, key, def, 0);
  3990. }
  3991. bool has_header(const std::string &key) const {
  3992. return headers_.find(key) != headers_.end();
  3993. }
  3994. #ifdef CPPHTTPLIB_SSL_ENABLED
  3995. Result(Error err, int status, Headers &&headers, int ssl_error,
  3996. uint64_t ssl_backend_error)
  3997. : err_(err), status_(status), headers_(std::move(headers)),
  3998. ssl_error_(ssl_error), ssl_backend_error_(ssl_backend_error) {}
  3999. int ssl_error() const { return ssl_error_; }
  4000. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  4001. #endif
  4002. private:
  4003. Error err_ = Error::Unknown; // a default-constructed Result is falsy
  4004. int status_ = -1;
  4005. Headers headers_;
  4006. #ifdef CPPHTTPLIB_SSL_ENABLED
  4007. int ssl_error_ = 0;
  4008. uint64_t ssl_backend_error_ = 0;
  4009. #endif
  4010. };
  4011. namespace impl {
  4012. bool is_valid_utf8(const std::string &s);
  4013. // Three states: a frame, a failure (the connection cannot be read on), or a
  4014. // timeout with the stream still usable.
  4015. enum class FrameRead { Ok, Fail, Timeout };
  4016. // A frame read in as many calls as it takes. A timeout leaves what was read
  4017. // so far in place, and the next read() goes on from there, so the stream is
  4018. // usable after a timeout wherever in a frame it lands.
  4019. class FrameReader {
  4020. public:
  4021. FrameRead read(Stream &strm, Opcode &opcode, std::string &payload, bool &fin,
  4022. bool expect_masked, size_t max_len);
  4023. // Whether part of a frame has been read and the rest is still to come
  4024. bool begun() const { return have_ > 0; }
  4025. private:
  4026. void reset();
  4027. uint8_t head_[14] = {0}; // FIN + opcode, MASK + length, its extension, key
  4028. size_t have_ = 0; // bytes of the header read so far
  4029. size_t need_ = 2; // bytes of the header, once the second is read
  4030. bool sized_ = false; // the header is whole and its length checked
  4031. size_t len_ = 0; // the payload's length, once sized_
  4032. std::string payload_;
  4033. };
  4034. // A whole frame read in one go: a timeout before any of it came is reported,
  4035. // and one that cuts it short is a failure.
  4036. FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  4037. std::string &payload, bool &fin,
  4038. bool expect_masked, size_t max_len);
  4039. } // namespace impl
  4040. class WebSocket {
  4041. public:
  4042. WebSocket(const WebSocket &) = delete;
  4043. WebSocket &operator=(const WebSocket &) = delete;
  4044. ~WebSocket();
  4045. ReadResult read(std::string &msg);
  4046. bool send(const std::string &data);
  4047. bool send(const char *data, size_t len);
  4048. void close(CloseStatus status = CloseStatus::Normal,
  4049. const std::string &reason = "");
  4050. const Request &request() const;
  4051. bool is_open() const;
  4052. // Bound how long read() waits before returning Timeout. 0 waits forever.
  4053. // A server handler owns its connection's timeout this way; a client sets it
  4054. // through WebSocketClient. Safe to call while another thread is in read().
  4055. // It lands anywhere, inside a message too: what was read of it is kept,
  4056. // and the next read() goes on from there.
  4057. //
  4058. // Only a timeout set here is reported as Timeout. The compile-time default
  4059. // (CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND) is a backstop rather
  4060. // than a request for control, so when it elapses read() returns Fail and
  4061. // closes the connection, and `while (ws.read(msg))` ends as it always has.
  4062. void set_read_timeout(time_t sec, time_t usec = 0);
  4063. template <class Rep, class Period>
  4064. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  4065. private:
  4066. friend class httplib::Server;
  4067. friend class httplib::ws::WebSocketClient;
  4068. WebSocket(
  4069. Stream &strm, const Request &req, bool is_server,
  4070. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  4071. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
  4072. std::function<bool()> server_stopping = nullptr)
  4073. : strm_(strm), req_(req), is_server_(is_server),
  4074. ping_interval_sec_(ping_interval_sec),
  4075. max_missed_pongs_(max_missed_pongs),
  4076. server_stopping_(std::move(server_stopping)) {
  4077. interrupt_reads();
  4078. start_heartbeat();
  4079. }
  4080. WebSocket(
  4081. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  4082. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  4083. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
  4084. std::function<bool()> server_stopping = nullptr)
  4085. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  4086. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  4087. max_missed_pongs_(max_missed_pongs),
  4088. server_stopping_(std::move(server_stopping)) {
  4089. interrupt_reads();
  4090. start_heartbeat();
  4091. }
  4092. void interrupt_reads();
  4093. bool server_stopping() const {
  4094. return server_stopping_ && server_stopping_();
  4095. }
  4096. void start_heartbeat();
  4097. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  4098. Stream &strm_;
  4099. std::unique_ptr<Stream> owned_strm_;
  4100. Request req_;
  4101. bool is_server_;
  4102. time_t ping_interval_sec_;
  4103. int max_missed_pongs_;
  4104. int unacked_pings_ = 0;
  4105. std::atomic<bool> closed_{false};
  4106. // Set when the peer stopped answering pings, to end a read() waiting on it
  4107. std::atomic<bool> pong_timed_out_{false};
  4108. // A server connection's view of Server::stop(), which ends its read() too
  4109. std::function<bool()> server_stopping_;
  4110. // Set once the caller has bounded read() through set_read_timeout(). Until
  4111. // then the timeout in effect is the compile-time default, and elapsing it
  4112. // is a failure that closes the connection, not a Timeout.
  4113. std::atomic<bool> read_timeout_set_{false};
  4114. std::mutex write_mutex_;
  4115. // Owned by whichever thread is parsing frames off strm_. Only one thread
  4116. // may do so: a frame is read until it has the whole declared length,
  4117. // across several read() calls when a timeout lands inside it (frames_
  4118. // below), so a second parser stealing bytes silently corrupts the message
  4119. // the first one is assembling.
  4120. std::mutex read_mutex_;
  4121. // What read() has of the frame and the message it has not finished, kept
  4122. // across a timeout. Guarded by read_mutex_.
  4123. impl::FrameReader frames_;
  4124. std::string message_;
  4125. ReadResult message_kind_ = Fail; // Text or Binary while one is assembled
  4126. std::thread ping_thread_;
  4127. std::mutex ping_mutex_;
  4128. std::condition_variable ping_cv_;
  4129. };
  4130. class WebSocketClient {
  4131. public:
  4132. explicit WebSocketClient(const std::string &scheme_host_port_path,
  4133. const Headers &headers = {});
  4134. ~WebSocketClient();
  4135. WebSocketClient(const WebSocketClient &) = delete;
  4136. WebSocketClient &operator=(const WebSocketClient &) = delete;
  4137. bool is_valid() const;
  4138. Result connect();
  4139. ReadResult read(std::string &msg);
  4140. bool send(const std::string &data);
  4141. bool send(const char *data, size_t len);
  4142. void close(CloseStatus status = CloseStatus::Normal,
  4143. const std::string &reason = "");
  4144. bool is_open() const;
  4145. const std::string &subprotocol() const;
  4146. void set_read_timeout(time_t sec, time_t usec = 0);
  4147. template <class Rep, class Period>
  4148. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  4149. void set_write_timeout(time_t sec, time_t usec = 0);
  4150. template <class Rep, class Period>
  4151. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  4152. void set_websocket_ping_interval(time_t sec);
  4153. void set_websocket_max_missed_pongs(int count);
  4154. void set_tcp_nodelay(bool on);
  4155. void set_address_family(int family);
  4156. void set_ipv6_v6only(bool on);
  4157. void set_socket_options(SocketOptions socket_options);
  4158. void set_connection_timeout(time_t sec, time_t usec = 0);
  4159. template <class Rep, class Period>
  4160. void
  4161. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  4162. void set_interface(const std::string &intf);
  4163. [[deprecated("Use set_direct_hostname_addr_map() instead.")]]
  4164. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  4165. void
  4166. set_direct_hostname_addr_map(std::map<std::string, std::string> addr_map);
  4167. void
  4168. set_tunnel_hostname_addr_map(std::map<std::string, std::string> addr_map);
  4169. void set_basic_auth(const std::string &username, const std::string &password);
  4170. void set_bearer_token_auth(const std::string &token);
  4171. void set_proxy(const std::string &host, int port);
  4172. void set_proxy_basic_auth(const std::string &username,
  4173. const std::string &password);
  4174. void set_proxy_bearer_token_auth(const std::string &token);
  4175. void set_no_proxy(const std::vector<std::string> &patterns);
  4176. #ifdef CPPHTTPLIB_SSL_ENABLED
  4177. struct PemMemory {
  4178. const char *cert_pem;
  4179. size_t cert_pem_len;
  4180. const char *key_pem;
  4181. size_t key_pem_len;
  4182. const char *private_key_password;
  4183. };
  4184. explicit WebSocketClient(const std::string &scheme_host_port_path,
  4185. const PemMemory &pem, const Headers &headers = {});
  4186. void set_ca_cert_path(const std::string &ca_cert_file_path,
  4187. const std::string &ca_cert_dir_path = std::string());
  4188. void set_ca_cert_store(tls::ca_store_t store);
  4189. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  4190. void enable_server_certificate_verification(bool enabled);
  4191. void enable_server_hostname_verification(bool enabled);
  4192. void enable_system_ca(bool enabled);
  4193. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  4194. void set_session_verifier(
  4195. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  4196. void set_proxy_digest_auth(const std::string &username,
  4197. const std::string &password);
  4198. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  4199. void enable_windows_certificate_verification(bool enabled);
  4200. #endif
  4201. #endif
  4202. private:
  4203. void shutdown_and_close();
  4204. std::pair<time_t, time_t> handshake_timeout() const;
  4205. bool create_stream(std::unique_ptr<Stream> &strm, Error &error,
  4206. int &ssl_error, uint64_t &ssl_backend_error);
  4207. void prepare_default_headers(Request &req);
  4208. bool is_proxy_enabled() const;
  4209. bool create_and_connect_socket(Error &error);
  4210. bool send_proxy_connect(Request &req, Response &proxy_res, Error &error);
  4211. bool connect_with_proxy(Response &proxy_res, Error &error);
  4212. std::string host_;
  4213. int port_;
  4214. std::string path_;
  4215. Headers headers_;
  4216. std::string subprotocol_;
  4217. bool is_valid_ = false;
  4218. socket_t sock_ = INVALID_SOCKET;
  4219. std::unique_ptr<WebSocket> ws_;
  4220. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND;
  4221. time_t read_timeout_usec_ = 0;
  4222. bool read_timeout_set_ = false; // see WebSocket::read_timeout_set_
  4223. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  4224. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  4225. time_t websocket_ping_interval_sec_ =
  4226. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  4227. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  4228. int address_family_ = AF_UNSPEC;
  4229. bool tcp_nodelay_ = CPPHTTPLIB_WEBSOCKET_TCP_NODELAY;
  4230. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  4231. SocketOptions socket_options_ = nullptr;
  4232. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  4233. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  4234. std::string interface_;
  4235. // Hostname to connection target map. The value is an IP literal or another
  4236. // hostname; only the connection target changes, never the identity.
  4237. std::map<std::string, std::string> addr_map_;
  4238. // Hostname to CONNECT target map, used only through a proxy.
  4239. std::map<std::string, std::string> tunnel_addr_map_;
  4240. std::string basic_auth_username_;
  4241. std::string basic_auth_password_;
  4242. std::string bearer_token_auth_token_;
  4243. std::string proxy_host_;
  4244. int proxy_port_ = -1;
  4245. std::string proxy_basic_auth_username_;
  4246. std::string proxy_basic_auth_password_;
  4247. std::string proxy_bearer_token_auth_token_;
  4248. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  4249. #ifdef CPPHTTPLIB_SSL_ENABLED
  4250. bool is_ssl_ = false;
  4251. tls::ctx_t tls_ctx_ = nullptr;
  4252. tls::session_t tls_session_ = nullptr;
  4253. std::string ca_cert_file_path_;
  4254. std::string ca_cert_dir_path_;
  4255. // Set by set_ca_cert_store() and load_ca_cert_store() even when they bring
  4256. // no certificate, so that a CA that failed to come through fails
  4257. // verification instead of letting the system CAs in.
  4258. bool custom_ca_loaded_ = false;
  4259. bool certs_loaded_ = false;
  4260. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  4261. bool server_certificate_verification_ = true;
  4262. bool server_hostname_verification_ = true;
  4263. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  4264. std::string proxy_digest_auth_username_;
  4265. std::string proxy_digest_auth_password_;
  4266. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  4267. bool enable_windows_cert_verification_ = true;
  4268. bool server_certificate_verifier_set_ = false;
  4269. #endif
  4270. #endif
  4271. };
  4272. template <class Rep, class Period>
  4273. inline void WebSocket::set_read_timeout(
  4274. const std::chrono::duration<Rep, Period> &duration) {
  4275. detail::duration_to_sec_and_usec(
  4276. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  4277. }
  4278. template <class Rep, class Period>
  4279. inline void WebSocketClient::set_read_timeout(
  4280. const std::chrono::duration<Rep, Period> &duration) {
  4281. detail::duration_to_sec_and_usec(
  4282. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  4283. }
  4284. template <class Rep, class Period>
  4285. inline void WebSocketClient::set_write_timeout(
  4286. const std::chrono::duration<Rep, Period> &duration) {
  4287. detail::duration_to_sec_and_usec(
  4288. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  4289. }
  4290. template <class Rep, class Period>
  4291. inline void WebSocketClient::set_connection_timeout(
  4292. const std::chrono::duration<Rep, Period> &duration) {
  4293. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  4294. set_connection_timeout(sec, usec);
  4295. });
  4296. }
  4297. } // namespace ws
  4298. namespace detail {
  4299. bool write_websocket_frame(Stream &strm, ws::Opcode opcode, const char *data,
  4300. size_t len, bool fin, bool mask);
  4301. } // namespace detail
  4302. // ----------------------------------------------------------------------------
  4303. /*
  4304. * Implementation that will be part of the .cc file if split into .h + .cc.
  4305. */
  4306. namespace stream {
  4307. // stream::Result implementations
  4308. inline Result::Result() : chunk_size_(8192) {}
  4309. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  4310. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  4311. inline Result::Result(Result &&other) noexcept
  4312. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  4313. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  4314. finished_(other.finished_) {
  4315. other.current_size_ = 0;
  4316. other.finished_ = true;
  4317. }
  4318. inline Result &Result::operator=(Result &&other) noexcept {
  4319. if (this != &other) {
  4320. handle_ = std::move(other.handle_);
  4321. buffer_ = std::move(other.buffer_);
  4322. current_size_ = other.current_size_;
  4323. chunk_size_ = other.chunk_size_;
  4324. finished_ = other.finished_;
  4325. other.current_size_ = 0;
  4326. other.finished_ = true;
  4327. }
  4328. return *this;
  4329. }
  4330. inline bool Result::is_valid() const { return handle_.is_valid(); }
  4331. inline Result::operator bool() const { return is_valid(); }
  4332. inline int Result::status() const {
  4333. return handle_.response ? handle_.response->status : -1;
  4334. }
  4335. inline const Headers &Result::headers() const {
  4336. static const Headers empty_headers;
  4337. return handle_.response ? handle_.response->headers : empty_headers;
  4338. }
  4339. inline std::string Result::get_header_value(const std::string &key,
  4340. const char *def) const {
  4341. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  4342. }
  4343. inline bool Result::has_header(const std::string &key) const {
  4344. return handle_.response ? handle_.response->has_header(key) : false;
  4345. }
  4346. inline Error Result::error() const { return handle_.error; }
  4347. inline Error Result::read_error() const { return handle_.get_read_error(); }
  4348. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  4349. inline bool Result::next() {
  4350. if (!handle_.is_valid() || finished_) { return false; }
  4351. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  4352. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  4353. if (n > 0) {
  4354. current_size_ = static_cast<size_t>(n);
  4355. return true;
  4356. }
  4357. current_size_ = 0;
  4358. finished_ = true;
  4359. return false;
  4360. }
  4361. inline const char *Result::data() const { return buffer_.data(); }
  4362. inline size_t Result::size() const { return current_size_; }
  4363. inline std::string Result::read_all() {
  4364. std::string result;
  4365. while (next()) {
  4366. result.append(data(), size());
  4367. }
  4368. return result;
  4369. }
  4370. } // namespace stream
  4371. namespace detail {
  4372. inline SSEParser::SSEParser(EventHandler on_event, IdHandler on_id,
  4373. RetryHandler on_retry, size_t max_event_length)
  4374. : on_event_(std::move(on_event)), on_id_(std::move(on_id)),
  4375. on_retry_(std::move(on_retry)), max_event_length_(max_event_length) {}
  4376. inline bool SSEParser::parse(const char *buf, size_t n) {
  4377. // What is left in the buffer has no line ending
  4378. auto search_pos = buffer_.size();
  4379. buffer_.append(buf, n);
  4380. // A line ends with \r\n, \n or \r per the SSE spec
  4381. size_t line_start = 0;
  4382. size_t eol_pos;
  4383. while ((eol_pos = buffer_.find_first_of("\r\n", search_pos)) !=
  4384. std::string::npos) {
  4385. auto line = buffer_.substr(line_start, eol_pos - line_start);
  4386. line_start = eol_pos + 1;
  4387. search_pos = line_start;
  4388. // The \n of a \r\n may arrive in a later chunk than its \r
  4389. auto is_lf_of_crlf = after_cr_ && line.empty() && buffer_[eol_pos] == '\n';
  4390. after_cr_ = buffer_[eol_pos] == '\r';
  4391. if (is_lf_of_crlf) { continue; }
  4392. // A UTF-8 BOM at the start of the stream is ignored per the SSE spec
  4393. if (first_line_) {
  4394. first_line_ = false;
  4395. if (line.compare(0, 3, "\xEF\xBB\xBF") == 0) { line.erase(0, 3); }
  4396. }
  4397. parse_line(line);
  4398. }
  4399. // Keep unprocessed data in buffer
  4400. buffer_.erase(0, line_start);
  4401. return max_event_length_ == 0 ||
  4402. buffer_.size() + msg_.data.size() <= max_event_length_;
  4403. }
  4404. inline void SSEParser::parse_line(const std::string &line) {
  4405. // Blank line signals end of event
  4406. if (line.empty()) {
  4407. // The id counts for Last-Event-ID even for an event that has no data. An
  4408. // empty id clears it.
  4409. if (has_id_ && on_id_) { on_id_(msg_.id); }
  4410. // An event without a data field is not dispatched
  4411. if (has_data_ && on_event_) { on_event_(msg_); }
  4412. msg_.clear();
  4413. has_data_ = false;
  4414. has_id_ = false;
  4415. return;
  4416. }
  4417. // Lines starting with ':' are comments (ignored)
  4418. if (line[0] == ':') { return; }
  4419. // Find the colon separator
  4420. auto colon_pos = line.find(':');
  4421. auto field = line.substr(0, colon_pos);
  4422. std::string value;
  4423. // Value starts after colon, skip optional single space
  4424. if (colon_pos != std::string::npos && colon_pos + 1 < line.size()) {
  4425. auto value_start = colon_pos + 1;
  4426. if (line[value_start] == ' ') { value_start++; }
  4427. value = line.substr(value_start);
  4428. }
  4429. // Handle known fields
  4430. if (field == "event") {
  4431. // An empty event type is dispatched as "message" per the SSE spec
  4432. msg_.event = value.empty() ? std::string("message") : std::move(value);
  4433. } else if (field == "data") {
  4434. // Multiple data lines are concatenated with newlines
  4435. if (has_data_) { msg_.data += "\n"; }
  4436. msg_.data += value;
  4437. has_data_ = true;
  4438. } else if (field == "id") {
  4439. // An id that cannot be sent back as Last-Event-ID is ignored. Empty id is
  4440. // valid (clears the last event ID)
  4441. if (fields::is_field_value(value)) {
  4442. msg_.id = value;
  4443. has_id_ = true;
  4444. }
  4445. } else if (field == "retry") {
  4446. // Parse retry interval in milliseconds
  4447. // Per the SSE spec, a value that is not all ASCII digits is ignored.
  4448. if (is_numeric(value)) {
  4449. int v = 0;
  4450. auto res = from_chars(value.data(), value.data() + value.size(), v);
  4451. if (res.ec == std::errc{} && on_retry_) { on_retry_(v); }
  4452. }
  4453. }
  4454. // Unknown fields are ignored per SSE spec
  4455. }
  4456. } // namespace detail
  4457. namespace sse {
  4458. // SSEMessage implementations
  4459. inline SSEMessage::SSEMessage() : event("message") {}
  4460. inline void SSEMessage::clear() {
  4461. event = "message";
  4462. data.clear();
  4463. id.clear();
  4464. }
  4465. // SSEClient implementations
  4466. inline SSEClient::SSEClient(Client &client, const std::string &path)
  4467. : client_(client), path_(path) {}
  4468. inline SSEClient::SSEClient(Client &client, const std::string &path,
  4469. const Headers &headers)
  4470. : client_(client), path_(path), headers_(headers) {}
  4471. inline SSEClient::~SSEClient() { stop(); }
  4472. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  4473. on_message_ = std::move(handler);
  4474. return *this;
  4475. }
  4476. inline SSEClient &SSEClient::on_event(const std::string &type,
  4477. MessageHandler handler) {
  4478. event_handlers_[type] = std::move(handler);
  4479. return *this;
  4480. }
  4481. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  4482. on_open_ = std::move(handler);
  4483. return *this;
  4484. }
  4485. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  4486. on_error_ = std::move(handler);
  4487. return *this;
  4488. }
  4489. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  4490. reconnect_interval_ms_ = ms;
  4491. return *this;
  4492. }
  4493. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  4494. max_reconnect_attempts_ = n;
  4495. return *this;
  4496. }
  4497. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  4498. std::lock_guard<std::mutex> lock(headers_mutex_);
  4499. headers_ = headers;
  4500. return *this;
  4501. }
  4502. inline bool SSEClient::is_connected() const { return connected_.load(); }
  4503. inline std::string SSEClient::last_event_id() const {
  4504. std::lock_guard<std::mutex> lock(last_event_id_mutex_);
  4505. return last_event_id_;
  4506. }
  4507. inline void SSEClient::start() {
  4508. running_.store(true);
  4509. run_event_loop();
  4510. }
  4511. inline void SSEClient::start_async() {
  4512. running_.store(true);
  4513. async_thread_ = std::thread([this]() { run_event_loop(); });
  4514. }
  4515. inline void SSEClient::stop() {
  4516. running_.store(false);
  4517. client_.stop(); // Cancel any pending operations
  4518. if (async_thread_.joinable()) { async_thread_.join(); }
  4519. }
  4520. inline void SSEClient::run_event_loop() {
  4521. auto reconnect_count = 0;
  4522. while (running_.load()) {
  4523. // Build headers, including Last-Event-ID if we have one
  4524. Headers request_headers;
  4525. {
  4526. std::lock_guard<std::mutex> lock(headers_mutex_);
  4527. request_headers = headers_;
  4528. }
  4529. if (!last_event_id_.empty()) {
  4530. request_headers.emplace("Last-Event-ID", last_event_id_);
  4531. }
  4532. // Open streaming connection. An event stream has no end, so each event is
  4533. // bounded instead of the whole body.
  4534. auto handle = client_.open_stream("GET", path_, {}, request_headers);
  4535. handle.body_reader_.payload_max_length = 0;
  4536. // stop() ends a read that is waiting for the next event
  4537. if (handle.stream_) {
  4538. handle.stream_->set_read_interrupt([this] { return !running_.load(); });
  4539. }
  4540. stream::Result result{std::move(handle)};
  4541. // Connection error handling
  4542. if (!result) {
  4543. connected_.store(false);
  4544. if (on_error_) { on_error_(result.error()); }
  4545. if (!should_reconnect(reconnect_count)) { break; }
  4546. wait_for_reconnect();
  4547. reconnect_count++;
  4548. continue;
  4549. }
  4550. if (result.status() != StatusCode::OK_200) {
  4551. connected_.store(false);
  4552. if (on_error_) { on_error_(Error::Connection); }
  4553. // For certain errors, don't reconnect.
  4554. // Note: 401 is intentionally absent so that handlers can refresh
  4555. // credentials via set_headers() and let the client reconnect.
  4556. if (result.status() == StatusCode::NoContent_204 ||
  4557. result.status() == StatusCode::NotFound_404 ||
  4558. result.status() == StatusCode::Forbidden_403) {
  4559. break;
  4560. }
  4561. if (!should_reconnect(reconnect_count)) { break; }
  4562. wait_for_reconnect();
  4563. reconnect_count++;
  4564. continue;
  4565. }
  4566. // Connection successful
  4567. connected_.store(true);
  4568. reconnect_count = 0;
  4569. if (on_open_) { on_open_(); }
  4570. // Event receiving loop
  4571. detail::SSEParser parser(
  4572. [this](const SSEMessage &msg) { dispatch_event(msg); },
  4573. [this](const std::string &id) {
  4574. std::lock_guard<std::mutex> lock(last_event_id_mutex_);
  4575. last_event_id_ = id;
  4576. },
  4577. [this](int retry_ms) { reconnect_interval_ms_ = retry_ms; });
  4578. auto event_too_long = false;
  4579. while (running_.load() && result.next()) {
  4580. if (!parser.parse(result.data(), result.size())) {
  4581. if (on_error_) { on_error_(Error::ExceedMaxPayloadSize); }
  4582. event_too_long = true;
  4583. break;
  4584. }
  4585. }
  4586. // Connection ended
  4587. connected_.store(false);
  4588. // Reconnecting would only get the same event again
  4589. if (!running_.load() || event_too_long) { break; }
  4590. // Check for read errors
  4591. if (result.has_read_error()) {
  4592. if (on_error_) { on_error_(result.read_error()); }
  4593. }
  4594. if (!should_reconnect(reconnect_count)) { break; }
  4595. wait_for_reconnect();
  4596. reconnect_count++;
  4597. }
  4598. connected_.store(false);
  4599. }
  4600. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  4601. // Check for specific event type handler first
  4602. auto it = event_handlers_.find(msg.event);
  4603. if (it != event_handlers_.end()) {
  4604. it->second(msg);
  4605. return;
  4606. }
  4607. // Fall back to generic message handler
  4608. if (on_message_) { on_message_(msg); }
  4609. }
  4610. inline bool SSEClient::should_reconnect(int count) const {
  4611. if (!running_.load()) { return false; }
  4612. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  4613. return count < max_reconnect_attempts_;
  4614. }
  4615. inline void SSEClient::wait_for_reconnect() {
  4616. // Use small increments to check running_ flag frequently.
  4617. // Always wait at least one increment, so that a zero interval (e.g.
  4618. // "retry: 0" from the server) cannot cause a busy reconnect loop.
  4619. const auto step_ms = 100;
  4620. auto interval_ms = (std::max)(reconnect_interval_ms_, step_ms);
  4621. auto waited = 0;
  4622. while (running_.load() && waited < interval_ms) {
  4623. std::this_thread::sleep_for(std::chrono::milliseconds(step_ms));
  4624. waited += step_ms;
  4625. }
  4626. }
  4627. } // namespace sse
  4628. #ifdef CPPHTTPLIB_SSL_ENABLED
  4629. /*
  4630. * TLS abstraction layer - internal function declarations
  4631. * These are implementation details and not part of the public API.
  4632. */
  4633. namespace tls {
  4634. // Client context
  4635. ctx_t create_client_context();
  4636. void free_context(ctx_t ctx);
  4637. bool set_min_version(ctx_t ctx, Version version);
  4638. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  4639. bool load_ca_file(ctx_t ctx, const char *file_path);
  4640. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  4641. bool load_system_certs(ctx_t ctx);
  4642. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4643. const char *password);
  4644. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  4645. const char *key_path, const char *password);
  4646. // Server context
  4647. ctx_t create_server_context();
  4648. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4649. const char *password);
  4650. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  4651. const char *key_path, const char *password);
  4652. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  4653. void set_verify_client(ctx_t ctx, bool require);
  4654. // Session management
  4655. session_t create_session(ctx_t ctx, socket_t sock);
  4656. void free_session(session_t session);
  4657. bool set_sni(session_t session, const char *hostname, bool verify_hostname);
  4658. // Handshake (non-blocking capable)
  4659. TlsError connect(session_t session);
  4660. TlsError accept(session_t session);
  4661. // Handshake with timeout (blocking until timeout, or until interrupted)
  4662. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4663. time_t timeout_usec, TlsError *err,
  4664. const std::function<bool()> &interrupted = nullptr);
  4665. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4666. time_t timeout_usec, TlsError *err);
  4667. // I/O (non-blocking capable)
  4668. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  4669. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  4670. int pending(const_session_t session);
  4671. void shutdown(session_t session, bool graceful);
  4672. // Connection state
  4673. bool is_peer_closed(session_t session, socket_t sock);
  4674. // Certificate verification
  4675. cert_t get_peer_cert(const_session_t session);
  4676. // The certificates the peer sent, leaf first. Free each with free_cert(), and
  4677. // do not use them after free_session(), as with get_peer_cert().
  4678. size_t get_peer_certs(const_session_t session, std::vector<cert_t> &certs);
  4679. void free_cert(cert_t cert);
  4680. // Matches the host against the subjectAltName entries only, never the Common
  4681. // Name (RFC 9525).
  4682. bool verify_hostname(cert_t cert, const char *hostname);
  4683. uint64_t hostname_mismatch_code();
  4684. long get_verify_result(const_session_t session);
  4685. // Certificate introspection
  4686. std::string get_cert_subject_cn(cert_t cert);
  4687. std::string get_cert_issuer_name(cert_t cert);
  4688. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  4689. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  4690. std::string get_cert_serial(cert_t cert);
  4691. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  4692. const char *get_sni(const_session_t session);
  4693. // CA store management
  4694. ca_store_t create_ca_store(const char *pem, size_t len);
  4695. void free_ca_store(ca_store_t store);
  4696. bool set_ca_store(ctx_t ctx, ca_store_t store);
  4697. // Free each with free_cert(), and do not use them once the context's CA
  4698. // certificates change.
  4699. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  4700. std::vector<std::string> get_ca_names(ctx_t ctx);
  4701. // Dynamic certificate update (for servers)
  4702. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  4703. const char *password);
  4704. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  4705. // Certificate verification callback
  4706. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  4707. long get_verify_error(const_session_t session);
  4708. std::string verify_error_string(long error_code);
  4709. // TlsError information
  4710. uint64_t peek_error();
  4711. uint64_t get_error();
  4712. std::string error_string(uint64_t code);
  4713. } // namespace tls
  4714. #endif // CPPHTTPLIB_SSL_ENABLED
  4715. /*
  4716. * Group 1: detail namespace - Non-SSL utilities
  4717. */
  4718. namespace detail {
  4719. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  4720. const void *optval, socklen_t optlen) {
  4721. return setsockopt(sock, level, optname,
  4722. #ifdef _WIN32
  4723. reinterpret_cast<const char *>(optval),
  4724. #else
  4725. optval,
  4726. #endif
  4727. optlen) == 0;
  4728. }
  4729. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  4730. time_t sec, time_t usec) {
  4731. #ifdef _WIN32
  4732. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  4733. #else
  4734. timeval timeout;
  4735. timeout.tv_sec = static_cast<long>(sec);
  4736. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  4737. #endif
  4738. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  4739. }
  4740. inline bool is_hex(char c, int &v) {
  4741. if (is_ascii_digit(c)) {
  4742. v = c - '0';
  4743. return true;
  4744. } else if ('A' <= c && c <= 'F') {
  4745. v = c - 'A' + 10;
  4746. return true;
  4747. } else if ('a' <= c && c <= 'f') {
  4748. v = c - 'a' + 10;
  4749. return true;
  4750. }
  4751. return false;
  4752. }
  4753. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  4754. int &val) {
  4755. if (i >= s.size()) { return false; }
  4756. val = 0;
  4757. for (; cnt; i++, cnt--) {
  4758. if (!s[i]) { return false; }
  4759. auto v = 0;
  4760. if (is_hex(s[i], v)) {
  4761. val = val * 16 + v;
  4762. } else {
  4763. return false;
  4764. }
  4765. }
  4766. return true;
  4767. }
  4768. inline std::string from_i_to_hex(size_t n) {
  4769. static const auto charset = "0123456789abcdef";
  4770. std::string ret;
  4771. do {
  4772. ret = charset[n & 15] + ret;
  4773. n >>= 4;
  4774. } while (n > 0);
  4775. return ret;
  4776. }
  4777. // A round trip rather than `n <= SIZE_MAX`, which is always true on 64-bit
  4778. // builds and trips -Wtautological-type-limit-compare.
  4779. inline bool fits_in_size_t(uint64_t n) {
  4780. return static_cast<uint64_t>(static_cast<size_t>(n)) == n;
  4781. }
  4782. inline std::string compute_etag(const FileStat &fs,
  4783. const std::string &suffix = std::string()) {
  4784. if (!fs.is_file()) { return std::string(); }
  4785. // If mtime cannot be determined (negative value indicates an error
  4786. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  4787. // value like 0 could collide with a real file that legitimately has
  4788. // mtime == 0 (epoch) and lead to misleading validators.
  4789. auto mtime_raw = fs.mtime();
  4790. if (mtime_raw < 0) { return std::string(); }
  4791. auto mtime = static_cast<size_t>(mtime_raw);
  4792. auto size = fs.size();
  4793. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  4794. from_i_to_hex(size) + suffix + "\"";
  4795. }
  4796. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  4797. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  4798. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  4799. inline std::string file_mtime_to_http_date(time_t mtime) {
  4800. if (mtime < 0) { return std::string(); }
  4801. struct tm tm_buf;
  4802. #ifdef _WIN32
  4803. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  4804. #else
  4805. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  4806. #endif
  4807. char buf[64];
  4808. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  4809. return std::string();
  4810. }
  4811. return std::string(buf);
  4812. }
  4813. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  4814. inline time_t parse_http_date(const std::string &date_str) {
  4815. struct tm tm_buf;
  4816. // Create a classic locale object once for all parsing attempts
  4817. const std::locale classic_locale = std::locale::classic();
  4818. // Try to parse using std::get_time (C++11, cross-platform)
  4819. auto try_parse = [&](const char *fmt) -> bool {
  4820. std::istringstream ss(date_str);
  4821. ss.imbue(classic_locale);
  4822. memset(&tm_buf, 0, sizeof(tm_buf));
  4823. ss >> std::get_time(&tm_buf, fmt);
  4824. return !ss.fail();
  4825. };
  4826. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  4827. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  4828. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  4829. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  4830. // asctime format: "Sun Nov 6 08:49:37 1994"
  4831. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  4832. return static_cast<time_t>(-1);
  4833. }
  4834. }
  4835. }
  4836. #ifdef _WIN32
  4837. return _mkgmtime(&tm_buf);
  4838. #elif defined _AIX
  4839. return mktime(&tm_buf);
  4840. #else
  4841. return timegm(&tm_buf);
  4842. #endif
  4843. }
  4844. inline bool is_weak_etag(const std::string &s) {
  4845. // Check if the string is a weak ETag (starts with 'W/"')
  4846. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  4847. }
  4848. inline bool is_strong_etag(const std::string &s) {
  4849. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  4850. // chars)
  4851. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  4852. }
  4853. inline size_t to_utf8(int code, char *buff) {
  4854. if (code < 0x0080) {
  4855. buff[0] = static_cast<char>(code & 0x7F);
  4856. return 1;
  4857. } else if (code < 0x0800) {
  4858. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  4859. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  4860. return 2;
  4861. } else if (code < 0xD800) {
  4862. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4863. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4864. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4865. return 3;
  4866. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  4867. return 0;
  4868. } else if (code < 0x10000) {
  4869. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4870. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4871. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4872. return 3;
  4873. } else if (code < 0x110000) {
  4874. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  4875. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  4876. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4877. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  4878. return 4;
  4879. }
  4880. // NOTREACHED
  4881. return 0;
  4882. }
  4883. } // namespace detail
  4884. namespace ws {
  4885. namespace impl {
  4886. inline bool is_valid_utf8(const std::string &s) {
  4887. size_t i = 0;
  4888. auto n = s.size();
  4889. while (i < n) {
  4890. auto c = static_cast<unsigned char>(s[i]);
  4891. size_t len;
  4892. uint32_t cp;
  4893. if (c < 0x80) {
  4894. i++;
  4895. continue;
  4896. } else if ((c & 0xE0) == 0xC0) {
  4897. len = 2;
  4898. cp = c & 0x1F;
  4899. } else if ((c & 0xF0) == 0xE0) {
  4900. len = 3;
  4901. cp = c & 0x0F;
  4902. } else if ((c & 0xF8) == 0xF0) {
  4903. len = 4;
  4904. cp = c & 0x07;
  4905. } else {
  4906. return false;
  4907. }
  4908. if (i + len > n) { return false; }
  4909. for (size_t j = 1; j < len; j++) {
  4910. auto b = static_cast<unsigned char>(s[i + j]);
  4911. if ((b & 0xC0) != 0x80) { return false; }
  4912. cp = (cp << 6) | (b & 0x3F);
  4913. }
  4914. // Overlong encoding check
  4915. if (len == 2 && cp < 0x80) { return false; }
  4916. if (len == 3 && cp < 0x800) { return false; }
  4917. if (len == 4 && cp < 0x10000) { return false; }
  4918. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  4919. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  4920. if (cp > 0x10FFFF) { return false; }
  4921. i += len;
  4922. }
  4923. return true;
  4924. }
  4925. } // namespace impl
  4926. } // namespace ws
  4927. namespace detail {
  4928. // NOTE: This code came up with the following stackoverflow post:
  4929. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  4930. inline std::string base64_encode(const std::string &in) {
  4931. static const auto lookup =
  4932. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4933. std::string out;
  4934. out.reserve(in.size());
  4935. // Unsigned: the accumulator is never masked, so with a signed int the
  4936. // `val << 8` below overflows once enough bytes are folded in (undefined
  4937. // behaviour before C++20). Only the low bits are ever emitted, so the
  4938. // wrap-around of an unsigned accumulator does not affect the output.
  4939. uint32_t val = 0;
  4940. auto valb = -6;
  4941. for (auto c : in) {
  4942. val = (val << 8) + static_cast<uint8_t>(c);
  4943. valb += 8;
  4944. while (valb >= 0) {
  4945. out.push_back(lookup[(val >> valb) & 0x3F]);
  4946. valb -= 6;
  4947. }
  4948. }
  4949. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  4950. while (out.size() % 4) {
  4951. out.push_back('=');
  4952. }
  4953. return out;
  4954. }
  4955. inline std::string sha1(const std::string &input) {
  4956. // RFC 3174 SHA-1 implementation
  4957. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  4958. return (x << n) | (x >> (32 - n));
  4959. };
  4960. uint32_t h0 = 0x67452301;
  4961. uint32_t h1 = 0xEFCDAB89;
  4962. uint32_t h2 = 0x98BADCFE;
  4963. uint32_t h3 = 0x10325476;
  4964. uint32_t h4 = 0xC3D2E1F0;
  4965. // Pre-processing: adding padding bits
  4966. std::string msg = input;
  4967. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  4968. msg.push_back(static_cast<char>(0x80u));
  4969. while (msg.size() % 64 != 56) {
  4970. msg.push_back(0);
  4971. }
  4972. // Append original length in bits as 64-bit big-endian
  4973. for (int i = 56; i >= 0; i -= 8) {
  4974. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  4975. }
  4976. // Process each 512-bit chunk
  4977. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  4978. uint32_t w[80];
  4979. for (size_t i = 0; i < 16; i++) {
  4980. w[i] =
  4981. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  4982. << 24) |
  4983. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  4984. << 16) |
  4985. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  4986. << 8) |
  4987. (static_cast<uint32_t>(
  4988. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  4989. }
  4990. for (int i = 16; i < 80; i++) {
  4991. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  4992. }
  4993. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  4994. for (int i = 0; i < 80; i++) {
  4995. uint32_t f, k;
  4996. if (i < 20) {
  4997. f = (b & c) | ((~b) & d);
  4998. k = 0x5A827999;
  4999. } else if (i < 40) {
  5000. f = b ^ c ^ d;
  5001. k = 0x6ED9EBA1;
  5002. } else if (i < 60) {
  5003. f = (b & c) | (b & d) | (c & d);
  5004. k = 0x8F1BBCDC;
  5005. } else {
  5006. f = b ^ c ^ d;
  5007. k = 0xCA62C1D6;
  5008. }
  5009. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  5010. e = d;
  5011. d = c;
  5012. c = left_rotate(b, 30);
  5013. b = a;
  5014. a = temp;
  5015. }
  5016. h0 += a;
  5017. h1 += b;
  5018. h2 += c;
  5019. h3 += d;
  5020. h4 += e;
  5021. }
  5022. // Produce the final hash as a 20-byte binary string
  5023. std::string hash(20, '\0');
  5024. for (size_t i = 0; i < 4; i++) {
  5025. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  5026. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  5027. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  5028. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  5029. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  5030. }
  5031. return hash;
  5032. }
  5033. inline std::string websocket_accept_key(const std::string &client_key) {
  5034. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  5035. return base64_encode(sha1(client_key + magic));
  5036. }
  5037. inline bool is_websocket_upgrade(const Request &req) {
  5038. if (req.method != "GET") { return false; }
  5039. // Check Upgrade: websocket. RFC 9110 7.8 defines Upgrade as a comma-separated
  5040. // list of protocols and asks recipients to match each name
  5041. // case-insensitively, so look for the token rather than compare the whole
  5042. // field value.
  5043. if (!has_header_token(req.headers, "Upgrade", "websocket")) { return false; }
  5044. // Check Connection: Upgrade
  5045. if (!has_header_token(req.headers, "Connection", "upgrade")) { return false; }
  5046. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  5047. // RFC 6455 Section 4.2.1
  5048. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  5049. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  5050. return false;
  5051. }
  5052. static const std::string b64chars =
  5053. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5054. for (size_t i = 0; i < 22; i++) {
  5055. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  5056. }
  5057. // Check Sec-WebSocket-Version: 13
  5058. auto version = req.get_header_value("Sec-WebSocket-Version");
  5059. if (version != "13") { return false; }
  5060. return true;
  5061. }
  5062. // Unpredictable bytes for masking keys (RFC 6455 Section 5.3) and nonces
  5063. inline void fill_random_bytes(unsigned char *out, size_t n) {
  5064. thread_local std::random_device rd;
  5065. size_t filled = 0;
  5066. while (filled < n) {
  5067. auto v = rd();
  5068. for (size_t b = 0; b < sizeof(v) && filled < n; ++b, ++filled) {
  5069. out[filled] = static_cast<unsigned char>((v >> (b * 8)) & 0xFFu);
  5070. }
  5071. }
  5072. }
  5073. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  5074. const char *data, size_t len, bool fin,
  5075. bool mask) {
  5076. // The header (FIN + opcode, MASK + length, the extended length, the mask
  5077. // key: 14 bytes at most) goes out in one write with the payload's first
  5078. // chunk, so that under TCP_NODELAY a small frame is one segment, not three.
  5079. uint8_t header[14];
  5080. size_t header_len = 0;
  5081. header[header_len++] = static_cast<uint8_t>(
  5082. (fin ? 0x80 : 0x00) | (static_cast<uint8_t>(opcode) & 0x0F));
  5083. uint8_t mask_bit = mask ? 0x80 : 0x00;
  5084. if (len < 126) {
  5085. header[header_len++] = static_cast<uint8_t>(len) | mask_bit;
  5086. } else if (len <= 0xFFFF) {
  5087. header[header_len++] = 126 | mask_bit;
  5088. header[header_len++] = static_cast<uint8_t>((len >> 8) & 0xFF);
  5089. header[header_len++] = static_cast<uint8_t>(len & 0xFF);
  5090. } else {
  5091. header[header_len++] = 127 | mask_bit;
  5092. for (int i = 7; i >= 0; i--) {
  5093. header[header_len++] =
  5094. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  5095. }
  5096. }
  5097. uint8_t mask_key[4] = {0};
  5098. if (mask) {
  5099. fill_random_bytes(mask_key, sizeof(mask_key));
  5100. std::copy(mask_key, mask_key + 4, header + header_len);
  5101. header_len += 4;
  5102. }
  5103. // `n` bytes of the payload from `offset`, masked if they are to be, at `out`
  5104. auto put = [&](char *out, size_t offset, size_t n) {
  5105. for (size_t i = 0; i < n; i++) {
  5106. out[i] = mask ? data[offset + i] ^
  5107. static_cast<char>(mask_key[(offset + i) % 4])
  5108. : data[offset + i];
  5109. }
  5110. };
  5111. const size_t chunk_size = 4096;
  5112. size_t first = (std::min)(len, chunk_size);
  5113. std::vector<char> buf(header_len + first);
  5114. std::copy(header, header + header_len, buf.begin());
  5115. put(buf.data() + header_len, 0, first);
  5116. if (!write_data(strm, buf.data(), buf.size())) { return false; }
  5117. // The rest, masked a chunk at a time, or else as it is
  5118. if (!mask) {
  5119. return first == len || write_data(strm, data + first, len - first);
  5120. }
  5121. for (size_t offset = first; offset < len; offset += chunk_size) {
  5122. size_t n = (std::min)(chunk_size, len - offset);
  5123. put(buf.data(), offset, n);
  5124. if (!write_data(strm, buf.data(), n)) { return false; }
  5125. }
  5126. return true;
  5127. }
  5128. } // namespace detail
  5129. namespace ws {
  5130. namespace impl {
  5131. inline void FrameReader::reset() {
  5132. have_ = 0;
  5133. need_ = 2;
  5134. sized_ = false;
  5135. len_ = 0;
  5136. payload_.clear();
  5137. }
  5138. // Stream::read may return less than asked for -- it hands back whatever its
  5139. // buffer already holds -- so each part of the frame is read in a loop, a byte
  5140. // at a time if that is how it comes. (When read() fails it always records why,
  5141. // so the error belongs to this call and not to an earlier one.)
  5142. inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
  5143. std::string &payload, bool &fin,
  5144. bool expect_masked, size_t max_len) {
  5145. // A timeout keeps what was read; anything else ends the frame
  5146. auto stopped = [&]() {
  5147. if (strm.get_error() == Error::Timeout) { return FrameRead::Timeout; }
  5148. reset();
  5149. return FrameRead::Fail;
  5150. };
  5151. auto fail = [&]() {
  5152. reset();
  5153. return FrameRead::Fail;
  5154. };
  5155. while (have_ < need_) {
  5156. auto n = strm.read(reinterpret_cast<char *>(head_) + have_, need_ - have_);
  5157. if (n <= 0) { return stopped(); }
  5158. have_ += static_cast<size_t>(n);
  5159. if (have_ < 2 || need_ > 2) { continue; }
  5160. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  5161. if (head_[0] & 0x70) { return fail(); }
  5162. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  5163. // MUST have a payload length of 125 bytes or less
  5164. auto len7 = head_[1] & 0x7F;
  5165. if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) {
  5166. return fail();
  5167. }
  5168. auto masked = (head_[1] & 0x80) != 0;
  5169. if (masked != expect_masked) { return fail(); }
  5170. // The extended length and the mask key follow
  5171. need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0);
  5172. }
  5173. if (!sized_) {
  5174. uint64_t len = head_[1] & 0x7F;
  5175. if (len == 126) {
  5176. len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3];
  5177. } else if (len == 127) {
  5178. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  5179. if (head_[2] & 0x80) { return fail(); }
  5180. len = 0;
  5181. for (size_t i = 2; i < 10; i++) {
  5182. len = (len << 8) | head_[i];
  5183. }
  5184. }
  5185. // A max_len of 0 means no limit, as payload_max_length does, and a length
  5186. // size_t cannot hold (32-bit builds) is refused either way.
  5187. if ((max_len > 0 && len > max_len) || !detail::fits_in_size_t(len)) {
  5188. return fail();
  5189. }
  5190. len_ = static_cast<size_t>(len);
  5191. sized_ = true;
  5192. }
  5193. // Grow the payload only as it arrives, since a header alone can announce
  5194. // max_len bytes that never come.
  5195. while (payload_.size() < len_) {
  5196. auto offset = payload_.size();
  5197. auto n = (std::min)(len_ - offset, CPPHTTPLIB_RECV_BUFSIZ);
  5198. payload_.resize(offset + n);
  5199. auto got = strm.read(&payload_[offset], n);
  5200. if (got <= 0) {
  5201. payload_.resize(offset);
  5202. return stopped();
  5203. }
  5204. payload_.resize(offset + static_cast<size_t>(got));
  5205. }
  5206. if (head_[1] & 0x80) {
  5207. const auto *mask_key = head_ + need_ - 4;
  5208. for (size_t i = 0; i < payload_.size(); i++) {
  5209. payload_[i] ^= static_cast<char>(mask_key[i % 4]);
  5210. }
  5211. }
  5212. fin = (head_[0] & 0x80) != 0;
  5213. opcode = static_cast<Opcode>(head_[0] & 0x0F);
  5214. payload = std::move(payload_);
  5215. reset();
  5216. return FrameRead::Ok;
  5217. }
  5218. inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  5219. std::string &payload, bool &fin,
  5220. bool expect_masked, size_t max_len) {
  5221. FrameReader reader;
  5222. auto r = reader.read(strm, opcode, payload, fin, expect_masked, max_len);
  5223. return r == FrameRead::Timeout && reader.begun() ? FrameRead::Fail : r;
  5224. }
  5225. // RFC 6455 §5.5.1, §7.4: a Close payload is empty, or a status code that may
  5226. // be sent followed by a UTF-8 reason.
  5227. inline bool is_valid_close_payload(const std::string &payload) {
  5228. if (payload.empty()) { return true; }
  5229. if (payload.size() < 2) { return false; }
  5230. auto code = (static_cast<uint8_t>(payload[0]) << 8) |
  5231. static_cast<uint8_t>(payload[1]);
  5232. auto may_be_sent = (1000 <= code && code <= 1003) ||
  5233. (1007 <= code && code <= 1014) ||
  5234. (3000 <= code && code <= 4999);
  5235. return may_be_sent && is_valid_utf8(payload.substr(2));
  5236. }
  5237. } // namespace impl
  5238. } // namespace ws
  5239. namespace detail {
  5240. // A path a mount point serves: absolute, with no empty segment except a
  5241. // trailing '/', no segment ending in '.' or a space (which covers "." and
  5242. // ".." and names Windows trims into another file's name) and, on Windows, no
  5243. // ':' (which names an NTFS stream, so "a.txt::$DATA" is a.txt), so the file
  5244. // served is the one that req.path names to the handlers that ran before it.
  5245. inline bool is_valid_path(const std::string &path) {
  5246. if (path.empty() || path[0] != '/') { return false; }
  5247. auto beg = size_t{1};
  5248. for (auto i = beg; i <= path.size(); i++) {
  5249. if (i < path.size() && path[i] != '/') {
  5250. if (path[i] == '\0' || path[i] == '\\') { return false; }
  5251. #ifdef _WIN32
  5252. if (path[i] == ':') { return false; }
  5253. #endif
  5254. continue;
  5255. }
  5256. auto len = i - beg;
  5257. if ((len == 0 && i < path.size()) ||
  5258. (len > 0 && (path[i - 1] == '.' || path[i - 1] == ' '))) {
  5259. return false;
  5260. }
  5261. beg = i + 1;
  5262. }
  5263. return true;
  5264. }
  5265. inline bool canonicalize_path(const char *path, std::string &resolved) {
  5266. #if defined(_WIN32)
  5267. // Resolve junctions and symlinks, as realpath() does
  5268. auto wpath = u8string_to_wstring(path);
  5269. if (wpath.empty()) { return false; }
  5270. CREATEFILE2_EXTENDED_PARAMETERS params{};
  5271. params.dwSize = sizeof(params);
  5272. params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS; // Needed to open a directory
  5273. auto h = ::CreateFile2(wpath.c_str(), 0,
  5274. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  5275. OPEN_EXISTING, &params);
  5276. if (h == INVALID_HANDLE_VALUE) { return false; }
  5277. auto guard = scope_exit([&]() { ::CloseHandle(h); });
  5278. std::wstring wbuf(MAX_PATH, L'\0');
  5279. auto len = ::GetFinalPathNameByHandleW(
  5280. h, &wbuf[0], static_cast<DWORD>(wbuf.size()), FILE_NAME_NORMALIZED);
  5281. if (len >= wbuf.size()) {
  5282. wbuf.resize(len);
  5283. len = ::GetFinalPathNameByHandleW(
  5284. h, &wbuf[0], static_cast<DWORD>(wbuf.size()), FILE_NAME_NORMALIZED);
  5285. }
  5286. if (len == 0 || len >= wbuf.size()) { return false; }
  5287. auto n = ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), static_cast<int>(len),
  5288. nullptr, 0, nullptr, nullptr);
  5289. if (n <= 0) { return false; }
  5290. resolved.assign(static_cast<size_t>(n), '\0');
  5291. ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), static_cast<int>(len),
  5292. &resolved[0], n, nullptr, nullptr);
  5293. #elif defined(PATH_MAX)
  5294. char buf[PATH_MAX];
  5295. if (realpath(path, buf) == nullptr) { return false; }
  5296. resolved = buf;
  5297. #else
  5298. auto buf = realpath(path, nullptr);
  5299. auto guard = scope_exit([&]() { std::free(buf); });
  5300. if (buf == nullptr) { return false; }
  5301. resolved = buf;
  5302. #endif
  5303. return true;
  5304. }
  5305. inline bool is_path_within_base(const std::string &resolved_path,
  5306. const std::string &resolved_base) {
  5307. #if defined(_WIN32)
  5308. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  5309. resolved_base.size()) == 0;
  5310. #else
  5311. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  5312. resolved_base.size()) == 0;
  5313. #endif
  5314. }
  5315. inline FileStat::FileStat(const std::string &path) {
  5316. #if defined(_WIN32)
  5317. auto wpath = u8string_to_wstring(path.c_str());
  5318. ret_ = _wstat(wpath.c_str(), &st_);
  5319. #else
  5320. ret_ = stat(path.c_str(), &st_);
  5321. #endif
  5322. }
  5323. inline bool FileStat::is_file() const {
  5324. return ret_ >= 0 && S_ISREG(st_.st_mode);
  5325. }
  5326. inline bool FileStat::is_dir() const {
  5327. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  5328. }
  5329. inline time_t FileStat::mtime() const {
  5330. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  5331. : static_cast<time_t>(-1);
  5332. }
  5333. inline size_t FileStat::size() const {
  5334. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  5335. }
  5336. inline std::string encode_path(const std::string &s) {
  5337. std::string result;
  5338. result.reserve(s.size());
  5339. for (size_t i = 0; s[i]; i++) {
  5340. switch (s[i]) {
  5341. case ' ': result += "%20"; break;
  5342. case '+': result += "%2B"; break;
  5343. case '\'': result += "%27"; break;
  5344. case ',': result += "%2C"; break;
  5345. // case ':': result += "%3A"; break; // ok? probably...
  5346. case ';': result += "%3B"; break;
  5347. default:
  5348. auto c = static_cast<uint8_t>(s[i]);
  5349. // Control characters (incl. CR/LF) and non-ASCII bytes are not allowed
  5350. // in a request-target as-is.
  5351. if (c < 0x20 || c == 0x7f || c >= 0x80) {
  5352. result += '%';
  5353. char hex[4];
  5354. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  5355. assert(len == 2);
  5356. result.append(hex, static_cast<size_t>(len));
  5357. } else {
  5358. result += s[i];
  5359. }
  5360. break;
  5361. }
  5362. }
  5363. return result;
  5364. }
  5365. inline std::string file_extension(const std::string &path) {
  5366. auto i = path.size();
  5367. while (i > 0 && is_ascii_alnum(path[i - 1])) {
  5368. i--;
  5369. }
  5370. if (i == path.size() || i == 0 || path[i - 1] != '.') {
  5371. return std::string();
  5372. }
  5373. return path.substr(i);
  5374. }
  5375. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  5376. template <typename T>
  5377. inline bool parse_header(const char *beg, const char *end, T fn);
  5378. template <typename T>
  5379. inline bool parse_header(const char *beg, const char *end, T fn) {
  5380. // Skip trailing spaces and tabs.
  5381. while (beg < end && is_space_or_tab(end[-1])) {
  5382. end--;
  5383. }
  5384. auto p = beg;
  5385. while (p < end && *p != ':') {
  5386. p++;
  5387. }
  5388. auto name = std::string(beg, p);
  5389. if (!detail::fields::is_field_name(name)) { return false; }
  5390. if (p == end) { return false; }
  5391. auto key_end = p;
  5392. if (*p++ != ':') { return false; }
  5393. while (p < end && is_space_or_tab(*p)) {
  5394. p++;
  5395. }
  5396. if (p <= end) {
  5397. auto key_len = key_end - beg;
  5398. if (!key_len) { return false; }
  5399. auto key = std::string(beg, key_end);
  5400. auto val = std::string(p, end);
  5401. if (!detail::fields::is_field_value(val)) { return false; }
  5402. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  5403. // percent-decoded by the recipient. Applications that need to interpret a
  5404. // value as a URI component should call httplib::decode_uri_component()
  5405. // (or decode_path_component()) explicitly.
  5406. fn(key, val);
  5407. return true;
  5408. }
  5409. return false;
  5410. }
  5411. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  5412. const Headers &src_headers) {
  5413. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  5414. // transfer coding is complete when a chunk with a chunk-size of zero is
  5415. // received, possibly followed by a trailer section, and finally terminated by
  5416. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  5417. //
  5418. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  5419. // doesn't care for the existence of the final CRLF. In other words, it seems
  5420. // to be ok whether the final CRLF exists or not in the chunked data.
  5421. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  5422. //
  5423. // According to the reference code in RFC 9112, cpp-httplib now allows
  5424. // chunked transfer coding data without the final CRLF.
  5425. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  5426. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  5427. "transfer-encoding",
  5428. "content-length",
  5429. "host",
  5430. "authorization",
  5431. "www-authenticate",
  5432. "proxy-authenticate",
  5433. "proxy-authorization",
  5434. "cookie",
  5435. "set-cookie",
  5436. "cache-control",
  5437. "expect",
  5438. "max-forwards",
  5439. "pragma",
  5440. "range",
  5441. "te",
  5442. "age",
  5443. "expires",
  5444. "date",
  5445. "location",
  5446. "retry-after",
  5447. "vary",
  5448. "warning",
  5449. "content-encoding",
  5450. "content-type",
  5451. "content-range",
  5452. "trailer"};
  5453. case_ignore::unordered_set<std::string> declared_trailers;
  5454. auto trailer_header = get_combined_header_value(src_headers, "Trailer");
  5455. if (!trailer_header.empty()) {
  5456. // split() trims each token and skips empty ones, so the name arrives ready
  5457. // to look up.
  5458. split(trailer_header.data(), trailer_header.data() + trailer_header.size(),
  5459. ',', [&](const char *b, const char *e) {
  5460. // A legitimate message declares only a handful of trailers. Cap the
  5461. // set so a peer cannot grow it without bound: an oversized set only
  5462. // arises from an attempt to force many colliding names into
  5463. // quadratic lookups (case_ignore::hash is unkeyed).
  5464. if (declared_trailers.size() >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  5465. return;
  5466. }
  5467. std::string key(b, e);
  5468. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  5469. declared_trailers.insert(key);
  5470. }
  5471. });
  5472. }
  5473. size_t trailer_header_count = 0;
  5474. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  5475. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5476. // Count every received trailer field, not only the declared ones stored in
  5477. // dest, so undeclared fields cannot keep this loop running past the limit.
  5478. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5479. constexpr auto line_terminator_len = 2;
  5480. auto line_beg = line_reader.ptr();
  5481. auto line_end =
  5482. line_reader.ptr() + line_reader.size() - line_terminator_len;
  5483. if (!parse_header(line_beg, line_end,
  5484. [&](const std::string &key, const std::string &val) {
  5485. if (declared_trailers.find(key) !=
  5486. declared_trailers.end()) {
  5487. dest.emplace(key, val);
  5488. }
  5489. })) {
  5490. return false;
  5491. }
  5492. trailer_header_count++;
  5493. if (!line_reader.getline()) { return false; }
  5494. }
  5495. return true;
  5496. }
  5497. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  5498. size_t right) {
  5499. while (b + left < e && is_space_or_tab(b[left])) {
  5500. left++;
  5501. }
  5502. while (right > 0 && is_space_or_tab(b[right - 1])) {
  5503. right--;
  5504. }
  5505. return std::make_pair(left, right);
  5506. }
  5507. inline std::string trim_copy(const std::string &s) {
  5508. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  5509. return s.substr(r.first, r.second - r.first);
  5510. }
  5511. inline std::string trim_double_quotes_copy(const std::string &s) {
  5512. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  5513. return s.substr(1, s.size() - 2);
  5514. }
  5515. return s;
  5516. }
  5517. // Takes the quotes off a parameter value. Only \" and \\ are quoted-pairs
  5518. // here, as browsers send any other backslash, such as one in a Windows path,
  5519. // as it is.
  5520. inline std::string unquote_param(const std::string &s) {
  5521. if (s.size() < 2 || s.front() != '"' || s.back() != '"') { return s; }
  5522. std::string out;
  5523. for (size_t i = 1; i + 1 < s.size(); i++) {
  5524. if (s[i] == '\\' && i + 2 < s.size() &&
  5525. (s[i + 1] == '"' || s[i + 1] == '\\')) {
  5526. i++;
  5527. }
  5528. out += s[i];
  5529. }
  5530. return out;
  5531. }
  5532. inline void
  5533. divide(const char *data, std::size_t size, char d,
  5534. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  5535. fn) {
  5536. const auto it = std::find(data, data + size, d);
  5537. const auto found = static_cast<std::size_t>(it != data + size);
  5538. const auto lhs_data = data;
  5539. const auto lhs_size = static_cast<std::size_t>(it - data);
  5540. const auto rhs_data = it + found;
  5541. const auto rhs_size = size - lhs_size - found;
  5542. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  5543. }
  5544. inline void
  5545. divide(const std::string &str, char d,
  5546. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  5547. fn) {
  5548. divide(str.data(), str.size(), d, std::move(fn));
  5549. }
  5550. inline void split(const char *b, const char *e, char d,
  5551. std::function<void(const char *, const char *)> fn) {
  5552. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  5553. }
  5554. inline void split(const char *b, const char *e, char d, size_t m,
  5555. std::function<void(const char *, const char *)> fn) {
  5556. size_t i = 0;
  5557. size_t beg = 0;
  5558. size_t count = 1;
  5559. while (e ? (b + i < e) : (b[i] != '\0')) {
  5560. if (b[i] == d && count < m) {
  5561. auto r = trim(b, e, beg, i);
  5562. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5563. beg = i + 1;
  5564. count++;
  5565. }
  5566. i++;
  5567. }
  5568. if (i) {
  5569. auto r = trim(b, e, beg, i);
  5570. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5571. }
  5572. }
  5573. // Same contract as split(), except that a delimiter inside a quoted-string is
  5574. // not a delimiter. RFC 9110 Section 5.6.6 lets a parameter value be a
  5575. // quoted-string, and ';' and '=' are legal characters inside one.
  5576. inline void split_unquoted(const char *b, const char *e, char d, size_t m,
  5577. std::function<void(const char *, const char *)> fn) {
  5578. size_t i = 0;
  5579. size_t beg = 0;
  5580. size_t count = 1;
  5581. auto in_quotes = false;
  5582. auto has = [&](size_t j) { return e ? (b + j < e) : (b[j] != '\0'); };
  5583. while (has(i)) {
  5584. if (in_quotes && b[i] == '\\' && has(i + 1)) {
  5585. // A quoted-pair, whose second character does not end the string.
  5586. i++;
  5587. } else if (b[i] == '"') {
  5588. in_quotes = !in_quotes;
  5589. } else if (b[i] == d && !in_quotes && count < m) {
  5590. auto r = trim(b, e, beg, i);
  5591. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5592. beg = i + 1;
  5593. count++;
  5594. }
  5595. i++;
  5596. }
  5597. if (i) {
  5598. auto r = trim(b, e, beg, i);
  5599. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5600. }
  5601. }
  5602. inline void split_unquoted(const char *b, const char *e, char d,
  5603. std::function<void(const char *, const char *)> fn) {
  5604. return split_unquoted(b, e, d, (std::numeric_limits<size_t>::max)(),
  5605. std::move(fn));
  5606. }
  5607. // Divide a header parameter at its first '='. RFC 9110 Section 5.6.6 makes the
  5608. // key a token, so the first '=' is the separator even when the value is a
  5609. // quoted-string carrying more of them.
  5610. inline void divide_param_pair(const char *b, const char *e, std::string &key,
  5611. std::string &val) {
  5612. divide(
  5613. b, static_cast<std::size_t>(e - b), '=',
  5614. [&](const char *kb, std::size_t klen, const char *vb, std::size_t vlen) {
  5615. const auto kr = trim(kb, kb + klen, 0, klen);
  5616. key.assign(kb + kr.first, kb + kr.second);
  5617. const auto vr = trim(vb, vb + vlen, 0, vlen);
  5618. val.assign(vb + vr.first, vb + vr.second);
  5619. });
  5620. }
  5621. inline bool split_find(const char *b, const char *e, char d, size_t m,
  5622. std::function<bool(const char *, const char *)> fn) {
  5623. size_t i = 0;
  5624. size_t beg = 0;
  5625. size_t count = 1;
  5626. while (e ? (b + i < e) : (b[i] != '\0')) {
  5627. if (b[i] == d && count < m) {
  5628. auto r = trim(b, e, beg, i);
  5629. if (r.first < r.second) {
  5630. auto found = fn(&b[r.first], &b[r.second]);
  5631. if (found) { return true; }
  5632. }
  5633. beg = i + 1;
  5634. count++;
  5635. }
  5636. i++;
  5637. }
  5638. if (i) {
  5639. auto r = trim(b, e, beg, i);
  5640. if (r.first < r.second) {
  5641. auto found = fn(&b[r.first], &b[r.second]);
  5642. if (found) { return true; }
  5643. }
  5644. }
  5645. return false;
  5646. }
  5647. inline bool split_find(const char *b, const char *e, char d,
  5648. std::function<bool(const char *, const char *)> fn) {
  5649. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  5650. std::move(fn));
  5651. }
  5652. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  5653. size_t fixed_buffer_size)
  5654. : strm_(strm), fixed_buffer_(fixed_buffer),
  5655. fixed_buffer_size_(fixed_buffer_size) {}
  5656. inline const char *stream_line_reader::ptr() const {
  5657. if (growable_buffer_.empty()) {
  5658. return fixed_buffer_;
  5659. } else {
  5660. return growable_buffer_.data();
  5661. }
  5662. }
  5663. inline size_t stream_line_reader::size() const {
  5664. if (growable_buffer_.empty()) {
  5665. return fixed_buffer_used_size_;
  5666. } else {
  5667. return growable_buffer_.size();
  5668. }
  5669. }
  5670. inline bool stream_line_reader::end_with_crlf() const {
  5671. auto end = ptr() + size();
  5672. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  5673. }
  5674. inline bool stream_line_reader::getline() {
  5675. fixed_buffer_used_size_ = 0;
  5676. growable_buffer_.clear();
  5677. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5678. char prev_byte = 0;
  5679. #endif
  5680. for (size_t i = 0;; i++) {
  5681. // Fast path: whatever the stream has already buffered can be scanned for
  5682. // the terminator in one pass. Asking for a byte at a time costs a virtual
  5683. // call, a bounds check and a one-byte copy per character of the request.
  5684. size_t buffered_size = 0;
  5685. if (auto buffered = strm_.buffered_data(buffered_size)) {
  5686. auto take = buffered_size;
  5687. auto terminated = false;
  5688. for (size_t at = 0; at < buffered_size;) {
  5689. auto nl = static_cast<const char *>(
  5690. memchr(buffered + at, '\n', buffered_size - at));
  5691. if (!nl) { break; }
  5692. auto pos = static_cast<size_t>(nl - buffered);
  5693. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5694. take = pos + 1;
  5695. terminated = true;
  5696. break;
  5697. #else
  5698. // A bare LF does not end the line; keep looking for CRLF. The CR may
  5699. // be the last byte of an earlier chunk, hence prev_byte.
  5700. if ((pos > 0 ? buffered[pos - 1] : prev_byte) == '\r') {
  5701. take = pos + 1;
  5702. terminated = true;
  5703. break;
  5704. }
  5705. at = pos + 1;
  5706. #endif
  5707. }
  5708. if (size() + take > CPPHTTPLIB_MAX_LINE_LENGTH) { return false; }
  5709. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5710. prev_byte = buffered[take - 1];
  5711. #endif
  5712. append(buffered, take);
  5713. strm_.consume_buffered(take);
  5714. i += take;
  5715. if (terminated) { return true; }
  5716. continue;
  5717. }
  5718. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  5719. // Treat exceptionally long lines as an error to
  5720. // prevent infinite loops/memory exhaustion
  5721. return false;
  5722. }
  5723. char byte;
  5724. auto n = strm_.read(&byte, 1);
  5725. if (n < 0) {
  5726. return false;
  5727. } else if (n == 0) {
  5728. if (i == 0) {
  5729. return false;
  5730. } else {
  5731. break;
  5732. }
  5733. }
  5734. append(byte);
  5735. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5736. if (byte == '\n') { break; }
  5737. #else
  5738. if (prev_byte == '\r' && byte == '\n') { break; }
  5739. prev_byte = byte;
  5740. #endif
  5741. }
  5742. return true;
  5743. }
  5744. inline void stream_line_reader::append(char c) { append(&c, 1); }
  5745. inline void stream_line_reader::append(const char *data, size_t size) {
  5746. // Once the line has outgrown the fixed buffer everything must keep going to
  5747. // the growable one, even if a later chunk would have fit. Without the
  5748. // emptiness check a short append after a long one would land in the fixed
  5749. // buffer, which ptr() and size() no longer look at, and be lost.
  5750. if (growable_buffer_.empty() &&
  5751. fixed_buffer_used_size_ + size < fixed_buffer_size_) {
  5752. memcpy(fixed_buffer_ + fixed_buffer_used_size_, data, size);
  5753. fixed_buffer_used_size_ += size;
  5754. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  5755. } else {
  5756. // Unlike the per-character overload, this can be the very first append of
  5757. // the line, so the fixed buffer may hold nothing and carry no terminator
  5758. // yet. assign() takes an explicit length and does not need one.
  5759. if (growable_buffer_.empty()) {
  5760. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  5761. }
  5762. growable_buffer_.append(data, size);
  5763. }
  5764. }
  5765. inline mmap::mmap(const char *path) { open(path); }
  5766. inline mmap::~mmap() { close(); }
  5767. inline bool mmap::open(const char *path) {
  5768. close();
  5769. #if defined(_WIN32)
  5770. auto wpath = u8string_to_wstring(path);
  5771. if (wpath.empty()) { return false; }
  5772. hFile_ =
  5773. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  5774. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  5775. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  5776. LARGE_INTEGER size{};
  5777. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  5778. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  5779. // See:
  5780. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  5781. if (!fits_in_size_t(static_cast<uint64_t>(size.QuadPart))) { return false; }
  5782. size_ = static_cast<size_t>(size.QuadPart);
  5783. hMapping_ =
  5784. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  5785. // Special treatment for an empty file...
  5786. if (hMapping_ == NULL && size_ == 0) {
  5787. close();
  5788. is_open_empty_file = true;
  5789. return true;
  5790. }
  5791. if (hMapping_ == NULL) {
  5792. close();
  5793. return false;
  5794. }
  5795. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  5796. if (addr_ == nullptr) {
  5797. close();
  5798. return false;
  5799. }
  5800. #else
  5801. // O_NONBLOCK so that opening a FIFO does not wait for a writer.
  5802. fd_ = ::open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
  5803. if (fd_ == -1) { return false; }
  5804. // Only a regular file has a size to serve, unlike a directory or a device.
  5805. struct stat sb;
  5806. if (fstat(fd_, &sb) == -1 || !S_ISREG(sb.st_mode) ||
  5807. !fits_in_size_t(static_cast<uint64_t>(sb.st_size))) {
  5808. close();
  5809. return false;
  5810. }
  5811. size_ = static_cast<size_t>(sb.st_size);
  5812. #endif
  5813. return true;
  5814. }
  5815. inline bool mmap::is_open() const {
  5816. #if defined(_WIN32)
  5817. return is_open_empty_file ? true : addr_ != nullptr;
  5818. #else
  5819. return fd_ != -1;
  5820. #endif
  5821. }
  5822. inline size_t mmap::size() const { return size_; }
  5823. inline void mmap::close() {
  5824. #if defined(_WIN32)
  5825. if (addr_) {
  5826. ::UnmapViewOfFile(addr_);
  5827. addr_ = nullptr;
  5828. }
  5829. if (hMapping_) {
  5830. ::CloseHandle(hMapping_);
  5831. hMapping_ = NULL;
  5832. }
  5833. if (hFile_ != INVALID_HANDLE_VALUE) {
  5834. ::CloseHandle(hFile_);
  5835. hFile_ = INVALID_HANDLE_VALUE;
  5836. }
  5837. is_open_empty_file = false;
  5838. #else
  5839. if (fd_ != -1) {
  5840. ::close(fd_);
  5841. fd_ = -1;
  5842. }
  5843. #endif
  5844. size_ = 0;
  5845. }
  5846. inline int close_socket(socket_t sock) noexcept {
  5847. #ifdef _WIN32
  5848. return closesocket(sock);
  5849. #else
  5850. return close(sock);
  5851. #endif
  5852. }
  5853. template <typename T> inline ssize_t handle_EINTR(T fn) {
  5854. ssize_t res = 0;
  5855. while (true) {
  5856. res = fn();
  5857. if (res < 0 && errno == EINTR) {
  5858. std::this_thread::sleep_for(std::chrono::microseconds{1});
  5859. continue;
  5860. }
  5861. break;
  5862. }
  5863. return res;
  5864. }
  5865. inline size_t mmap::read(size_t offset, char *buf, size_t len) const {
  5866. if (offset >= size_) { return 0; }
  5867. len = (std::min)(len, size_ - offset);
  5868. #if defined(_WIN32)
  5869. // Windows does not let a mapped file be truncated.
  5870. std::memcpy(buf, static_cast<const char *>(addr_) + offset, len);
  5871. return len;
  5872. #else
  5873. auto n = handle_EINTR(
  5874. [&]() { return ::pread(fd_, buf, len, static_cast<off_t>(offset)); });
  5875. return n > 0 ? static_cast<size_t>(n) : 0;
  5876. #endif
  5877. }
  5878. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  5879. return handle_EINTR([&]() {
  5880. return recv(sock,
  5881. #ifdef _WIN32
  5882. static_cast<char *>(ptr), static_cast<int>(size),
  5883. #else
  5884. ptr, size,
  5885. #endif
  5886. flags);
  5887. });
  5888. }
  5889. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  5890. int flags) {
  5891. return handle_EINTR([&]() {
  5892. return send(sock,
  5893. #ifdef _WIN32
  5894. static_cast<const char *>(ptr), static_cast<int>(size),
  5895. #else
  5896. ptr, size,
  5897. #endif
  5898. flags);
  5899. });
  5900. }
  5901. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  5902. #ifdef _WIN32
  5903. return ::WSAPoll(fds, nfds, timeout);
  5904. #else
  5905. return ::poll(fds, nfds, timeout);
  5906. #endif
  5907. }
  5908. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  5909. time_t usec) {
  5910. struct pollfd pfd;
  5911. pfd.fd = sock;
  5912. pfd.events = events;
  5913. pfd.revents = 0;
  5914. // A negative timeout waits forever, poll's own convention. 0 keeps meaning
  5915. // "return immediately", which callers here rely on to probe a socket.
  5916. auto timeout = sec < 0 ? -1 : static_cast<int>(sec * 1000 + usec / 1000);
  5917. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  5918. }
  5919. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  5920. return select_impl(sock, POLLIN, sec, usec);
  5921. }
  5922. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  5923. return select_impl(sock, POLLOUT, sec, usec);
  5924. }
  5925. // The point sec and usec from now, for select_until(). A negative sec, or one
  5926. // past what the clock reaches, never comes.
  5927. inline std::chrono::steady_clock::time_point deadline_after(time_t sec,
  5928. time_t usec) {
  5929. auto now = std::chrono::steady_clock::now();
  5930. auto never = (std::chrono::steady_clock::time_point::max)();
  5931. if (sec < 0 ||
  5932. sec >= std::chrono::duration_cast<std::chrono::seconds>(never - now)
  5933. .count()) {
  5934. return never;
  5935. }
  5936. return now + std::chrono::seconds(sec) + std::chrono::microseconds(usec);
  5937. }
  5938. // Waits only for the time left until deadline, so that all the waits of one
  5939. // TLS handshake come out of a single timeout. With interrupted, it waits in
  5940. // slices and gives up once interrupted() returns true, as a local shutdown()
  5941. // would not wake the wait on Windows.
  5942. inline ssize_t
  5943. select_until(socket_t sock, short events,
  5944. std::chrono::steady_clock::time_point deadline,
  5945. const std::function<bool()> &interrupted = nullptr) {
  5946. if (!interrupted) {
  5947. if (deadline == (std::chrono::steady_clock::time_point::max)()) {
  5948. return select_impl(sock, events, -1, 0);
  5949. }
  5950. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  5951. deadline - std::chrono::steady_clock::now())
  5952. .count();
  5953. if (left <= 0) { return 0; }
  5954. return select_impl(sock, events, static_cast<time_t>(left / 1000000),
  5955. static_cast<time_t>(left % 1000000));
  5956. }
  5957. const auto slice = std::chrono::microseconds(100000);
  5958. while (!interrupted()) {
  5959. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  5960. deadline - std::chrono::steady_clock::now());
  5961. auto last = left < slice;
  5962. // poll() takes whole milliseconds, so round the last wait up to keep it
  5963. // from ending before the deadline.
  5964. auto wait_usec = last ? (std::max)((left.count() + 999) / 1000 * 1000,
  5965. static_cast<decltype(left.count())>(0))
  5966. : slice.count();
  5967. auto ret = select_impl(sock, events, 0, static_cast<time_t>(wait_usec));
  5968. if (ret != 0 || last) { return ret; }
  5969. }
  5970. return 0;
  5971. }
  5972. // select_impl(), but waits in slices and gives up once interrupted() returns
  5973. // true
  5974. inline ssize_t select_interruptible(socket_t sock, short events, time_t sec,
  5975. time_t usec,
  5976. const std::function<bool()> &interrupted) {
  5977. if (!interrupted) { return select_impl(sock, events, sec, usec); }
  5978. return select_until(sock, events, deadline_after(sec, usec), interrupted);
  5979. }
  5980. inline ssize_t
  5981. select_read_interruptible(socket_t sock, time_t sec, time_t usec,
  5982. const std::function<bool()> &interrupted) {
  5983. return select_interruptible(sock, POLLIN, sec, usec, interrupted);
  5984. }
  5985. // Waits for a connect in progress, which ends as Error::Canceled once
  5986. // interrupted() returns true
  5987. inline Error
  5988. wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec,
  5989. const std::function<bool()> &interrupted = nullptr) {
  5990. auto ret =
  5991. select_interruptible(sock, POLLIN | POLLOUT, sec, usec, interrupted);
  5992. if (ret == 0) {
  5993. return interrupted && interrupted() ? Error::Canceled
  5994. : Error::ConnectionTimeout;
  5995. }
  5996. if (ret < 0) { return Error::Connection; }
  5997. // A failed connect reports its error here, whatever events poll() returned
  5998. auto error = 0;
  5999. socklen_t len = sizeof(error);
  6000. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  6001. reinterpret_cast<char *>(&error), &len);
  6002. return res >= 0 && !error ? Error::Success : Error::Connection;
  6003. }
  6004. inline bool is_socket_alive(socket_t sock) {
  6005. const auto val = detail::select_read(sock, 0, 0);
  6006. if (val == 0) {
  6007. return true;
  6008. } else if (val < 0 && errno == EBADF) {
  6009. return false;
  6010. }
  6011. char buf[1];
  6012. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  6013. }
  6014. class SocketStream final : public Stream {
  6015. public:
  6016. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6017. time_t write_timeout_sec, time_t write_timeout_usec,
  6018. time_t max_timeout_msec = 0,
  6019. std::chrono::time_point<std::chrono::steady_clock> start_time =
  6020. (std::chrono::steady_clock::time_point::min)());
  6021. ~SocketStream() override;
  6022. bool is_readable() const override;
  6023. bool wait_readable() const override;
  6024. bool wait_writable() const override;
  6025. bool is_peer_alive() const override;
  6026. ssize_t read(char *ptr, size_t size) override;
  6027. ssize_t write(const char *ptr, size_t size) override;
  6028. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  6029. void get_local_ip_and_port(std::string &ip, int &port) const override;
  6030. socket_t socket() const override;
  6031. time_t duration() const override;
  6032. void set_read_timeout(time_t sec, time_t usec = 0) override;
  6033. void set_max_timeout(time_t msec) override;
  6034. void set_read_interrupt(std::function<bool()> interrupted) override;
  6035. const char *buffered_data(size_t &size) const override;
  6036. void consume_buffered(size_t size) override;
  6037. // The caller has just seen this socket become readable. Lets the next read
  6038. // skip its own readiness wait, which would otherwise ask the kernel a
  6039. // question that was answered a moment ago. Consumed by that read.
  6040. void set_readable_hint() { readable_hint_ = true; }
  6041. // Frees the read buffer of an idle stream until its next read. Nothing may
  6042. // be buffered.
  6043. void release_buffer();
  6044. private:
  6045. bool ensure_readable();
  6046. socket_t sock_;
  6047. // Atomic because ws::WebSocket::set_read_timeout() reaches this from another
  6048. // thread while a read is in flight -- that is the point of it, for a caller
  6049. // holding one connection and wanting control back to send on it.
  6050. std::atomic<time_t> read_timeout_sec_;
  6051. std::atomic<time_t> read_timeout_usec_;
  6052. time_t write_timeout_sec_;
  6053. time_t write_timeout_usec_;
  6054. time_t max_timeout_msec_;
  6055. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  6056. std::function<bool()> read_interrupted_;
  6057. std::vector<char> read_buff_;
  6058. size_t read_buff_off_ = 0;
  6059. size_t read_buff_content_size_ = 0;
  6060. bool readable_hint_ = false;
  6061. static const size_t read_buff_size_ = 1024l * 4;
  6062. };
  6063. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  6064. time_t keep_alive_timeout_sec) {
  6065. using namespace std::chrono;
  6066. const auto interval_usec =
  6067. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  6068. // Avoid expensive `steady_clock::now()` call for the first time
  6069. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  6070. const auto start = steady_clock::now() - microseconds{interval_usec};
  6071. const auto timeout = seconds{keep_alive_timeout_sec};
  6072. while (true) {
  6073. if (svr_sock == INVALID_SOCKET) {
  6074. break; // Server socket is closed
  6075. }
  6076. auto val = select_read(sock, 0, interval_usec);
  6077. if (val < 0) {
  6078. break; // Ssocket error
  6079. } else if (val == 0) {
  6080. if (steady_clock::now() - start > timeout) {
  6081. break; // Timeout
  6082. }
  6083. } else {
  6084. return true; // Ready for read
  6085. }
  6086. }
  6087. return false;
  6088. }
  6089. // Serves the requests of one connection while they come. A client may
  6090. // pipeline its requests (RFC 9112 9.3.2), so reading one request can pull the
  6091. // start of the next one into the stream's buffer; that request must be served
  6092. // without waiting for the socket to become readable again, since its bytes are
  6093. // no longer on the socket. Otherwise `wait_for_next_request` waits for the
  6094. // socket, and returning false ends the loop. `served` counts the requests
  6095. // served on this connection so far.
  6096. template <typename S, typename W, typename T>
  6097. inline bool process_server_socket_core(S &strm, size_t &served,
  6098. size_t keep_alive_max_count,
  6099. W wait_for_next_request, T callback) {
  6100. auto ret = false;
  6101. // A keep_alive_max_count of 0 sets no limit.
  6102. for (; keep_alive_max_count == 0 || served < keep_alive_max_count; served++) {
  6103. if (!strm.is_readable()) {
  6104. if (!wait_for_next_request()) { break; }
  6105. strm.set_readable_hint();
  6106. }
  6107. auto close_connection = served + 1 == keep_alive_max_count;
  6108. auto connection_closed = false;
  6109. ret = callback(strm, close_connection, connection_closed);
  6110. if (!ret || connection_closed) { break; }
  6111. }
  6112. return ret;
  6113. }
  6114. template <typename T>
  6115. inline bool
  6116. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  6117. size_t keep_alive_max_count,
  6118. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  6119. time_t read_timeout_usec, time_t write_timeout_sec,
  6120. time_t write_timeout_usec, T callback) {
  6121. // One stream per connection: its read buffer can already hold the start of
  6122. // the next, pipelined request.
  6123. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  6124. write_timeout_sec, write_timeout_usec);
  6125. size_t served = 0;
  6126. return process_server_socket_core(
  6127. strm, served, keep_alive_max_count,
  6128. [&]() { return keep_alive(svr_sock, sock, keep_alive_timeout_sec); },
  6129. callback);
  6130. }
  6131. inline bool process_client_socket(
  6132. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6133. time_t write_timeout_sec, time_t write_timeout_usec,
  6134. time_t max_timeout_msec,
  6135. std::chrono::time_point<std::chrono::steady_clock> start_time,
  6136. std::function<bool(Stream &)> callback) {
  6137. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  6138. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  6139. start_time);
  6140. return callback(strm);
  6141. }
  6142. inline int shutdown_socket(socket_t sock) noexcept {
  6143. #ifdef _WIN32
  6144. return shutdown(sock, SD_BOTH);
  6145. #else
  6146. return shutdown(sock, SHUT_RDWR);
  6147. #endif
  6148. }
  6149. // Half-closes the write side and drains any in-flight/queued bytes before
  6150. // the final shutdown+close. Closing with unread data in the receive queue
  6151. // (or bytes arriving after the receive side is closed) makes the stack send
  6152. // an abortive RST instead of a graceful FIN, which can make the peer see the
  6153. // response as a failed read even though it was fully written. With a
  6154. // `wait_msec` of 0, it reads once, without waiting.
  6155. inline void drain_and_close_socket(socket_t sock,
  6156. time_t wait_msec = 100) noexcept {
  6157. #ifdef _WIN32
  6158. shutdown(sock, SD_SEND);
  6159. #else
  6160. shutdown(sock, SHUT_WR);
  6161. #endif
  6162. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6163. size_t total = 0;
  6164. const auto deadline = std::chrono::steady_clock::now() +
  6165. std::chrono::milliseconds(wait_msec); // bound #1
  6166. auto usec_left = [&]() {
  6167. const auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  6168. deadline - std::chrono::steady_clock::now())
  6169. .count();
  6170. return static_cast<time_t>(
  6171. (std::max)(left, std::chrono::microseconds::rep(0)));
  6172. };
  6173. do {
  6174. if (select_read(sock, 0, usec_left()) <= 0) { break; }
  6175. const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  6176. if (n <= 0) { break; }
  6177. total += static_cast<size_t>(n);
  6178. } while (usec_left() > 0 && total < size_t(1024u * 1024u)); // bound #2
  6179. shutdown_socket(sock);
  6180. close_socket(sock);
  6181. }
  6182. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  6183. if (s.size() > 1 && s[0] == '\0') {
  6184. auto ret = s;
  6185. ret[0] = '@';
  6186. return ret;
  6187. }
  6188. return s;
  6189. }
  6190. inline std::string
  6191. unescape_abstract_namespace_unix_domain(const std::string &s) {
  6192. if (s.size() > 1 && s[0] == '@') {
  6193. auto ret = s;
  6194. ret[0] = '\0';
  6195. return ret;
  6196. }
  6197. return s;
  6198. }
  6199. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  6200. const struct addrinfo *hints,
  6201. struct addrinfo **res, time_t timeout_sec) {
  6202. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  6203. if (timeout_sec <= 0) {
  6204. // No timeout specified, use standard getaddrinfo
  6205. return getaddrinfo(node, service, hints, res);
  6206. }
  6207. #ifdef _WIN32
  6208. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  6209. OVERLAPPED overlapped = {};
  6210. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  6211. if (!event) { return EAI_FAIL; }
  6212. overlapped.hEvent = event;
  6213. PADDRINFOEXW result_addrinfo = nullptr;
  6214. HANDLE cancel_handle = nullptr;
  6215. ADDRINFOEXW hints_ex = {};
  6216. if (hints) {
  6217. hints_ex.ai_flags = hints->ai_flags;
  6218. hints_ex.ai_family = hints->ai_family;
  6219. hints_ex.ai_socktype = hints->ai_socktype;
  6220. hints_ex.ai_protocol = hints->ai_protocol;
  6221. }
  6222. auto wnode = u8string_to_wstring(node);
  6223. auto wservice = u8string_to_wstring(service);
  6224. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  6225. hints ? &hints_ex : nullptr, &result_addrinfo,
  6226. nullptr, &overlapped, nullptr, &cancel_handle);
  6227. if (ret == WSA_IO_PENDING) {
  6228. auto wait_result =
  6229. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  6230. if (wait_result == WAIT_TIMEOUT) {
  6231. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  6232. ::CloseHandle(event);
  6233. return EAI_AGAIN;
  6234. }
  6235. DWORD bytes_returned;
  6236. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  6237. &bytes_returned, FALSE)) {
  6238. ::CloseHandle(event);
  6239. return ::WSAGetLastError();
  6240. }
  6241. }
  6242. ::CloseHandle(event);
  6243. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  6244. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  6245. return 0;
  6246. }
  6247. return ret;
  6248. #elif TARGET_OS_MAC && defined(__clang__)
  6249. if (!node) { return EAI_NONAME; }
  6250. // macOS implementation using CFHost API for asynchronous DNS resolution
  6251. CFStringRef hostname_ref = CFStringCreateWithCString(
  6252. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  6253. if (!hostname_ref) { return EAI_MEMORY; }
  6254. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  6255. CFRelease(hostname_ref);
  6256. if (!host_ref) { return EAI_MEMORY; }
  6257. // Set up context for callback
  6258. struct CFHostContext {
  6259. bool completed = false;
  6260. bool success = false;
  6261. CFArrayRef addresses = nullptr;
  6262. std::mutex mutex;
  6263. std::condition_variable cv;
  6264. } context;
  6265. CFHostClientContext client_context;
  6266. memset(&client_context, 0, sizeof(client_context));
  6267. client_context.info = &context;
  6268. // Set callback
  6269. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  6270. const CFStreamError *error, void *info) {
  6271. auto ctx = static_cast<CFHostContext *>(info);
  6272. std::lock_guard<std::mutex> lock(ctx->mutex);
  6273. if (error && error->error != 0) {
  6274. ctx->success = false;
  6275. } else {
  6276. Boolean hasBeenResolved;
  6277. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  6278. if (ctx->addresses && hasBeenResolved) {
  6279. CFRetain(ctx->addresses);
  6280. ctx->success = true;
  6281. } else {
  6282. ctx->success = false;
  6283. }
  6284. }
  6285. ctx->completed = true;
  6286. ctx->cv.notify_one();
  6287. };
  6288. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  6289. CFRelease(host_ref);
  6290. return EAI_SYSTEM;
  6291. }
  6292. // Schedule on run loop
  6293. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  6294. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  6295. // Start resolution
  6296. CFStreamError stream_error;
  6297. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  6298. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  6299. CFRelease(host_ref);
  6300. return EAI_FAIL;
  6301. }
  6302. // Wait for completion with timeout
  6303. auto timeout_time =
  6304. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  6305. bool timed_out = false;
  6306. {
  6307. std::unique_lock<std::mutex> lock(context.mutex);
  6308. while (!context.completed) {
  6309. auto now = std::chrono::steady_clock::now();
  6310. if (now >= timeout_time) {
  6311. timed_out = true;
  6312. break;
  6313. }
  6314. // Run the runloop for a short time
  6315. lock.unlock();
  6316. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  6317. lock.lock();
  6318. }
  6319. }
  6320. // Clean up
  6321. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  6322. CFHostSetClient(host_ref, nullptr, nullptr);
  6323. if (timed_out || !context.completed) {
  6324. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  6325. CFRelease(host_ref);
  6326. return EAI_AGAIN;
  6327. }
  6328. if (!context.success || !context.addresses) {
  6329. CFRelease(host_ref);
  6330. return EAI_NODATA;
  6331. }
  6332. // Convert CFArray to addrinfo
  6333. CFIndex count = CFArrayGetCount(context.addresses);
  6334. if (count == 0) {
  6335. CFRelease(context.addresses);
  6336. CFRelease(host_ref);
  6337. return EAI_NODATA;
  6338. }
  6339. struct addrinfo *result_addrinfo = nullptr;
  6340. struct addrinfo **current = &result_addrinfo;
  6341. for (CFIndex i = 0; i < count; i++) {
  6342. CFDataRef addr_data =
  6343. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  6344. if (!addr_data) continue;
  6345. const struct sockaddr *sockaddr_ptr =
  6346. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  6347. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  6348. // Allocate addrinfo structure
  6349. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  6350. if (!*current) {
  6351. freeaddrinfo(result_addrinfo);
  6352. CFRelease(context.addresses);
  6353. CFRelease(host_ref);
  6354. return EAI_MEMORY;
  6355. }
  6356. memset(*current, 0, sizeof(struct addrinfo));
  6357. // Set up addrinfo fields
  6358. (*current)->ai_family = sockaddr_ptr->sa_family;
  6359. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  6360. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  6361. (*current)->ai_addrlen = sockaddr_len;
  6362. // Copy sockaddr
  6363. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  6364. if (!(*current)->ai_addr) {
  6365. freeaddrinfo(result_addrinfo);
  6366. CFRelease(context.addresses);
  6367. CFRelease(host_ref);
  6368. return EAI_MEMORY;
  6369. }
  6370. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  6371. // Set port if service is specified
  6372. if (service && *service) {
  6373. int port = 0;
  6374. if (parse_port(service, strlen(service), port)) {
  6375. if (sockaddr_ptr->sa_family == AF_INET) {
  6376. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  6377. ->sin_port = htons(static_cast<uint16_t>(port));
  6378. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  6379. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  6380. ->sin6_port = htons(static_cast<uint16_t>(port));
  6381. }
  6382. }
  6383. }
  6384. current = &((*current)->ai_next);
  6385. }
  6386. CFRelease(context.addresses);
  6387. CFRelease(host_ref);
  6388. *res = result_addrinfo;
  6389. return 0;
  6390. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  6391. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) && \
  6392. !defined(CPPHTTPLIB_THREAD_SANITIZER)
  6393. // Skipped under TSan: glibc's internal resolver thread is invisible to it.
  6394. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  6395. // the resolver worker still references the stack-local gaicb. The cancel
  6396. // path therefore waits (gai_suspend with no timeout) for the worker to
  6397. // actually finish before letting the stack frame go. The trade-off is that
  6398. // a wedged DNS server can hold this thread for the system resolver timeout
  6399. // (~30s by default) past the caller's connection timeout.
  6400. struct gaicb request{};
  6401. struct gaicb *requests[1] = {&request};
  6402. struct sigevent sevp{};
  6403. struct timespec timeout{timeout_sec, 0};
  6404. request.ar_name = node;
  6405. request.ar_service = service;
  6406. request.ar_request = hints;
  6407. sevp.sigev_notify = SIGEV_NONE;
  6408. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  6409. if (rc != 0) { return rc; }
  6410. auto cleanup = scope_exit([&] {
  6411. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  6412. });
  6413. int wait_result = gai_suspend(requests, 1, &timeout);
  6414. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  6415. int gai_result = gai_error(&request);
  6416. if (gai_result == 0) {
  6417. *res = request.ar_result;
  6418. request.ar_result = nullptr;
  6419. return 0;
  6420. }
  6421. return gai_result;
  6422. }
  6423. gai_cancel(&request);
  6424. while (gai_error(&request) == EAI_INPROGRESS) {
  6425. gai_suspend(requests, 1, nullptr);
  6426. }
  6427. return wait_result;
  6428. #else
  6429. // Fallback implementation using thread-based timeout for other Unix systems.
  6430. struct GetAddrInfoState {
  6431. ~GetAddrInfoState() {
  6432. if (info) { freeaddrinfo(info); }
  6433. }
  6434. std::mutex mutex;
  6435. std::condition_variable result_cv;
  6436. bool completed = false;
  6437. int result = EAI_SYSTEM;
  6438. std::string node;
  6439. std::string service;
  6440. struct addrinfo hints;
  6441. struct addrinfo *info = nullptr;
  6442. };
  6443. // Allocate on the heap, so the resolver thread can keep using the data.
  6444. auto state = std::make_shared<GetAddrInfoState>();
  6445. if (node) { state->node = node; }
  6446. state->service = service;
  6447. state->hints = *hints;
  6448. std::thread resolve_thread([state]() {
  6449. auto thread_result =
  6450. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  6451. &state->info);
  6452. std::lock_guard<std::mutex> lock(state->mutex);
  6453. state->result = thread_result;
  6454. state->completed = true;
  6455. state->result_cv.notify_one();
  6456. });
  6457. // Wait for completion or timeout
  6458. std::unique_lock<std::mutex> lock(state->mutex);
  6459. auto finished =
  6460. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  6461. [&] { return state->completed; });
  6462. if (finished) {
  6463. // Operation completed within timeout
  6464. resolve_thread.join();
  6465. *res = state->info;
  6466. state->info = nullptr; // Pass ownership to caller
  6467. return state->result;
  6468. } else {
  6469. // Timeout occurred
  6470. resolve_thread.detach(); // Let the thread finish in background
  6471. return EAI_AGAIN; // Return timeout error
  6472. }
  6473. #endif
  6474. #else
  6475. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  6476. return getaddrinfo(node, service, hints, res);
  6477. #endif
  6478. }
  6479. template <typename BindOrConnect>
  6480. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  6481. int address_family, int socket_flags, bool tcp_nodelay,
  6482. bool ipv6_v6only, SocketOptions socket_options,
  6483. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  6484. // Get address info
  6485. const char *node = nullptr;
  6486. struct addrinfo hints;
  6487. struct addrinfo *result;
  6488. memset(&hints, 0, sizeof(struct addrinfo));
  6489. hints.ai_socktype = SOCK_STREAM;
  6490. hints.ai_protocol = IPPROTO_IP;
  6491. if (!ip.empty()) {
  6492. node = ip.c_str();
  6493. // Ask getaddrinfo to convert IP in c-string to address
  6494. hints.ai_family = AF_UNSPEC;
  6495. hints.ai_flags = AI_NUMERICHOST;
  6496. } else {
  6497. if (!host.empty()) { node = host.c_str(); }
  6498. hints.ai_family = address_family;
  6499. hints.ai_flags = socket_flags;
  6500. }
  6501. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  6502. if (hints.ai_family == AF_UNIX) {
  6503. const auto addrlen = host.length();
  6504. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  6505. #ifdef SOCK_CLOEXEC
  6506. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  6507. hints.ai_protocol);
  6508. #else
  6509. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  6510. #endif
  6511. if (sock != INVALID_SOCKET) {
  6512. sockaddr_un addr{};
  6513. addr.sun_family = AF_UNIX;
  6514. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  6515. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  6516. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  6517. hints.ai_addrlen = static_cast<socklen_t>(
  6518. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  6519. #ifndef SOCK_CLOEXEC
  6520. #ifndef _WIN32
  6521. fcntl(sock, F_SETFD, FD_CLOEXEC);
  6522. #endif
  6523. #endif
  6524. if (socket_options) { socket_options(sock); }
  6525. #ifdef _WIN32
  6526. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  6527. // remove the option.
  6528. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  6529. #endif
  6530. bool dummy;
  6531. if (!bind_or_connect(sock, hints, dummy)) {
  6532. close_socket(sock);
  6533. sock = INVALID_SOCKET;
  6534. }
  6535. }
  6536. return sock;
  6537. }
  6538. #endif
  6539. auto service = std::to_string(port);
  6540. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  6541. timeout_sec)) {
  6542. #if defined __linux__ && !defined __ANDROID__
  6543. res_init();
  6544. #endif
  6545. return INVALID_SOCKET;
  6546. }
  6547. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6548. for (auto rp = result; rp; rp = rp->ai_next) {
  6549. // Create a socket
  6550. #ifdef _WIN32
  6551. auto sock =
  6552. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  6553. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  6554. /**
  6555. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  6556. * and above the socket creation fails on older Windows Systems.
  6557. *
  6558. * Let's try to create a socket the old way in this case.
  6559. *
  6560. * Reference:
  6561. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  6562. *
  6563. * WSA_FLAG_NO_HANDLE_INHERIT:
  6564. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  6565. * SP1, and later
  6566. *
  6567. */
  6568. if (sock == INVALID_SOCKET) {
  6569. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  6570. }
  6571. #else
  6572. #ifdef SOCK_CLOEXEC
  6573. auto sock =
  6574. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  6575. #else
  6576. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  6577. #endif
  6578. #endif
  6579. if (sock == INVALID_SOCKET) { continue; }
  6580. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  6581. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  6582. close_socket(sock);
  6583. continue;
  6584. }
  6585. #endif
  6586. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  6587. if (rp->ai_family == AF_INET6) {
  6588. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  6589. }
  6590. if (socket_options) { socket_options(sock); }
  6591. // bind or connect
  6592. auto quit = false;
  6593. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  6594. close_socket(sock);
  6595. if (quit) { break; }
  6596. }
  6597. return INVALID_SOCKET;
  6598. }
  6599. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  6600. #ifdef _WIN32
  6601. auto flags = nonblocking ? 1UL : 0UL;
  6602. ioctlsocket(sock, FIONBIO, &flags);
  6603. #else
  6604. auto flags = fcntl(sock, F_GETFL, 0);
  6605. fcntl(sock, F_SETFL,
  6606. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  6607. #endif
  6608. }
  6609. inline bool is_connection_error() {
  6610. #ifdef _WIN32
  6611. return WSAGetLastError() != WSAEWOULDBLOCK;
  6612. #else
  6613. return errno != EINPROGRESS;
  6614. #endif
  6615. }
  6616. // accept() failed because the process or the network stack is temporarily out
  6617. // of resources. The listening socket is still usable, so back off briefly and
  6618. // try again.
  6619. inline bool is_accept_resource_error() {
  6620. #ifdef _WIN32
  6621. auto err = WSAGetLastError();
  6622. return err == WSAEMFILE || err == WSAENOBUFS;
  6623. #else
  6624. auto err = errno;
  6625. return err == EMFILE || err == ENFILE || err == ENOBUFS || err == ENOMEM;
  6626. #endif
  6627. }
  6628. // accept() failed for a reason that says nothing about the listening socket:
  6629. // the pending connection went away before it could be accepted, or the call
  6630. // was interrupted. Retry immediately. WSAAccept()'s own documentation omits
  6631. // WSAECONNRESET, but the accept() it wraps reports an aborted pending
  6632. // connection that way.
  6633. inline bool is_accept_transient_error() {
  6634. #ifdef _WIN32
  6635. auto err = WSAGetLastError();
  6636. return err == WSAEINTR || err == WSAEWOULDBLOCK || err == WSAECONNRESET ||
  6637. err == WSAECONNABORTED;
  6638. #else
  6639. auto err = errno;
  6640. return err == EINTR || err == EAGAIN || err == EWOULDBLOCK ||
  6641. err == ECONNABORTED;
  6642. #endif
  6643. }
  6644. inline socket_t accept_socket(socket_t svr_sock) {
  6645. #if defined _WIN32
  6646. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  6647. // OVERLAPPED
  6648. return WSAAccept(svr_sock, nullptr, nullptr, nullptr, 0);
  6649. #elif defined SOCK_CLOEXEC
  6650. return accept4(svr_sock, nullptr, nullptr, SOCK_CLOEXEC);
  6651. #else
  6652. return accept(svr_sock, nullptr, nullptr);
  6653. #endif
  6654. }
  6655. inline bool is_would_block_error() {
  6656. #ifdef _WIN32
  6657. return WSAGetLastError() == WSAEWOULDBLOCK;
  6658. #else
  6659. return errno == EAGAIN || errno == EWOULDBLOCK;
  6660. #endif
  6661. }
  6662. inline bool create_socket_pair(socket_t sv[2]) {
  6663. #ifdef _WIN32
  6664. auto listener = create_socket(
  6665. std::string(), "127.0.0.1", 0, AF_INET, 0, false, false, nullptr,
  6666. [](socket_t sock, struct addrinfo &ai, bool &) {
  6667. return ::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen)) == 0 &&
  6668. ::listen(sock, 1) == 0;
  6669. });
  6670. if (listener == INVALID_SOCKET) { return false; }
  6671. socket_t a = INVALID_SOCKET;
  6672. socket_t b = INVALID_SOCKET;
  6673. sockaddr_in addr{};
  6674. auto addr_len = static_cast<int>(sizeof(addr));
  6675. if (::getsockname(listener, reinterpret_cast<sockaddr *>(&addr), &addr_len) ==
  6676. 0) {
  6677. a = create_socket(std::string(), "127.0.0.1", ntohs(addr.sin_port), AF_INET,
  6678. 0, true, false, nullptr,
  6679. [](socket_t sock, struct addrinfo &ai, bool &) {
  6680. return ::connect(sock, ai.ai_addr,
  6681. static_cast<int>(ai.ai_addrlen)) == 0;
  6682. });
  6683. // Unlike accept(), this keeps the listener's no-inherit flag.
  6684. if (a != INVALID_SOCKET) {
  6685. b = WSAAccept(listener, nullptr, nullptr, nullptr, 0);
  6686. }
  6687. }
  6688. close_socket(listener);
  6689. // Any local process could connect while the listener was open, so make sure
  6690. // that the connection we accepted is the one we made.
  6691. if (b != INVALID_SOCKET) {
  6692. sockaddr_in local{}, peer{};
  6693. auto local_len = static_cast<int>(sizeof(local));
  6694. auto peer_len = static_cast<int>(sizeof(peer));
  6695. if (::getsockname(a, reinterpret_cast<sockaddr *>(&local), &local_len) !=
  6696. 0 ||
  6697. ::getpeername(b, reinterpret_cast<sockaddr *>(&peer), &peer_len) != 0 ||
  6698. local.sin_port != peer.sin_port ||
  6699. local.sin_addr.s_addr != peer.sin_addr.s_addr) {
  6700. close_socket(b);
  6701. b = INVALID_SOCKET;
  6702. }
  6703. }
  6704. if (b == INVALID_SOCKET) {
  6705. if (a != INVALID_SOCKET) { close_socket(a); }
  6706. return false;
  6707. }
  6708. sv[0] = a;
  6709. sv[1] = b;
  6710. return true;
  6711. #else
  6712. #ifdef SOCK_CLOEXEC
  6713. return ::socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) == 0;
  6714. #else
  6715. if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) { return false; }
  6716. fcntl(sv[0], F_SETFD, FD_CLOEXEC);
  6717. fcntl(sv[1], F_SETFD, FD_CLOEXEC);
  6718. return true;
  6719. #endif
  6720. #endif
  6721. }
  6722. inline PollerWaker::~PollerWaker() {
  6723. if (pair_fd_ != INVALID_SOCKET) { close_socket(pair_fd_); }
  6724. if (fd_ != INVALID_SOCKET) { close_socket(fd_); }
  6725. }
  6726. inline bool PollerWaker::open() {
  6727. // wake() must not block its caller, and drain() must not block the poller.
  6728. #ifdef __linux__
  6729. fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
  6730. return fd_ != INVALID_SOCKET;
  6731. #else
  6732. socket_t sv[2];
  6733. if (!create_socket_pair(sv)) { return false; }
  6734. fd_ = sv[0];
  6735. pair_fd_ = sv[1];
  6736. set_nonblocking(fd_, true);
  6737. set_nonblocking(pair_fd_, true);
  6738. return true;
  6739. #endif
  6740. }
  6741. inline void PollerWaker::wake() noexcept {
  6742. if (pending_.exchange(true)) { return; }
  6743. #ifdef __linux__
  6744. const uint64_t one = 1;
  6745. auto r = write(fd_, &one, sizeof(one));
  6746. (void)r;
  6747. #else
  6748. const char c = 1;
  6749. send_socket(pair_fd_, &c, 1, CPPHTTPLIB_SEND_FLAGS);
  6750. #endif
  6751. }
  6752. inline void PollerWaker::drain() noexcept {
  6753. // While pending_ is set, at most one wake is unread, and one read takes it.
  6754. #ifdef __linux__
  6755. uint64_t count;
  6756. auto r = read(fd_, &count, sizeof(count));
  6757. (void)r;
  6758. #else
  6759. char buf[64];
  6760. read_socket(fd_, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  6761. #endif
  6762. // Only after the read: cleared before it, a wake() in between would be read
  6763. // here and leave pending_ set with nothing to read. One skipped during the
  6764. // read is fine, as the caller checks what it was woken for afterwards.
  6765. pending_ = false;
  6766. }
  6767. inline std::unique_ptr<Poller> PollPoller::create() {
  6768. std::unique_ptr<PollPoller> poller(new PollPoller());
  6769. if (!poller->waker_.open()) { return nullptr; }
  6770. struct pollfd pfd;
  6771. pfd.fd = poller->waker_.fd();
  6772. pfd.events = POLLIN;
  6773. pfd.revents = 0;
  6774. poller->fds_.push_back(pfd);
  6775. poller->tokens_.push_back(0);
  6776. return std::unique_ptr<Poller>(poller.release());
  6777. }
  6778. inline bool PollPoller::arm(socket_t fd, Token token) {
  6779. assert(index_.find(fd) == index_.end());
  6780. struct pollfd pfd;
  6781. pfd.fd = fd;
  6782. pfd.events = POLLIN;
  6783. pfd.revents = 0;
  6784. index_[fd] = fds_.size();
  6785. fds_.push_back(pfd);
  6786. tokens_.push_back(token);
  6787. return true;
  6788. }
  6789. inline void PollPoller::disarm(socket_t fd) {
  6790. auto it = index_.find(fd);
  6791. if (it != index_.end()) { remove_at(it->second); }
  6792. }
  6793. // Fills the hole with the last entry, so that arm() and disarm() are O(1).
  6794. inline void PollPoller::remove_at(size_t index) {
  6795. assert(index > 0 && index < fds_.size());
  6796. auto last = fds_.size() - 1;
  6797. index_.erase(fds_[index].fd);
  6798. if (index != last) {
  6799. fds_[index] = fds_[last];
  6800. tokens_[index] = tokens_[last];
  6801. index_[fds_[index].fd] = index;
  6802. }
  6803. fds_.pop_back();
  6804. tokens_.pop_back();
  6805. }
  6806. inline bool PollPoller::wait(int timeout_ms, std::vector<Token> &ready) {
  6807. ready.clear();
  6808. auto n = handle_EINTR([&]() {
  6809. return poll_wrapper(fds_.data(), static_cast<nfds_t>(fds_.size()),
  6810. timeout_ms);
  6811. });
  6812. if (n <= 0) { return false; }
  6813. auto woken = fds_[0].revents != 0;
  6814. if (woken) {
  6815. n--;
  6816. waker_.drain();
  6817. }
  6818. // Walk backwards: remove_at() moves the last entry, already seen, into the
  6819. // freed slot.
  6820. for (auto i = fds_.size(); n > 0 && i-- > 1;) {
  6821. auto revents = fds_[i].revents;
  6822. if (revents == 0) { continue; }
  6823. n--;
  6824. assert(!(revents & POLLNVAL)); // closed while armed
  6825. if (!(revents & POLLNVAL)) { ready.push_back(tokens_[i]); }
  6826. remove_at(i);
  6827. }
  6828. return woken;
  6829. }
  6830. #ifdef __linux__
  6831. inline std::unique_ptr<Poller> EpollPoller::create() {
  6832. std::unique_ptr<EpollPoller> poller(new EpollPoller());
  6833. poller->epfd_ = epoll_create1(EPOLL_CLOEXEC);
  6834. if (poller->epfd_ < 0 || !poller->waker_.open()) { return nullptr; }
  6835. epoll_event ev{};
  6836. ev.events = EPOLLIN; // level-triggered: it stays readable until drained
  6837. ev.data.u64 = poller->waker_.token();
  6838. if (epoll_ctl(poller->epfd_, EPOLL_CTL_ADD, poller->waker_.fd(), &ev) != 0) {
  6839. return nullptr;
  6840. }
  6841. poller->events_.resize(256);
  6842. return std::unique_ptr<Poller>(poller.release());
  6843. }
  6844. inline EpollPoller::~EpollPoller() {
  6845. if (epfd_ >= 0) { close(epfd_); }
  6846. }
  6847. inline bool EpollPoller::arm(socket_t fd, Token token) {
  6848. epoll_event ev{};
  6849. ev.events = EPOLLIN | EPOLLONESHOT;
  6850. ev.data.u64 = token;
  6851. // A delivered descriptor stays registered, only disabled, so modify it.
  6852. // One that was closed in between, or never armed, has to be added.
  6853. return epoll_ctl(epfd_, EPOLL_CTL_MOD, fd, &ev) == 0 ||
  6854. (errno == ENOENT && epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) == 0);
  6855. }
  6856. inline void EpollPoller::disarm(socket_t fd) {
  6857. epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, nullptr);
  6858. }
  6859. inline bool EpollPoller::wait(int timeout_ms, std::vector<Token> &ready) {
  6860. ready.clear();
  6861. auto n = handle_EINTR([&]() {
  6862. return epoll_wait(epfd_, events_.data(), static_cast<int>(events_.size()),
  6863. timeout_ms);
  6864. });
  6865. auto woken = false;
  6866. for (auto i = 0; i < n; i++) {
  6867. auto token = static_cast<Token>(events_[static_cast<size_t>(i)].data.u64);
  6868. if (token == waker_.token()) {
  6869. woken = true;
  6870. waker_.drain();
  6871. } else {
  6872. ready.push_back(token);
  6873. }
  6874. }
  6875. return woken;
  6876. }
  6877. #endif
  6878. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  6879. inline std::unique_ptr<Poller> KqueuePoller::create() {
  6880. std::unique_ptr<KqueuePoller> poller(new KqueuePoller());
  6881. poller->kq_ = kqueue();
  6882. if (poller->kq_ < 0) { return nullptr; }
  6883. fcntl(poller->kq_, F_SETFD, FD_CLOEXEC);
  6884. if (!poller->waker_.open()) { return nullptr; }
  6885. // Level-triggered: it stays readable until drained.
  6886. struct kevent ev;
  6887. EV_SET(&ev, poller->waker_.fd(), EVFILT_READ, EV_ADD, 0, 0,
  6888. reinterpret_cast<void *>(poller->waker_.token()));
  6889. if (kevent(poller->kq_, &ev, 1, nullptr, 0, nullptr) != 0) { return nullptr; }
  6890. poller->events_.resize(256);
  6891. return std::unique_ptr<Poller>(poller.release());
  6892. }
  6893. inline KqueuePoller::~KqueuePoller() {
  6894. if (kq_ >= 0) { close(kq_); }
  6895. }
  6896. inline bool KqueuePoller::arm(socket_t fd, Token token) {
  6897. // EV_ONESHOT deletes the event once it is delivered.
  6898. struct kevent ev;
  6899. EV_SET(&ev, fd, EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0,
  6900. reinterpret_cast<void *>(token));
  6901. return kevent(kq_, &ev, 1, nullptr, 0, nullptr) == 0;
  6902. }
  6903. inline void KqueuePoller::disarm(socket_t fd) {
  6904. struct kevent ev;
  6905. EV_SET(&ev, fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr);
  6906. kevent(kq_, &ev, 1, nullptr, 0, nullptr);
  6907. }
  6908. inline bool KqueuePoller::wait(int timeout_ms, std::vector<Token> &ready) {
  6909. ready.clear();
  6910. struct timespec ts;
  6911. ts.tv_sec = timeout_ms / 1000;
  6912. ts.tv_nsec = static_cast<long>(timeout_ms % 1000) * 1000000;
  6913. auto n = handle_EINTR([&]() {
  6914. return kevent(kq_, nullptr, 0, events_.data(),
  6915. static_cast<int>(events_.size()),
  6916. timeout_ms < 0 ? nullptr : &ts);
  6917. });
  6918. auto woken = false;
  6919. for (auto i = 0; i < n; i++) {
  6920. auto token = reinterpret_cast<Token>(events_[static_cast<size_t>(i)].udata);
  6921. if (token == waker_.token()) {
  6922. woken = true;
  6923. waker_.drain();
  6924. } else {
  6925. ready.push_back(token);
  6926. }
  6927. }
  6928. return woken;
  6929. }
  6930. #endif
  6931. inline std::unique_ptr<Poller> make_poller() {
  6932. #if defined(__linux__)
  6933. auto poller = EpollPoller::create();
  6934. if (poller) { return poller; }
  6935. #elif defined(CPPHTTPLIB_KQUEUE_POLLER)
  6936. auto poller = KqueuePoller::create();
  6937. if (poller) { return poller; }
  6938. #endif
  6939. return PollPoller::create();
  6940. }
  6941. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  6942. struct addrinfo hints;
  6943. struct addrinfo *result;
  6944. memset(&hints, 0, sizeof(struct addrinfo));
  6945. hints.ai_family = AF_UNSPEC;
  6946. hints.ai_socktype = SOCK_STREAM;
  6947. hints.ai_protocol = 0;
  6948. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  6949. return false;
  6950. }
  6951. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6952. auto ret = false;
  6953. for (auto rp = result; rp; rp = rp->ai_next) {
  6954. const auto &ai = *rp;
  6955. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6956. ret = true;
  6957. break;
  6958. }
  6959. }
  6960. return ret;
  6961. }
  6962. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  6963. #define USE_IF2IP
  6964. #endif
  6965. #ifdef USE_IF2IP
  6966. inline std::string if2ip(int address_family, const std::string &ifn) {
  6967. struct ifaddrs *ifap;
  6968. getifaddrs(&ifap);
  6969. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  6970. std::string addr_candidate;
  6971. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  6972. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  6973. (AF_UNSPEC == address_family ||
  6974. ifa->ifa_addr->sa_family == address_family)) {
  6975. if (ifa->ifa_addr->sa_family == AF_INET) {
  6976. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  6977. char buf[INET_ADDRSTRLEN];
  6978. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  6979. return std::string(buf, INET_ADDRSTRLEN);
  6980. }
  6981. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  6982. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  6983. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  6984. char buf[INET6_ADDRSTRLEN] = {};
  6985. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  6986. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  6987. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  6988. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  6989. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  6990. } else {
  6991. return std::string(buf, INET6_ADDRSTRLEN);
  6992. }
  6993. }
  6994. }
  6995. }
  6996. }
  6997. }
  6998. return addr_candidate;
  6999. }
  7000. #endif
  7001. inline socket_t
  7002. create_client_socket(const std::string &host, const std::string &ip, int port,
  7003. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  7004. SocketOptions socket_options,
  7005. time_t connection_timeout_sec,
  7006. time_t connection_timeout_usec, time_t read_timeout_sec,
  7007. time_t read_timeout_usec, time_t write_timeout_sec,
  7008. time_t write_timeout_usec, const std::string &intf,
  7009. Error &error, const std::function<bool()> &interrupted) {
  7010. auto sock = create_socket(
  7011. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  7012. std::move(socket_options),
  7013. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  7014. if (!intf.empty()) {
  7015. #ifdef USE_IF2IP
  7016. auto ip_from_if = if2ip(address_family, intf);
  7017. if (ip_from_if.empty()) { ip_from_if = intf; }
  7018. if (!bind_ip_address(sock2, ip_from_if)) {
  7019. error = Error::BindIPAddress;
  7020. return false;
  7021. }
  7022. #endif
  7023. }
  7024. set_nonblocking(sock2, true);
  7025. auto ret =
  7026. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  7027. if (ret < 0) {
  7028. if (is_connection_error()) {
  7029. error = Error::Connection;
  7030. return false;
  7031. }
  7032. error =
  7033. wait_until_socket_is_ready(sock2, connection_timeout_sec,
  7034. connection_timeout_usec, interrupted);
  7035. if (error != Error::Success) {
  7036. if (error == Error::ConnectionTimeout || error == Error::Canceled) {
  7037. quit = true;
  7038. }
  7039. return false;
  7040. }
  7041. }
  7042. set_nonblocking(sock2, false);
  7043. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  7044. read_timeout_usec);
  7045. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  7046. write_timeout_usec);
  7047. error = Error::Success;
  7048. return true;
  7049. },
  7050. connection_timeout_sec); // Pass DNS timeout
  7051. if (sock != INVALID_SOCKET) {
  7052. error = Error::Success;
  7053. } else {
  7054. if (error == Error::Success) { error = Error::Connection; }
  7055. }
  7056. return sock;
  7057. }
  7058. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  7059. socklen_t addr_len, std::string &ip, int &port) {
  7060. if (addr.ss_family == AF_INET) {
  7061. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  7062. } else if (addr.ss_family == AF_INET6) {
  7063. port =
  7064. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  7065. } else {
  7066. return false;
  7067. }
  7068. std::array<char, NI_MAXHOST> ipstr{};
  7069. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  7070. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  7071. 0, NI_NUMERICHOST)) {
  7072. return false;
  7073. }
  7074. ip = ipstr.data();
  7075. return true;
  7076. }
  7077. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  7078. struct sockaddr_storage addr;
  7079. socklen_t addr_len = sizeof(addr);
  7080. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  7081. &addr_len)) {
  7082. get_ip_and_port(addr, addr_len, ip, port);
  7083. }
  7084. }
  7085. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  7086. struct sockaddr_storage addr;
  7087. socklen_t addr_len = sizeof(addr);
  7088. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  7089. &addr_len)) {
  7090. #ifndef _WIN32
  7091. if (addr.ss_family == AF_UNIX) {
  7092. #if defined(__linux__)
  7093. struct ucred ucred;
  7094. socklen_t len = sizeof(ucred);
  7095. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  7096. port = ucred.pid;
  7097. }
  7098. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  7099. pid_t pid;
  7100. socklen_t len = sizeof(pid);
  7101. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  7102. port = pid;
  7103. }
  7104. #endif
  7105. return;
  7106. }
  7107. #endif
  7108. get_ip_and_port(addr, addr_len, ip, port);
  7109. }
  7110. }
  7111. inline std::string
  7112. find_content_type(const std::string &path,
  7113. const std::map<std::string, std::string> &user_data,
  7114. const std::string &default_content_type) {
  7115. // Extensions are matched regardless of case, as web servers do
  7116. auto ext = case_ignore::to_lower(file_extension(path));
  7117. auto it = user_data.find(ext);
  7118. if (it != user_data.end()) { return it->second; }
  7119. static const struct {
  7120. const char *ext;
  7121. const char *type;
  7122. } types[] = {
  7123. {"css", "text/css"},
  7124. {"csv", "text/csv"},
  7125. {"htm", "text/html"},
  7126. {"html", "text/html"},
  7127. {"js", "text/javascript"},
  7128. {"mjs", "text/javascript"},
  7129. {"txt", "text/plain"},
  7130. {"vtt", "text/vtt"},
  7131. {"apng", "image/apng"},
  7132. {"avif", "image/avif"},
  7133. {"bmp", "image/bmp"},
  7134. {"gif", "image/gif"},
  7135. {"png", "image/png"},
  7136. {"svg", "image/svg+xml"},
  7137. {"webp", "image/webp"},
  7138. {"ico", "image/x-icon"},
  7139. {"tif", "image/tiff"},
  7140. {"tiff", "image/tiff"},
  7141. {"jpg", "image/jpeg"},
  7142. {"jpeg", "image/jpeg"},
  7143. {"mp4", "video/mp4"},
  7144. {"mpeg", "video/mpeg"},
  7145. {"webm", "video/webm"},
  7146. {"mp3", "audio/mp3"},
  7147. {"mpga", "audio/mpeg"},
  7148. {"weba", "audio/webm"},
  7149. {"wav", "audio/wave"},
  7150. {"otf", "font/otf"},
  7151. {"ttf", "font/ttf"},
  7152. {"woff", "font/woff"},
  7153. {"woff2", "font/woff2"},
  7154. {"7z", "application/x-7z-compressed"},
  7155. {"atom", "application/atom+xml"},
  7156. {"pdf", "application/pdf"},
  7157. {"json", "application/json"},
  7158. {"rss", "application/rss+xml"},
  7159. {"tar", "application/x-tar"},
  7160. {"xht", "application/xhtml+xml"},
  7161. {"xhtml", "application/xhtml+xml"},
  7162. {"xslt", "application/xslt+xml"},
  7163. {"xml", "application/xml"},
  7164. {"gz", "application/gzip"},
  7165. {"zip", "application/zip"},
  7166. {"wasm", "application/wasm"},
  7167. };
  7168. for (const auto &t : types) {
  7169. if (ext == t.ext) { return t.type; }
  7170. }
  7171. return default_content_type;
  7172. }
  7173. inline std::string
  7174. extract_media_type(const std::string &content_type,
  7175. std::map<std::string, std::string> *params = nullptr) {
  7176. // Extract type/subtype from Content-Type value (RFC 2045)
  7177. // e.g. "application/json; charset=utf-8" -> "application/json"
  7178. auto media_type = content_type;
  7179. auto semicolon_pos = media_type.find(';');
  7180. if (semicolon_pos != std::string::npos) {
  7181. auto param_str = media_type.substr(semicolon_pos + 1);
  7182. media_type = media_type.substr(0, semicolon_pos);
  7183. if (params) {
  7184. // Parse parameters: key=value pairs separated by ';'
  7185. split_unquoted(param_str.data(), param_str.data() + param_str.size(), ';',
  7186. [&](const char *b, const char *e) {
  7187. std::string key;
  7188. std::string val;
  7189. divide_param_pair(b, e, key, val);
  7190. // Parameter names are case-insensitive (RFC 9110
  7191. // §5.6.6)
  7192. if (!key.empty()) {
  7193. params->emplace(case_ignore::to_lower(trim_copy(key)),
  7194. unquote_param(val));
  7195. }
  7196. });
  7197. }
  7198. }
  7199. // Trim whitespace from media type
  7200. return trim_copy(media_type);
  7201. }
  7202. inline bool can_compress_content_type(const std::string &content_type) {
  7203. // Media types are case-insensitive (RFC 9110 §8.3.1)
  7204. auto mime_type = case_ignore::to_lower(extract_media_type(content_type));
  7205. static const char *const compressible[] = {
  7206. "image/svg+xml",
  7207. "application/javascript",
  7208. "application/x-javascript",
  7209. "application/json",
  7210. "application/ld+json",
  7211. "application/xml",
  7212. "application/xhtml+xml",
  7213. "application/rss+xml",
  7214. "application/atom+xml",
  7215. "application/xslt+xml",
  7216. "application/protobuf",
  7217. };
  7218. for (auto type : compressible) {
  7219. if (mime_type == type) { return true; }
  7220. }
  7221. return mime_type != "text/event-stream" && !mime_type.rfind("text/", 0);
  7222. }
  7223. inline bool parse_quality(const char *b, const char *e, std::string &token,
  7224. double &quality) {
  7225. quality = 1.0;
  7226. token.clear();
  7227. // Split on first ';': left = token name, right = parameters
  7228. const char *params_b = nullptr;
  7229. std::size_t params_len = 0;
  7230. divide(
  7231. b, static_cast<std::size_t>(e - b), ';',
  7232. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  7233. auto r = trim(lb, lb + llen, 0, llen);
  7234. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  7235. params_b = rb;
  7236. params_len = rlen;
  7237. });
  7238. if (token.empty()) { return false; }
  7239. if (params_len == 0) { return true; }
  7240. // Scan parameters for q= (stops on first match)
  7241. bool invalid = false;
  7242. split_find(params_b, params_b + params_len, ';',
  7243. (std::numeric_limits<size_t>::max)(),
  7244. [&](const char *pb, const char *pe) -> bool {
  7245. // Match exactly "q=" or "Q=" (not "query=" etc.)
  7246. auto len = static_cast<size_t>(pe - pb);
  7247. if (len < 2) { return false; }
  7248. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  7249. return false;
  7250. }
  7251. // Trim the value portion
  7252. auto r = trim(pb, pe, 2, len);
  7253. if (r.first >= r.second) {
  7254. invalid = true;
  7255. return true;
  7256. }
  7257. double v = 0.0;
  7258. auto res = from_chars(pb + r.first, pb + r.second, v);
  7259. if (res.ec != std::errc{} || res.ptr != pb + r.second ||
  7260. v < 0.0 || v > 1.0) {
  7261. invalid = true;
  7262. return true;
  7263. }
  7264. quality = v;
  7265. return true;
  7266. });
  7267. return !invalid;
  7268. }
  7269. inline EncodingType encoding_type(const Request &req,
  7270. const std::string &content_type) {
  7271. if (!can_compress_content_type(content_type)) { return EncodingType::None; }
  7272. auto s = get_combined_header_value(req.headers, "Accept-Encoding");
  7273. if (s.empty()) { return EncodingType::None; }
  7274. // Single-pass: iterate tokens and track the best supported encoding.
  7275. // Server preference breaks ties (br > gzip > zstd).
  7276. EncodingType best = EncodingType::None;
  7277. double best_q = 0.0; // q=0 means "not acceptable"
  7278. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  7279. auto priority = [](EncodingType t) -> int {
  7280. switch (t) {
  7281. case EncodingType::Brotli: return 0;
  7282. case EncodingType::Gzip: return 1;
  7283. case EncodingType::Zstd: return 2;
  7284. default: return 3;
  7285. }
  7286. };
  7287. std::string name;
  7288. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  7289. double quality = 1.0;
  7290. if (!parse_quality(b, e, name, quality)) { return; }
  7291. if (quality <= 0.0) { return; }
  7292. EncodingType type = EncodingType::None;
  7293. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7294. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  7295. #endif
  7296. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7297. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  7298. type = EncodingType::Gzip;
  7299. }
  7300. #endif
  7301. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7302. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  7303. type = EncodingType::Zstd;
  7304. }
  7305. #endif
  7306. if (type == EncodingType::None) { return; }
  7307. // Higher q-value wins; for equal q, server preference breaks ties
  7308. if (quality > best_q ||
  7309. (quality == best_q && priority(type) < priority(best))) {
  7310. best_q = quality;
  7311. best = type;
  7312. }
  7313. });
  7314. return best;
  7315. }
  7316. // `content_type` is taken separately because a file-backed response has not
  7317. // been given one yet when its coding has to be decided.
  7318. inline EncodingType encoding_type(const Request &req, const Response &res,
  7319. const std::string &content_type) {
  7320. // The response already names a content coding of its own: a handler serving
  7321. // a body it encoded itself (pre-compressed static assets, say), or a mount
  7322. // point whose headers name the coding its files are stored in. Applying one
  7323. // on top of that would double-encode the body and append a second
  7324. // `Content-Encoding` field line.
  7325. if (res.has_header("Content-Encoding")) { return EncodingType::None; }
  7326. return encoding_type(req, content_type);
  7327. }
  7328. inline EncodingType encoding_type(const Request &req, const Response &res) {
  7329. return encoding_type(req, res, res.get_header_value("Content-Type"));
  7330. }
  7331. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  7332. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7333. if (type == EncodingType::Gzip) {
  7334. return detail::make_unique<gzip_compressor>();
  7335. }
  7336. #endif
  7337. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7338. if (type == EncodingType::Brotli) {
  7339. return detail::make_unique<brotli_compressor>();
  7340. }
  7341. #endif
  7342. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7343. if (type == EncodingType::Zstd) {
  7344. return detail::make_unique<zstd_compressor>();
  7345. }
  7346. #endif
  7347. (void)type;
  7348. return nullptr;
  7349. }
  7350. inline const char *encoding_name(EncodingType type) {
  7351. switch (type) {
  7352. case EncodingType::Gzip: return "gzip";
  7353. case EncodingType::Brotli: return "br";
  7354. case EncodingType::Zstd: return "zstd";
  7355. default: return "";
  7356. }
  7357. }
  7358. inline bool nocompressor::compress(const char *data, size_t data_length,
  7359. bool /*last*/, Callback callback) {
  7360. if (!data_length) { return true; }
  7361. return callback(data, data_length);
  7362. }
  7363. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7364. inline gzip_compressor::gzip_compressor() {
  7365. std::memset(&strm_, 0, sizeof(strm_));
  7366. strm_.zalloc = Z_NULL;
  7367. strm_.zfree = Z_NULL;
  7368. strm_.opaque = Z_NULL;
  7369. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  7370. Z_DEFAULT_STRATEGY) == Z_OK;
  7371. }
  7372. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  7373. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  7374. bool last, Callback callback) {
  7375. assert(is_valid_);
  7376. do {
  7377. constexpr size_t max_avail_in =
  7378. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  7379. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  7380. (std::min)(data_length, max_avail_in));
  7381. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  7382. data_length -= strm_.avail_in;
  7383. data += strm_.avail_in;
  7384. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  7385. auto ret = Z_OK;
  7386. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7387. do {
  7388. strm_.avail_out = static_cast<uInt>(buff.size());
  7389. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  7390. ret = deflate(&strm_, flush);
  7391. if (ret == Z_STREAM_ERROR) { return false; }
  7392. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  7393. return false;
  7394. }
  7395. } while (strm_.avail_out == 0);
  7396. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  7397. (flush == Z_NO_FLUSH && ret == Z_OK));
  7398. assert(strm_.avail_in == 0);
  7399. } while (data_length > 0);
  7400. return true;
  7401. }
  7402. inline gzip_decompressor::gzip_decompressor() {
  7403. std::memset(&strm_, 0, sizeof(strm_));
  7404. strm_.zalloc = Z_NULL;
  7405. strm_.zfree = Z_NULL;
  7406. strm_.opaque = Z_NULL;
  7407. // 15 is the value of wbits, which should be at the maximum possible value
  7408. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  7409. // that the stream type should be automatically detected either gzip or
  7410. // deflate.
  7411. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  7412. }
  7413. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  7414. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  7415. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  7416. Callback callback) {
  7417. assert(is_valid_);
  7418. auto ret = Z_OK;
  7419. do {
  7420. constexpr size_t max_avail_in =
  7421. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  7422. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  7423. (std::min)(data_length, max_avail_in));
  7424. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  7425. data_length -= strm_.avail_in;
  7426. data += strm_.avail_in;
  7427. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7428. while (strm_.avail_in > 0 && ret == Z_OK) {
  7429. strm_.avail_out = static_cast<uInt>(buff.size());
  7430. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  7431. ret = inflate(&strm_, Z_NO_FLUSH);
  7432. assert(ret != Z_STREAM_ERROR);
  7433. switch (ret) {
  7434. case Z_NEED_DICT:
  7435. case Z_DATA_ERROR:
  7436. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  7437. }
  7438. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  7439. return false;
  7440. }
  7441. }
  7442. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  7443. } while (data_length > 0);
  7444. return true;
  7445. }
  7446. #endif
  7447. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7448. inline brotli_compressor::brotli_compressor() {
  7449. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  7450. }
  7451. inline brotli_compressor::~brotli_compressor() {
  7452. BrotliEncoderDestroyInstance(state_);
  7453. }
  7454. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  7455. bool last, Callback callback) {
  7456. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7457. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  7458. auto available_in = data_length;
  7459. auto next_in = reinterpret_cast<const uint8_t *>(data);
  7460. for (;;) {
  7461. if (last) {
  7462. if (BrotliEncoderIsFinished(state_)) { break; }
  7463. } else {
  7464. if (!available_in) { break; }
  7465. }
  7466. auto available_out = buff.size();
  7467. auto next_out = buff.data();
  7468. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  7469. &available_out, &next_out, nullptr)) {
  7470. return false;
  7471. }
  7472. auto output_bytes = buff.size() - available_out;
  7473. if (output_bytes) {
  7474. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  7475. }
  7476. }
  7477. return true;
  7478. }
  7479. inline brotli_decompressor::brotli_decompressor() {
  7480. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  7481. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  7482. : BROTLI_DECODER_RESULT_ERROR;
  7483. }
  7484. inline brotli_decompressor::~brotli_decompressor() {
  7485. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  7486. }
  7487. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  7488. inline bool brotli_decompressor::decompress(const char *data,
  7489. size_t data_length,
  7490. Callback callback) {
  7491. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  7492. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  7493. return 0;
  7494. }
  7495. auto next_in = reinterpret_cast<const uint8_t *>(data);
  7496. size_t avail_in = data_length;
  7497. size_t total_out;
  7498. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  7499. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7500. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  7501. char *next_out = buff.data();
  7502. size_t avail_out = buff.size();
  7503. decoder_r = BrotliDecoderDecompressStream(
  7504. decoder_s, &avail_in, &next_in, &avail_out,
  7505. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  7506. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  7507. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  7508. }
  7509. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  7510. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  7511. }
  7512. #endif
  7513. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7514. inline zstd_compressor::zstd_compressor() {
  7515. ctx_ = ZSTD_createCCtx();
  7516. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  7517. }
  7518. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  7519. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  7520. bool last, Callback callback) {
  7521. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7522. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  7523. ZSTD_inBuffer input = {data, data_length, 0};
  7524. bool finished;
  7525. do {
  7526. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  7527. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  7528. if (ZSTD_isError(remaining)) { return false; }
  7529. if (!callback(buff.data(), output.pos)) { return false; }
  7530. finished = last ? (remaining == 0) : (input.pos == input.size);
  7531. } while (!finished);
  7532. return true;
  7533. }
  7534. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  7535. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  7536. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  7537. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  7538. Callback callback) {
  7539. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  7540. ZSTD_inBuffer input = {data, data_length, 0};
  7541. while (input.pos < input.size) {
  7542. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  7543. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  7544. if (ZSTD_isError(remaining)) { return false; }
  7545. if (!callback(buff.data(), output.pos)) { return false; }
  7546. }
  7547. return true;
  7548. }
  7549. #endif
  7550. // Content codings are case-insensitive (RFC 9110 8.4.1). Matching them
  7551. // case-sensitively would make a response labeled e.g. "GZIP" look like an
  7552. // unknown coding, and its payload would be handed back still compressed.
  7553. inline bool is_zlib_encoding(const std::string &encoding) {
  7554. return case_ignore::equal(encoding, "gzip") ||
  7555. case_ignore::equal(encoding, "deflate");
  7556. }
  7557. inline bool is_brotli_encoding(const std::string &encoding) {
  7558. return case_ignore::equal(encoding, "br");
  7559. }
  7560. inline bool is_zstd_encoding(const std::string &encoding) {
  7561. return case_ignore::equal(encoding, "zstd");
  7562. }
  7563. // Returns true if the content coding is one cpp-httplib is able to decompress
  7564. // when the corresponding support is compiled in.
  7565. inline bool is_known_content_encoding(const std::string &encoding) {
  7566. return is_zlib_encoding(encoding) || is_brotli_encoding(encoding) ||
  7567. is_zstd_encoding(encoding);
  7568. }
  7569. inline std::unique_ptr<decompressor>
  7570. create_decompressor(const std::string &encoding) {
  7571. std::unique_ptr<decompressor> decompressor;
  7572. if (is_zlib_encoding(encoding)) {
  7573. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7574. decompressor = detail::make_unique<gzip_decompressor>();
  7575. #endif
  7576. } else if (is_brotli_encoding(encoding)) {
  7577. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7578. decompressor = detail::make_unique<brotli_decompressor>();
  7579. #endif
  7580. } else if (is_zstd_encoding(encoding)) {
  7581. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7582. decompressor = detail::make_unique<zstd_decompressor>();
  7583. #endif
  7584. }
  7585. return decompressor;
  7586. }
  7587. // Returns the best available compressor and its Content-Encoding name.
  7588. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  7589. inline std::pair<std::unique_ptr<compressor>, const char *>
  7590. create_compressor() {
  7591. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7592. return {detail::make_unique<brotli_compressor>(), "br"};
  7593. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7594. return {detail::make_unique<gzip_compressor>(), "gzip"};
  7595. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7596. return {detail::make_unique<zstd_compressor>(), "zstd"};
  7597. #else
  7598. return {nullptr, nullptr};
  7599. #endif
  7600. }
  7601. inline bool is_prohibited_header_name(const std::string &name) {
  7602. // Field names are case-insensitive (RFC 9110 §5.1)
  7603. return case_ignore::equal(name, "REMOTE_ADDR") ||
  7604. case_ignore::equal(name, "REMOTE_PORT") ||
  7605. case_ignore::equal(name, "LOCAL_ADDR") ||
  7606. case_ignore::equal(name, "LOCAL_PORT");
  7607. }
  7608. inline bool has_header(const Headers &headers, const std::string &key) {
  7609. if (is_prohibited_header_name(key)) { return false; }
  7610. return headers.find(key) != headers.end();
  7611. }
  7612. inline const char *get_header_value(const Headers &headers,
  7613. const std::string &key, const char *def,
  7614. size_t id) {
  7615. if (is_prohibited_header_name(key)) {
  7616. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7617. std::string msg = "Prohibited header name '" + key + "' is specified.";
  7618. throw std::invalid_argument(msg);
  7619. #else
  7620. return "";
  7621. #endif
  7622. }
  7623. auto rng = headers.equal_range(key);
  7624. auto it = bounded_next(rng.first, id, rng.second);
  7625. if (it != rng.second) { return it->second.c_str(); }
  7626. return def;
  7627. }
  7628. inline size_t get_header_value_count(const Headers &headers,
  7629. const std::string &key) {
  7630. return headers.count(key);
  7631. }
  7632. // RFC 9110 Section 5.2 and 5.3: a field that is defined as a comma-separated
  7633. // list may be sent as several field lines, and the combined field value is
  7634. // those values joined by commas in the order they were received. Callers that
  7635. // parse such a list must work on the combined value; reading only the first
  7636. // occurrence silently drops whatever the later field lines carry.
  7637. inline std::string get_combined_header_value(const Headers &headers,
  7638. const std::string &key) {
  7639. std::string combined;
  7640. auto rng = headers.equal_range(key);
  7641. for (auto it = rng.first; it != rng.second; ++it) {
  7642. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  7643. // elements, so an empty field line must not contribute a bare comma to the
  7644. // combined value.
  7645. if (it->second.empty()) { continue; }
  7646. if (!combined.empty()) { combined += ", "; }
  7647. combined += it->second;
  7648. }
  7649. return combined;
  7650. }
  7651. inline bool has_header_token(const Headers &headers, const std::string &key,
  7652. const std::string &token) {
  7653. // RFC 9110 7.6.1: a comma-separated token list field such as Connection may
  7654. // carry several tokens, and RFC 9110 5.3 lets that list be split across
  7655. // several lines. Match complete tokens rather than searching the raw value,
  7656. // so that a value such as "notupgrade" is not read as the token "upgrade".
  7657. auto rng = headers.equal_range(key);
  7658. for (auto it = rng.first; it != rng.second; ++it) {
  7659. const auto &value = it->second;
  7660. if (split_find(value.data(), value.data() + value.size(), ',',
  7661. [&](const char *b, const char *e) {
  7662. return case_ignore::equal(std::string(b, e), token);
  7663. })) {
  7664. return true;
  7665. }
  7666. }
  7667. return false;
  7668. }
  7669. template <typename Map>
  7670. inline typename Map::mapped_type
  7671. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  7672. auto rng = m.equal_range(key);
  7673. auto it = bounded_next(rng.first, id, rng.second);
  7674. if (it != rng.second) { return it->second; }
  7675. return typename Map::mapped_type();
  7676. }
  7677. inline void set_header(Headers &headers, const std::string &key,
  7678. const std::string &val) {
  7679. if (fields::is_field_valid(key, val)) { headers.emplace(key, val); }
  7680. }
  7681. // Drops the fields set_header() would refuse, from headers an application can
  7682. // fill directly: CR/LF in one would split the message.
  7683. inline void erase_invalid_fields(Headers &headers) {
  7684. for (auto it = headers.begin(); it != headers.end();) {
  7685. if (fields::is_field_valid(it->first, it->second)) {
  7686. ++it;
  7687. } else {
  7688. it = headers.erase(it);
  7689. }
  7690. }
  7691. }
  7692. inline bool read_headers(Stream &strm, Headers &headers) {
  7693. const auto bufsiz = 2048;
  7694. char buf[bufsiz];
  7695. stream_line_reader line_reader(strm, buf, bufsiz);
  7696. size_t header_count = 0;
  7697. for (;;) {
  7698. if (!line_reader.getline()) { return false; }
  7699. // Check if the line ends with CRLF.
  7700. auto line_terminator_len = 2;
  7701. if (line_reader.end_with_crlf()) {
  7702. // Blank line indicates end of headers.
  7703. if (line_reader.size() == 2) { break; }
  7704. } else {
  7705. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  7706. // Blank line indicates end of headers.
  7707. if (line_reader.size() == 1) { break; }
  7708. line_terminator_len = 1;
  7709. #else
  7710. continue; // Skip invalid line.
  7711. #endif
  7712. }
  7713. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  7714. // Check header count limit
  7715. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  7716. // Exclude line terminator
  7717. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  7718. if (!parse_header(line_reader.ptr(), end,
  7719. [&](const std::string &key, const std::string &val) {
  7720. headers.emplace(key, val);
  7721. })) {
  7722. return false;
  7723. }
  7724. header_count++;
  7725. }
  7726. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  7727. // headers that have different values to prevent request smuggling.
  7728. auto cl_range = headers.equal_range("Content-Length");
  7729. if (cl_range.first != cl_range.second) {
  7730. const auto &first_val = cl_range.first->second;
  7731. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  7732. if (it->second != first_val) { return false; }
  7733. }
  7734. }
  7735. return true;
  7736. }
  7737. // Parsed by hand: std::regex_match recurses once per character of the reason
  7738. // phrase, which a server can make as long as a whole line.
  7739. inline bool parse_status_line(const char *line, std::string &version,
  7740. int &status, std::string &reason) {
  7741. if (std::strncmp(line, "HTTP/1.", 7) != 0 ||
  7742. (line[7] != '0' && line[7] != '1') || line[8] != ' ' ||
  7743. !is_ascii_digit(line[9]) || !is_ascii_digit(line[10]) ||
  7744. !is_ascii_digit(line[11])) {
  7745. return false;
  7746. }
  7747. auto p = line + 12;
  7748. auto reason_begin = p;
  7749. if (*p == ' ') {
  7750. reason_begin = ++p;
  7751. p += std::strcspn(p, "\r\n");
  7752. }
  7753. auto reason_end = p;
  7754. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  7755. if (*p == '\r') { p++; }
  7756. #else
  7757. if (*p++ != '\r') { return false; }
  7758. #endif
  7759. if (*p++ != '\n' || *p != '\0') { return false; }
  7760. version.assign(line, 8);
  7761. status = (line[9] - '0') * 100 + (line[10] - '0') * 10 + (line[11] - '0');
  7762. reason.assign(reason_begin, reason_end);
  7763. return true;
  7764. }
  7765. // Everything WebSocketClient::connect() reports about the upgrade exchange.
  7766. // status stays -1 until a status line is parsed, mirroring stream::Result.
  7767. struct WebSocketUpgradeResponse {
  7768. Error error = Error::Success;
  7769. int status = -1;
  7770. Headers headers;
  7771. std::string selected_subprotocol;
  7772. };
  7773. // Reads a response's status line and headers, leaving any body unread. An
  7774. // unparsable status line is no stream error; it just leaves `status` as is.
  7775. inline bool read_response_head(Stream &strm, int &status, Headers &headers) {
  7776. const auto bufsiz = 2048;
  7777. char buf[bufsiz];
  7778. stream_line_reader line_reader(strm, buf, bufsiz);
  7779. if (!line_reader.getline()) { return false; }
  7780. std::string version;
  7781. std::string reason;
  7782. if (!parse_status_line(line_reader.ptr(), version, status, reason)) {
  7783. return true;
  7784. }
  7785. return read_headers(strm, headers);
  7786. }
  7787. inline bool
  7788. read_websocket_upgrade_response(Stream &strm,
  7789. const std::string &expected_accept,
  7790. const std::string &offered_subprotocols,
  7791. WebSocketUpgradeResponse &upgrade) {
  7792. // The headers of a rejection are kept so the caller can see why the server
  7793. // refused the upgrade.
  7794. if (!read_response_head(strm, upgrade.status, upgrade.headers)) {
  7795. upgrade.error = Error::Read;
  7796. return false;
  7797. }
  7798. const auto &headers = upgrade.headers;
  7799. if (upgrade.status != StatusCode::SwitchingProtocol_101) {
  7800. upgrade.error = Error::WebSocketHandshake;
  7801. return false;
  7802. }
  7803. // Verify Upgrade: websocket (a comma-separated list, matched per token)
  7804. if (!has_header_token(headers, "Upgrade", "websocket")) {
  7805. upgrade.error = Error::WebSocketHandshake;
  7806. return false;
  7807. }
  7808. // Verify Connection: Upgrade
  7809. if (!has_header_token(headers, "Connection", "upgrade")) {
  7810. upgrade.error = Error::WebSocketHandshake;
  7811. return false;
  7812. }
  7813. // Verify Sec-WebSocket-Accept header value
  7814. auto it = headers.find("Sec-WebSocket-Accept");
  7815. if (it == headers.end() || it->second != expected_accept) {
  7816. upgrade.error = Error::WebSocketHandshake;
  7817. return false;
  7818. }
  7819. // Extract negotiated subprotocol
  7820. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  7821. if (proto_it != headers.end()) {
  7822. upgrade.selected_subprotocol = proto_it->second;
  7823. }
  7824. // Verify the subprotocol is one the client offered (RFC 6455 4.1)
  7825. if (!upgrade.selected_subprotocol.empty()) {
  7826. auto was_offered = false;
  7827. split(offered_subprotocols.data(),
  7828. offered_subprotocols.data() + offered_subprotocols.size(), ',',
  7829. [&](const char *b, const char *e) {
  7830. if (std::string(b, e) == upgrade.selected_subprotocol) {
  7831. was_offered = true;
  7832. }
  7833. });
  7834. if (!was_offered) {
  7835. upgrade.error = Error::WebSocketHandshake;
  7836. return false;
  7837. }
  7838. }
  7839. return true;
  7840. }
  7841. enum class ReadContentResult {
  7842. Success, // Successfully read the content
  7843. PayloadTooLarge, // The content exceeds the specified payload limit
  7844. Error // An error occurred while reading the content
  7845. };
  7846. inline ReadContentResult read_content_with_length(
  7847. Stream &strm, size_t len, DownloadProgress progress,
  7848. ContentReceiverWithProgress out,
  7849. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  7850. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7851. detail::BodyReader br;
  7852. br.stream = &strm;
  7853. br.has_content_length = true;
  7854. br.content_length = len;
  7855. br.payload_max_length = payload_max_length;
  7856. br.chunked = false;
  7857. br.bytes_read = 0;
  7858. br.last_error = Error::Success;
  7859. size_t r = 0;
  7860. while (r < len) {
  7861. auto read_len = static_cast<size_t>(len - r);
  7862. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  7863. auto n = detail::read_body_content(&strm, br, buf, to_read);
  7864. if (n <= 0) {
  7865. // Check if it was a payload size error
  7866. if (br.last_error == Error::ExceedMaxPayloadSize) {
  7867. return ReadContentResult::PayloadTooLarge;
  7868. }
  7869. return ReadContentResult::Error;
  7870. }
  7871. if (!out(buf, static_cast<size_t>(n), r, len)) {
  7872. return ReadContentResult::Error;
  7873. }
  7874. r += static_cast<size_t>(n);
  7875. if (progress) {
  7876. if (!progress(r, len)) { return ReadContentResult::Error; }
  7877. }
  7878. }
  7879. return ReadContentResult::Success;
  7880. }
  7881. inline ReadContentResult
  7882. read_content_without_length(Stream &strm, size_t payload_max_length,
  7883. ContentReceiverWithProgress out) {
  7884. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7885. size_t r = 0;
  7886. for (;;) {
  7887. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  7888. if (n == 0) { return ReadContentResult::Success; }
  7889. if (n < 0) { return ReadContentResult::Error; }
  7890. // Check if adding this data would exceed the payload limit
  7891. if (payload_max_length > 0 &&
  7892. (r > payload_max_length ||
  7893. payload_max_length - r < static_cast<size_t>(n))) {
  7894. return ReadContentResult::PayloadTooLarge;
  7895. }
  7896. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  7897. return ReadContentResult::Error;
  7898. }
  7899. r += static_cast<size_t>(n);
  7900. }
  7901. return ReadContentResult::Success;
  7902. }
  7903. template <typename T>
  7904. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  7905. size_t payload_max_length,
  7906. ContentReceiverWithProgress out) {
  7907. detail::ChunkedDecoder dec(strm);
  7908. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7909. size_t total_len = 0;
  7910. for (;;) {
  7911. size_t chunk_offset = 0;
  7912. size_t chunk_total = 0;
  7913. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  7914. if (n < 0) { return ReadContentResult::Error; }
  7915. if (n == 0) {
  7916. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  7917. return ReadContentResult::Error;
  7918. }
  7919. return ReadContentResult::Success;
  7920. }
  7921. if (payload_max_length > 0 &&
  7922. (total_len > payload_max_length ||
  7923. payload_max_length - total_len < static_cast<size_t>(n))) {
  7924. return ReadContentResult::PayloadTooLarge;
  7925. }
  7926. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  7927. return ReadContentResult::Error;
  7928. }
  7929. total_len += static_cast<size_t>(n);
  7930. }
  7931. }
  7932. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  7933. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  7934. // is the final transfer coding. A single field value may list several
  7935. // codings ("gzip, chunked"), and RFC 9110 5.3 lets that list be split across
  7936. // several Transfer-Encoding lines, which combine into one comma-separated
  7937. // list in the order the lines were received. Headers preserves that order,
  7938. // so the final coding is the last token of the last line. Match it
  7939. // case-insensitively rather than comparing the whole value against
  7940. // "chunked".
  7941. //
  7942. // Security: reading a chunked message as unframed leaves its body in the
  7943. // socket, where a keep-alive connection parses it as a smuggled request.
  7944. // Server::process_request() answers 400 and closes when the final coding is
  7945. // not chunked, so a request whose framing cannot be determined never
  7946. // reaches the "no body" path.
  7947. auto rng = headers.equal_range("Transfer-Encoding");
  7948. if (rng.first == rng.second) { return false; }
  7949. // Cleared per line, so a trailing line carrying no coding at all leaves the
  7950. // combined list ending in nothing rather than inheriting the line before it.
  7951. std::string last_coding;
  7952. for (auto it = rng.first; it != rng.second; ++it) {
  7953. const auto &value = it->second;
  7954. last_coding.clear();
  7955. split(value.data(), value.data() + value.size(), ',',
  7956. [&](const char *b, const char *e) { last_coding.assign(b, e); });
  7957. }
  7958. return case_ignore::equal(last_coding, "chunked");
  7959. }
  7960. // RFC 9112 6.1: a message framed by Transfer-Encoding next to a Content-Length,
  7961. // or in HTTP/1.0, leaves the connection unfit to carry another one.
  7962. template <typename T> inline bool has_faulty_transfer_encoding(const T &msg) {
  7963. return msg.has_header("Transfer-Encoding") &&
  7964. (msg.has_header("Content-Length") || msg.version == "HTTP/1.0");
  7965. }
  7966. inline bool has_conflicting_content_length(const Headers &headers) {
  7967. // RFC 9112 §6.3: a message carrying both Transfer-Encoding and a non-zero
  7968. // Content-Length is framed ambiguously. The body readers here delimit it by
  7969. // the transfer coding and drop Content-Length, while an intermediary may do
  7970. // the reverse, so the two disagree on where the body ends and a reused
  7971. // connection is desynchronised (request/response smuggling). Content-Length:
  7972. // 0 is tolerated for compatibility with existing peers.
  7973. return has_header(headers, "Transfer-Encoding") &&
  7974. get_header_value_u64(headers, "Content-Length", 0, 0) > 0;
  7975. }
  7976. template <typename T, typename U>
  7977. bool prepare_content_receiver(T &x, int &status,
  7978. ContentReceiverWithProgress receiver,
  7979. bool decompress, size_t payload_max_length,
  7980. bool &exceed_payload_max_length, U callback) {
  7981. if (decompress) {
  7982. auto encoding = get_combined_header_value(x.headers, "Content-Encoding");
  7983. std::unique_ptr<decompressor> decompressor;
  7984. if (!encoding.empty()) {
  7985. // A coding we know about but were not built with is an error. An
  7986. // unrecognized coding (including "identity") is left alone and the
  7987. // payload is passed through as-is, since some servers misuse the header,
  7988. // e.g. by sending a character set such as "Content-Encoding: UTF-8".
  7989. decompressor = detail::create_decompressor(encoding);
  7990. if (!decompressor && detail::is_known_content_encoding(encoding)) {
  7991. status = StatusCode::UnsupportedMediaType_415;
  7992. return false;
  7993. }
  7994. }
  7995. if (decompressor) {
  7996. if (decompressor->is_valid()) {
  7997. size_t decompressed_size = 0;
  7998. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  7999. size_t off, size_t len) {
  8000. return decompressor->decompress(
  8001. buf, n, [&](const char *buf2, size_t n2) {
  8002. // Guard against zip-bomb: check
  8003. // decompressed size against limit.
  8004. if (payload_max_length > 0 &&
  8005. (decompressed_size >= payload_max_length ||
  8006. n2 > payload_max_length - decompressed_size)) {
  8007. exceed_payload_max_length = true;
  8008. return false;
  8009. }
  8010. decompressed_size += n2;
  8011. return receiver(buf2, n2, off, len);
  8012. });
  8013. };
  8014. return callback(std::move(out));
  8015. } else {
  8016. status = StatusCode::InternalServerError_500;
  8017. return false;
  8018. }
  8019. }
  8020. }
  8021. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  8022. size_t len) {
  8023. return receiver(buf, n, off, len);
  8024. };
  8025. return callback(std::move(out));
  8026. }
  8027. template <typename T>
  8028. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  8029. DownloadProgress progress,
  8030. ContentReceiverWithProgress receiver, bool decompress) {
  8031. bool exceed_payload_max_length = false;
  8032. return prepare_content_receiver(
  8033. x, status, std::move(receiver), decompress, payload_max_length,
  8034. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  8035. auto ret = true;
  8036. // Note: exceed_payload_max_length may also be set by the decompressor
  8037. // wrapper in prepare_content_receiver when the decompressed payload
  8038. // size exceeds the limit.
  8039. if (is_chunked_transfer_encoding(x.headers)) {
  8040. auto result = read_content_chunked(strm, x, payload_max_length, out);
  8041. if (result == ReadContentResult::Success) {
  8042. ret = true;
  8043. } else if (result == ReadContentResult::PayloadTooLarge) {
  8044. exceed_payload_max_length = true;
  8045. ret = false;
  8046. } else {
  8047. ret = false;
  8048. }
  8049. } else if (!has_header(x.headers, "Content-Length")) {
  8050. auto result =
  8051. read_content_without_length(strm, payload_max_length, out);
  8052. if (result == ReadContentResult::Success) {
  8053. ret = true;
  8054. } else if (result == ReadContentResult::PayloadTooLarge) {
  8055. exceed_payload_max_length = true;
  8056. ret = false;
  8057. } else {
  8058. ret = false;
  8059. }
  8060. } else {
  8061. auto is_invalid_value = false;
  8062. auto len = get_header_value_u64(x.headers, "Content-Length",
  8063. (std::numeric_limits<size_t>::max)(),
  8064. 0, is_invalid_value);
  8065. if (is_invalid_value) {
  8066. ret = false;
  8067. } else if (len > 0) {
  8068. auto result = read_content_with_length(
  8069. strm, len, std::move(progress), out, payload_max_length);
  8070. ret = (result == ReadContentResult::Success);
  8071. if (result == ReadContentResult::PayloadTooLarge) {
  8072. exceed_payload_max_length = true;
  8073. }
  8074. }
  8075. }
  8076. if (!ret) {
  8077. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  8078. : StatusCode::BadRequest_400;
  8079. }
  8080. return ret;
  8081. });
  8082. }
  8083. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  8084. const std::string &path) {
  8085. // Neither the method nor the request target may carry CR/LF, SP or other
  8086. // control octets; otherwise a value smuggled into either splits the request
  8087. // line and injects headers or a whole request.
  8088. if (!fields::is_token(method)) { return -1; }
  8089. if (!fields::is_request_target(path)) { return -1; }
  8090. std::string s = method;
  8091. s += ' ';
  8092. s += path;
  8093. s += " HTTP/1.1\r\n";
  8094. return strm.write(s.data(), s.size());
  8095. }
  8096. inline ssize_t write_response_line(Stream &strm, int status) {
  8097. std::string s = "HTTP/1.1 ";
  8098. s += std::to_string(status);
  8099. s += ' ';
  8100. s += httplib::status_message(status);
  8101. s += "\r\n";
  8102. return strm.write(s.data(), s.size());
  8103. }
  8104. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  8105. ssize_t write_len = 0;
  8106. for (const auto &x : headers) {
  8107. std::string s;
  8108. s = x.first;
  8109. s += ": ";
  8110. s += x.second;
  8111. s += "\r\n";
  8112. auto len = strm.write(s.data(), s.size());
  8113. if (len < 0) { return len; }
  8114. write_len += len;
  8115. }
  8116. auto len = strm.write("\r\n");
  8117. if (len < 0) { return len; }
  8118. write_len += len;
  8119. return write_len;
  8120. }
  8121. inline bool write_data(Stream &strm, const char *d, size_t l) {
  8122. size_t offset = 0;
  8123. while (offset < l) {
  8124. auto length = strm.write(d + offset, l - offset);
  8125. if (length < 0) { return false; }
  8126. offset += static_cast<size_t>(length);
  8127. }
  8128. return true;
  8129. }
  8130. template <typename T>
  8131. inline bool write_content_with_progress(Stream &strm,
  8132. const ContentProvider &content_provider,
  8133. size_t offset, size_t length,
  8134. T is_shutting_down,
  8135. const UploadProgress &upload_progress,
  8136. Error &error) {
  8137. size_t end_offset = offset + length;
  8138. size_t start_offset = offset;
  8139. auto ok = true;
  8140. auto finished = false;
  8141. DataSink data_sink;
  8142. data_sink.write = [&](const char *d, size_t l) -> bool {
  8143. if (ok) {
  8144. // Bytes past `length` would follow the framed body, where the peer reads
  8145. // them as the next message. Write only what fits and fail the rest.
  8146. if (l > end_offset - offset) {
  8147. l = end_offset - offset;
  8148. ok = false;
  8149. }
  8150. if (write_data(strm, d, l)) {
  8151. offset += l;
  8152. if (upload_progress && length > 0) {
  8153. size_t current_written = offset - start_offset;
  8154. if (!upload_progress(current_written, length)) {
  8155. ok = false;
  8156. return false;
  8157. }
  8158. }
  8159. } else {
  8160. ok = false;
  8161. }
  8162. }
  8163. return ok;
  8164. };
  8165. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  8166. // The body is framed by `length`, so a provider that reports itself done
  8167. // early has truncated it. Record that and let the short-body check below
  8168. // fail the write, rather than calling the provider again forever.
  8169. data_sink.done = [&]() { finished = true; };
  8170. while (offset < end_offset && !finished && !is_shutting_down()) {
  8171. auto last_offset = offset;
  8172. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  8173. error = Error::Write;
  8174. return false;
  8175. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  8176. error = Error::Canceled;
  8177. return false;
  8178. } else if (!ok) {
  8179. error = Error::Write;
  8180. return false;
  8181. }
  8182. // A provider that reports success without writing anything and without
  8183. // reporting itself done gets handed the same offset and length again on
  8184. // the next pass, so it would spin here for as long as the peer stays
  8185. // connected. Treat making no progress as a short body, like done() early.
  8186. if (!finished && offset == last_offset) {
  8187. error = Error::Write;
  8188. return false;
  8189. }
  8190. }
  8191. if (offset < end_offset) { // done() called early, or is_shutting_down()
  8192. error = Error::Write;
  8193. return false;
  8194. }
  8195. error = Error::Success;
  8196. return true;
  8197. }
  8198. template <typename T>
  8199. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  8200. size_t offset, size_t length, T is_shutting_down,
  8201. Error &error) {
  8202. return write_content_with_progress<T>(strm, content_provider, offset, length,
  8203. is_shutting_down, nullptr, error);
  8204. }
  8205. template <typename T>
  8206. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  8207. size_t offset, size_t length,
  8208. const T &is_shutting_down) {
  8209. auto error = Error::Success;
  8210. return write_content(strm, content_provider, offset, length, is_shutting_down,
  8211. error);
  8212. }
  8213. template <typename T>
  8214. inline bool
  8215. write_content_without_length(Stream &strm,
  8216. const ContentProvider &content_provider,
  8217. const T &is_shutting_down) {
  8218. size_t offset = 0;
  8219. auto data_available = true;
  8220. auto ok = true;
  8221. DataSink data_sink;
  8222. data_sink.write = [&](const char *d, size_t l) -> bool {
  8223. if (ok) {
  8224. offset += l;
  8225. if (!write_data(strm, d, l)) { ok = false; }
  8226. }
  8227. return ok;
  8228. };
  8229. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  8230. data_sink.done = [&](void) { data_available = false; };
  8231. while (data_available && !is_shutting_down()) {
  8232. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  8233. return false;
  8234. } else if (!content_provider(offset, 0, data_sink)) {
  8235. return false;
  8236. } else if (!ok) {
  8237. return false;
  8238. }
  8239. }
  8240. return !data_available; // true only if done() was called, false if shutting
  8241. // down
  8242. }
  8243. // Runs a known-length content provider to completion and compresses what it
  8244. // writes into `out`, chunk by chunk, without holding the identity form.
  8245. inline bool compress_content_provider(const ContentProvider &content_provider,
  8246. size_t length, compressor &cmp,
  8247. std::string &out) {
  8248. size_t offset = 0;
  8249. auto ok = true;
  8250. auto finished = false;
  8251. DataSink data_sink;
  8252. auto append = [&](const char *data, size_t data_len) {
  8253. out.append(data, data_len);
  8254. return true;
  8255. };
  8256. data_sink.write = [&](const char *d, size_t l) -> bool {
  8257. if (!ok) { return false; }
  8258. offset += l;
  8259. if (l > 0 && !cmp.compress(d, l, false, append)) { ok = false; }
  8260. return ok;
  8261. };
  8262. // The body is framed by `length`, so a provider that reports itself done
  8263. // early has truncated it; the short-body check below turns that into a
  8264. // failure rather than calling the provider again forever.
  8265. data_sink.done = [&]() { finished = true; };
  8266. while (offset < length && !finished) {
  8267. auto prev_offset = offset;
  8268. if (!content_provider(offset, length - offset, data_sink) || !ok) {
  8269. return false;
  8270. }
  8271. // No Stream to block on here, so a provider that keeps returning true
  8272. // without writing would spin. Treat a pass that made no progress as a
  8273. // failure.
  8274. if (offset == prev_offset) { return false; }
  8275. }
  8276. if (offset != length) { return false; }
  8277. return cmp.compress(nullptr, 0, true, append);
  8278. }
  8279. // Serves `m` as the response body. `set_content_provider()` clears the coding
  8280. // and the file flag, so recording them has to come after; keeping all of it
  8281. // here means a third file-serving path cannot get that order wrong.
  8282. inline void set_file_content_provider(Response &res,
  8283. const std::shared_ptr<mmap> &m,
  8284. const std::string &content_type,
  8285. EncodingType encoding) {
  8286. // One read and one write move up to this much of the file at a time.
  8287. auto buf = std::make_shared<std::vector<char>>(
  8288. (std::min)(m->size(), size_t(256 * 1024)));
  8289. res.set_content_provider(
  8290. m->size(), content_type,
  8291. [m, buf](size_t offset, size_t length, DataSink &sink) -> bool {
  8292. // Never read past the file, which ends the response early if it has
  8293. // shrunk since it was opened.
  8294. auto n = m->read(offset, buf->data(), (std::min)(length, buf->size()));
  8295. if (n == 0) { return false; }
  8296. sink.write(buf->data(), n);
  8297. return true;
  8298. });
  8299. res.is_file_content_provider_ = true;
  8300. res.content_coding_ = encoding;
  8301. }
  8302. template <typename T, typename U>
  8303. inline bool
  8304. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  8305. const T &is_shutting_down, U &compressor, Error &error) {
  8306. size_t offset = 0;
  8307. auto data_available = true;
  8308. auto ok = true;
  8309. DataSink data_sink;
  8310. data_sink.write = [&](const char *d, size_t l) -> bool {
  8311. // Only done()/done_with_trailer() end a chunked body. A pass with nothing
  8312. // to hand over is ordinary (an empty buffer popped off a queue), and a
  8313. // zero-length chunk is the terminator, so it must not be emitted here.
  8314. if (ok && l > 0) {
  8315. offset += l;
  8316. std::string payload;
  8317. if (compressor.compress(d, l, false,
  8318. [&](const char *data, size_t data_len) {
  8319. payload.append(data, data_len);
  8320. return true;
  8321. })) {
  8322. if (!payload.empty()) {
  8323. // Emit chunked response header and footer for each chunk
  8324. auto chunk =
  8325. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  8326. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  8327. }
  8328. } else {
  8329. ok = false;
  8330. }
  8331. }
  8332. return ok;
  8333. };
  8334. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  8335. auto done_with_trailer = [&](const Headers *trailer) {
  8336. if (!ok) { return; }
  8337. data_available = false;
  8338. std::string payload;
  8339. if (!compressor.compress(nullptr, 0, true,
  8340. [&](const char *data, size_t data_len) {
  8341. payload.append(data, data_len);
  8342. return true;
  8343. })) {
  8344. ok = false;
  8345. return;
  8346. }
  8347. if (!payload.empty()) {
  8348. // Emit chunked response header and footer for each chunk
  8349. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  8350. if (!write_data(strm, chunk.data(), chunk.size())) {
  8351. ok = false;
  8352. return;
  8353. }
  8354. }
  8355. constexpr const char done_marker[] = "0\r\n";
  8356. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  8357. // Trailer
  8358. if (trailer) {
  8359. for (const auto &kv : *trailer) {
  8360. // Skip fields with invalid names or values to prevent response
  8361. // splitting via CR/LF injection, matching set_header().
  8362. if (!fields::is_field_valid(kv.first, kv.second)) { continue; }
  8363. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  8364. if (!write_data(strm, field_line.data(), field_line.size())) {
  8365. ok = false;
  8366. }
  8367. }
  8368. }
  8369. constexpr const char crlf[] = "\r\n";
  8370. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  8371. };
  8372. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  8373. data_sink.done_with_trailer = [&](const Headers &trailer) {
  8374. done_with_trailer(&trailer);
  8375. };
  8376. while (data_available && !is_shutting_down()) {
  8377. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  8378. error = Error::Write;
  8379. return false;
  8380. } else if (!content_provider(offset, 0, data_sink)) {
  8381. error = Error::Canceled;
  8382. return false;
  8383. } else if (!ok) {
  8384. error = Error::Write;
  8385. return false;
  8386. }
  8387. }
  8388. if (data_available) { // exited due to is_shutting_down(), not done()
  8389. error = Error::Write;
  8390. return false;
  8391. }
  8392. error = Error::Success;
  8393. return true;
  8394. }
  8395. template <typename T, typename U>
  8396. inline bool write_content_chunked(Stream &strm,
  8397. const ContentProvider &content_provider,
  8398. const T &is_shutting_down, U &compressor) {
  8399. auto error = Error::Success;
  8400. return write_content_chunked(strm, content_provider, is_shutting_down,
  8401. compressor, error);
  8402. }
  8403. template <typename T>
  8404. inline bool redirect(T &cli, Request &req, Response &res,
  8405. const std::string &path, const std::string &location,
  8406. Error &error) {
  8407. Request new_req = req;
  8408. new_req.path = path;
  8409. new_req.params.clear();
  8410. new_req.redirect_count_ -= 1;
  8411. if (res.status == StatusCode::SeeOther_303 &&
  8412. (req.method != "GET" && req.method != "HEAD")) {
  8413. new_req.method = "GET";
  8414. new_req.body.clear();
  8415. new_req.headers.clear();
  8416. new_req.content_length_ = 0;
  8417. new_req.content_provider_ = nullptr;
  8418. new_req.is_chunked_content_provider_ = false;
  8419. }
  8420. Response new_res;
  8421. auto ret = cli.send(new_req, new_res, error);
  8422. if (ret) {
  8423. req = std::move(new_req);
  8424. res = std::move(new_res);
  8425. if (res.location.empty()) { res.location = location; }
  8426. }
  8427. return ret;
  8428. }
  8429. inline std::string params_to_query_str(const Params &params) {
  8430. std::string query;
  8431. for (auto it = params.begin(); it != params.end(); ++it) {
  8432. if (it != params.begin()) { query += '&'; }
  8433. query += encode_query_component(it->first);
  8434. query += '=';
  8435. query += encode_query_component(it->second);
  8436. }
  8437. return query;
  8438. }
  8439. // Splits one "key=value" span of a query string at its first '='. A span with
  8440. // no '=' at all lands entirely in key, leaving val empty, which is how a bare
  8441. // "?flag" keeps its name.
  8442. inline void divide_query_pair(const char *b, const char *e, std::string &key,
  8443. std::string &val) {
  8444. divide(b, static_cast<std::size_t>(e - b), '=',
  8445. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  8446. std::size_t rhs_size) {
  8447. key.assign(lhs_data, lhs_size);
  8448. val.assign(rhs_data, rhs_size);
  8449. });
  8450. }
  8451. inline void parse_query_text(const char *data, std::size_t size,
  8452. Params &params) {
  8453. std::set<std::string> cache;
  8454. split(data, data + size, '&', [&](const char *b, const char *e) {
  8455. std::string kv(b, e);
  8456. if (cache.find(kv) != cache.end()) { return; }
  8457. cache.insert(std::move(kv));
  8458. std::string key;
  8459. std::string val;
  8460. divide_query_pair(b, e, key, val);
  8461. if (!key.empty()) {
  8462. params.emplace(decode_query_component(key), decode_query_component(val));
  8463. }
  8464. });
  8465. }
  8466. inline void parse_query_text(const std::string &s, Params &params) {
  8467. parse_query_text(s.data(), s.size(), params);
  8468. }
  8469. // Normalize a query string by decoding and re-encoding each key/value pair
  8470. // while preserving the original parameter order. This avoids double-encoding
  8471. // and ensures consistent encoding. It works on the raw string rather than
  8472. // parsing into Params and re-serializing, because that round trip cannot
  8473. // reproduce the input: params_to_query_str() always emits '=', so a bare
  8474. // "flag" would come back as "flag=", and parse_query_text() drops exactly
  8475. // duplicated pairs.
  8476. inline std::string normalize_query_string(const std::string &query) {
  8477. std::string result;
  8478. split(query.data(), query.data() + query.size(), '&',
  8479. [&](const char *b, const char *e) {
  8480. std::string key;
  8481. std::string val;
  8482. divide_query_pair(b, e, key, val);
  8483. if (!key.empty()) {
  8484. auto dec_key = decode_query_component(key);
  8485. auto dec_val = decode_query_component(val);
  8486. if (!result.empty()) { result += '&'; }
  8487. result += encode_query_component(dec_key);
  8488. if (!val.empty() || std::find(b, e, '=') != e) {
  8489. result += '=';
  8490. result += encode_query_component(dec_val);
  8491. }
  8492. }
  8493. });
  8494. return result;
  8495. }
  8496. // The query of a client's path: what follows '?', up to the fragment.
  8497. inline std::string query_of(const std::string &path) {
  8498. auto fragment_pos = path.find('#');
  8499. auto query_pos = path.find('?');
  8500. return query_pos < fragment_pos
  8501. ? path.substr(query_pos + 1, fragment_pos - query_pos - 1)
  8502. : std::string();
  8503. }
  8504. // Build the request target that goes on the wire from a caller-supplied path.
  8505. // Shared by the buffered send path and the streaming API so that both put the
  8506. // same bytes in the request line for the same input.
  8507. inline std::string encode_request_target(const std::string &uri,
  8508. bool path_encode) {
  8509. // The fragment stays with the client (RFC 9110 §7.1).
  8510. auto target = uri.substr(0, uri.find('#'));
  8511. // `substr(0, npos)` yields the whole string, which is what the no-query
  8512. // case needs.
  8513. auto query_pos = target.find('?');
  8514. auto path_part = target.substr(0, query_pos);
  8515. std::string query_part;
  8516. if (query_pos != std::string::npos) {
  8517. query_part = target.substr(query_pos + 1);
  8518. }
  8519. auto result = path_encode ? encode_path(path_part) : std::move(path_part);
  8520. if (!query_part.empty()) {
  8521. // When path encoding is disabled the caller has supplied an already-encoded
  8522. // target and expects the exact bytes to be sent on the wire, so skip
  8523. // normalization for the query too. Normalizing would decode-then-re-encode
  8524. // it and corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  8525. // which a strict RFC 3986 server decodes back as `+`, not a space).
  8526. if (path_encode) {
  8527. auto normalized = normalize_query_string(query_part);
  8528. if (!normalized.empty()) {
  8529. result += '?';
  8530. result += normalized;
  8531. }
  8532. } else {
  8533. result += '?';
  8534. result += query_part;
  8535. }
  8536. }
  8537. return result;
  8538. }
  8539. inline bool parse_multipart_boundary(const std::string &content_type,
  8540. std::string &boundary) {
  8541. std::map<std::string, std::string> params;
  8542. extract_media_type(content_type, &params);
  8543. auto it = params.find("boundary");
  8544. if (it == params.end()) { return false; }
  8545. boundary = it->second;
  8546. // RFC 2046 5.1.1 caps a boundary at 70 characters. The parser scans the body
  8547. // for "--" + boundary, so a body crafted to repeat that delimiter's leading
  8548. // bytes costs a nearly full comparison at nearly every position: the
  8549. // boundary's length multiplies the worst-case cost of scanning a body.
  8550. return !boundary.empty() && boundary.size() <= 70;
  8551. }
  8552. inline void parse_disposition_params(const std::string &s, Params &params) {
  8553. std::set<std::string> cache;
  8554. split_unquoted(
  8555. s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  8556. std::string kv(b, e);
  8557. if (cache.find(kv) != cache.end()) { return; }
  8558. cache.insert(kv);
  8559. std::string key;
  8560. std::string val;
  8561. divide_param_pair(b, e, key, val);
  8562. if (!key.empty()) {
  8563. params.emplace(trim_double_quotes_copy(key), unquote_param(val));
  8564. }
  8565. });
  8566. }
  8567. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8568. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  8569. #else
  8570. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  8571. #endif
  8572. auto is_valid = [](const std::string &str) {
  8573. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  8574. };
  8575. if (s.size() > 7 && case_ignore::equal(s.substr(0, 6), "bytes=")) {
  8576. const auto pos = static_cast<size_t>(6);
  8577. const auto len = static_cast<size_t>(s.size() - 6);
  8578. auto all_valid_ranges = true;
  8579. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  8580. if (!all_valid_ranges) { return; }
  8581. const auto it = std::find(b, e, '-');
  8582. if (it == e) {
  8583. all_valid_ranges = false;
  8584. return;
  8585. }
  8586. const auto lhs = std::string(b, it);
  8587. const auto rhs = std::string(it + 1, e);
  8588. if (!is_valid(lhs) || !is_valid(rhs)) {
  8589. all_valid_ranges = false;
  8590. return;
  8591. }
  8592. ssize_t first = -1;
  8593. if (!lhs.empty()) {
  8594. // Reject an overflowing first-byte-pos; treating it as absent (-1)
  8595. // would turn the range into a suffix range.
  8596. auto res =
  8597. detail::from_chars(lhs.data(), lhs.data() + lhs.size(), first);
  8598. if (res.ec != std::errc{}) {
  8599. all_valid_ranges = false;
  8600. return;
  8601. }
  8602. }
  8603. ssize_t last = -1;
  8604. if (!rhs.empty()) {
  8605. // An overflowing last-byte-pos is past any content length, so keeping
  8606. // -1 ("remainder", RFC 9110 14.1.2) is correct here.
  8607. ssize_t v;
  8608. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  8609. if (res.ec == std::errc{}) { last = v; }
  8610. }
  8611. if ((first == -1 && last == -1) ||
  8612. (first != -1 && last != -1 && first > last)) {
  8613. all_valid_ranges = false;
  8614. return;
  8615. }
  8616. ranges.emplace_back(first, last);
  8617. });
  8618. return all_valid_ranges && !ranges.empty();
  8619. }
  8620. return false;
  8621. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8622. }
  8623. #else
  8624. } catch (...) { return false; }
  8625. #endif
  8626. // Removes each quoted-string, honoring a quoted-pair (RFC 9110 Section 5.6.4)
  8627. inline std::string remove_quoted_strings(const std::string &s) {
  8628. std::string out;
  8629. auto in_quotes = false;
  8630. for (size_t i = 0; i < s.size(); i++) {
  8631. if (s[i] == '"') {
  8632. in_quotes = !in_quotes;
  8633. } else if (!in_quotes) {
  8634. out += s[i];
  8635. } else if (s[i] == '\\') {
  8636. i++;
  8637. }
  8638. }
  8639. return out;
  8640. }
  8641. inline bool parse_accept_header(const std::string &s,
  8642. std::vector<std::string> &content_types) {
  8643. // Parameter values are not used here, so a quoted-string is dropped rather
  8644. // than parsed: a ',' or ';' inside one must not be read as a delimiter.
  8645. if (s.find('"') != std::string::npos) {
  8646. return parse_accept_header(remove_quoted_strings(s), content_types);
  8647. }
  8648. content_types.clear();
  8649. // Empty string is considered valid (no preference)
  8650. if (s.empty()) { return true; }
  8651. struct AcceptEntry {
  8652. std::string media_type;
  8653. double quality;
  8654. int order;
  8655. };
  8656. std::vector<AcceptEntry> entries;
  8657. int order = 0;
  8658. bool has_invalid_entry = false;
  8659. // Split by comma and parse each entry. RFC 9110 Section 5.6.1.2: a recipient
  8660. // has to parse and ignore empty list elements, so a leading, trailing or
  8661. // doubled comma must not turn a legal Accept value into 400 Bad Request.
  8662. // split() skips them, and the header length limit bounds how many a sender
  8663. // can send, so ignoring all of them cannot be used as a denial-of-service
  8664. // vector.
  8665. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  8666. std::string entry(b, e);
  8667. entry = trim_copy(entry);
  8668. AcceptEntry accept_entry;
  8669. accept_entry.order = order++;
  8670. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  8671. accept_entry.media_type, accept_entry.quality)) {
  8672. has_invalid_entry = true;
  8673. return;
  8674. }
  8675. // Remove additional parameters from media type
  8676. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  8677. // Basic validation of media type format
  8678. if (accept_entry.media_type.empty()) {
  8679. has_invalid_entry = true;
  8680. return;
  8681. }
  8682. // Check for basic media type format (should contain '/' or be '*')
  8683. if (accept_entry.media_type != "*" &&
  8684. accept_entry.media_type.find('/') == std::string::npos) {
  8685. has_invalid_entry = true;
  8686. return;
  8687. }
  8688. entries.push_back(std::move(accept_entry));
  8689. });
  8690. // Return false if any invalid entry was found
  8691. if (has_invalid_entry) { return false; }
  8692. // Sort by quality (descending), then by original order (ascending)
  8693. std::sort(entries.begin(), entries.end(),
  8694. [](const AcceptEntry &a, const AcceptEntry &b) {
  8695. if (a.quality != b.quality) {
  8696. return a.quality > b.quality; // Higher quality first
  8697. }
  8698. return a.order < b.order; // Earlier order first for same quality
  8699. });
  8700. // Extract sorted media types
  8701. content_types.reserve(entries.size());
  8702. for (auto &entry : entries) {
  8703. content_types.push_back(std::move(entry.media_type));
  8704. }
  8705. return true;
  8706. }
  8707. class FormDataParser {
  8708. public:
  8709. FormDataParser() = default;
  8710. void set_boundary(std::string &&boundary) {
  8711. boundary_ = std::move(boundary);
  8712. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  8713. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  8714. }
  8715. bool is_valid() const { return is_valid_; }
  8716. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  8717. const ContentReceiver &content_callback) {
  8718. // Once the close delimiter has been seen the rest of the body is epilogue
  8719. // to be discarded (RFC 2046). Drop it without buffering so a large epilogue
  8720. // spread across reads is not copied in only to be erased right away.
  8721. if (state_ == 5) { return true; }
  8722. buf_append(buf, n);
  8723. while (buf_size() > 0) {
  8724. switch (state_) {
  8725. case 0: { // Initial boundary
  8726. auto pos = buf_find(dash_boundary_crlf_);
  8727. if (pos == buf_size()) {
  8728. // Not found yet: keep only a possible partial boundary at the tail so
  8729. // that a body which never contains the boundary cannot grow the
  8730. // buffer (and get rescanned from the start) without bound.
  8731. auto keep = dash_boundary_crlf_.size() - 1;
  8732. if (buf_size() > keep) { buf_erase(buf_size() - keep); }
  8733. return true;
  8734. }
  8735. buf_erase(pos + dash_boundary_crlf_.size());
  8736. state_ = 1;
  8737. break;
  8738. }
  8739. case 1: { // New entry
  8740. clear_file_info();
  8741. header_searched_ = 0;
  8742. state_ = 2;
  8743. break;
  8744. }
  8745. case 2: { // Headers
  8746. // Resume where the last call stopped looking, so that a line arriving
  8747. // a few bytes at a time is not searched from its start each time.
  8748. auto pos = buf_find(crlf_, header_searched_);
  8749. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  8750. while (pos < buf_size()) {
  8751. // Empty line
  8752. if (pos == 0) {
  8753. if (!header_callback(file_)) {
  8754. is_valid_ = false;
  8755. return false;
  8756. }
  8757. buf_erase(crlf_.size());
  8758. state_ = 3;
  8759. break;
  8760. }
  8761. // Check header count limit
  8762. if (header_count_ >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  8763. is_valid_ = false;
  8764. return false;
  8765. }
  8766. header_count_++;
  8767. const auto header = buf_head(pos);
  8768. if (!parse_header(header.data(), header.data() + header.size(),
  8769. [&](const std::string &, const std::string &) {})) {
  8770. is_valid_ = false;
  8771. return false;
  8772. }
  8773. // Parse and emplace space trimmed headers into a map
  8774. if (!parse_header(
  8775. header.data(), header.data() + header.size(),
  8776. [&](const std::string &key, const std::string &val) {
  8777. file_.headers.emplace(key, val);
  8778. })) {
  8779. is_valid_ = false;
  8780. return false;
  8781. }
  8782. constexpr const char header_content_type[] = "Content-Type:";
  8783. if (start_with_case_ignore(header, header_content_type)) {
  8784. file_.content_type =
  8785. trim_copy(header.substr(str_len(header_content_type)));
  8786. } else {
  8787. std::string disposition_params;
  8788. if (parse_content_disposition(header, disposition_params)) {
  8789. Params params;
  8790. parse_disposition_params(disposition_params, params);
  8791. auto it = params.find("name");
  8792. if (it != params.end()) {
  8793. file_.name = it->second;
  8794. } else {
  8795. is_valid_ = false;
  8796. return false;
  8797. }
  8798. it = params.find("filename");
  8799. if (it != params.end()) { file_.filename = it->second; }
  8800. it = params.find("filename*");
  8801. if (it != params.end()) {
  8802. // RFC 5987: only UTF-8 encoding is allowed
  8803. const auto &val = it->second;
  8804. constexpr const char utf8_prefix[] = "UTF-8''";
  8805. constexpr size_t prefix_len = str_len(utf8_prefix);
  8806. if (val.size() > prefix_len &&
  8807. start_with_case_ignore(val, utf8_prefix)) {
  8808. file_.filename = decode_path_component(
  8809. val.substr(prefix_len)); // override...
  8810. } else {
  8811. is_valid_ = false;
  8812. return false;
  8813. }
  8814. }
  8815. }
  8816. }
  8817. buf_erase(pos + crlf_.size());
  8818. pos = buf_find(crlf_);
  8819. }
  8820. if (state_ != 3) {
  8821. // The CR of the CRLF may be the last byte so far.
  8822. header_searched_ = buf_size() > 0 ? buf_size() - 1 : 0;
  8823. return true;
  8824. }
  8825. break;
  8826. }
  8827. case 3: { // Body
  8828. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  8829. auto pos = buf_find(crlf_dash_boundary_);
  8830. if (pos < buf_size()) {
  8831. if (!content_callback(buf_data(), pos)) {
  8832. is_valid_ = false;
  8833. return false;
  8834. }
  8835. buf_erase(pos + crlf_dash_boundary_.size());
  8836. state_ = 4;
  8837. } else {
  8838. auto len = buf_size() - crlf_dash_boundary_.size();
  8839. if (len > 0) {
  8840. if (!content_callback(buf_data(), len)) {
  8841. is_valid_ = false;
  8842. return false;
  8843. }
  8844. buf_erase(len);
  8845. }
  8846. return true;
  8847. }
  8848. break;
  8849. }
  8850. case 4: { // Boundary
  8851. if (crlf_.size() > buf_size()) { return true; }
  8852. if (buf_start_with(crlf_)) {
  8853. buf_erase(crlf_.size());
  8854. state_ = 1;
  8855. } else if (buf_start_with(dash_)) {
  8856. buf_erase(dash_.size());
  8857. is_valid_ = true;
  8858. state_ = 5;
  8859. } else {
  8860. // Only CRLF (another part follows) and "--" (close-delimiter) are
  8861. // accepted after a boundary; RFC 2046 allows transport-padding in
  8862. // between, but this parser has never supported it. Either way the
  8863. // body is already destined to be rejected, so fail now instead of
  8864. // buffering the rest of it. Both are two bytes, so the check above
  8865. // already guarantees enough buffered data to decide.
  8866. is_valid_ = false;
  8867. return false;
  8868. }
  8869. break;
  8870. }
  8871. case 5: { // Epilogue
  8872. buf_erase(buf_size());
  8873. break;
  8874. }
  8875. }
  8876. }
  8877. return true;
  8878. }
  8879. private:
  8880. void clear_file_info() {
  8881. file_.name.clear();
  8882. file_.filename.clear();
  8883. file_.content_type.clear();
  8884. file_.headers.clear();
  8885. header_count_ = 0;
  8886. }
  8887. bool start_with_case_ignore(const std::string &a, const char *b,
  8888. size_t offset = 0) const {
  8889. const auto b_len = strlen(b);
  8890. if (a.size() < offset + b_len) { return false; }
  8891. for (size_t i = 0; i < b_len; i++) {
  8892. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  8893. return false;
  8894. }
  8895. }
  8896. return true;
  8897. }
  8898. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  8899. // Returns true if header matches, with the params portion in `params_out`.
  8900. bool parse_content_disposition(const std::string &header,
  8901. std::string &params_out) const {
  8902. constexpr const char prefix[] = "Content-Disposition:";
  8903. constexpr size_t prefix_len = str_len(prefix);
  8904. if (!start_with_case_ignore(header, prefix)) { return false; }
  8905. // Skip whitespace after "Content-Disposition:"
  8906. auto pos = prefix_len;
  8907. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  8908. pos++;
  8909. }
  8910. // Match "form-data;" (case-insensitive)
  8911. constexpr const char form_data[] = "form-data;";
  8912. constexpr size_t form_data_len = str_len(form_data);
  8913. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  8914. pos += form_data_len;
  8915. // Skip whitespace after "form-data;"
  8916. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  8917. pos++;
  8918. }
  8919. params_out = header.substr(pos);
  8920. return true;
  8921. }
  8922. const std::string dash_ = "--";
  8923. const std::string crlf_ = "\r\n";
  8924. std::string boundary_;
  8925. std::string dash_boundary_crlf_;
  8926. std::string crlf_dash_boundary_;
  8927. size_t state_ = 0;
  8928. bool is_valid_ = false;
  8929. FormData file_;
  8930. size_t header_count_ = 0;
  8931. size_t header_searched_ = 0;
  8932. // Buffer
  8933. bool start_with(const std::string &a, size_t spos, size_t epos,
  8934. const std::string &b) const {
  8935. if (epos - spos < b.size()) { return false; }
  8936. for (size_t i = 0; i < b.size(); i++) {
  8937. if (a[i + spos] != b[i]) { return false; }
  8938. }
  8939. return true;
  8940. }
  8941. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  8942. const char *buf_data() const { return &buf_[buf_spos_]; }
  8943. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  8944. bool buf_start_with(const std::string &s) const {
  8945. return start_with(buf_, buf_spos_, buf_epos_, s);
  8946. }
  8947. size_t buf_find(const std::string &s, size_t from = 0) const {
  8948. auto c = s.front();
  8949. size_t off = buf_spos_ + from;
  8950. while (off < buf_epos_) {
  8951. auto pos = off;
  8952. while (true) {
  8953. if (pos == buf_epos_) { return buf_size(); }
  8954. if (buf_[pos] == c) { break; }
  8955. pos++;
  8956. }
  8957. auto remaining_size = buf_epos_ - pos;
  8958. if (s.size() > remaining_size) { return buf_size(); }
  8959. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  8960. off = pos + 1;
  8961. }
  8962. return buf_size();
  8963. }
  8964. void buf_append(const char *data, size_t n) {
  8965. auto remaining_size = buf_size();
  8966. if (remaining_size > 0 && buf_spos_ > 0) {
  8967. for (size_t i = 0; i < remaining_size; i++) {
  8968. buf_[i] = buf_[buf_spos_ + i];
  8969. }
  8970. }
  8971. buf_spos_ = 0;
  8972. buf_epos_ = remaining_size;
  8973. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  8974. for (size_t i = 0; i < n; i++) {
  8975. buf_[buf_epos_ + i] = data[i];
  8976. }
  8977. buf_epos_ += n;
  8978. }
  8979. void buf_erase(size_t size) { buf_spos_ += size; }
  8980. std::string buf_;
  8981. size_t buf_spos_ = 0;
  8982. size_t buf_epos_ = 0;
  8983. };
  8984. inline std::string random_string(size_t length) {
  8985. constexpr const char data[] =
  8986. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  8987. std::string result(length, '\0');
  8988. fill_random_bytes(reinterpret_cast<unsigned char *>(&result[0]), length);
  8989. for (auto &c : result) {
  8990. c = data[static_cast<unsigned char>(c) % (sizeof(data) - 1)];
  8991. }
  8992. return result;
  8993. }
  8994. inline std::string make_multipart_data_boundary() {
  8995. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  8996. }
  8997. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  8998. auto valid = true;
  8999. for (size_t i = 0; i < boundary.size(); i++) {
  9000. auto c = boundary[i];
  9001. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  9002. valid = false;
  9003. break;
  9004. }
  9005. }
  9006. return valid;
  9007. }
  9008. // Escape a multipart field name/filename following the WHATWG HTML standard
  9009. // ("escape a multipart form-data name"): '"' -> %22, CR -> %0D, LF -> %0A.
  9010. // As the value is a quoted-string, '\' -> '\\' too, which browsers leave out.
  9011. // With quoted = false, only CR and LF are escaped; this is for header values
  9012. // outside a quoted-string (e.g. Content-Type), where '"' and '\' are legal.
  9013. inline std::string escape_multipart_field(const std::string &s,
  9014. bool quoted = true) {
  9015. std::string result;
  9016. result.reserve(s.size());
  9017. for (auto c : s) {
  9018. switch (c) {
  9019. case '"':
  9020. if (quoted) {
  9021. result += "%22";
  9022. } else {
  9023. result += c;
  9024. }
  9025. break;
  9026. case '\\':
  9027. // A lone backslash would escape the character after it (RFC 9110
  9028. // 5.6.4).
  9029. if (quoted) { result += '\\'; }
  9030. result += c;
  9031. break;
  9032. case '\r': result += "%0D"; break;
  9033. case '\n': result += "%0A"; break;
  9034. default: result += c; break;
  9035. }
  9036. }
  9037. return result;
  9038. }
  9039. template <typename T>
  9040. inline std::string
  9041. serialize_multipart_formdata_item_begin(const T &item,
  9042. const std::string &boundary) {
  9043. std::string body = "--" + boundary + "\r\n";
  9044. body += "Content-Disposition: form-data; name=\"" +
  9045. escape_multipart_field(item.name) + "\"";
  9046. if (!item.filename.empty()) {
  9047. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  9048. }
  9049. body += "\r\n";
  9050. if (!item.content_type.empty()) {
  9051. body +=
  9052. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  9053. "\r\n";
  9054. }
  9055. body += "\r\n";
  9056. return body;
  9057. }
  9058. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  9059. inline std::string
  9060. serialize_multipart_formdata_finish(const std::string &boundary) {
  9061. return "--" + boundary + "--\r\n";
  9062. }
  9063. inline std::string
  9064. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  9065. return "multipart/form-data; boundary=" + boundary;
  9066. }
  9067. inline std::string
  9068. serialize_multipart_formdata(const UploadFormDataItems &items,
  9069. const std::string &boundary, bool finish = true) {
  9070. std::string body;
  9071. for (const auto &item : items) {
  9072. body += serialize_multipart_formdata_item_begin(item, boundary);
  9073. body += item.content + serialize_multipart_formdata_item_end();
  9074. }
  9075. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  9076. return body;
  9077. }
  9078. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  9079. const std::string &boundary) {
  9080. size_t total = 0;
  9081. for (const auto &item : items) {
  9082. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  9083. total += item.content.size();
  9084. total += serialize_multipart_formdata_item_end().size();
  9085. }
  9086. total += serialize_multipart_formdata_finish(boundary).size();
  9087. return total;
  9088. }
  9089. struct MultipartSegment {
  9090. const char *data;
  9091. size_t size;
  9092. };
  9093. // NOTE: items must outlive the returned ContentProvider
  9094. // (safe for synchronous use inside Post/Put/Patch)
  9095. inline ContentProvider
  9096. make_multipart_content_provider(const UploadFormDataItems &items,
  9097. const std::string &boundary) {
  9098. // Own the per-item header strings and the finish string
  9099. std::vector<std::string> owned;
  9100. owned.reserve(items.size() + 1);
  9101. for (const auto &item : items)
  9102. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  9103. owned.push_back(serialize_multipart_formdata_finish(boundary));
  9104. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  9105. std::vector<MultipartSegment> segs;
  9106. segs.reserve(items.size() * 3 + 1);
  9107. static const char crlf[] = "\r\n";
  9108. for (size_t i = 0; i < items.size(); i++) {
  9109. segs.push_back({owned[i].data(), owned[i].size()});
  9110. segs.push_back({items[i].content.data(), items[i].content.size()});
  9111. segs.push_back({crlf, 2});
  9112. }
  9113. segs.push_back({owned.back().data(), owned.back().size()});
  9114. struct MultipartState {
  9115. std::vector<std::string> owned;
  9116. std::vector<MultipartSegment> segs;
  9117. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  9118. };
  9119. auto state = std::make_shared<MultipartState>();
  9120. state->owned = std::move(owned);
  9121. // `segs` holds raw pointers into owned strings; std::string move preserves
  9122. // the data pointer, so these pointers remain valid after the move above.
  9123. state->segs = std::move(segs);
  9124. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  9125. // Buffer multiple small segments into fewer, larger writes to avoid
  9126. // excessive TCP packets when there are many form data items (#2410)
  9127. auto &buf = state->buf;
  9128. auto buf_size = buf.size();
  9129. size_t buf_len = 0;
  9130. size_t remaining = length;
  9131. // Find the first segment containing 'offset'
  9132. size_t pos = 0;
  9133. size_t seg_idx = 0;
  9134. for (; seg_idx < state->segs.size(); seg_idx++) {
  9135. const auto &seg = state->segs[seg_idx];
  9136. if (seg.size > 0 && offset - pos < seg.size) { break; }
  9137. pos += seg.size;
  9138. }
  9139. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  9140. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  9141. const auto &seg = state->segs[seg_idx];
  9142. size_t available = seg.size - seg_offset;
  9143. size_t to_copy = (std::min)(available, remaining);
  9144. const char *src = seg.data + seg_offset;
  9145. seg_offset = 0; // only the first segment has a non-zero offset
  9146. while (to_copy > 0) {
  9147. size_t space = buf_size - buf_len;
  9148. size_t chunk = (std::min)(to_copy, space);
  9149. std::memcpy(buf.data() + buf_len, src, chunk);
  9150. buf_len += chunk;
  9151. src += chunk;
  9152. to_copy -= chunk;
  9153. remaining -= chunk;
  9154. if (buf_len == buf_size) {
  9155. if (!sink.write(buf.data(), buf_len)) { return false; }
  9156. buf_len = 0;
  9157. }
  9158. }
  9159. }
  9160. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  9161. return true;
  9162. };
  9163. }
  9164. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  9165. if (ranges.size() <= 1) return;
  9166. // Sort ranges by start position
  9167. std::sort(ranges.begin(), ranges.end(),
  9168. [](const Range &a, const Range &b) { return a.first < b.first; });
  9169. Ranges coalesced;
  9170. coalesced.reserve(ranges.size());
  9171. for (auto &r : ranges) {
  9172. auto first_pos = r.first;
  9173. auto last_pos = r.second;
  9174. // Handle special cases like in range_error
  9175. if (first_pos == -1 && last_pos == -1) {
  9176. first_pos = 0;
  9177. last_pos = static_cast<ssize_t>(content_length);
  9178. }
  9179. if (first_pos == -1) {
  9180. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  9181. last_pos = static_cast<ssize_t>(content_length) - 1;
  9182. }
  9183. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  9184. last_pos = static_cast<ssize_t>(content_length) - 1;
  9185. }
  9186. // Skip invalid ranges
  9187. if (!(0 <= first_pos && first_pos <= last_pos &&
  9188. last_pos < static_cast<ssize_t>(content_length))) {
  9189. continue;
  9190. }
  9191. // Coalesce with previous range if overlapping or adjacent (but not
  9192. // identical)
  9193. if (!coalesced.empty()) {
  9194. auto &prev = coalesced.back();
  9195. // Check if current range overlaps or is adjacent to previous range
  9196. // but don't coalesce identical ranges (allow duplicates)
  9197. if (first_pos <= prev.second + 1 &&
  9198. !(first_pos == prev.first && last_pos == prev.second)) {
  9199. // Extend the previous range
  9200. prev.second = (std::max)(prev.second, last_pos);
  9201. continue;
  9202. }
  9203. }
  9204. // Add new range
  9205. coalesced.emplace_back(first_pos, last_pos);
  9206. }
  9207. ranges = std::move(coalesced);
  9208. }
  9209. inline bool range_error(Request &req, Response &res) {
  9210. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  9211. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  9212. req.ranges.clear();
  9213. if (res.status == StatusCode::PartialContent_206) {
  9214. res.status = StatusCode::OK_200;
  9215. }
  9216. return false;
  9217. }
  9218. ssize_t content_len = static_cast<ssize_t>(
  9219. res.content_length_ ? res.content_length_ : res.body.size());
  9220. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  9221. size_t overwrapping_count = 0;
  9222. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  9223. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  9224. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  9225. // Too many ranges
  9226. if (CPPHTTPLIB_RANGE_MAX_COUNT > 0 &&
  9227. req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) {
  9228. return true;
  9229. }
  9230. for (auto &r : req.ranges) {
  9231. auto &first_pos = r.first;
  9232. auto &last_pos = r.second;
  9233. if (first_pos == -1 && last_pos == -1) {
  9234. first_pos = 0;
  9235. last_pos = content_len;
  9236. }
  9237. // RFC 9110 14.1.2: a suffix-length longer than the representation
  9238. // selects the entire representation.
  9239. if (first_pos == -1) {
  9240. first_pos = (std::max)(static_cast<ssize_t>(0), content_len - last_pos);
  9241. last_pos = content_len - 1;
  9242. }
  9243. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  9244. // A client can limit the number of bytes requested without knowing the
  9245. // size of the selected representation. If the last-pos value is absent,
  9246. // or if the value is greater than or equal to the current length of the
  9247. // representation data, the byte range is interpreted as the remainder of
  9248. // the representation (i.e., the server replaces the value of last-pos
  9249. // with a value that is one less than the current length of the selected
  9250. // representation).
  9251. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  9252. if (last_pos == -1 || last_pos >= content_len) {
  9253. last_pos = content_len - 1;
  9254. }
  9255. // Range must be within content length
  9256. if (!(0 <= first_pos && first_pos <= last_pos &&
  9257. last_pos <= content_len - 1)) {
  9258. return true;
  9259. }
  9260. // Request must not have more than two overlapping ranges
  9261. for (const auto &processed_range : processed_ranges) {
  9262. if (!(last_pos < processed_range.first ||
  9263. first_pos > processed_range.second)) {
  9264. overwrapping_count++;
  9265. if (overwrapping_count > 2) { return true; }
  9266. break; // Only count once per range
  9267. }
  9268. }
  9269. processed_ranges.emplace_back(first_pos, last_pos);
  9270. }
  9271. // After validation, coalesce overlapping ranges as per RFC 9110
  9272. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  9273. }
  9274. return false;
  9275. }
  9276. inline std::pair<size_t, size_t>
  9277. get_range_offset_and_length(Range r, size_t content_length) {
  9278. assert(r.first != -1 && r.second != -1);
  9279. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  9280. assert(r.first <= r.second &&
  9281. r.second < static_cast<ssize_t>(content_length));
  9282. (void)(content_length);
  9283. return std::make_pair(static_cast<size_t>(r.first),
  9284. static_cast<size_t>(r.second - r.first) + 1);
  9285. }
  9286. inline std::string make_content_range_header_field(
  9287. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  9288. auto st = offset_and_length.first;
  9289. auto ed = st + offset_and_length.second - 1;
  9290. std::string field = "bytes ";
  9291. field += std::to_string(st);
  9292. field += '-';
  9293. field += std::to_string(ed);
  9294. field += '/';
  9295. field += std::to_string(content_length);
  9296. return field;
  9297. }
  9298. template <typename SToken, typename CToken, typename Content>
  9299. bool process_multipart_ranges_data(const Request &req,
  9300. const std::string &boundary,
  9301. const std::string &content_type,
  9302. size_t content_length, SToken stoken,
  9303. CToken ctoken, Content content) {
  9304. for (size_t i = 0; i < req.ranges.size(); i++) {
  9305. ctoken("--");
  9306. stoken(boundary);
  9307. ctoken("\r\n");
  9308. if (!content_type.empty()) {
  9309. ctoken("Content-Type: ");
  9310. stoken(content_type);
  9311. ctoken("\r\n");
  9312. }
  9313. auto offset_and_length =
  9314. get_range_offset_and_length(req.ranges[i], content_length);
  9315. ctoken("Content-Range: ");
  9316. stoken(make_content_range_header_field(offset_and_length, content_length));
  9317. ctoken("\r\n");
  9318. ctoken("\r\n");
  9319. if (!content(offset_and_length.first, offset_and_length.second)) {
  9320. return false;
  9321. }
  9322. ctoken("\r\n");
  9323. }
  9324. ctoken("--");
  9325. stoken(boundary);
  9326. ctoken("--");
  9327. return true;
  9328. }
  9329. inline void make_multipart_ranges_data(const Request &req, Response &res,
  9330. const std::string &boundary,
  9331. const std::string &content_type,
  9332. size_t content_length,
  9333. std::string &data) {
  9334. process_multipart_ranges_data(
  9335. req, boundary, content_type, content_length,
  9336. [&](const std::string &token) { data += token; },
  9337. [&](const std::string &token) { data += token; },
  9338. [&](size_t offset, size_t length) {
  9339. assert(offset + length <= content_length);
  9340. data += res.body.substr(offset, length);
  9341. return true;
  9342. });
  9343. }
  9344. inline size_t get_multipart_ranges_data_length(const Request &req,
  9345. const std::string &boundary,
  9346. const std::string &content_type,
  9347. size_t content_length) {
  9348. size_t data_length = 0;
  9349. process_multipart_ranges_data(
  9350. req, boundary, content_type, content_length,
  9351. [&](const std::string &token) { data_length += token.size(); },
  9352. [&](const std::string &token) { data_length += token.size(); },
  9353. [&](size_t /*offset*/, size_t length) {
  9354. data_length += length;
  9355. return true;
  9356. });
  9357. return data_length;
  9358. }
  9359. template <typename T>
  9360. inline bool
  9361. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  9362. const std::string &boundary,
  9363. const std::string &content_type,
  9364. size_t content_length, const T &is_shutting_down) {
  9365. return process_multipart_ranges_data(
  9366. req, boundary, content_type, content_length,
  9367. [&](const std::string &token) { strm.write(token); },
  9368. [&](const std::string &token) { strm.write(token); },
  9369. [&](size_t offset, size_t length) {
  9370. return write_content(strm, res.content_provider_, offset, length,
  9371. is_shutting_down);
  9372. });
  9373. }
  9374. inline bool has_framed_body(const Request &req) {
  9375. return is_chunked_transfer_encoding(req.headers) ||
  9376. req.get_header_value_u64("Content-Length") > 0;
  9377. }
  9378. inline bool expect_content(const Request &req) {
  9379. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  9380. req.method == "DELETE") {
  9381. return true;
  9382. }
  9383. return has_framed_body(req);
  9384. }
  9385. #ifdef _WIN32
  9386. class WSInit {
  9387. public:
  9388. WSInit() {
  9389. WSADATA wsaData;
  9390. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  9391. }
  9392. ~WSInit() {
  9393. if (is_valid_) WSACleanup();
  9394. }
  9395. bool is_valid_ = false;
  9396. };
  9397. static WSInit wsinit_;
  9398. #endif
  9399. inline std::string unescape_quoted_pairs(const std::string &s) {
  9400. std::string out;
  9401. out.reserve(s.size());
  9402. for (size_t i = 0; i < s.size(); i++) {
  9403. if (s[i] == '\\' && i + 1 < s.size()) {
  9404. out += s[++i];
  9405. } else {
  9406. out += s[i];
  9407. }
  9408. }
  9409. return out;
  9410. }
  9411. // Inverse of unescape_quoted_pairs: prepares a value to sit inside a
  9412. // quoted-string. RFC 9110 §5.6.4 requires a literal '\' or '"' to be sent as a
  9413. // quoted-pair, so the recipient recovers the original value.
  9414. inline std::string escape_quoted_pairs(const std::string &s) {
  9415. std::string out;
  9416. out.reserve(s.size());
  9417. for (auto c : s) {
  9418. if (c == '\\' || c == '"') { out += '\\'; }
  9419. out += c;
  9420. }
  9421. return out;
  9422. }
  9423. // RFC 9110 Section 11.6.1 defines a challenge list as
  9424. // WWW-Authenticate = #challenge
  9425. // challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
  9426. // auth-param = token BWS "=" BWS ( token / quoted-string )
  9427. // so a server may offer several schemes, each with its own comma-separated
  9428. // auth-param list, in either order and either as separate field lines or
  9429. // packed into one. Splitting on every comma would break apart a challenge's
  9430. // own param list; splitting only on the first space would miss a Digest
  9431. // challenge that isn't first. Split on commas that aren't inside a
  9432. // quoted-string instead (split_unquoted), then track which scheme each
  9433. // resulting segment belongs to: a segment whose text before "=" contains
  9434. // whitespace (or that has no "=" at all) starts a new challenge named by its
  9435. // leading token.
  9436. inline bool parse_www_authenticate(const Response &res,
  9437. std::map<std::string, std::string> &auth,
  9438. bool is_proxy) {
  9439. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  9440. auto combined = get_combined_header_value(res.headers, auth_key);
  9441. if (combined.empty()) { return false; }
  9442. auto found_digest = false;
  9443. auto in_digest_challenge = false;
  9444. split_unquoted(
  9445. combined.data(), combined.data() + combined.size(), ',',
  9446. [&](const char *b, const char *e) {
  9447. std::string segment(b, e);
  9448. auto eq_pos = segment.find('=');
  9449. // BWS is allowed on both sides of "=", so the text naming the key (or,
  9450. // for the first segment of a challenge, "<scheme> <key>") must be
  9451. // trimmed before its boundaries are inspected.
  9452. auto key_part = trim_copy(
  9453. eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
  9454. auto space_pos = key_part.find_last_of(" \t");
  9455. if (space_pos != std::string::npos || eq_pos == std::string::npos) {
  9456. // "<scheme>[ <key>]" starts a new challenge.
  9457. auto scheme_end =
  9458. space_pos == std::string::npos ? key_part.size() : space_pos;
  9459. // RFC 7616 Section 3.7: a server may offer more than one Digest
  9460. // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
  9461. // from one challenge is never paired with another's algorithm.
  9462. in_digest_challenge =
  9463. !found_digest &&
  9464. case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
  9465. if (in_digest_challenge) { found_digest = true; }
  9466. if (space_pos == std::string::npos) {
  9467. // Bare scheme (or a token68), no auth-param on this segment.
  9468. return;
  9469. }
  9470. key_part = key_part.substr(space_pos + 1);
  9471. }
  9472. if (!in_digest_challenge) { return; }
  9473. auto val = trim_copy(segment.substr(eq_pos + 1));
  9474. auto unquoted = trim_double_quotes_copy(val);
  9475. if (unquoted.size() != val.size()) {
  9476. unquoted = unescape_quoted_pairs(unquoted);
  9477. }
  9478. auth[std::move(key_part)] = std::move(unquoted);
  9479. });
  9480. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
  9481. // make_digest_authentication_header() dereferences both unconditionally, so
  9482. // a challenge missing either can't produce a usable Authorization header.
  9483. // Treat it the same as no Digest challenge at all.
  9484. return found_digest && auth.find("realm") != auth.end() &&
  9485. auth.find("nonce") != auth.end();
  9486. }
  9487. class ContentProviderAdapter {
  9488. public:
  9489. explicit ContentProviderAdapter(
  9490. ContentProviderWithoutLength &&content_provider)
  9491. : content_provider_(std::move(content_provider)) {}
  9492. bool operator()(size_t offset, size_t, DataSink &sink) {
  9493. return content_provider_(offset, sink);
  9494. }
  9495. private:
  9496. ContentProviderWithoutLength content_provider_;
  9497. };
  9498. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  9499. namespace fields {
  9500. inline bool is_token_char(char c) {
  9501. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  9502. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  9503. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  9504. }
  9505. inline bool is_token(const std::string &s) {
  9506. if (s.empty()) { return false; }
  9507. for (auto c : s) {
  9508. if (!is_token_char(c)) { return false; }
  9509. }
  9510. return true;
  9511. }
  9512. inline bool is_field_name(const std::string &s) { return is_token(s); }
  9513. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  9514. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  9515. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  9516. inline bool is_field_content(const std::string &s) {
  9517. if (s.empty()) { return true; }
  9518. if (s.size() == 1) {
  9519. return is_field_vchar(s[0]);
  9520. } else if (s.size() == 2) {
  9521. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  9522. } else {
  9523. size_t i = 0;
  9524. if (!is_field_vchar(s[i])) { return false; }
  9525. i++;
  9526. while (i < s.size() - 1) {
  9527. auto c = s[i++];
  9528. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  9529. } else {
  9530. return false;
  9531. }
  9532. }
  9533. return is_field_vchar(s[i]);
  9534. }
  9535. }
  9536. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  9537. inline bool is_field_valid(const std::string &name, const std::string &value) {
  9538. return is_field_name(name) && is_field_value(value);
  9539. }
  9540. // RFC 9112 §2.2/§3.2: the request-target has no SP, HTAB or other control
  9541. // characters (incl. bare CR). obs-text (raw UTF-8) is allowed.
  9542. inline bool is_request_target(const std::string &s) {
  9543. return std::all_of(s.begin(), s.end(), is_field_vchar);
  9544. }
  9545. // RFC 9110 §7.2: the bytes of uri-host [ ":" port ], i.e. unreserved,
  9546. // sub-delims, "%", ":" and the IP-literal brackets. An empty value is valid.
  9547. inline bool is_host(const std::string &s) {
  9548. return std::all_of(s.begin(), s.end(), [](char c) {
  9549. return is_ascii_alnum(c) || c == '-' || c == '.' || c == '_' || c == '~' ||
  9550. c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  9551. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  9552. c == '=' || c == '%' || c == ':' || c == '[' || c == ']';
  9553. });
  9554. }
  9555. } // namespace fields
  9556. // Built in memory first, like ClientImpl::write_request, so a rejected header
  9557. // never leaves a partial request on the wire.
  9558. inline bool write_request_head(Stream &strm, Request &req, Error &error) {
  9559. BufferStream bstrm;
  9560. if (write_request_line(bstrm, req.method, req.path) < 0) {
  9561. error = Error::Write;
  9562. return false;
  9563. }
  9564. if (!check_and_write_headers(bstrm, req.headers, write_headers, error)) {
  9565. return false;
  9566. }
  9567. const auto &data = bstrm.get_buffer();
  9568. if (!write_data(strm, data.data(), data.size())) {
  9569. error = Error::Write;
  9570. return false;
  9571. }
  9572. return true;
  9573. }
  9574. inline bool perform_websocket_handshake(Stream &strm, Request &req,
  9575. WebSocketUpgradeResponse &upgrade) {
  9576. // Generate a random 16-byte Sec-WebSocket-Key (RFC 6455 Section 4.1)
  9577. std::string key_bytes(16, '\0');
  9578. fill_random_bytes(reinterpret_cast<unsigned char *>(&key_bytes[0]),
  9579. key_bytes.size());
  9580. auto client_key = base64_encode(key_bytes);
  9581. req.headers.erase("Upgrade");
  9582. req.headers.erase("Connection");
  9583. req.headers.erase("Sec-WebSocket-Key");
  9584. req.headers.erase("Sec-WebSocket-Version");
  9585. req.headers.emplace("Upgrade", "websocket");
  9586. req.headers.emplace("Connection", "Upgrade");
  9587. req.headers.emplace("Sec-WebSocket-Key", client_key);
  9588. req.headers.emplace("Sec-WebSocket-Version", "13");
  9589. if (!write_request_head(strm, req, upgrade.error)) { return false; }
  9590. // Verify 101 response and Sec-WebSocket-Accept header
  9591. auto expected_accept = websocket_accept_key(client_key);
  9592. auto offered_subprotocols =
  9593. get_combined_header_value(req.headers, "Sec-WebSocket-Protocol");
  9594. return read_websocket_upgrade_response(strm, expected_accept,
  9595. offered_subprotocols, upgrade);
  9596. }
  9597. inline bool is_ip_address(const std::string &host) {
  9598. struct in_addr addr4;
  9599. struct in6_addr addr6;
  9600. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  9601. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  9602. }
  9603. // One spelling for an IPv6 address, and the IPv4 one for an IPv4-mapped IPv6
  9604. // address, which is how a dual-stack socket reports an IPv4 peer. Anything
  9605. // else, including an address with a zone ID, is returned as it is.
  9606. inline std::string canonical_ip(const std::string &addr) {
  9607. struct in6_addr addr6;
  9608. if (addr.find('%') != std::string::npos ||
  9609. inet_pton(AF_INET6, addr.c_str(), &addr6) != 1) {
  9610. return addr;
  9611. }
  9612. char buf[INET6_ADDRSTRLEN];
  9613. if (IN6_IS_ADDR_V4MAPPED(&addr6)) {
  9614. return inet_ntop(AF_INET, &addr6.s6_addr[12], buf, sizeof(buf)) ? buf
  9615. : addr;
  9616. }
  9617. return inet_ntop(AF_INET6, &addr6, buf, sizeof(buf)) ? buf : addr;
  9618. }
  9619. // `trusted_proxies` holds canonical_ip() spellings.
  9620. inline bool is_trusted_proxy(const std::string &addr,
  9621. const std::vector<std::string> &trusted_proxies) {
  9622. if (trusted_proxies.empty()) { return false; }
  9623. return std::find(trusted_proxies.begin(), trusted_proxies.end(),
  9624. canonical_ip(addr)) != trusted_proxies.end();
  9625. }
  9626. // Resolve where a client should connect for `host`, honoring a user-supplied
  9627. // hostname-to-address map. `host` itself is never rewritten, so it keeps
  9628. // supplying the Host header and SNI; only the connection target changes.
  9629. //
  9630. // A mapped IP literal goes to `ip`, which keeps create_socket's AI_NUMERICHOST
  9631. // path. Anything else goes to `connect_host`, which create_socket resolves as
  9632. // a name, or uses as the socket path when the address family is AF_UNIX. An
  9633. // absent or empty mapping leaves `host` as the connection target; without the
  9634. // empty check the value would reach getaddrinfo as a null node and silently
  9635. // resolve to loopback.
  9636. inline void apply_addr_map(const std::map<std::string, std::string> &addr_map,
  9637. const std::string &host, std::string &connect_host,
  9638. std::string &ip) {
  9639. connect_host = host;
  9640. ip.clear();
  9641. auto it = addr_map.find(host);
  9642. if (it == addr_map.end() || it->second.empty()) { return; }
  9643. if (is_ip_address(it->second)) {
  9644. ip = it->second;
  9645. } else {
  9646. connect_host = it->second;
  9647. }
  9648. }
  9649. } // namespace detail
  9650. /*
  9651. * Group 2: detail namespace - SSL common utilities
  9652. */
  9653. #ifdef CPPHTTPLIB_SSL_ENABLED
  9654. namespace detail {
  9655. class SSLSocketStream final : public Stream {
  9656. public:
  9657. SSLSocketStream(
  9658. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9659. time_t read_timeout_usec, time_t write_timeout_sec,
  9660. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  9661. std::chrono::time_point<std::chrono::steady_clock> start_time =
  9662. (std::chrono::steady_clock::time_point::min)());
  9663. ~SSLSocketStream() override;
  9664. bool is_readable() const override;
  9665. bool wait_readable() const override;
  9666. bool wait_writable() const override;
  9667. bool is_peer_alive() const override;
  9668. ssize_t read(char *ptr, size_t size) override;
  9669. ssize_t write(const char *ptr, size_t size) override;
  9670. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  9671. void get_local_ip_and_port(std::string &ip, int &port) const override;
  9672. socket_t socket() const override;
  9673. time_t duration() const override;
  9674. void set_read_timeout(time_t sec, time_t usec = 0) override;
  9675. void set_max_timeout(time_t msec) override;
  9676. void set_read_interrupt(std::function<bool()> interrupted) override;
  9677. // See SocketStream::set_readable_hint().
  9678. void set_readable_hint() { readable_hint_ = true; }
  9679. // The error from the last read() or write() that failed in the TLS layer,
  9680. // with code Success if none did
  9681. const tls::TlsError &tls_error() const { return tls_error_; }
  9682. private:
  9683. bool ensure_readable();
  9684. socket_t sock_;
  9685. tls::session_t session_;
  9686. time_t read_timeout_sec_;
  9687. time_t read_timeout_usec_;
  9688. time_t write_timeout_sec_;
  9689. time_t write_timeout_usec_;
  9690. time_t max_timeout_msec_;
  9691. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  9692. std::function<bool()> read_interrupted_;
  9693. bool readable_hint_ = false;
  9694. tls::TlsError tls_error_;
  9695. };
  9696. // A TLS stream for WebSocket connections, where the receive path and the
  9697. // send path (application send() plus the heartbeat ping thread) run on
  9698. // different threads. A single TLS session must never be entered
  9699. // concurrently, so every call into the session is serialized by one mutex.
  9700. //
  9701. // Unlike SSLSocketStream, the socket is kept non-blocking for the stream's
  9702. // whole lifetime and each read()/write() performs a single non-blocking TLS
  9703. // call under the lock, then waits for readiness with select() outside the
  9704. // lock. The lock is therefore held only for CPU-bound work, so a reader
  9705. // blocked waiting for data never stalls a concurrent sender.
  9706. //
  9707. // This stream is used only for wss:// connections. Plain ws:// and ordinary
  9708. // HTTP/HTTPS keep using SocketStream/SSLSocketStream unchanged.
  9709. class WebSocketSSLStream final : public Stream {
  9710. public:
  9711. WebSocketSSLStream(socket_t sock, tls::session_t session,
  9712. time_t read_timeout_sec, time_t read_timeout_usec,
  9713. time_t write_timeout_sec, time_t write_timeout_usec);
  9714. ~WebSocketSSLStream() override;
  9715. bool is_readable() const override;
  9716. bool wait_readable() const override;
  9717. bool wait_writable() const override;
  9718. ssize_t read(char *ptr, size_t size) override;
  9719. ssize_t write(const char *ptr, size_t size) override;
  9720. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  9721. void get_local_ip_and_port(std::string &ip, int &port) const override;
  9722. socket_t socket() const override;
  9723. time_t duration() const override;
  9724. void set_read_timeout(time_t sec, time_t usec = 0) override;
  9725. void set_max_timeout(time_t msec) override;
  9726. void set_read_interrupt(std::function<bool()> interrupted) override;
  9727. private:
  9728. mutable std::mutex session_mutex_;
  9729. socket_t sock_;
  9730. tls::session_t session_;
  9731. // May change while another thread is in wait_readable(); write timeouts don't
  9732. std::atomic<time_t> read_timeout_sec_;
  9733. std::atomic<time_t> read_timeout_usec_;
  9734. time_t write_timeout_sec_;
  9735. time_t write_timeout_usec_;
  9736. std::atomic<time_t> max_timeout_msec_{0};
  9737. std::atomic<std::chrono::steady_clock::rep> start_time_;
  9738. std::function<bool()> read_interrupted_;
  9739. };
  9740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9741. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  9742. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  9743. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  9744. unsigned int hash_length = 0;
  9745. unsigned char hash[EVP_MAX_MD_SIZE];
  9746. EVP_DigestInit_ex(context.get(), algo, nullptr);
  9747. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  9748. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  9749. std::stringstream ss;
  9750. for (auto i = 0u; i < hash_length; ++i) {
  9751. ss << std::hex << std::setw(2) << std::setfill('0')
  9752. << static_cast<unsigned int>(hash[i]);
  9753. }
  9754. return ss.str();
  9755. }
  9756. inline std::string MD5(const std::string &s) {
  9757. return message_digest(s, EVP_md5());
  9758. }
  9759. inline std::string SHA_256(const std::string &s) {
  9760. return message_digest(s, EVP_sha256());
  9761. }
  9762. inline std::string SHA_512(const std::string &s) {
  9763. return message_digest(s, EVP_sha512());
  9764. }
  9765. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  9766. namespace {
  9767. template <size_t N>
  9768. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  9769. std::stringstream ss;
  9770. for (size_t i = 0; i < N; ++i) {
  9771. ss << std::hex << std::setw(2) << std::setfill('0')
  9772. << static_cast<unsigned int>(hash[i]);
  9773. }
  9774. return ss.str();
  9775. }
  9776. } // namespace
  9777. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9778. // Mbed TLS 4.x provides hashing (and TLS RNG) via PSA Crypto, which must be
  9779. // initialized once. PSA state is process-global; do not free it.
  9780. inline bool ensure_mbedtls_psa_crypto() {
  9781. static std::once_flag once;
  9782. static bool ok = false;
  9783. std::call_once(once, []() { ok = (psa_crypto_init() == PSA_SUCCESS); });
  9784. return ok;
  9785. }
  9786. inline bool psa_hash(psa_algorithm_t alg, const std::string &s,
  9787. unsigned char *out, size_t out_size) {
  9788. if (!ensure_mbedtls_psa_crypto()) { return false; }
  9789. size_t olen = 0;
  9790. return psa_hash_compute(alg, reinterpret_cast<const uint8_t *>(s.data()),
  9791. s.size(), out, out_size, &olen) == PSA_SUCCESS &&
  9792. olen == out_size;
  9793. }
  9794. #endif
  9795. inline std::string MD5(const std::string &s) {
  9796. unsigned char hash[16];
  9797. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9798. if (!psa_hash(PSA_ALG_MD5, s, hash, sizeof(hash))) { return {}; }
  9799. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  9800. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9801. hash);
  9802. #else
  9803. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9804. hash);
  9805. #endif
  9806. return hash_to_hex(hash);
  9807. }
  9808. inline std::string SHA_256(const std::string &s) {
  9809. unsigned char hash[32];
  9810. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9811. if (!psa_hash(PSA_ALG_SHA_256, s, hash, sizeof(hash))) { return {}; }
  9812. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  9813. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9814. hash, 0);
  9815. #else
  9816. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  9817. s.size(), hash, 0);
  9818. #endif
  9819. return hash_to_hex(hash);
  9820. }
  9821. inline std::string SHA_512(const std::string &s) {
  9822. unsigned char hash[64];
  9823. #ifdef CPPHTTPLIB_MBEDTLS_V4
  9824. if (!psa_hash(PSA_ALG_SHA_512, s, hash, sizeof(hash))) { return {}; }
  9825. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  9826. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  9827. hash, 0);
  9828. #else
  9829. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  9830. s.size(), hash, 0);
  9831. #endif
  9832. return hash_to_hex(hash);
  9833. }
  9834. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  9835. namespace {
  9836. template <size_t N>
  9837. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  9838. std::stringstream ss;
  9839. for (size_t i = 0; i < N; ++i) {
  9840. ss << std::hex << std::setw(2) << std::setfill('0')
  9841. << static_cast<unsigned int>(hash[i]);
  9842. }
  9843. return ss.str();
  9844. }
  9845. } // namespace
  9846. inline std::string MD5(const std::string &s) {
  9847. unsigned char hash[WC_MD5_DIGEST_SIZE];
  9848. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  9849. static_cast<word32>(s.size()), hash);
  9850. return hash_to_hex(hash);
  9851. }
  9852. inline std::string SHA_256(const std::string &s) {
  9853. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  9854. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  9855. static_cast<word32>(s.size()), hash);
  9856. return hash_to_hex(hash);
  9857. }
  9858. inline std::string SHA_512(const std::string &s) {
  9859. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  9860. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  9861. static_cast<word32>(s.size()), hash);
  9862. return hash_to_hex(hash);
  9863. }
  9864. #endif
  9865. template <typename T>
  9866. inline bool process_server_socket_ssl(
  9867. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  9868. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  9869. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  9870. time_t write_timeout_usec, T callback) {
  9871. // See process_server_socket(). The TLS library keeps already decrypted bytes
  9872. // of a pipelined request, which keep_alive() cannot see on the socket.
  9873. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  9874. write_timeout_sec, write_timeout_usec);
  9875. size_t served = 0;
  9876. return process_server_socket_core(
  9877. strm, served, keep_alive_max_count,
  9878. [&]() { return keep_alive(svr_sock, sock, keep_alive_timeout_sec); },
  9879. callback);
  9880. }
  9881. template <typename T>
  9882. inline bool process_client_socket_ssl(
  9883. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  9884. time_t read_timeout_usec, time_t write_timeout_sec,
  9885. time_t write_timeout_usec, time_t max_timeout_msec,
  9886. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  9887. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  9888. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  9889. start_time);
  9890. return callback(strm);
  9891. }
  9892. // `uri` is req's request-target in origin form, as curl sends it, also when
  9893. // the request line carries the absolute form for a proxy.
  9894. inline std::pair<std::string, std::string> make_digest_authentication_header(
  9895. const Request &req, const std::string &uri,
  9896. const std::map<std::string, std::string> &auth, size_t cnonce_count,
  9897. const std::string &cnonce, const std::string &username,
  9898. const std::string &password, bool is_proxy = false) {
  9899. std::string nc;
  9900. {
  9901. std::stringstream ss;
  9902. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  9903. nc = ss.str();
  9904. }
  9905. std::string qop;
  9906. if (auth.find("qop") != auth.end()) {
  9907. qop = auth.at("qop");
  9908. if (qop.find("auth-int") != std::string::npos) {
  9909. qop = "auth-int";
  9910. } else if (qop.find("auth") != std::string::npos) {
  9911. qop = "auth";
  9912. } else {
  9913. qop.clear();
  9914. }
  9915. }
  9916. std::string algo = "MD5";
  9917. if (auth.find("algorithm") != auth.end()) {
  9918. // algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
  9919. // not a token would otherwise be emitted verbatim and could carry commas
  9920. // or quotes that inject further auth-params into the header below.
  9921. const auto &a = auth.at("algorithm");
  9922. if (fields::is_token(a)) { algo = a; }
  9923. }
  9924. std::string response;
  9925. {
  9926. auto H = algo == "SHA-256" ? detail::SHA_256
  9927. : algo == "SHA-512" ? detail::SHA_512
  9928. : detail::MD5;
  9929. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  9930. auto A2 = req.method + ":" + uri;
  9931. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  9932. if (qop.empty()) {
  9933. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  9934. } else {
  9935. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  9936. ":" + qop + ":" + H(A2));
  9937. }
  9938. }
  9939. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  9940. // Every value placed inside a quoted-string is escaped so a '"' in it cannot
  9941. // close the string early. realm, nonce and opaque come straight from the
  9942. // server's challenge (parse_www_authenticate() already de-escaped them), so
  9943. // without this a crafted challenge injects extra auth-params into the header.
  9944. auto field =
  9945. "Digest username=\"" + detail::escape_quoted_pairs(username) +
  9946. "\", realm=\"" + detail::escape_quoted_pairs(auth.at("realm")) +
  9947. "\", nonce=\"" + detail::escape_quoted_pairs(auth.at("nonce")) +
  9948. "\", uri=\"" + detail::escape_quoted_pairs(uri) +
  9949. "\", algorithm=" + algo +
  9950. (qop.empty() ? ", response=\""
  9951. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce +
  9952. "\", response=\"") +
  9953. response + "\"" +
  9954. (opaque.empty()
  9955. ? ""
  9956. : ", opaque=\"" + detail::escape_quoted_pairs(opaque) + "\"");
  9957. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9958. return std::make_pair(key, field);
  9959. }
  9960. // Follows X509_check_host, which the OpenSSL backend uses, so that every
  9961. // backend accepts the same names.
  9962. inline bool match_hostname(const std::string &pattern,
  9963. const std::string &hostname) {
  9964. // A trailing dot on the host is ignored
  9965. auto host = hostname;
  9966. if (host.size() > 1 && host.back() == '.') { host.pop_back(); }
  9967. // Exact match (case-insensitive)
  9968. if (detail::case_ignore::equal(host, pattern)) { return true; }
  9969. // Split both pattern and hostname into components by '.', keeping any empty
  9970. // one, which no name may have
  9971. auto labels = [](const std::string &s) {
  9972. std::vector<std::string> v;
  9973. size_t b = 0;
  9974. while (true) {
  9975. auto e = s.find('.', b);
  9976. v.push_back(s.substr(b, e - b));
  9977. if (e == std::string::npos) { return v; }
  9978. b = e + 1;
  9979. }
  9980. };
  9981. auto pattern_components = labels(pattern);
  9982. auto host_components = labels(host);
  9983. auto has_empty_label = [](const std::vector<std::string> &v) {
  9984. return std::any_of(v.begin(), v.end(),
  9985. [](const std::string &l) { return l.empty(); });
  9986. };
  9987. if (has_empty_label(pattern_components) || has_empty_label(host_components)) {
  9988. return false;
  9989. }
  9990. // Component count must match
  9991. if (host_components.size() != pattern_components.size()) { return false; }
  9992. // A wildcard needs two labels after it, so that "*.com" matches nothing,
  9993. // and an IDNA label may not have one
  9994. const auto &leftmost = pattern_components.front();
  9995. if (leftmost.find('*') != std::string::npos &&
  9996. (pattern_components.size() < 3 ||
  9997. case_ignore::equal(leftmost.substr(0, 4), "xn--"))) {
  9998. return false;
  9999. }
  10000. // Compare each component with wildcard support
  10001. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  10002. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  10003. // Only the leftmost label may carry a wildcard (RFC 6125 6.4.3)
  10004. auto itr = pattern_components.begin();
  10005. for (const auto &h : host_components) {
  10006. auto &p = *itr;
  10007. auto is_leftmost = itr == pattern_components.begin();
  10008. if (!detail::case_ignore::equal(p, h) && !(is_leftmost && p == "*")) {
  10009. bool partial_match = false;
  10010. if (is_leftmost && !p.empty() && p[p.size() - 1] == '*') {
  10011. const auto prefix_length = p.size() - 1;
  10012. if (prefix_length == 0) {
  10013. partial_match = true;
  10014. } else if (h.size() >= prefix_length) {
  10015. partial_match =
  10016. std::equal(p.begin(),
  10017. p.begin() + static_cast<std::string::difference_type>(
  10018. prefix_length),
  10019. h.begin(), [](const char ca, const char cb) {
  10020. return detail::case_ignore::to_lower(ca) ==
  10021. detail::case_ignore::to_lower(cb);
  10022. });
  10023. }
  10024. }
  10025. if (!partial_match) { return false; }
  10026. }
  10027. ++itr;
  10028. }
  10029. return true;
  10030. }
  10031. #ifdef _WIN32
  10032. // Verify certificate using Windows CertGetCertificateChain API.
  10033. // This provides real-time certificate validation with Windows Update
  10034. // integration, independent of the TLS backend.
  10035. inline bool verify_cert_with_windows_schannel(
  10036. const std::vector<unsigned char> &der_cert, const std::string &hostname,
  10037. bool verify_hostname, uint64_t &out_error, tls::const_session_t session) {
  10038. if (der_cert.empty()) { return false; }
  10039. out_error = 0;
  10040. // Create Windows certificate context from DER data
  10041. auto cert_context = CertCreateCertificateContext(
  10042. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  10043. static_cast<DWORD>(der_cert.size()));
  10044. if (!cert_context) {
  10045. out_error = GetLastError();
  10046. return false;
  10047. }
  10048. auto cert_guard =
  10049. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  10050. // Give CryptoAPI the certificates the server sent. Without them it follows
  10051. // the leaf's AIA URL, which may lead to an issuer under an untrusted root.
  10052. std::vector<tls::cert_t> peer_certs;
  10053. tls::get_peer_certs(session, peer_certs);
  10054. auto store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, nullptr);
  10055. auto store_guard = scope_exit([&] {
  10056. for (auto cert : peer_certs) {
  10057. tls::free_cert(cert);
  10058. }
  10059. if (store) { CertCloseStore(store, 0); }
  10060. });
  10061. for (auto cert : peer_certs) {
  10062. std::vector<unsigned char> der;
  10063. if (store && tls::get_cert_der(cert, der)) {
  10064. CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING, der.data(),
  10065. static_cast<DWORD>(der.size()),
  10066. CERT_STORE_ADD_USE_EXISTING, nullptr);
  10067. }
  10068. }
  10069. // Setup chain parameters
  10070. CERT_CHAIN_PARA chain_para = {};
  10071. chain_para.cbSize = sizeof(chain_para);
  10072. // Require the server authentication usage along the chain, which also
  10073. // rejects roots that Windows trusts only for other purposes.
  10074. LPSTR server_auth = const_cast<LPSTR>(szOID_PKIX_KP_SERVER_AUTH);
  10075. chain_para.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
  10076. chain_para.RequestedUsage.Usage.cUsageIdentifier = 1;
  10077. chain_para.RequestedUsage.Usage.rgpszUsageIdentifier = &server_auth;
  10078. // Build certificate chain with revocation checking
  10079. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  10080. auto chain_result = CertGetCertificateChain(
  10081. nullptr, cert_context, nullptr, store, &chain_para,
  10082. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  10083. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  10084. nullptr, &chain_context);
  10085. if (!chain_result || !chain_context) {
  10086. out_error = GetLastError();
  10087. return false;
  10088. }
  10089. auto chain_guard =
  10090. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  10091. // Verify SSL policy
  10092. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  10093. extra_policy_para.cbSize = sizeof(extra_policy_para);
  10094. #ifdef AUTHTYPE_SERVER
  10095. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  10096. #endif
  10097. std::wstring whost;
  10098. if (verify_hostname) {
  10099. whost = u8string_to_wstring(hostname.c_str());
  10100. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  10101. }
  10102. CERT_CHAIN_POLICY_PARA policy_para = {};
  10103. policy_para.cbSize = sizeof(policy_para);
  10104. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  10105. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  10106. #else
  10107. policy_para.dwFlags = 0;
  10108. #endif
  10109. policy_para.pvExtraPolicyPara = &extra_policy_para;
  10110. CERT_CHAIN_POLICY_STATUS policy_status = {};
  10111. policy_status.cbSize = sizeof(policy_status);
  10112. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  10113. &policy_para, &policy_status)) {
  10114. out_error = GetLastError();
  10115. return false;
  10116. }
  10117. if (policy_status.dwError != 0) {
  10118. out_error = policy_status.dwError;
  10119. return false;
  10120. }
  10121. return true;
  10122. }
  10123. #endif // _WIN32
  10124. // Loads CA file/dir configuration and applies the system CA policy to a
  10125. // client TLS context. PEM data and native stores are applied to the context
  10126. // directly at set time; has_custom_store reflects them for the Auto policy
  10127. // decision.
  10128. inline bool load_client_ca_config(tls::ctx_t ctx,
  10129. const std::string &ca_cert_file_path,
  10130. const std::string &ca_cert_dir_path,
  10131. bool has_custom_store, SystemCAMode mode,
  10132. uint64_t &backend_error) {
  10133. auto ret = true;
  10134. if (!ca_cert_file_path.empty()) {
  10135. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  10136. backend_error = tls::get_error();
  10137. ret = false;
  10138. }
  10139. } else if (!ca_cert_dir_path.empty()) {
  10140. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  10141. backend_error = tls::get_error();
  10142. ret = false;
  10143. }
  10144. }
  10145. auto has_custom_ca = !ca_cert_file_path.empty() ||
  10146. !ca_cert_dir_path.empty() || has_custom_store;
  10147. if (mode == SystemCAMode::Enabled ||
  10148. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  10149. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  10150. }
  10151. return ret;
  10152. }
  10153. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10154. // Schannel is skipped when a custom CA is specified, as the Windows
  10155. // certificate store would not know about it, and when system CA trust is
  10156. // explicitly disabled.
  10157. inline bool use_windows_cert_verification(bool enabled,
  10158. const std::string &ca_cert_file_path,
  10159. const std::string &ca_cert_dir_path,
  10160. bool has_custom_store,
  10161. SystemCAMode mode) {
  10162. return enabled && mode != SystemCAMode::Disabled &&
  10163. ca_cert_file_path.empty() && ca_cert_dir_path.empty() &&
  10164. !has_custom_store;
  10165. }
  10166. #endif
  10167. // Serializes the CA certificates installed in ctx as PEM, so they can be
  10168. // loaded into another context.
  10169. inline std::string ca_certs_to_pem(tls::ctx_t ctx) {
  10170. std::string pem;
  10171. std::vector<tls::cert_t> certs;
  10172. tls::get_ca_certs(ctx, certs);
  10173. for (auto cert : certs) {
  10174. std::vector<unsigned char> der;
  10175. if (tls::get_cert_der(cert, der)) {
  10176. auto b64 = base64_encode(std::string(der.begin(), der.end()));
  10177. pem += "-----BEGIN CERTIFICATE-----\n";
  10178. for (size_t i = 0; i < b64.size(); i += 64) {
  10179. pem += b64.substr(i, 64);
  10180. pem += '\n';
  10181. }
  10182. pem += "-----END CERTIFICATE-----\n";
  10183. }
  10184. tls::free_cert(cert);
  10185. }
  10186. return pem;
  10187. }
  10188. // Returns a PemMemory field as a NUL-terminated string: its first len bytes,
  10189. // copied to buf, or pem itself when len is 0.
  10190. inline const char *pem_c_str(const char *pem, size_t len, std::string &buf) {
  10191. if (!pem || len == 0) { return pem; }
  10192. buf.assign(pem, len);
  10193. return buf.c_str();
  10194. }
  10195. // The parts of session setup that only SSLClient needs, plus the handful
  10196. // WebSocketClient also exposes; everything else takes the defaults, which is
  10197. // what keeps the two clients on one implementation.
  10198. struct ClientTlsSessionOptions {
  10199. // Both SSLClient and WebSocketClient expose this independently of
  10200. // certificate verification.
  10201. bool server_hostname_verification = true;
  10202. std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
  10203. // When set, ends the handshake as a timeout does once it returns true
  10204. std::function<bool()> interrupted;
  10205. // When non-null, guards session creation against concurrent use of the
  10206. // context. A WebSocketClient is not safe to use from several threads to
  10207. // begin with, so it passes nothing.
  10208. std::mutex *ctx_mutex = nullptr;
  10209. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10210. // See use_windows_cert_verification().
  10211. bool windows_cert_verification = false;
  10212. // A server certificate verifier works on the backend's chain verification,
  10213. // so the backend keeps deciding and Schannel only adds its own check.
  10214. bool server_certificate_verifier_set = false;
  10215. #endif
  10216. };
  10217. // Filled in on failure for callers that report error details.
  10218. struct ClientTlsSessionError {
  10219. Error error = Error::Success;
  10220. int ssl_error = 0;
  10221. uint64_t backend_error = 0;
  10222. };
  10223. // Establishes a client TLS session on an already connected socket. On failure
  10224. // the session is left for the caller to free: SSLClient frees it right away,
  10225. // WebSocketClient keeps it in a member that shutdown_and_close() cleans up.
  10226. inline bool setup_client_tls_session(
  10227. const std::string &host, tls::ctx_t ctx, tls::session_t &session,
  10228. socket_t sock, bool server_certificate_verification, time_t timeout_sec,
  10229. time_t timeout_usec, ClientTlsSessionError *out_error = nullptr,
  10230. const ClientTlsSessionOptions &options = ClientTlsSessionOptions()) {
  10231. using namespace tls;
  10232. auto fail = [&](Error error, int ssl_error, uint64_t backend_error) {
  10233. if (out_error) {
  10234. out_error->error = error;
  10235. out_error->ssl_error = ssl_error;
  10236. out_error->backend_error = backend_error;
  10237. }
  10238. return false;
  10239. };
  10240. // A TLS failure, whose verification codes name the Error too
  10241. auto fail_tls = [&](ErrorCode code, uint64_t backend_error) {
  10242. auto error = Error::SSLConnection;
  10243. if (code == ErrorCode::CertVerifyFailed) {
  10244. error = Error::SSLServerVerification;
  10245. } else if (code == ErrorCode::HostnameMismatch) {
  10246. error = Error::SSLServerHostnameVerification;
  10247. }
  10248. return fail(error, static_cast<int>(code), backend_error);
  10249. };
  10250. if (!ctx) {
  10251. session = nullptr;
  10252. return fail(Error::SSLConnection, 0, 0);
  10253. }
  10254. // With Windows verification on and no server certificate verifier set,
  10255. // Schannel is the only chain verifier. The backend's trust store is a
  10256. // snapshot of the Windows stores that lacks the roots Windows fetches on
  10257. // demand, so the backend's verdict is not used.
  10258. auto windows_verifies_chain = false;
  10259. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10260. windows_verifies_chain = options.windows_cert_verification &&
  10261. !options.server_certificate_verifier_set;
  10262. #endif
  10263. // The chain, and a host name, are verified during the handshake, so that a
  10264. // server failing them never gets to see a client certificate. Unless
  10265. // Schannel verifies the chain instead, this holds for IP hosts too, whose
  10266. // identity is checked after the handshake by verify_hostname().
  10267. auto verify_in_handshake =
  10268. server_certificate_verification && !windows_verifies_chain;
  10269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10270. // A session verifier may accept a certificate the built-in check rejects,
  10271. // and runs only after the handshake
  10272. verify_in_handshake = verify_in_handshake && !options.session_verifier;
  10273. #endif
  10274. {
  10275. std::unique_lock<std::mutex> guard;
  10276. if (options.ctx_mutex) {
  10277. guard = std::unique_lock<std::mutex>(*options.ctx_mutex);
  10278. }
  10279. // The mode is set on the context, so under the same lock
  10280. set_verify_client(ctx, verify_in_handshake);
  10281. session = create_session(ctx, sock);
  10282. }
  10283. if (!session) { return fail(Error::SSLConnection, 0, get_error()); }
  10284. // RFC 6066: SNI must not be set for IP addresses; skip it for IP hosts, so
  10285. // their identity is checked post-handshake below instead.
  10286. if (!is_ip_address(host)) {
  10287. if (!set_sni(session, host.c_str(),
  10288. verify_in_handshake && options.server_hostname_verification)) {
  10289. return fail(Error::SSLConnection, 0, get_error());
  10290. }
  10291. }
  10292. TlsError tls_err;
  10293. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, &tls_err,
  10294. options.interrupted)) {
  10295. return fail_tls(tls_err.code, tls_err.backend_code);
  10296. }
  10297. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  10298. if (options.session_verifier) {
  10299. verification_status = options.session_verifier(session);
  10300. }
  10301. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  10302. return fail(Error::SSLServerVerification, 0, get_error());
  10303. }
  10304. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  10305. server_certificate_verification) {
  10306. if (!windows_verifies_chain) {
  10307. auto verify_result = get_verify_result(session);
  10308. if (verify_result != 0) {
  10309. return fail_tls(ErrorCode::CertVerifyFailed,
  10310. static_cast<uint64_t>(verify_result));
  10311. }
  10312. }
  10313. auto server_cert = get_peer_cert(session);
  10314. if (!server_cert) {
  10315. return fail_tls(ErrorCode::CertVerifyFailed, get_error());
  10316. }
  10317. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  10318. // Identity check against the peer certificate, post-handshake for all
  10319. // backends. For IP hosts this is the only identity verification, since no
  10320. // hostname is bound during the handshake.
  10321. if (options.server_hostname_verification) {
  10322. if (!verify_hostname(server_cert, host.c_str())) {
  10323. return fail_tls(ErrorCode::HostnameMismatch, hostname_mismatch_code());
  10324. }
  10325. }
  10326. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  10327. // Windows Schannel verification, which lets Windows fetch missing roots
  10328. // and intermediates on demand. It must not be skipped: unless a server
  10329. // certificate verifier is set, it is the only chain check.
  10330. if (options.windows_cert_verification) {
  10331. std::vector<unsigned char> der;
  10332. uint64_t wincrypt_error = 0;
  10333. if (!get_cert_der(server_cert, der) ||
  10334. !verify_cert_with_windows_schannel(
  10335. der, host, options.server_hostname_verification, wincrypt_error,
  10336. session)) {
  10337. return fail_tls(ErrorCode::CertVerifyFailed, wincrypt_error);
  10338. }
  10339. }
  10340. #endif
  10341. }
  10342. return true;
  10343. }
  10344. } // namespace detail
  10345. #endif // CPPHTTPLIB_SSL_ENABLED
  10346. /*
  10347. * Group 3: httplib namespace - Non-SSL public API implementations
  10348. */
  10349. inline void default_socket_options(socket_t sock) {
  10350. set_socket_opt(sock, SOL_SOCKET,
  10351. #ifdef SO_REUSEPORT
  10352. SO_REUSEPORT,
  10353. #else
  10354. SO_REUSEADDR,
  10355. #endif
  10356. 1);
  10357. }
  10358. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  10359. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  10360. sizeof(optval));
  10361. }
  10362. inline std::string get_bearer_token_auth(const Request &req) {
  10363. // The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
  10364. // than the prefix carries no token.
  10365. constexpr const char bearer_prefix[] = "Bearer ";
  10366. constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
  10367. auto value = req.get_header_value("Authorization");
  10368. if (value.size() >= bearer_prefix_len &&
  10369. detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
  10370. bearer_prefix)) {
  10371. return value.substr(bearer_prefix_len);
  10372. }
  10373. return "";
  10374. }
  10375. inline const char *status_message(int status) {
  10376. switch (status) {
  10377. case StatusCode::Continue_100: return "Continue";
  10378. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  10379. case StatusCode::Processing_102: return "Processing";
  10380. case StatusCode::EarlyHints_103: return "Early Hints";
  10381. case StatusCode::OK_200: return "OK";
  10382. case StatusCode::Created_201: return "Created";
  10383. case StatusCode::Accepted_202: return "Accepted";
  10384. case StatusCode::NonAuthoritativeInformation_203:
  10385. return "Non-Authoritative Information";
  10386. case StatusCode::NoContent_204: return "No Content";
  10387. case StatusCode::ResetContent_205: return "Reset Content";
  10388. case StatusCode::PartialContent_206: return "Partial Content";
  10389. case StatusCode::MultiStatus_207: return "Multi-Status";
  10390. case StatusCode::AlreadyReported_208: return "Already Reported";
  10391. case StatusCode::IMUsed_226: return "IM Used";
  10392. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  10393. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  10394. case StatusCode::Found_302: return "Found";
  10395. case StatusCode::SeeOther_303: return "See Other";
  10396. case StatusCode::NotModified_304: return "Not Modified";
  10397. case StatusCode::UseProxy_305: return "Use Proxy";
  10398. case StatusCode::unused_306: return "unused";
  10399. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  10400. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  10401. case StatusCode::BadRequest_400: return "Bad Request";
  10402. case StatusCode::Unauthorized_401: return "Unauthorized";
  10403. case StatusCode::PaymentRequired_402: return "Payment Required";
  10404. case StatusCode::Forbidden_403: return "Forbidden";
  10405. case StatusCode::NotFound_404: return "Not Found";
  10406. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  10407. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  10408. case StatusCode::ProxyAuthenticationRequired_407:
  10409. return "Proxy Authentication Required";
  10410. case StatusCode::RequestTimeout_408: return "Request Timeout";
  10411. case StatusCode::Conflict_409: return "Conflict";
  10412. case StatusCode::Gone_410: return "Gone";
  10413. case StatusCode::LengthRequired_411: return "Length Required";
  10414. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  10415. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  10416. case StatusCode::UriTooLong_414: return "URI Too Long";
  10417. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  10418. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  10419. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  10420. case StatusCode::ImATeapot_418: return "I'm a teapot";
  10421. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  10422. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  10423. case StatusCode::Locked_423: return "Locked";
  10424. case StatusCode::FailedDependency_424: return "Failed Dependency";
  10425. case StatusCode::TooEarly_425: return "Too Early";
  10426. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  10427. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  10428. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  10429. case StatusCode::RequestHeaderFieldsTooLarge_431:
  10430. return "Request Header Fields Too Large";
  10431. case StatusCode::UnavailableForLegalReasons_451:
  10432. return "Unavailable For Legal Reasons";
  10433. case StatusCode::NotImplemented_501: return "Not Implemented";
  10434. case StatusCode::BadGateway_502: return "Bad Gateway";
  10435. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  10436. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  10437. case StatusCode::HttpVersionNotSupported_505:
  10438. return "HTTP Version Not Supported";
  10439. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  10440. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  10441. case StatusCode::LoopDetected_508: return "Loop Detected";
  10442. case StatusCode::NotExtended_510: return "Not Extended";
  10443. case StatusCode::NetworkAuthenticationRequired_511:
  10444. return "Network Authentication Required";
  10445. default:
  10446. case StatusCode::InternalServerError_500: return "Internal Server Error";
  10447. }
  10448. }
  10449. inline std::string to_string(const Error error) {
  10450. switch (error) {
  10451. case Error::Success: return "Success (no error)";
  10452. case Error::Unknown: return "Unknown";
  10453. case Error::Connection: return "Could not establish connection";
  10454. case Error::BindIPAddress: return "Failed to bind IP address";
  10455. case Error::Read: return "Failed to read connection";
  10456. case Error::Write: return "Failed to write connection";
  10457. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  10458. case Error::Canceled: return "Connection handling canceled";
  10459. case Error::SSLConnection: return "SSL connection failed";
  10460. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  10461. case Error::SSLServerVerification: return "SSL server verification failed";
  10462. case Error::SSLServerHostnameVerification:
  10463. return "SSL server hostname verification failed";
  10464. case Error::UnsupportedMultipartBoundaryChars:
  10465. return "Unsupported HTTP multipart boundary characters";
  10466. case Error::Compression: return "Compression failed";
  10467. case Error::ConnectionTimeout: return "Connection timed out";
  10468. case Error::ProxyConnection: return "Proxy connection failed";
  10469. case Error::ConnectionClosed: return "Connection closed by server";
  10470. case Error::Timeout: return "Read timeout";
  10471. case Error::ResourceExhaustion: return "Resource exhaustion";
  10472. case Error::TooManyFormDataFiles: return "Too many form data files";
  10473. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  10474. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  10475. case Error::ExceedMaxSocketDescriptorCount:
  10476. return "Exceeded maximum socket descriptor count";
  10477. case Error::InvalidRequestLine: return "Invalid request line";
  10478. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  10479. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  10480. case Error::InvalidHeaders: return "Invalid headers";
  10481. case Error::MultipartParsing: return "Multipart parsing failed";
  10482. case Error::OpenFile: return "Failed to open file";
  10483. case Error::Listen: return "Failed to listen on socket";
  10484. case Error::GetSockName: return "Failed to get socket name";
  10485. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  10486. case Error::HTTPParsing: return "HTTP parsing failed";
  10487. case Error::InvalidRangeHeader: return "Invalid Range header";
  10488. case Error::UnsupportedContentEncoding: return "Unsupported Content-Encoding";
  10489. case Error::WebSocketHandshake: return "WebSocket handshake failed";
  10490. case Error::UserCallbackException: return "User callback threw an exception";
  10491. default: break;
  10492. }
  10493. return "Invalid";
  10494. }
  10495. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  10496. os << to_string(obj);
  10497. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  10498. return os;
  10499. }
  10500. inline std::string hosted_at(const std::string &hostname) {
  10501. std::vector<std::string> addrs;
  10502. hosted_at(hostname, addrs);
  10503. if (addrs.empty()) { return std::string(); }
  10504. return addrs[0];
  10505. }
  10506. inline void hosted_at(const std::string &hostname,
  10507. std::vector<std::string> &addrs) {
  10508. struct addrinfo hints;
  10509. struct addrinfo *result;
  10510. memset(&hints, 0, sizeof(struct addrinfo));
  10511. hints.ai_family = AF_UNSPEC;
  10512. hints.ai_socktype = SOCK_STREAM;
  10513. hints.ai_protocol = 0;
  10514. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  10515. &result, 0)) {
  10516. #if defined __linux__ && !defined __ANDROID__
  10517. res_init();
  10518. #endif
  10519. return;
  10520. }
  10521. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  10522. for (auto rp = result; rp; rp = rp->ai_next) {
  10523. const auto &addr =
  10524. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  10525. std::string ip;
  10526. auto dummy = -1;
  10527. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  10528. dummy)) {
  10529. addrs.emplace_back(std::move(ip));
  10530. }
  10531. }
  10532. }
  10533. inline std::string encode_uri_component(const std::string &value) {
  10534. std::ostringstream escaped;
  10535. escaped.fill('0');
  10536. escaped << std::hex;
  10537. for (auto c : value) {
  10538. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  10539. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  10540. escaped << c;
  10541. } else {
  10542. escaped << std::uppercase;
  10543. escaped << '%' << std::setw(2)
  10544. << static_cast<int>(static_cast<unsigned char>(c));
  10545. escaped << std::nouppercase;
  10546. }
  10547. }
  10548. return escaped.str();
  10549. }
  10550. inline std::string encode_uri(const std::string &value) {
  10551. std::ostringstream escaped;
  10552. escaped.fill('0');
  10553. escaped << std::hex;
  10554. for (auto c : value) {
  10555. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  10556. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  10557. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  10558. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  10559. escaped << c;
  10560. } else {
  10561. escaped << std::uppercase;
  10562. escaped << '%' << std::setw(2)
  10563. << static_cast<int>(static_cast<unsigned char>(c));
  10564. escaped << std::nouppercase;
  10565. }
  10566. }
  10567. return escaped.str();
  10568. }
  10569. inline std::string decode_uri_component(const std::string &value) {
  10570. std::string result;
  10571. for (size_t i = 0; i < value.size(); i++) {
  10572. if (value[i] == '%' && i + 2 < value.size()) {
  10573. auto val = 0;
  10574. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  10575. result += static_cast<char>(val);
  10576. i += 2;
  10577. } else {
  10578. result += value[i];
  10579. }
  10580. } else {
  10581. result += value[i];
  10582. }
  10583. }
  10584. return result;
  10585. }
  10586. inline std::string decode_uri(const std::string &value) {
  10587. std::string result;
  10588. for (size_t i = 0; i < value.size(); i++) {
  10589. if (value[i] == '%' && i + 2 < value.size()) {
  10590. auto val = 0;
  10591. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  10592. auto c = static_cast<char>(val);
  10593. // Keep escapes of the reserved characters that encode_uri leaves
  10594. // literal, so decode_uri is the inverse of encode_uri and an escaped
  10595. // delimiter is not promoted into a real one (as with JS decodeURI).
  10596. if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  10597. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' ||
  10598. c == '#') {
  10599. result += value[i];
  10600. result += value[i + 1];
  10601. result += value[i + 2];
  10602. } else {
  10603. result += c;
  10604. }
  10605. i += 2;
  10606. } else {
  10607. result += value[i];
  10608. }
  10609. } else {
  10610. result += value[i];
  10611. }
  10612. }
  10613. return result;
  10614. }
  10615. inline std::string encode_path_component(const std::string &component) {
  10616. std::string result;
  10617. result.reserve(component.size() * 3);
  10618. for (size_t i = 0; i < component.size(); i++) {
  10619. auto c = static_cast<unsigned char>(component[i]);
  10620. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  10621. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  10622. c == '_' || c == '~') {
  10623. result += static_cast<char>(c);
  10624. }
  10625. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  10626. // "," / ";" / "="
  10627. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  10628. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  10629. c == '=') {
  10630. result += static_cast<char>(c);
  10631. }
  10632. // Colon is allowed in path segments except first segment
  10633. else if (c == ':') {
  10634. result += static_cast<char>(c);
  10635. }
  10636. // @ is allowed in path
  10637. else if (c == '@') {
  10638. result += static_cast<char>(c);
  10639. } else {
  10640. result += '%';
  10641. char hex[3];
  10642. snprintf(hex, sizeof(hex), "%02X", c);
  10643. result.append(hex, 2);
  10644. }
  10645. }
  10646. return result;
  10647. }
  10648. inline std::string decode_path_component(const std::string &component) {
  10649. std::string result;
  10650. result.reserve(component.size());
  10651. for (size_t i = 0; i < component.size(); i++) {
  10652. if (component[i] == '%' && i + 1 < component.size()) {
  10653. if (component[i + 1] == 'u') {
  10654. // Unicode %uXXXX encoding
  10655. auto val = 0;
  10656. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  10657. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  10658. char buff[4];
  10659. size_t len = 0;
  10660. if (detail::from_hex_to_i(component, i + 2, 4, val) &&
  10661. (len = detail::to_utf8(val, buff)) > 0) {
  10662. result.append(buff, len);
  10663. i += 5; // 'u0000'
  10664. } else {
  10665. // Not 4 hex digits, or a surrogate, which is no character: the
  10666. // escape is kept as it is rather than joining its neighbours
  10667. result += component[i];
  10668. }
  10669. } else {
  10670. // Standard %XX encoding
  10671. auto val = 0;
  10672. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  10673. // 2 digits hex codes
  10674. result += static_cast<char>(val);
  10675. i += 2; // 'XX'
  10676. } else {
  10677. result += component[i];
  10678. }
  10679. }
  10680. } else {
  10681. result += component[i];
  10682. }
  10683. }
  10684. return result;
  10685. }
  10686. inline std::string encode_query_component(const std::string &component,
  10687. bool space_as_plus) {
  10688. std::string result;
  10689. result.reserve(component.size() * 3);
  10690. for (size_t i = 0; i < component.size(); i++) {
  10691. auto c = static_cast<unsigned char>(component[i]);
  10692. // Unreserved characters per RFC 3986
  10693. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  10694. c == '_' || c == '~') {
  10695. result += static_cast<char>(c);
  10696. }
  10697. // Space handling
  10698. else if (c == ' ') {
  10699. if (space_as_plus) {
  10700. result += '+';
  10701. } else {
  10702. result += "%20";
  10703. }
  10704. }
  10705. // Plus sign handling
  10706. else if (c == '+') {
  10707. if (space_as_plus) {
  10708. result += "%2B";
  10709. } else {
  10710. result += static_cast<char>(c);
  10711. }
  10712. }
  10713. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  10714. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  10715. c == '*' || c == ',' || c == ';') {
  10716. result += static_cast<char>(c);
  10717. }
  10718. // Colon and @ are allowed in query
  10719. else if (c == ':' || c == '@') {
  10720. result += static_cast<char>(c);
  10721. }
  10722. // Forward slash is allowed in query values
  10723. else if (c == '/') {
  10724. result += static_cast<char>(c);
  10725. }
  10726. // Question mark is allowed in query values (after first ?)
  10727. else if (c == '?') {
  10728. result += static_cast<char>(c);
  10729. } else {
  10730. result += '%';
  10731. char hex[3];
  10732. snprintf(hex, sizeof(hex), "%02X", c);
  10733. result.append(hex, 2);
  10734. }
  10735. }
  10736. return result;
  10737. }
  10738. inline std::string decode_query_component(const std::string &component,
  10739. bool plus_as_space) {
  10740. std::string result;
  10741. result.reserve(component.size());
  10742. for (size_t i = 0; i < component.size(); i++) {
  10743. if (component[i] == '%' && i + 2 < component.size()) {
  10744. auto val = 0;
  10745. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  10746. result += static_cast<char>(val);
  10747. i += 2;
  10748. } else {
  10749. result += component[i];
  10750. }
  10751. } else if (component[i] == '+' && plus_as_space) {
  10752. result += ' '; // + becomes space in form-urlencoded
  10753. } else {
  10754. result += component[i];
  10755. }
  10756. }
  10757. return result;
  10758. }
  10759. inline std::string sanitize_filename(const std::string &filename) {
  10760. // Extract basename: find the last path separator (/ or \) and, on Windows,
  10761. // ':', which ends a drive prefix ("C:..") or names an NTFS stream ("a:b")
  10762. #ifdef _WIN32
  10763. auto pos = filename.find_last_of("/\\:");
  10764. #else
  10765. auto pos = filename.find_last_of("/\\");
  10766. #endif
  10767. auto result =
  10768. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  10769. // Strip null bytes
  10770. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  10771. // Trim whitespace
  10772. {
  10773. auto start = result.find_first_not_of(" \t");
  10774. auto end = result.find_last_not_of(" \t");
  10775. result = (start == std::string::npos)
  10776. ? ""
  10777. : result.substr(start, end - start + 1);
  10778. }
  10779. // Reject . and ..
  10780. if (result == "." || result == "..") { return ""; }
  10781. return result;
  10782. }
  10783. inline std::string append_query_params(const std::string &path,
  10784. const Params &params) {
  10785. // The query ends at the fragment (RFC 3986 3.5), so the params go before it.
  10786. auto fragment_pos = path.find('#');
  10787. auto path_with_query = path.substr(0, fragment_pos);
  10788. path_with_query += path_with_query.find('?') == std::string::npos ? '?' : '&';
  10789. path_with_query += detail::params_to_query_str(params);
  10790. if (fragment_pos != std::string::npos) {
  10791. path_with_query.append(path, fragment_pos, std::string::npos);
  10792. }
  10793. return path_with_query;
  10794. }
  10795. // Header utilities
  10796. inline std::pair<std::string, std::string>
  10797. make_range_header(const Ranges &ranges) {
  10798. std::string field = "bytes=";
  10799. auto i = 0;
  10800. for (const auto &r : ranges) {
  10801. if (i != 0) { field += ", "; }
  10802. if (r.first != -1) { field += std::to_string(r.first); }
  10803. field += '-';
  10804. if (r.second != -1) { field += std::to_string(r.second); }
  10805. i++;
  10806. }
  10807. return std::make_pair("Range", std::move(field));
  10808. }
  10809. inline std::pair<std::string, std::string>
  10810. make_basic_authentication_header(const std::string &username,
  10811. const std::string &password, bool is_proxy) {
  10812. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  10813. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  10814. return std::make_pair(key, std::move(field));
  10815. }
  10816. inline std::pair<std::string, std::string>
  10817. make_bearer_token_authentication_header(const std::string &token,
  10818. bool is_proxy = false) {
  10819. auto field = "Bearer " + token;
  10820. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  10821. return std::make_pair(key, std::move(field));
  10822. }
  10823. namespace detail {
  10824. // Basic auth when a username or password is set, otherwise a bearer token,
  10825. // unless the request already carries the header.
  10826. inline void add_authorization_header(Request &req, const std::string &username,
  10827. const std::string &password,
  10828. const std::string &token, bool is_proxy) {
  10829. if (req.has_header(is_proxy ? "Proxy-Authorization" : "Authorization")) {
  10830. return;
  10831. }
  10832. if (!username.empty() || !password.empty()) {
  10833. req.headers.insert(
  10834. make_basic_authentication_header(username, password, is_proxy));
  10835. } else if (!token.empty()) {
  10836. req.headers.insert(
  10837. make_bearer_token_authentication_header(token, is_proxy));
  10838. }
  10839. }
  10840. } // namespace detail
  10841. // Request implementation
  10842. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  10843. size_t id) const {
  10844. return detail::get_header_value_u64(headers, key, def, id);
  10845. }
  10846. inline bool Request::has_header(const std::string &key) const {
  10847. return detail::has_header(headers, key);
  10848. }
  10849. inline std::string Request::get_header_value(const std::string &key,
  10850. const char *def, size_t id) const {
  10851. return detail::get_header_value(headers, key, def, id);
  10852. }
  10853. inline size_t Request::get_header_value_count(const std::string &key) const {
  10854. return detail::get_header_value_count(headers, key);
  10855. }
  10856. inline void Request::set_header(const std::string &key,
  10857. const std::string &val) {
  10858. detail::set_header(headers, key, val);
  10859. }
  10860. inline bool Request::has_trailer(const std::string &key) const {
  10861. return trailers.find(key) != trailers.end();
  10862. }
  10863. inline std::string Request::get_trailer_value(const std::string &key,
  10864. size_t id) const {
  10865. return detail::get_multimap_value(trailers, key, id);
  10866. }
  10867. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  10868. return trailers.count(key);
  10869. }
  10870. inline bool Request::has_param(const std::string &key) const {
  10871. return params.find(key) != params.end();
  10872. }
  10873. inline std::string Request::get_param_value(const std::string &key,
  10874. size_t id) const {
  10875. return detail::get_multimap_value(params, key, id);
  10876. }
  10877. inline std::vector<std::string>
  10878. Request::get_param_values(const std::string &key) const {
  10879. auto rng = params.equal_range(key);
  10880. std::vector<std::string> values;
  10881. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  10882. for (auto it = rng.first; it != rng.second; ++it) {
  10883. values.push_back(it->second);
  10884. }
  10885. return values;
  10886. }
  10887. inline size_t Request::get_param_value_count(const std::string &key) const {
  10888. return params.count(key);
  10889. }
  10890. inline bool Request::is_multipart_form_data() const {
  10891. const auto &content_type = get_header_value("Content-Type");
  10892. return detail::case_ignore::equal(detail::extract_media_type(content_type),
  10893. "multipart/form-data");
  10894. }
  10895. // Multipart FormData implementation
  10896. inline std::string MultipartFormData::get_field(const std::string &key,
  10897. size_t id) const {
  10898. auto rng = fields.equal_range(key);
  10899. auto it = detail::bounded_next(rng.first, id, rng.second);
  10900. if (it != rng.second) { return it->second.content; }
  10901. return std::string();
  10902. }
  10903. inline std::vector<std::string>
  10904. MultipartFormData::get_fields(const std::string &key) const {
  10905. std::vector<std::string> values;
  10906. auto rng = fields.equal_range(key);
  10907. for (auto it = rng.first; it != rng.second; it++) {
  10908. values.push_back(it->second.content);
  10909. }
  10910. return values;
  10911. }
  10912. inline bool MultipartFormData::has_field(const std::string &key) const {
  10913. return fields.find(key) != fields.end();
  10914. }
  10915. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  10916. return fields.count(key);
  10917. }
  10918. inline FormData MultipartFormData::get_file(const std::string &key,
  10919. size_t id) const {
  10920. return detail::get_multimap_value(files, key, id);
  10921. }
  10922. inline std::vector<FormData>
  10923. MultipartFormData::get_files(const std::string &key) const {
  10924. std::vector<FormData> values;
  10925. auto rng = files.equal_range(key);
  10926. for (auto it = rng.first; it != rng.second; it++) {
  10927. values.push_back(it->second);
  10928. }
  10929. return values;
  10930. }
  10931. inline bool MultipartFormData::has_file(const std::string &key) const {
  10932. return files.find(key) != files.end();
  10933. }
  10934. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  10935. return files.count(key);
  10936. }
  10937. // Multipart FormData writer implementation
  10938. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  10939. return detail::is_multipart_boundary_chars_valid(boundary);
  10940. }
  10941. inline MultipartFormDataWriter::MultipartFormDataWriter()
  10942. : boundary_(detail::make_multipart_data_boundary()) {}
  10943. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  10944. : boundary_(std::move(boundary)) {}
  10945. inline const std::string &MultipartFormDataWriter::boundary() const {
  10946. return boundary_;
  10947. }
  10948. inline std::string MultipartFormDataWriter::content_type() const {
  10949. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  10950. }
  10951. inline std::string
  10952. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  10953. return detail::serialize_multipart_formdata(items, boundary_);
  10954. }
  10955. inline size_t MultipartFormDataWriter::content_length(
  10956. const UploadFormDataItems &items) const {
  10957. return detail::get_multipart_content_length(items, boundary_);
  10958. }
  10959. inline std::string
  10960. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  10961. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  10962. }
  10963. inline std::string MultipartFormDataWriter::item_end() {
  10964. return detail::serialize_multipart_formdata_item_end();
  10965. }
  10966. inline std::string MultipartFormDataWriter::finish() const {
  10967. return detail::serialize_multipart_formdata_finish(boundary_);
  10968. }
  10969. // Response implementation
  10970. namespace detail {
  10971. // A response has one content source: `body`, a content provider, or a file.
  10972. // Each content setter calls this so that the one called last wins.
  10973. inline void clear_content_provider(Response &res) {
  10974. auto releaser = std::move(res.content_provider_resource_releaser_);
  10975. auto success = res.content_provider_success_;
  10976. res.content_length_ = 0;
  10977. res.content_provider_ = nullptr;
  10978. res.content_provider_resource_releaser_ = nullptr;
  10979. res.is_chunked_content_provider_ = false;
  10980. res.is_file_content_provider_ = false;
  10981. res.content_provider_success_ = false;
  10982. res.content_coding_ = EncodingType::None;
  10983. res.file_content_path_.clear();
  10984. res.file_content_content_type_.clear();
  10985. if (releaser) { releaser(success); }
  10986. }
  10987. inline void clear_content(Response &res) {
  10988. res.body.clear();
  10989. clear_content_provider(res);
  10990. }
  10991. // The Content-Type of the old content goes with it.
  10992. inline void set_content_type(Response &res, const std::string &content_type) {
  10993. res.headers.erase("Content-Type");
  10994. res.set_header("Content-Type", content_type);
  10995. }
  10996. // `body` is public, so it can be assigned directly after a provider or a file
  10997. // was set. It came last, so it wins.
  10998. inline void prefer_assigned_body(Response &res) {
  10999. if (!res.body.empty() &&
  11000. (res.content_provider_ || !res.file_content_path_.empty())) {
  11001. clear_content_provider(res);
  11002. }
  11003. }
  11004. // RFC 9112 6.3: a 1xx, 204 or 304 response ends with its header section.
  11005. inline bool body_allowed_for_status(int status) {
  11006. return status >= 200 && status != StatusCode::NoContent_204 &&
  11007. status != StatusCode::NotModified_304;
  11008. }
  11009. // Only a 206 response is served as a partial representation. range_error()
  11010. // validates `req.ranges` only for a 2xx status, so slicing under any other
  11011. // status would start from an unchecked offset.
  11012. inline bool is_partial_content(const Request &req, const Response &res) {
  11013. return !req.ranges.empty() && res.status == StatusCode::PartialContent_206;
  11014. }
  11015. // Sets the Content-Length or Transfer-Encoding framing the body that
  11016. // Server::write_response_core() writes, or closes the connection after a body
  11017. // that has neither. Only the library sets them: one from a handler would go
  11018. // out next to it, or describe some other body.
  11019. inline void set_framing_headers(const Request &req, Response &res,
  11020. const std::string &boundary,
  11021. const std::string &content_type) {
  11022. // A HEAD response may give the length a GET would have had (RFC 9110 9.3.2).
  11023. auto head_length = req.method == "HEAD"
  11024. ? res.get_header_value("Content-Length")
  11025. : std::string();
  11026. res.headers.erase("Content-Length");
  11027. res.headers.erase("Transfer-Encoding");
  11028. if (!body_allowed_for_status(res.status)) { return; }
  11029. if (res.content_provider_) {
  11030. if (res.content_length_ == 0) {
  11031. if (res.is_chunked_content_provider_) {
  11032. res.set_header("Transfer-Encoding", "chunked");
  11033. } else if (req.method != "HEAD") {
  11034. // RFC 9112 6.3: a body with neither ends where the connection does.
  11035. res.headers.erase("Keep-Alive");
  11036. if (!has_header_token(res.headers, "Connection", "close")) {
  11037. res.set_header("Connection", "close");
  11038. }
  11039. }
  11040. return;
  11041. }
  11042. // The part Server::write_content_with_provider() writes.
  11043. auto length = res.content_length_;
  11044. if (is_partial_content(req, res)) {
  11045. length = req.ranges.size() == 1
  11046. ? get_range_offset_and_length(req.ranges[0], length).second
  11047. : get_multipart_ranges_data_length(req, boundary,
  11048. content_type, length);
  11049. }
  11050. res.set_header("Content-Length", std::to_string(length));
  11051. } else if (!res.body.empty()) {
  11052. res.set_header("Content-Length", std::to_string(res.body.size()));
  11053. } else {
  11054. res.set_header("Content-Length", head_length.empty() ? "0" : head_length);
  11055. }
  11056. }
  11057. } // namespace detail
  11058. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  11059. size_t id) const {
  11060. return detail::get_header_value_u64(headers, key, def, id);
  11061. }
  11062. inline bool Response::has_header(const std::string &key) const {
  11063. return headers.find(key) != headers.end();
  11064. }
  11065. inline std::string Response::get_header_value(const std::string &key,
  11066. const char *def,
  11067. size_t id) const {
  11068. return detail::get_header_value(headers, key, def, id);
  11069. }
  11070. inline size_t Response::get_header_value_count(const std::string &key) const {
  11071. return detail::get_header_value_count(headers, key);
  11072. }
  11073. inline void Response::set_header(const std::string &key,
  11074. const std::string &val) {
  11075. detail::set_header(headers, key, val);
  11076. }
  11077. inline bool Response::has_trailer(const std::string &key) const {
  11078. return trailers.find(key) != trailers.end();
  11079. }
  11080. inline std::string Response::get_trailer_value(const std::string &key,
  11081. size_t id) const {
  11082. return detail::get_multimap_value(trailers, key, id);
  11083. }
  11084. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  11085. return trailers.count(key);
  11086. }
  11087. inline void Response::set_redirect(const std::string &url, int stat) {
  11088. if (detail::fields::is_field_value(url)) {
  11089. set_header("Location", url);
  11090. if (300 <= stat && stat < 400) {
  11091. this->status = stat;
  11092. } else {
  11093. this->status = StatusCode::Found_302;
  11094. }
  11095. }
  11096. }
  11097. inline void Response::set_content(const char *s, size_t n,
  11098. const std::string &content_type) {
  11099. body.assign(s, n); // Before the releaser runs; it may own `s`.
  11100. detail::clear_content_provider(*this);
  11101. detail::set_content_type(*this, content_type);
  11102. }
  11103. inline void Response::set_content(const std::string &s,
  11104. const std::string &content_type) {
  11105. set_content(s.data(), s.size(), content_type);
  11106. }
  11107. inline void Response::set_content(std::string &&s,
  11108. const std::string &content_type) {
  11109. body = std::move(s);
  11110. detail::clear_content_provider(*this);
  11111. detail::set_content_type(*this, content_type);
  11112. }
  11113. inline void Response::set_content_provider(
  11114. size_t in_length, const std::string &content_type, ContentProvider provider,
  11115. ContentProviderResourceReleaser resource_releaser) {
  11116. detail::clear_content(*this);
  11117. detail::set_content_type(*this, content_type);
  11118. content_length_ = in_length;
  11119. if (in_length > 0) { content_provider_ = std::move(provider); }
  11120. content_provider_resource_releaser_ = std::move(resource_releaser);
  11121. }
  11122. inline void Response::set_content_provider(
  11123. const std::string &content_type, ContentProviderWithoutLength provider,
  11124. ContentProviderResourceReleaser resource_releaser) {
  11125. detail::clear_content(*this);
  11126. detail::set_content_type(*this, content_type);
  11127. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  11128. content_provider_resource_releaser_ = std::move(resource_releaser);
  11129. }
  11130. inline void Response::set_chunked_content_provider(
  11131. const std::string &content_type, ContentProviderWithoutLength provider,
  11132. ContentProviderResourceReleaser resource_releaser) {
  11133. set_content_provider(content_type, std::move(provider),
  11134. std::move(resource_releaser));
  11135. is_chunked_content_provider_ = true;
  11136. }
  11137. inline void Response::set_file_content(const std::string &path,
  11138. const std::string &content_type) {
  11139. detail::clear_content(*this);
  11140. headers.erase("Content-Type");
  11141. file_content_path_ = path;
  11142. file_content_content_type_ = content_type;
  11143. }
  11144. inline void Response::set_file_content(const std::string &path) {
  11145. set_file_content(path, std::string());
  11146. }
  11147. // Result implementation
  11148. inline size_t Result::get_request_header_value_u64(const std::string &key,
  11149. size_t def,
  11150. size_t id) const {
  11151. return detail::get_header_value_u64(request_headers_, key, def, id);
  11152. }
  11153. inline bool Result::has_request_header(const std::string &key) const {
  11154. return request_headers_.find(key) != request_headers_.end();
  11155. }
  11156. inline std::string Result::get_request_header_value(const std::string &key,
  11157. const char *def,
  11158. size_t id) const {
  11159. return detail::get_header_value(request_headers_, key, def, id);
  11160. }
  11161. inline size_t
  11162. Result::get_request_header_value_count(const std::string &key) const {
  11163. return request_headers_.count(key);
  11164. }
  11165. // Stream implementation
  11166. inline ssize_t Stream::write(const char *ptr) {
  11167. return write(ptr, strlen(ptr));
  11168. }
  11169. inline ssize_t Stream::write(const std::string &s) {
  11170. return write(s.data(), s.size());
  11171. }
  11172. // BodyReader implementation
  11173. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  11174. if (!stream) {
  11175. last_error = Error::Connection;
  11176. return -1;
  11177. }
  11178. if (eof) { return 0; }
  11179. if (!chunked) {
  11180. // Content-Length based reading
  11181. if (has_content_length && bytes_read >= content_length) {
  11182. eof = true;
  11183. return 0;
  11184. }
  11185. auto to_read = len;
  11186. if (has_content_length) {
  11187. auto remaining = content_length - bytes_read;
  11188. to_read = (std::min)(len, remaining);
  11189. }
  11190. auto n = stream->read(buf, to_read);
  11191. // Without Content-Length the body ends when the connection closes
  11192. // (RFC 9112 §6.3); with one, an EOF here came too early
  11193. if (n < 0 || (n == 0 && has_content_length)) {
  11194. last_error = stream->get_error();
  11195. if (last_error == Error::Success) { last_error = Error::Read; }
  11196. }
  11197. if (n <= 0) {
  11198. eof = true;
  11199. return n;
  11200. }
  11201. bytes_read += static_cast<size_t>(n);
  11202. if (has_content_length && bytes_read >= content_length) { eof = true; }
  11203. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  11204. last_error = Error::ExceedMaxPayloadSize;
  11205. eof = true;
  11206. return -1;
  11207. }
  11208. return n;
  11209. }
  11210. // Chunked transfer encoding: delegate to shared decoder instance.
  11211. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  11212. size_t chunk_offset = 0;
  11213. size_t chunk_total = 0;
  11214. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  11215. if (n < 0) {
  11216. last_error = stream->get_error();
  11217. if (last_error == Error::Success) { last_error = Error::Read; }
  11218. eof = true;
  11219. return n;
  11220. }
  11221. if (n == 0) {
  11222. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  11223. eof = true;
  11224. return 0;
  11225. }
  11226. bytes_read += static_cast<size_t>(n);
  11227. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  11228. last_error = Error::ExceedMaxPayloadSize;
  11229. eof = true;
  11230. return -1;
  11231. }
  11232. return n;
  11233. }
  11234. // ThreadPool implementation
  11235. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  11236. time_t idle_timeout_sec)
  11237. : base_thread_count_(n), max_queued_requests_(mqr),
  11238. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  11239. shutdown_(false) {
  11240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11241. if (max_n != 0 && max_n < n) {
  11242. std::string msg = "max_threads must be >= base_threads";
  11243. throw std::invalid_argument(msg);
  11244. }
  11245. #endif
  11246. max_thread_count_ = max_n == 0 ? n : max_n;
  11247. threads_.reserve(base_thread_count_);
  11248. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11249. try {
  11250. #endif
  11251. for (size_t i = 0; i < base_thread_count_; i++) {
  11252. threads_.emplace_back(std::thread([this]() { worker(false); }));
  11253. }
  11254. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11255. } catch (...) {
  11256. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  11257. // signal the workers we already spawned to exit and join them so the
  11258. // vector destructor does not see joinable threads (which would call
  11259. // std::terminate). Then rethrow so the caller learns of the failure.
  11260. {
  11261. std::unique_lock<std::mutex> lock(mutex_);
  11262. shutdown_ = true;
  11263. }
  11264. cond_.notify_all();
  11265. for (auto &t : threads_) {
  11266. if (t.joinable()) { t.join(); }
  11267. }
  11268. throw;
  11269. }
  11270. #endif
  11271. }
  11272. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  11273. {
  11274. std::unique_lock<std::mutex> lock(mutex_);
  11275. if (shutdown_) { return false; }
  11276. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  11277. return false;
  11278. }
  11279. jobs_.push_back(std::move(fn));
  11280. // Spawn a dynamic thread if jobs outnumber idle threads and under max
  11281. if (jobs_.size() > idle_thread_count_ &&
  11282. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  11283. cleanup_finished_threads();
  11284. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11285. try {
  11286. #endif
  11287. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  11288. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11289. } catch (const std::system_error &) {
  11290. // No thread budget left: keep the job queued for an existing worker
  11291. // instead of letting the exception escape the accept loop.
  11292. }
  11293. #endif
  11294. }
  11295. }
  11296. cond_.notify_one();
  11297. return true;
  11298. }
  11299. inline void ThreadPool::shutdown() {
  11300. {
  11301. std::unique_lock<std::mutex> lock(mutex_);
  11302. shutdown_ = true;
  11303. }
  11304. cond_.notify_all();
  11305. for (auto &t : threads_) {
  11306. if (t.joinable()) { t.join(); }
  11307. }
  11308. // Move dynamic_threads_ to a local list under the lock to avoid racing
  11309. // with worker threads that call move_to_finished() concurrently.
  11310. std::list<std::thread> remaining_dynamic;
  11311. {
  11312. std::unique_lock<std::mutex> lock(mutex_);
  11313. remaining_dynamic = std::move(dynamic_threads_);
  11314. }
  11315. for (auto &t : remaining_dynamic) {
  11316. if (t.joinable()) { t.join(); }
  11317. }
  11318. std::unique_lock<std::mutex> lock(mutex_);
  11319. cleanup_finished_threads();
  11320. }
  11321. inline void ThreadPool::move_to_finished(std::thread::id id) {
  11322. // Must be called with mutex_ held
  11323. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  11324. if (it->get_id() == id) {
  11325. finished_threads_.push_back(std::move(*it));
  11326. dynamic_threads_.erase(it);
  11327. return;
  11328. }
  11329. }
  11330. }
  11331. inline void ThreadPool::cleanup_finished_threads() {
  11332. // Must be called with mutex_ held
  11333. for (auto &t : finished_threads_) {
  11334. if (t.joinable()) { t.join(); }
  11335. }
  11336. finished_threads_.clear();
  11337. }
  11338. inline void ThreadPool::worker(bool is_dynamic) {
  11339. for (;;) {
  11340. std::function<void()> fn;
  11341. {
  11342. std::unique_lock<std::mutex> lock(mutex_);
  11343. idle_thread_count_++;
  11344. if (is_dynamic) {
  11345. auto has_work =
  11346. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  11347. [&] { return !jobs_.empty() || shutdown_; });
  11348. if (!has_work) {
  11349. // Timed out with no work - exit this dynamic thread
  11350. idle_thread_count_--;
  11351. move_to_finished(std::this_thread::get_id());
  11352. break;
  11353. }
  11354. } else {
  11355. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  11356. }
  11357. idle_thread_count_--;
  11358. if (shutdown_ && jobs_.empty()) { break; }
  11359. fn = std::move(jobs_.front());
  11360. jobs_.pop_front();
  11361. }
  11362. assert(true == static_cast<bool>(fn));
  11363. fn();
  11364. }
  11365. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  11366. !defined(LIBRESSL_VERSION_NUMBER)
  11367. OPENSSL_thread_stop();
  11368. #endif
  11369. }
  11370. /*
  11371. * Group 1 (continued): detail namespace - Stream implementations
  11372. */
  11373. namespace detail {
  11374. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  11375. time_t timeout_sec, time_t timeout_usec,
  11376. time_t &actual_timeout_sec,
  11377. time_t &actual_timeout_usec) {
  11378. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  11379. auto actual_timeout_msec =
  11380. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  11381. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  11382. actual_timeout_sec = actual_timeout_msec / 1000;
  11383. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  11384. }
  11385. // Socket stream implementation
  11386. inline SocketStream::SocketStream(
  11387. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  11388. time_t write_timeout_sec, time_t write_timeout_usec,
  11389. time_t max_timeout_msec,
  11390. std::chrono::time_point<std::chrono::steady_clock> start_time)
  11391. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  11392. read_timeout_usec_(read_timeout_usec),
  11393. write_timeout_sec_(write_timeout_sec),
  11394. write_timeout_usec_(write_timeout_usec),
  11395. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {}
  11396. inline SocketStream::~SocketStream() = default;
  11397. inline bool SocketStream::is_readable() const {
  11398. return read_buff_off_ < read_buff_content_size_;
  11399. }
  11400. inline bool SocketStream::wait_readable() const {
  11401. if (max_timeout_msec_ <= 0) {
  11402. return select_read_interruptible(sock_, read_timeout_sec_,
  11403. read_timeout_usec_, read_interrupted_) > 0;
  11404. }
  11405. time_t read_timeout_sec;
  11406. time_t read_timeout_usec;
  11407. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  11408. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  11409. return select_read_interruptible(sock_, read_timeout_sec, read_timeout_usec,
  11410. read_interrupted_) > 0;
  11411. }
  11412. inline bool SocketStream::wait_writable() const {
  11413. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  11414. }
  11415. inline bool SocketStream::ensure_readable() {
  11416. if (readable_hint_) {
  11417. readable_hint_ = false;
  11418. return true;
  11419. }
  11420. return wait_readable();
  11421. }
  11422. inline const char *SocketStream::buffered_data(size_t &size) const {
  11423. size = read_buff_content_size_ - read_buff_off_;
  11424. return size ? read_buff_.data() + read_buff_off_ : nullptr;
  11425. }
  11426. inline void SocketStream::release_buffer() {
  11427. assert(read_buff_off_ == read_buff_content_size_);
  11428. std::vector<char>().swap(read_buff_);
  11429. }
  11430. inline void SocketStream::consume_buffered(size_t size) {
  11431. assert(size <= read_buff_content_size_ - read_buff_off_);
  11432. read_buff_off_ += size;
  11433. }
  11434. inline bool SocketStream::is_peer_alive() const {
  11435. return detail::is_socket_alive(sock_);
  11436. }
  11437. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  11438. #ifdef _WIN32
  11439. size =
  11440. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  11441. #else
  11442. size = (std::min)(size,
  11443. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  11444. #endif
  11445. if (read_buff_off_ < read_buff_content_size_) {
  11446. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  11447. if (size <= remaining_size) {
  11448. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  11449. read_buff_off_ += size;
  11450. return static_cast<ssize_t>(size);
  11451. } else {
  11452. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  11453. read_buff_off_ += remaining_size;
  11454. return static_cast<ssize_t>(remaining_size);
  11455. }
  11456. }
  11457. if (!ensure_readable()) {
  11458. error_ = Error::Timeout;
  11459. return -1;
  11460. }
  11461. read_buff_off_ = 0;
  11462. read_buff_content_size_ = 0;
  11463. if (size < read_buff_size_) {
  11464. // Allocated on the first use, which an idle connection may never make.
  11465. if (read_buff_.empty()) { read_buff_.resize(read_buff_size_); }
  11466. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  11467. CPPHTTPLIB_RECV_FLAGS);
  11468. if (n <= 0) {
  11469. if (n == 0) {
  11470. error_ = Error::ConnectionClosed;
  11471. } else {
  11472. error_ = Error::Read;
  11473. }
  11474. return n;
  11475. } else if (n <= static_cast<ssize_t>(size)) {
  11476. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  11477. return n;
  11478. } else {
  11479. memcpy(ptr, read_buff_.data(), size);
  11480. read_buff_off_ = size;
  11481. read_buff_content_size_ = static_cast<size_t>(n);
  11482. return static_cast<ssize_t>(size);
  11483. }
  11484. } else {
  11485. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  11486. if (n <= 0) {
  11487. if (n == 0) {
  11488. error_ = Error::ConnectionClosed;
  11489. } else {
  11490. error_ = Error::Read;
  11491. }
  11492. }
  11493. return n;
  11494. }
  11495. }
  11496. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  11497. if (!wait_writable()) { return -1; }
  11498. // Winsock's send() takes an int length, even on 64-bit Windows
  11499. #ifdef _WIN32
  11500. size =
  11501. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  11502. #endif
  11503. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  11504. }
  11505. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  11506. int &port) const {
  11507. return detail::get_remote_ip_and_port(sock_, ip, port);
  11508. }
  11509. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  11510. int &port) const {
  11511. return detail::get_local_ip_and_port(sock_, ip, port);
  11512. }
  11513. inline socket_t SocketStream::socket() const { return sock_; }
  11514. inline time_t SocketStream::duration() const {
  11515. return static_cast<time_t>(
  11516. std::chrono::duration_cast<std::chrono::milliseconds>(
  11517. std::chrono::steady_clock::now() - start_time_)
  11518. .count());
  11519. }
  11520. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  11521. read_timeout_sec_ = sec;
  11522. read_timeout_usec_ = usec;
  11523. }
  11524. inline void SocketStream::set_max_timeout(time_t msec) {
  11525. max_timeout_msec_ = msec;
  11526. start_time_ = std::chrono::steady_clock::now();
  11527. }
  11528. inline void
  11529. SocketStream::set_read_interrupt(std::function<bool()> interrupted) {
  11530. read_interrupted_ = std::move(interrupted);
  11531. }
  11532. // Buffer stream implementation
  11533. inline bool BufferStream::is_readable() const { return true; }
  11534. inline bool BufferStream::wait_readable() const { return true; }
  11535. inline bool BufferStream::wait_writable() const { return true; }
  11536. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  11537. #if defined(_MSC_VER) && _MSC_VER < 1910
  11538. auto len_read = buffer._Copy_s(ptr, size, size, position);
  11539. #else
  11540. auto len_read = buffer.copy(ptr, size, position);
  11541. #endif
  11542. position += static_cast<size_t>(len_read);
  11543. return static_cast<ssize_t>(len_read);
  11544. }
  11545. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  11546. buffer.append(ptr, size);
  11547. return static_cast<ssize_t>(size);
  11548. }
  11549. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  11550. int & /*port*/) const {}
  11551. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  11552. int & /*port*/) const {}
  11553. inline socket_t BufferStream::socket() const { return 0; }
  11554. inline time_t BufferStream::duration() const { return 0; }
  11555. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  11556. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  11557. : MatcherBase(pattern) {
  11558. constexpr const char marker[] = "/:";
  11559. // One past the last ending position of a path param substring
  11560. std::size_t last_param_end = 0;
  11561. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11562. // Needed to ensure that parameter names are unique during matcher
  11563. // construction
  11564. // If exceptions are disabled, only last duplicate path
  11565. // parameter will be set
  11566. std::unordered_set<std::string> param_name_set;
  11567. #endif
  11568. while (true) {
  11569. const auto marker_pos = pattern.find(
  11570. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  11571. if (marker_pos == std::string::npos) { break; }
  11572. static_fragments_.push_back(
  11573. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  11574. const auto param_name_start = marker_pos + str_len(marker);
  11575. auto sep_pos = pattern.find(separator, param_name_start);
  11576. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  11577. auto param_name =
  11578. pattern.substr(param_name_start, sep_pos - param_name_start);
  11579. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11580. if (param_name_set.find(param_name) != param_name_set.cend()) {
  11581. std::string msg = "Encountered path parameter '" + param_name +
  11582. "' multiple times in route pattern '" + pattern + "'.";
  11583. throw std::invalid_argument(msg);
  11584. }
  11585. #endif
  11586. param_names_.push_back(std::move(param_name));
  11587. last_param_end = sep_pos + 1;
  11588. }
  11589. if (last_param_end < pattern.length()) {
  11590. static_fragments_.push_back(pattern.substr(last_param_end));
  11591. }
  11592. }
  11593. inline bool PathParamsMatcher::match(Request &request) const {
  11594. request.matches = std::smatch();
  11595. request.path_params.clear();
  11596. // A pattern without parameters is just a literal path to compare against
  11597. if (param_names_.empty()) { return request.path == pattern(); }
  11598. request.path_params.reserve(param_names_.size());
  11599. // One past the position at which the path matched the pattern last time
  11600. std::size_t starting_pos = 0;
  11601. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  11602. const auto &fragment = static_fragments_[i];
  11603. if (starting_pos + fragment.length() > request.path.length()) {
  11604. return false;
  11605. }
  11606. // Avoid unnecessary allocation by using strncmp instead of substr +
  11607. // comparison
  11608. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  11609. fragment.length()) != 0) {
  11610. return false;
  11611. }
  11612. starting_pos += fragment.length();
  11613. // Should only happen when we have a static fragment after a param
  11614. // Example: '/users/:id/subscriptions'
  11615. // The 'subscriptions' fragment here does not have a corresponding param
  11616. if (i >= param_names_.size()) { continue; }
  11617. auto sep_pos = request.path.find(separator, starting_pos);
  11618. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  11619. const auto &param_name = param_names_[i];
  11620. request.path_params.emplace(
  11621. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  11622. // Mark everything up to '/' as matched
  11623. starting_pos = sep_pos + 1;
  11624. }
  11625. // Returns false if the path is longer than the pattern
  11626. return starting_pos >= request.path.length();
  11627. }
  11628. inline bool RegexMatcher::match(Request &request) const {
  11629. request.path_params.clear();
  11630. // See CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH: an overlong path is treated as
  11631. // a non-match rather than risking a stack overflow in std::regex_match.
  11632. if (request.path.length() > CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH) {
  11633. return false;
  11634. }
  11635. return std::regex_match(request.path, request.matches, regex_);
  11636. }
  11637. // Enclose IPv6 address in brackets if needed
  11638. inline std::string prepare_host_string(const std::string &host) {
  11639. // Enclose IPv6 address in brackets (but not if already enclosed)
  11640. if (host.find(':') == std::string::npos ||
  11641. (!host.empty() && host[0] == '[')) {
  11642. // IPv4, hostname, or already bracketed IPv6
  11643. return host;
  11644. } else {
  11645. // IPv6 address without brackets
  11646. return "[" + host + "]";
  11647. }
  11648. }
  11649. inline std::string make_host_and_port_string(const std::string &host, int port,
  11650. bool is_ssl) {
  11651. auto result = prepare_host_string(host);
  11652. // Append port if not default
  11653. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  11654. ; // do nothing
  11655. } else {
  11656. result += ":" + std::to_string(port);
  11657. }
  11658. return result;
  11659. }
  11660. // Create "host:port" string always including port number (for CONNECT method)
  11661. inline std::string
  11662. make_host_and_port_string_always_port(const std::string &host, int port) {
  11663. return prepare_host_string(host) + ":" + std::to_string(port);
  11664. }
  11665. // Where a client connects for `host`, as one string: the mapped address or
  11666. // name, or `host` itself.
  11667. inline std::string
  11668. addr_map_target(const std::map<std::string, std::string> &addr_map,
  11669. const std::string &host) {
  11670. std::string connect_host;
  11671. std::string ip;
  11672. apply_addr_map(addr_map, host, connect_host, ip);
  11673. return ip.empty() ? connect_host : ip;
  11674. }
  11675. // Request target of a CONNECT for `host`, with `addr_map` applied.
  11676. inline std::string
  11677. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  11678. const std::string &host, int port) {
  11679. return make_host_and_port_string_always_port(addr_map_target(addr_map, host),
  11680. port);
  11681. }
  11682. // Value for the Host header a client sends when the caller supplied none.
  11683. // Only the value: callers decide where in their header list it goes.
  11684. inline std::string make_default_host_header_value(const std::string &host,
  11685. int port, bool is_ssl,
  11686. int address_family) {
  11687. if (address_family == AF_UNIX) { return "localhost"; }
  11688. return make_host_and_port_string(host, port, is_ssl);
  11689. }
  11690. inline void add_default_user_agent_header(Request &req) {
  11691. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11692. if (!req.has_header("User-Agent")) {
  11693. req.set_header("User-Agent",
  11694. std::string("cpp-httplib/") + CPPHTTPLIB_VERSION);
  11695. }
  11696. #else
  11697. (void)req;
  11698. #endif
  11699. }
  11700. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  11701. NormalizedTarget normalize_target(const std::string &host);
  11702. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  11703. bool host_matches_no_proxy(const NormalizedTarget &target,
  11704. const std::vector<NoProxyEntry> &entries);
  11705. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  11706. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  11707. if (prefix_bits == 0) { return true; }
  11708. int full_bytes = prefix_bits / 8;
  11709. int rem_bits = prefix_bits % 8;
  11710. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  11711. static_cast<size_t>(full_bytes)) != 0) {
  11712. return false;
  11713. }
  11714. if (rem_bits == 0) { return true; }
  11715. auto i = static_cast<size_t>(full_bytes);
  11716. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  11717. return (ip[i] & mask) == (net[i] & mask);
  11718. }
  11719. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  11720. if (token.empty()) { return false; }
  11721. if (token == "*") {
  11722. out.kind = NoProxyKind::Wildcard;
  11723. return true;
  11724. }
  11725. auto slash = token.find('/');
  11726. std::string addr_part =
  11727. (slash == std::string::npos) ? token : token.substr(0, slash);
  11728. std::string prefix_part =
  11729. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  11730. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  11731. // don't silently treat it as a /32 (or /128).
  11732. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  11733. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  11734. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  11735. // when brackets are present.
  11736. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  11737. addr_part.back() == ']';
  11738. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  11739. if (!bracketed) {
  11740. struct in_addr v4;
  11741. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  11742. int prefix = 32;
  11743. if (!prefix_part.empty() &&
  11744. !parse_int_in_range(prefix_part.data(), prefix_part.size(), 0, 32,
  11745. prefix)) {
  11746. return false;
  11747. }
  11748. out.kind = NoProxyKind::IPv4Cidr;
  11749. std::memcpy(out.net.data(), &v4, sizeof(v4));
  11750. out.prefix_bits = prefix;
  11751. return true;
  11752. }
  11753. }
  11754. struct in6_addr v6;
  11755. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  11756. int prefix = 128;
  11757. if (!prefix_part.empty() &&
  11758. !parse_int_in_range(prefix_part.data(), prefix_part.size(), 0, 128,
  11759. prefix)) {
  11760. return false;
  11761. }
  11762. out.kind = NoProxyKind::IPv6Cidr;
  11763. std::memcpy(out.net.data(), &v6, sizeof(v6));
  11764. out.prefix_bits = prefix;
  11765. return true;
  11766. }
  11767. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  11768. // the entry is malformed — don't fall through to the hostname branch.
  11769. if (bracketed) { return false; }
  11770. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  11771. if (slash != std::string::npos) { return false; }
  11772. // Port-specific entries (host:port) are not supported.
  11773. if (token.find(':') != std::string::npos) { return false; }
  11774. std::string hostname = case_ignore::to_lower(token);
  11775. while (!hostname.empty() && hostname.front() == '.') {
  11776. hostname.erase(hostname.begin());
  11777. }
  11778. while (!hostname.empty() && hostname.back() == '.') {
  11779. hostname.pop_back();
  11780. }
  11781. if (hostname.empty()) { return false; }
  11782. out.kind = NoProxyKind::HostnameSuffix;
  11783. out.hostname_pattern = std::move(hostname);
  11784. return true;
  11785. }
  11786. inline std::vector<NoProxyEntry>
  11787. parse_no_proxy_entries(const std::vector<std::string> &patterns) {
  11788. std::vector<NoProxyEntry> entries;
  11789. entries.reserve(patterns.size());
  11790. for (const auto &p : patterns) {
  11791. auto trimmed = trim_copy(p);
  11792. if (trimmed.empty()) { continue; }
  11793. NoProxyEntry entry;
  11794. if (parse_no_proxy_entry(trimmed, entry)) {
  11795. entries.push_back(std::move(entry));
  11796. }
  11797. }
  11798. return entries;
  11799. }
  11800. inline NormalizedTarget normalize_target(const std::string &host) {
  11801. NormalizedTarget t;
  11802. std::string h = host;
  11803. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  11804. h = h.substr(1, h.size() - 2);
  11805. }
  11806. // Strip a single trailing dot so "example.com." canonicalizes to
  11807. // "example.com".
  11808. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  11809. t.hostname = case_ignore::to_lower(h);
  11810. if (!t.hostname.empty()) {
  11811. struct in_addr v4;
  11812. struct in6_addr v6;
  11813. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  11814. t.is_ipv4 = true;
  11815. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  11816. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  11817. t.is_ipv6 = true;
  11818. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  11819. }
  11820. }
  11821. return t;
  11822. }
  11823. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  11824. const std::vector<NoProxyEntry> &entries) {
  11825. if (target.hostname.empty()) { return false; }
  11826. for (const auto &e : entries) {
  11827. switch (e.kind) {
  11828. case NoProxyKind::Wildcard: return true;
  11829. case NoProxyKind::IPv4Cidr:
  11830. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  11831. return true;
  11832. }
  11833. break;
  11834. case NoProxyKind::IPv6Cidr:
  11835. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  11836. return true;
  11837. }
  11838. break;
  11839. case NoProxyKind::HostnameSuffix:
  11840. if (target.is_ipv4 || target.is_ipv6) { break; }
  11841. if (target.hostname == e.hostname_pattern) { return true; }
  11842. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  11843. // an entry of "example.com".
  11844. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  11845. auto offset = target.hostname.size() - e.hostname_pattern.size();
  11846. if (target.hostname[offset - 1] == '.' &&
  11847. target.hostname.compare(offset, e.hostname_pattern.size(),
  11848. e.hostname_pattern) == 0) {
  11849. return true;
  11850. }
  11851. }
  11852. break;
  11853. }
  11854. }
  11855. return false;
  11856. }
  11857. template <typename T>
  11858. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  11859. T header_writer, Error &error) {
  11860. for (const auto &h : headers) {
  11861. if (!detail::fields::is_field_valid(h.first, h.second)) {
  11862. error = Error::InvalidHeaders;
  11863. return false;
  11864. }
  11865. }
  11866. if (header_writer(strm, headers) <= 0) {
  11867. error = Error::Write;
  11868. return false;
  11869. }
  11870. return true;
  11871. }
  11872. } // namespace detail
  11873. /*
  11874. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  11875. */
  11876. #ifdef CPPHTTPLIB_SSL_ENABLED
  11877. namespace detail {
  11878. // SSL socket stream implementation
  11879. inline SSLSocketStream::SSLSocketStream(
  11880. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  11881. time_t read_timeout_usec, time_t write_timeout_sec,
  11882. time_t write_timeout_usec, time_t max_timeout_msec,
  11883. std::chrono::time_point<std::chrono::steady_clock> start_time)
  11884. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  11885. read_timeout_usec_(read_timeout_usec),
  11886. write_timeout_sec_(write_timeout_sec),
  11887. write_timeout_usec_(write_timeout_usec),
  11888. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  11889. tls_error_.code = tls::ErrorCode::Success;
  11890. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11891. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  11892. // Note: create_session() also clears this, but SSLClient currently
  11893. // uses ssl_new() which does not. Until full TLS API migration is complete,
  11894. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  11895. // SSL session was created.
  11896. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  11897. #endif
  11898. }
  11899. inline SSLSocketStream::~SSLSocketStream() = default;
  11900. inline bool SSLSocketStream::is_readable() const {
  11901. return tls::pending(session_) > 0;
  11902. }
  11903. inline bool SSLSocketStream::wait_readable() const {
  11904. if (max_timeout_msec_ <= 0) {
  11905. return select_read_interruptible(sock_, read_timeout_sec_,
  11906. read_timeout_usec_, read_interrupted_) > 0;
  11907. }
  11908. time_t read_timeout_sec;
  11909. time_t read_timeout_usec;
  11910. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  11911. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  11912. return select_read_interruptible(sock_, read_timeout_sec, read_timeout_usec,
  11913. read_interrupted_) > 0;
  11914. }
  11915. inline bool SSLSocketStream::wait_writable() const {
  11916. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  11917. !tls::is_peer_closed(session_, sock_);
  11918. }
  11919. inline bool SSLSocketStream::ensure_readable() {
  11920. if (readable_hint_) {
  11921. readable_hint_ = false;
  11922. return true;
  11923. }
  11924. return wait_readable();
  11925. }
  11926. inline bool SSLSocketStream::is_peer_alive() const {
  11927. return !tls::is_peer_closed(session_, sock_);
  11928. }
  11929. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  11930. if (tls::pending(session_) > 0) {
  11931. tls::TlsError err;
  11932. auto ret = tls::read(session_, ptr, size, err);
  11933. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  11934. error_ = Error::ConnectionClosed;
  11935. } else if (ret < 0) {
  11936. tls_error_ = err;
  11937. }
  11938. return ret;
  11939. } else if (ensure_readable()) {
  11940. tls::TlsError err;
  11941. auto ret = tls::read(session_, ptr, size, err);
  11942. if (ret < 0) {
  11943. auto n = 1000;
  11944. #ifdef _WIN32
  11945. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  11946. (err.code == tls::ErrorCode::SyscallError &&
  11947. WSAGetLastError() == WSAETIMEDOUT))) {
  11948. #else
  11949. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  11950. #endif
  11951. if (tls::pending(session_) > 0) {
  11952. ret = tls::read(session_, ptr, size, err);
  11953. if (ret >= 0) { return ret; }
  11954. break;
  11955. } else if (wait_readable()) {
  11956. std::this_thread::sleep_for(std::chrono::microseconds{10});
  11957. ret = tls::read(session_, ptr, size, err);
  11958. if (ret >= 0) { return ret; }
  11959. } else {
  11960. break;
  11961. }
  11962. }
  11963. assert(ret < 0);
  11964. tls_error_ = err;
  11965. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  11966. error_ = Error::ConnectionClosed;
  11967. }
  11968. return ret;
  11969. } else {
  11970. error_ = Error::Timeout;
  11971. return -1;
  11972. }
  11973. }
  11974. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  11975. if (wait_writable()) {
  11976. auto handle_size =
  11977. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  11978. tls::TlsError err;
  11979. auto ret = tls::write(session_, ptr, handle_size, err);
  11980. if (ret < 0) {
  11981. auto n = 1000;
  11982. #ifdef _WIN32
  11983. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  11984. (err.code == tls::ErrorCode::SyscallError &&
  11985. WSAGetLastError() == WSAETIMEDOUT))) {
  11986. #else
  11987. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  11988. #endif
  11989. if (wait_writable()) {
  11990. std::this_thread::sleep_for(std::chrono::microseconds{10});
  11991. ret = tls::write(session_, ptr, handle_size, err);
  11992. if (ret >= 0) { return ret; }
  11993. } else {
  11994. break;
  11995. }
  11996. }
  11997. assert(ret < 0);
  11998. tls_error_ = err;
  11999. }
  12000. return ret;
  12001. }
  12002. return -1;
  12003. }
  12004. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  12005. int &port) const {
  12006. detail::get_remote_ip_and_port(sock_, ip, port);
  12007. }
  12008. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  12009. int &port) const {
  12010. detail::get_local_ip_and_port(sock_, ip, port);
  12011. }
  12012. inline socket_t SSLSocketStream::socket() const { return sock_; }
  12013. inline time_t SSLSocketStream::duration() const {
  12014. return static_cast<time_t>(
  12015. std::chrono::duration_cast<std::chrono::milliseconds>(
  12016. std::chrono::steady_clock::now() - start_time_)
  12017. .count());
  12018. }
  12019. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  12020. read_timeout_sec_ = sec;
  12021. read_timeout_usec_ = usec;
  12022. }
  12023. inline void SSLSocketStream::set_max_timeout(time_t msec) {
  12024. max_timeout_msec_ = msec;
  12025. start_time_ = std::chrono::steady_clock::now();
  12026. }
  12027. inline void
  12028. SSLSocketStream::set_read_interrupt(std::function<bool()> interrupted) {
  12029. read_interrupted_ = std::move(interrupted);
  12030. }
  12031. inline WebSocketSSLStream::WebSocketSSLStream(socket_t sock,
  12032. tls::session_t session,
  12033. time_t read_timeout_sec,
  12034. time_t read_timeout_usec,
  12035. time_t write_timeout_sec,
  12036. time_t write_timeout_usec)
  12037. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  12038. read_timeout_usec_(read_timeout_usec),
  12039. write_timeout_sec_(write_timeout_sec),
  12040. write_timeout_usec_(write_timeout_usec),
  12041. start_time_(std::chrono::steady_clock::now().time_since_epoch().count()) {
  12042. // The receive and send paths run on different threads, so each TLS call is
  12043. // driven in non-blocking mode and readiness is awaited with select()
  12044. // outside the session lock. Set the socket non-blocking once here; it is
  12045. // never flipped back, so no thread races on the flag.
  12046. detail::set_nonblocking(sock_, true);
  12047. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12048. SSL_clear_mode(static_cast<SSL *>(session_), SSL_MODE_AUTO_RETRY);
  12049. #endif
  12050. }
  12051. inline WebSocketSSLStream::~WebSocketSSLStream() = default;
  12052. inline bool WebSocketSSLStream::is_readable() const {
  12053. std::lock_guard<std::mutex> guard(session_mutex_);
  12054. return tls::pending(session_) > 0;
  12055. }
  12056. inline bool WebSocketSSLStream::wait_readable() const {
  12057. auto max_timeout_msec = max_timeout_msec_.load();
  12058. if (max_timeout_msec <= 0) {
  12059. return select_read_interruptible(sock_, read_timeout_sec_,
  12060. read_timeout_usec_, read_interrupted_) > 0;
  12061. }
  12062. time_t read_timeout_sec;
  12063. time_t read_timeout_usec;
  12064. calc_actual_timeout(max_timeout_msec, duration(), read_timeout_sec_,
  12065. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  12066. return select_read_interruptible(sock_, read_timeout_sec, read_timeout_usec,
  12067. read_interrupted_) > 0;
  12068. }
  12069. inline bool WebSocketSSLStream::wait_writable() const {
  12070. // Unlike SSLSocketStream, this deliberately does not call is_peer_closed():
  12071. // that probe toggles the socket's blocking flag, which would race with the
  12072. // concurrent reader on a permanently non-blocking socket.
  12073. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  12074. }
  12075. inline ssize_t WebSocketSSLStream::read(char *ptr, size_t size) {
  12076. tls::TlsError err;
  12077. auto n = 1000;
  12078. while (--n >= 0) {
  12079. {
  12080. std::lock_guard<std::mutex> guard(session_mutex_);
  12081. auto ret = tls::read(session_, ptr, size, err);
  12082. if (ret > 0) { return ret; }
  12083. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  12084. error_ = Error::ConnectionClosed;
  12085. return ret;
  12086. }
  12087. }
  12088. // ret < 0. On a non-blocking socket a TLS read can stop needing either
  12089. // direction: the send path shares this session, so output it left pending
  12090. // has to be flushed before more input can be decrypted. Anything else is
  12091. // a hard error.
  12092. auto needs_readable = err.code == tls::ErrorCode::WantRead;
  12093. #ifdef _WIN32
  12094. // On Windows a socket timeout surfaces as a syscall error, not WantRead.
  12095. needs_readable =
  12096. needs_readable || (err.code == tls::ErrorCode::SyscallError &&
  12097. WSAGetLastError() == WSAETIMEDOUT);
  12098. #endif
  12099. if (!needs_readable && err.code != tls::ErrorCode::WantWrite) {
  12100. error_ = Error::Read;
  12101. return -1;
  12102. }
  12103. if (!(needs_readable ? wait_readable() : wait_writable())) {
  12104. error_ = Error::Timeout;
  12105. return -1;
  12106. }
  12107. }
  12108. // Out of retries. Recording a reason matters: a caller that reads get_error()
  12109. // to tell a timeout from a close would otherwise see whatever the previous
  12110. // failure left behind (error_ is never cleared on success).
  12111. error_ = Error::Read;
  12112. return -1;
  12113. }
  12114. inline ssize_t WebSocketSSLStream::write(const char *ptr, size_t size) {
  12115. auto handle_size = std::min<size_t>(size, (std::numeric_limits<int>::max)());
  12116. tls::TlsError err;
  12117. auto n = 1000;
  12118. while (--n >= 0) {
  12119. {
  12120. std::lock_guard<std::mutex> guard(session_mutex_);
  12121. auto ret = tls::write(session_, ptr, handle_size, err);
  12122. if (ret >= 0) { return ret; }
  12123. }
  12124. // ret < 0. As in read(), either direction can be needed: a renegotiation
  12125. // or a post-handshake message must be consumed before the record goes
  12126. // out. Anything else is a hard error.
  12127. auto needs_writable = err.code == tls::ErrorCode::WantWrite;
  12128. #ifdef _WIN32
  12129. // On Windows a socket timeout surfaces as a syscall error, not WantWrite.
  12130. needs_writable =
  12131. needs_writable || (err.code == tls::ErrorCode::SyscallError &&
  12132. WSAGetLastError() == WSAETIMEDOUT);
  12133. #endif
  12134. if (!needs_writable && err.code != tls::ErrorCode::WantRead) { return -1; }
  12135. if (!(needs_writable ? wait_writable() : wait_readable())) { return -1; }
  12136. }
  12137. return -1;
  12138. }
  12139. inline void WebSocketSSLStream::get_remote_ip_and_port(std::string &ip,
  12140. int &port) const {
  12141. detail::get_remote_ip_and_port(sock_, ip, port);
  12142. }
  12143. inline void WebSocketSSLStream::get_local_ip_and_port(std::string &ip,
  12144. int &port) const {
  12145. detail::get_local_ip_and_port(sock_, ip, port);
  12146. }
  12147. inline socket_t WebSocketSSLStream::socket() const { return sock_; }
  12148. inline time_t WebSocketSSLStream::duration() const {
  12149. auto start = std::chrono::steady_clock::time_point(
  12150. std::chrono::steady_clock::duration(start_time_.load()));
  12151. return static_cast<time_t>(
  12152. std::chrono::duration_cast<std::chrono::milliseconds>(
  12153. std::chrono::steady_clock::now() - start)
  12154. .count());
  12155. }
  12156. // Start time first: a reader that sees the new bound also sees its start
  12157. inline void WebSocketSSLStream::set_max_timeout(time_t msec) {
  12158. start_time_ = std::chrono::steady_clock::now().time_since_epoch().count();
  12159. max_timeout_msec_ = msec;
  12160. }
  12161. inline void WebSocketSSLStream::set_read_timeout(time_t sec, time_t usec) {
  12162. read_timeout_sec_ = sec;
  12163. read_timeout_usec_ = usec;
  12164. }
  12165. inline void
  12166. WebSocketSSLStream::set_read_interrupt(std::function<bool()> interrupted) {
  12167. read_interrupted_ = std::move(interrupted);
  12168. }
  12169. } // namespace detail
  12170. #endif // CPPHTTPLIB_SSL_ENABLED
  12171. /*
  12172. * Group 4: Server implementation
  12173. */
  12174. // A kept-alive connection that the event loop of set_keep_alive_parking()
  12175. // owns while it is idle, and a worker owns while it serves a request. A
  12176. // derived class adds the transport: the stream, and for TLS the session.
  12177. struct Server::KeepAliveConnection {
  12178. KeepAliveConnection(socket_t s, Server &server) : svr(server), sock(s) {}
  12179. // Every owner closes it before letting go, which the transport hooks need;
  12180. // this is only a net, which cannot reach them any more.
  12181. virtual ~KeepAliveConnection() {
  12182. if (sock != INVALID_SOCKET) { detail::drain_and_close_socket(sock, 0); }
  12183. }
  12184. // On a worker before the first request, e.g. for a TLS handshake. False
  12185. // closes the connection. One that reads from the socket clears turn.woken.
  12186. virtual bool open() { return true; }
  12187. // Serves requests while they come: serve_on() with the transport's stream.
  12188. virtual bool serve() = 0;
  12189. // Before it is parked. Nothing is buffered then.
  12190. virtual void release_buffers() {}
  12191. // Before the socket of an open connection is closed, e.g. to send TLS
  12192. // close_notify.
  12193. virtual void shut_down(bool /*graceful*/) {}
  12194. // On a worker, once the event loop has seen the socket readable. Afterwards
  12195. // turn.park tells whether it may be parked again.
  12196. bool resume() {
  12197. turn = Turn();
  12198. return svr.serve_guarded([this]() {
  12199. if (!opened) {
  12200. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  12201. detail::get_local_ip_and_port(sock, local_addr, local_port);
  12202. if (!open()) { return false; }
  12203. opened = true;
  12204. }
  12205. return serve();
  12206. });
  12207. }
  12208. // From the event loop, which must not wait for the peer.
  12209. void close_idle() {
  12210. assert(sock != INVALID_SOCKET);
  12211. if (opened) {
  12212. detail::set_nonblocking(sock, true);
  12213. shut_down(true);
  12214. }
  12215. detail::drain_and_close_socket(sock, 0);
  12216. sock = INVALID_SOCKET;
  12217. }
  12218. // From the worker that served it.
  12219. void close_served(bool graceful) {
  12220. assert(sock != INVALID_SOCKET);
  12221. if (opened) {
  12222. shut_down(graceful);
  12223. detail::drain_and_close_socket(sock);
  12224. } else {
  12225. // It never got as far as a request, e.g. a failed TLS handshake.
  12226. detail::shutdown_socket(sock);
  12227. detail::close_socket(sock);
  12228. }
  12229. sock = INVALID_SOCKET;
  12230. }
  12231. template <typename S>
  12232. bool serve_on(S &strm,
  12233. const std::function<void(Request &)> &setup_request = nullptr) {
  12234. return detail::process_server_socket_core(
  12235. strm, served, svr.keep_alive_max_count_,
  12236. [this]() { return wait_for_next_request(); },
  12237. [&](Stream &s, bool close_connection, bool &connection_closed) {
  12238. return svr.process_request(s, remote_addr, remote_port, local_addr,
  12239. local_port, close_connection,
  12240. connection_closed, setup_request,
  12241. &turn.websocket_upgraded);
  12242. });
  12243. }
  12244. bool wait_for_next_request() {
  12245. // The event loop saw the socket readable just before this ran.
  12246. if (turn.woken) {
  12247. turn.woken = false;
  12248. return true;
  12249. }
  12250. if (svr.is_stopping()) { return false; }
  12251. // Waiting here for a slow client would keep the worker from others.
  12252. turn.park = detail::select_read(sock, 0, 0) <= 0;
  12253. return !turn.park;
  12254. }
  12255. // A worker's time with it, from resume() until it is parked or closed.
  12256. struct Turn {
  12257. bool woken = true;
  12258. bool park = false;
  12259. bool websocket_upgraded = false;
  12260. };
  12261. Server &svr;
  12262. socket_t sock;
  12263. int remote_port = 0;
  12264. int local_port = 0;
  12265. bool opened = false; // by resume(), once open() has succeeded
  12266. Turn turn;
  12267. size_t served = 0;
  12268. std::string remote_addr;
  12269. std::string local_addr;
  12270. // While parked
  12271. std::list<std::shared_ptr<KeepAliveConnection>>::iterator parked_at;
  12272. std::chrono::steady_clock::time_point deadline;
  12273. };
  12274. struct Server::PlainConnection final : Server::KeepAliveConnection {
  12275. PlainConnection(socket_t s, Server &server)
  12276. : KeepAliveConnection(s, server),
  12277. strm(s, server.read_timeout_sec_, server.read_timeout_usec_,
  12278. server.write_timeout_sec_, server.write_timeout_usec_) {}
  12279. bool serve() override { return serve_on(strm); }
  12280. void release_buffers() override { strm.release_buffer(); }
  12281. // Kept across requests: it may hold the start of a pipelined request.
  12282. detail::SocketStream strm;
  12283. };
  12284. struct Server::ParkingState {
  12285. using Clock = std::chrono::steady_clock;
  12286. using Token = detail::Poller::Token;
  12287. using Connection = std::shared_ptr<KeepAliveConnection>;
  12288. // Kept for the Server's life, so that stop() can wake() it without a lock.
  12289. std::unique_ptr<detail::Poller> poller;
  12290. // The listening socket while parking_loop() watches it. Whichever of stop()
  12291. // and parking_loop() takes it out of here decides who closes it, so that it
  12292. // is never closed while the poller still watches it.
  12293. std::atomic<socket_t> listen_sock{INVALID_SOCKET};
  12294. // From stop(): whether parking_loop() takes over closing `sock`.
  12295. bool release_listen(socket_t sock) {
  12296. if (!listen_sock.compare_exchange_strong(sock, INVALID_SOCKET)) {
  12297. return false;
  12298. }
  12299. poller->wake();
  12300. return true;
  12301. }
  12302. // From a worker: hands an idle connection back, unless the loop has ended.
  12303. bool give_back(Connection conn) {
  12304. {
  12305. std::lock_guard<std::mutex> guard(mutex);
  12306. if (closed) { return false; }
  12307. returned.push_back(std::move(conn));
  12308. }
  12309. poller->wake();
  12310. return true;
  12311. }
  12312. // The rest belongs to parking_loop(). A parked connection's token is its
  12313. // address, and `parked` lists them in the order they expire.
  12314. // Closes it and returns false when the poller cannot watch it: unwatched,
  12315. // it would only wait for its deadline.
  12316. bool park(Connection conn, Clock::time_point deadline) {
  12317. auto &c = *conn;
  12318. c.deadline = deadline;
  12319. c.parked_at = parked.insert(parked.end(), std::move(conn));
  12320. if (poller->arm(c.sock, reinterpret_cast<Token>(&c))) { return true; }
  12321. unpark(reinterpret_cast<Token>(&c))->close_idle();
  12322. return false;
  12323. }
  12324. Connection unpark(Token token) {
  12325. auto &c = *reinterpret_cast<KeepAliveConnection *>(token);
  12326. auto conn = std::move(*c.parked_at);
  12327. parked.erase(c.parked_at);
  12328. return conn;
  12329. }
  12330. Clock::time_point next_deadline() const {
  12331. return parked.empty() ? (Clock::time_point::max)()
  12332. : parked.front()->deadline;
  12333. }
  12334. void expire(Clock::time_point now) {
  12335. while (!parked.empty() && parked.front()->deadline <= now) {
  12336. poller->disarm(parked.front()->sock);
  12337. parked.front()->close_idle();
  12338. parked.pop_front();
  12339. }
  12340. }
  12341. // Closes them here rather than wherever the last reference goes, which may
  12342. // be a worker that has just given one back, or the destructor, which cannot
  12343. // reach the transport.
  12344. void close_all() {
  12345. std::vector<Connection> left;
  12346. {
  12347. std::lock_guard<std::mutex> guard(mutex);
  12348. closed = true;
  12349. left.swap(returned);
  12350. }
  12351. for (auto &conn : parked) {
  12352. poller->disarm(conn->sock);
  12353. conn->close_idle();
  12354. }
  12355. for (auto &conn : left) {
  12356. conn->close_idle();
  12357. }
  12358. for (auto &conn : backlog) {
  12359. conn->close_idle();
  12360. }
  12361. parked.clear();
  12362. backlog.clear();
  12363. }
  12364. std::mutex mutex;
  12365. std::vector<Connection> returned;
  12366. bool closed = false;
  12367. std::list<Connection> parked;
  12368. std::list<Connection> backlog;
  12369. };
  12370. // HTTP server implementation
  12371. inline Server::Server()
  12372. : new_task_queue([] {
  12373. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  12374. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  12375. }) {
  12376. #ifndef _WIN32
  12377. signal(SIGPIPE, SIG_IGN);
  12378. #endif
  12379. set_keep_alive_parking(CPPHTTPLIB_KEEPALIVE_PARKING);
  12380. }
  12381. inline Server::~Server() = default;
  12382. inline std::unique_ptr<detail::MatcherBase>
  12383. Server::make_matcher(const std::string &pattern) {
  12384. // Path params take precedence, so "/users/:id/(.*)" keeps being matched as
  12385. // a path params pattern
  12386. if (pattern.find("/:") != std::string::npos) {
  12387. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  12388. }
  12389. // A pattern with no regex metacharacter only has to be compared literally,
  12390. // which is what PathParamsMatcher already does when it captures no
  12391. // parameter, so std::regex is only worth building for the patterns that
  12392. // actually need it
  12393. if (pattern.find_first_of(".^$|()[]{}*+?\\") == std::string::npos) {
  12394. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  12395. }
  12396. return detail::make_unique<detail::RegexMatcher>(pattern);
  12397. }
  12398. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  12399. return add_handler(get_handlers_, pattern, std::move(handler));
  12400. }
  12401. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  12402. return add_handler(post_handlers_, pattern, std::move(handler));
  12403. }
  12404. inline Server &Server::Post(const std::string &pattern,
  12405. HandlerWithContentReader handler) {
  12406. return add_handler(post_handlers_for_content_reader_, pattern,
  12407. std::move(handler));
  12408. }
  12409. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  12410. return add_handler(put_handlers_, pattern, std::move(handler));
  12411. }
  12412. inline Server &Server::Put(const std::string &pattern,
  12413. HandlerWithContentReader handler) {
  12414. return add_handler(put_handlers_for_content_reader_, pattern,
  12415. std::move(handler));
  12416. }
  12417. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  12418. return add_handler(patch_handlers_, pattern, std::move(handler));
  12419. }
  12420. inline Server &Server::Patch(const std::string &pattern,
  12421. HandlerWithContentReader handler) {
  12422. return add_handler(patch_handlers_for_content_reader_, pattern,
  12423. std::move(handler));
  12424. }
  12425. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  12426. return add_handler(delete_handlers_, pattern, std::move(handler));
  12427. }
  12428. inline Server &Server::Delete(const std::string &pattern,
  12429. HandlerWithContentReader handler) {
  12430. return add_handler(delete_handlers_for_content_reader_, pattern,
  12431. std::move(handler));
  12432. }
  12433. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  12434. return add_handler(options_handlers_, pattern, std::move(handler));
  12435. }
  12436. inline const std::set<std::string> &Server::builtin_methods() {
  12437. thread_local const std::set<std::string> methods{
  12438. "GET", "HEAD", "POST", "PUT", "DELETE",
  12439. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  12440. return methods;
  12441. }
  12442. inline Server::CustomHandlerEntry *
  12443. Server::custom_entry_for_registration(const std::string &method) {
  12444. // Built-in methods are refused for two different reasons. GET, HEAD, POST,
  12445. // PUT, DELETE, OPTIONS and PATCH are dispatched by the if/else chain in
  12446. // routing() before the custom tables are consulted, so a route registered
  12447. // for one of them could never fire. CONNECT, TRACE and PRI have no branch
  12448. // there and would be reachable, but they carry protocol-level meaning
  12449. // (tunnel setup, request echo, the HTTP/2 connection preface) that this
  12450. // library does not route.
  12451. if (!detail::fields::is_token(method) || builtin_methods().count(method)) {
  12452. output_error_log(Error::InvalidHTTPMethod, nullptr);
  12453. has_invalid_registration_ = true;
  12454. return nullptr;
  12455. }
  12456. return &custom_handlers_[method];
  12457. }
  12458. inline Server &Server::CustomRoute(const std::string &method,
  12459. const std::string &pattern,
  12460. Handler handler) {
  12461. auto *entry = custom_entry_for_registration(method);
  12462. if (!entry) { return *this; }
  12463. return add_handler(entry->handlers, pattern, std::move(handler));
  12464. }
  12465. inline Server &Server::CustomRoute(const std::string &method,
  12466. const std::string &pattern,
  12467. HandlerWithContentReader handler) {
  12468. auto *entry = custom_entry_for_registration(method);
  12469. if (!entry) { return *this; }
  12470. return add_handler(entry->handlers_for_content_reader, pattern,
  12471. std::move(handler));
  12472. }
  12473. inline const Server::CustomHandlerEntry *
  12474. Server::find_custom_entry(const std::string &method) const {
  12475. // find() alone would be correct here. The empty() check is what keeps the
  12476. // per-request cost off servers that never call CustomRoute(), which is the
  12477. // overwhelmingly common case; keep it rather than walking into the tree.
  12478. if (custom_handlers_.empty()) { return nullptr; }
  12479. auto it = custom_handlers_.find(method);
  12480. return it == custom_handlers_.end() ? nullptr : &it->second;
  12481. }
  12482. inline Server &Server::WebSocket(const std::string &pattern,
  12483. WebSocketHandler handler) {
  12484. websocket_handlers_.push_back(
  12485. {make_matcher(pattern), std::move(handler), nullptr});
  12486. return *this;
  12487. }
  12488. inline Server &Server::WebSocket(const std::string &pattern,
  12489. WebSocketHandler handler,
  12490. SubProtocolSelector sub_protocol_selector) {
  12491. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  12492. std::move(sub_protocol_selector)});
  12493. return *this;
  12494. }
  12495. inline bool Server::set_base_dir(const std::string &dir,
  12496. const std::string &mount_point) {
  12497. return set_mount_point(mount_point, dir);
  12498. }
  12499. inline bool Server::set_mount_point(const std::string &mount_point,
  12500. const std::string &dir, Headers headers) {
  12501. detail::FileStat stat(dir);
  12502. if (stat.is_dir()) {
  12503. std::string mnt = !mount_point.empty() ? mount_point : "/";
  12504. if (!mnt.empty() && mnt[0] == '/') {
  12505. // Without the resolved directory, a file could not be checked to be
  12506. // inside it.
  12507. std::string resolved_base;
  12508. if (!detail::canonicalize_path(dir.c_str(), resolved_base)) {
  12509. return false;
  12510. }
  12511. #if defined(_WIN32)
  12512. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  12513. resolved_base += '\\';
  12514. }
  12515. #else
  12516. if (resolved_base.back() != '/') { resolved_base += '/'; }
  12517. #endif
  12518. base_dirs_.push_back(
  12519. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  12520. return true;
  12521. }
  12522. }
  12523. return false;
  12524. }
  12525. inline bool Server::remove_mount_point(const std::string &mount_point) {
  12526. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  12527. if (it->mount_point == mount_point) {
  12528. base_dirs_.erase(it);
  12529. return true;
  12530. }
  12531. }
  12532. return false;
  12533. }
  12534. inline Server &
  12535. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  12536. const std::string &mime) {
  12537. // Keyed as find_content_type() looks it up
  12538. auto key = detail::case_ignore::to_lower(ext);
  12539. if (!key.empty() && key[0] == '.') { key.erase(0, 1); }
  12540. file_extension_and_mimetype_map_[key] = mime;
  12541. return *this;
  12542. }
  12543. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  12544. default_file_mimetype_ = mime;
  12545. return *this;
  12546. }
  12547. inline Server &Server::set_file_request_handler(Handler handler) {
  12548. file_request_handler_ = std::move(handler);
  12549. return *this;
  12550. }
  12551. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  12552. std::true_type) {
  12553. error_handler_ = std::move(handler);
  12554. return *this;
  12555. }
  12556. inline Server &Server::set_error_handler_core(Handler handler,
  12557. std::false_type) {
  12558. error_handler_ = [handler](const Request &req, Response &res) {
  12559. handler(req, res);
  12560. return HandlerResponse::Handled;
  12561. };
  12562. return *this;
  12563. }
  12564. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  12565. exception_handler_ = std::move(handler);
  12566. return *this;
  12567. }
  12568. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  12569. pre_routing_handler_ = std::move(handler);
  12570. return *this;
  12571. }
  12572. inline Server &Server::set_post_routing_handler(Handler handler) {
  12573. post_routing_handler_ = std::move(handler);
  12574. return *this;
  12575. }
  12576. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  12577. pre_request_handler_ = std::move(handler);
  12578. return *this;
  12579. }
  12580. inline Server &Server::set_logger(Logger logger) {
  12581. logger_ = std::move(logger);
  12582. return *this;
  12583. }
  12584. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  12585. error_logger_ = std::move(error_logger);
  12586. return *this;
  12587. }
  12588. inline Server &Server::set_pre_compression_logger(Logger logger) {
  12589. pre_compression_logger_ = std::move(logger);
  12590. return *this;
  12591. }
  12592. inline Server &
  12593. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  12594. expect_100_continue_handler_ = std::move(handler);
  12595. return *this;
  12596. }
  12597. inline Server &Server::set_start_handler(StartHandler handler) {
  12598. start_handler_ = std::move(handler);
  12599. return *this;
  12600. }
  12601. inline Server &Server::set_address_family(int family) {
  12602. address_family_ = family;
  12603. return *this;
  12604. }
  12605. inline Server &Server::set_tcp_nodelay(bool on) {
  12606. tcp_nodelay_ = on;
  12607. return *this;
  12608. }
  12609. inline Server &Server::set_ipv6_v6only(bool on) {
  12610. ipv6_v6only_ = on;
  12611. return *this;
  12612. }
  12613. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  12614. socket_options_ = std::move(socket_options);
  12615. return *this;
  12616. }
  12617. inline Server &Server::set_default_headers(Headers headers) {
  12618. default_headers_ = std::move(headers);
  12619. return *this;
  12620. }
  12621. inline Server &Server::set_header_writer(
  12622. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12623. header_writer_ = writer;
  12624. return *this;
  12625. }
  12626. inline Server &
  12627. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  12628. trusted_proxies_.clear();
  12629. trusted_proxies_.reserve(proxies.size());
  12630. for (const auto &proxy : proxies) {
  12631. trusted_proxies_.push_back(detail::canonical_ip(proxy));
  12632. }
  12633. return *this;
  12634. }
  12635. inline Server &Server::set_keep_alive_max_count(size_t count) {
  12636. keep_alive_max_count_ = count;
  12637. return *this;
  12638. }
  12639. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  12640. keep_alive_timeout_sec_ = sec;
  12641. return *this;
  12642. }
  12643. template <class Rep, class Period>
  12644. inline Server &Server::set_keep_alive_timeout(
  12645. const std::chrono::duration<Rep, Period> &duration) {
  12646. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  12647. set_keep_alive_timeout(sec);
  12648. });
  12649. return *this;
  12650. }
  12651. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  12652. read_timeout_sec_ = sec;
  12653. read_timeout_usec_ = usec;
  12654. return *this;
  12655. }
  12656. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  12657. write_timeout_sec_ = sec;
  12658. write_timeout_usec_ = usec;
  12659. return *this;
  12660. }
  12661. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  12662. idle_interval_sec_ = sec;
  12663. idle_interval_usec_ = usec;
  12664. idle_interval_set_ = true;
  12665. return *this;
  12666. }
  12667. inline Server &Server::set_keep_alive_parking(bool on) {
  12668. // Never destroyed once made: stop() may use it from another thread.
  12669. if (on && !parking_) {
  12670. auto poller = detail::make_poller();
  12671. if (poller) {
  12672. parking_.reset(new ParkingState());
  12673. parking_->poller = std::move(poller);
  12674. }
  12675. }
  12676. keep_alive_parking_ = on;
  12677. return *this;
  12678. }
  12679. inline Server &Server::set_payload_max_length(size_t length) {
  12680. payload_max_length_ = length;
  12681. return *this;
  12682. }
  12683. inline Server &Server::set_compress(bool on) {
  12684. compress_ = on;
  12685. return *this;
  12686. }
  12687. inline Server &Server::set_static_file_compression(bool on) {
  12688. static_file_compression_ = on;
  12689. return *this;
  12690. }
  12691. inline Server &Server::set_static_file_compression_min_length(size_t length) {
  12692. static_file_compression_min_length_ = length;
  12693. return *this;
  12694. }
  12695. inline Server &Server::set_static_file_compression_max_length(size_t length) {
  12696. static_file_compression_max_length_ = length;
  12697. return *this;
  12698. }
  12699. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  12700. websocket_max_missed_pongs_ = count;
  12701. return *this;
  12702. }
  12703. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  12704. websocket_ping_interval_sec_ = sec;
  12705. return *this;
  12706. }
  12707. template <class Rep, class Period>
  12708. inline Server &Server::set_websocket_ping_interval(
  12709. const std::chrono::duration<Rep, Period> &duration) {
  12710. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  12711. set_websocket_ping_interval(sec);
  12712. });
  12713. return *this;
  12714. }
  12715. inline bool Server::bind_to_port(const std::string &host, int port,
  12716. int socket_flags) {
  12717. auto ret = bind_internal(host, port, socket_flags);
  12718. if (ret == -1) { is_decommissioned = true; }
  12719. return ret >= 0;
  12720. }
  12721. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  12722. auto ret = bind_internal(host, 0, socket_flags);
  12723. if (ret == -1) { is_decommissioned = true; }
  12724. return ret;
  12725. }
  12726. inline bool Server::listen_after_bind() { return listen_internal(); }
  12727. inline bool Server::listen(const std::string &host, int port,
  12728. int socket_flags) {
  12729. return bind_to_port(host, port, socket_flags) && listen_internal();
  12730. }
  12731. inline bool Server::is_running() const { return is_running_; }
  12732. inline void Server::wait_until_ready() const {
  12733. while (!is_running_ && !is_decommissioned) {
  12734. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  12735. }
  12736. }
  12737. inline void Server::stop() noexcept {
  12738. // Release the listening socket whether or not the accept loop is running:
  12739. // bind_to_port() without listen_after_bind() still owns the descriptor. The
  12740. // exchange is what makes this safe to call concurrently with the accept loop.
  12741. socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
  12742. if (sock != INVALID_SOCKET && !(parking_ && parking_->release_listen(sock))) {
  12743. detail::shutdown_socket(sock);
  12744. detail::close_socket(sock);
  12745. }
  12746. is_decommissioned = false;
  12747. }
  12748. inline void Server::decommission() { is_decommissioned = true; }
  12749. inline bool Server::parse_request_line(const char *s, Request &req) const {
  12750. auto len = strlen(s);
  12751. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  12752. len -= 2;
  12753. {
  12754. // RFC 9112 §3: exactly one SP between the method, the target and the
  12755. // version. Taking other whitespace as a separator too lets recipients
  12756. // that parse more strictly see a different request.
  12757. auto end = s + len;
  12758. if (std::count(s, end, ' ') != 2) { return false; }
  12759. auto sp1 = std::find(s, end, ' ');
  12760. auto sp2 = std::find(sp1 + 1, end, ' ');
  12761. if (sp1 == s || sp2 == sp1 + 1 || sp2 + 1 == end) { return false; }
  12762. req.method.assign(s, sp1);
  12763. req.target.assign(sp1 + 1, sp2);
  12764. req.version.assign(sp2 + 1, end);
  12765. }
  12766. // A method outside the built-in set is accepted only when a handler has been
  12767. // registered for it with CustomRoute().
  12768. const auto &methods = builtin_methods();
  12769. if (methods.find(req.method) == methods.end() &&
  12770. !find_custom_entry(req.method)) {
  12771. output_error_log(Error::InvalidHTTPMethod, &req);
  12772. return false;
  12773. }
  12774. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  12775. output_error_log(Error::InvalidHTTPVersion, &req);
  12776. return false;
  12777. }
  12778. // A request-target has no fragment (RFC 9112 §3.2), and one stripped here
  12779. // would leave this server routing a different path than a cache or a
  12780. // filter in front of it sees.
  12781. if (!detail::fields::is_request_target(req.target) ||
  12782. req.target.find('#') != std::string::npos) {
  12783. return false;
  12784. }
  12785. {
  12786. detail::divide(req.target, '?',
  12787. [&](const char *lhs_data, std::size_t lhs_size,
  12788. const char *rhs_data, std::size_t rhs_size) {
  12789. req.path =
  12790. decode_path_component(std::string(lhs_data, lhs_size));
  12791. detail::parse_query_text(rhs_data, rhs_size, req.params);
  12792. });
  12793. }
  12794. return true;
  12795. }
  12796. inline bool Server::write_response(Stream &strm, bool close_connection,
  12797. Request &req, Response &res) {
  12798. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  12799. // incorrectly to the error content.
  12800. req.ranges.clear();
  12801. return write_response_core(strm, close_connection, req, res, false);
  12802. }
  12803. inline bool Server::write_response_with_content(Stream &strm,
  12804. bool close_connection,
  12805. const Request &req,
  12806. Response &res) {
  12807. return write_response_core(strm, close_connection, req, res, true);
  12808. }
  12809. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  12810. const Request &req, Response &res,
  12811. bool need_apply_ranges) {
  12812. assert(res.status != -1);
  12813. if (400 <= res.status && error_handler_ &&
  12814. error_handler_(req, res) == HandlerResponse::Handled) {
  12815. need_apply_ranges = true;
  12816. }
  12817. // Before anything below reads res.headers, which the handlers may have
  12818. // filled directly
  12819. detail::erase_invalid_fields(res.headers);
  12820. if (!detail::body_allowed_for_status(res.status)) {
  12821. detail::clear_content(res);
  12822. }
  12823. detail::prefer_assigned_body(res);
  12824. std::string content_type;
  12825. std::string boundary;
  12826. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  12827. // Prepare additional headers
  12828. if (close_connection ||
  12829. detail::has_header_token(req.headers, "Connection", "close") ||
  12830. 400 <= res.status || // Don't leave connections open after errors
  12831. // The client withholds the body until `100 Continue`, which was never
  12832. // sent, so whether and when the body follows is unknown.
  12833. (req.expect_100_continue_pending_ && detail::has_framed_body(req)) ||
  12834. // The body was left partway, e.g. by a content receiver that returned
  12835. // false, so the rest of it cannot be told from the next request.
  12836. (req.body_read_started_ && !req.body_consumed_)) {
  12837. res.set_header("Connection", "close");
  12838. } else {
  12839. std::string s = "timeout=";
  12840. s += std::to_string(keep_alive_timeout_sec_);
  12841. if (keep_alive_max_count_ > 0) {
  12842. s += ", max=";
  12843. s += std::to_string(keep_alive_max_count_);
  12844. }
  12845. res.set_header("Keep-Alive", s);
  12846. }
  12847. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  12848. !res.has_header("Content-Type")) {
  12849. res.set_header("Content-Type", "text/plain");
  12850. }
  12851. detail::set_framing_headers(req, res, boundary, content_type);
  12852. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  12853. res.set_header("Accept-Ranges", "bytes");
  12854. }
  12855. if (post_routing_handler_) {
  12856. post_routing_handler_(req, res);
  12857. detail::erase_invalid_fields(res.headers);
  12858. // Again, for a body or framing headers the handler changed.
  12859. detail::set_framing_headers(req, res, boundary, content_type);
  12860. }
  12861. // Response line and headers
  12862. detail::BufferStream bstrm;
  12863. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  12864. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  12865. // Combine a small body with the headers so the whole response leaves in a
  12866. // single write. A large body is written on its own instead: a copy of it
  12867. // costs more than the extra write saves.
  12868. auto send_body =
  12869. req.method != "HEAD" && detail::body_allowed_for_status(res.status);
  12870. auto body_is_separate = false;
  12871. auto provider_done = false;
  12872. if (send_body && !res.body.empty() && !res.content_provider_) {
  12873. if (res.body.size() < CPPHTTPLIB_SEND_BUFSIZ) {
  12874. bstrm.write(res.body.data(), res.body.size());
  12875. } else {
  12876. body_is_separate = true;
  12877. }
  12878. } else if (send_body && res.content_provider_ &&
  12879. res.is_file_content_provider_ &&
  12880. res.content_length_ < CPPHTTPLIB_SEND_BUFSIZ) {
  12881. // A small file is read into the same buffer. Other providers may produce
  12882. // their data over time, so they are never held back.
  12883. if (!write_content_with_provider(bstrm, req, res, boundary, content_type)) {
  12884. return false;
  12885. }
  12886. provider_done = true;
  12887. }
  12888. // Log before writing to avoid race condition with client-side code that
  12889. // accesses logger-captured data immediately after receiving the response.
  12890. output_log(req, res);
  12891. // Flush buffer
  12892. auto &data = bstrm.get_buffer();
  12893. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  12894. if (body_is_separate) {
  12895. return detail::write_data(strm, res.body.data(), res.body.size());
  12896. }
  12897. // Streaming body
  12898. if (send_body && res.content_provider_) {
  12899. if (!provider_done &&
  12900. !write_content_with_provider(strm, req, res, boundary, content_type)) {
  12901. return false;
  12902. }
  12903. res.content_provider_success_ = true;
  12904. }
  12905. return true;
  12906. }
  12907. inline bool
  12908. Server::write_content_with_provider(Stream &strm, const Request &req,
  12909. Response &res, const std::string &boundary,
  12910. const std::string &content_type) {
  12911. auto is_shutting_down = [this]() { return is_stopping(); };
  12912. if (res.content_length_ > 0) {
  12913. if (!detail::is_partial_content(req, res)) {
  12914. return detail::write_content(strm, res.content_provider_, 0,
  12915. res.content_length_, is_shutting_down);
  12916. } else if (req.ranges.size() == 1) {
  12917. auto offset_and_length = detail::get_range_offset_and_length(
  12918. req.ranges[0], res.content_length_);
  12919. return detail::write_content(strm, res.content_provider_,
  12920. offset_and_length.first,
  12921. offset_and_length.second, is_shutting_down);
  12922. } else {
  12923. return detail::write_multipart_ranges_data(
  12924. strm, req, res, boundary, content_type, res.content_length_,
  12925. is_shutting_down);
  12926. }
  12927. } else {
  12928. if (res.is_chunked_content_provider_) {
  12929. // Use the coding `apply_ranges()` chose when it wrote the headers;
  12930. // re-negotiating here would disagree with them, e.g. once a handler's
  12931. // own Content-Encoding header suppresses the negotiation.
  12932. auto compressor = detail::make_compressor(res.content_coding_);
  12933. if (!compressor) {
  12934. compressor = detail::make_unique<detail::nocompressor>();
  12935. }
  12936. return detail::write_content_chunked(strm, res.content_provider_,
  12937. is_shutting_down, *compressor);
  12938. } else {
  12939. return detail::write_content_without_length(strm, res.content_provider_,
  12940. is_shutting_down);
  12941. }
  12942. }
  12943. }
  12944. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  12945. FormFields::iterator cur_field;
  12946. FormFiles::iterator cur_file;
  12947. auto is_text_field = false;
  12948. size_t count = 0;
  12949. if (read_content_core(
  12950. strm, req, res,
  12951. // Regular
  12952. [&](const char *buf, size_t n) {
  12953. // Prevent arithmetic overflow when checking sizes.
  12954. // Avoid computing (req.body.size() + n) directly because
  12955. // adding two unsigned `size_t` values can wrap around and
  12956. // produce a small result instead of indicating overflow.
  12957. // Instead, check using subtraction: ensure `n` does not
  12958. // exceed the remaining capacity `max_size() - size()`.
  12959. if (req.body.size() >= req.body.max_size() ||
  12960. n > req.body.max_size() - req.body.size()) {
  12961. return false;
  12962. }
  12963. // Limit decompressed body size to payload_max_length_ to protect
  12964. // against "zip bomb" attacks where a small compressed payload
  12965. // decompresses to a massive size.
  12966. if (payload_max_length_ > 0 &&
  12967. (req.body.size() >= payload_max_length_ ||
  12968. n > payload_max_length_ - req.body.size())) {
  12969. return false;
  12970. }
  12971. req.body.append(buf, n);
  12972. return true;
  12973. },
  12974. // Multipart FormData
  12975. [&](const FormData &file) {
  12976. if (CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT > 0 &&
  12977. count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  12978. output_error_log(Error::TooManyFormDataFiles, &req);
  12979. return false;
  12980. }
  12981. if (file.filename.empty()) {
  12982. cur_field = req.form.fields.emplace(
  12983. file.name, FormField{file.name, file.content, file.headers});
  12984. is_text_field = true;
  12985. } else {
  12986. cur_file = req.form.files.emplace(file.name, file);
  12987. is_text_field = false;
  12988. }
  12989. return true;
  12990. },
  12991. [&](const char *buf, size_t n) {
  12992. if (is_text_field) {
  12993. auto &content = cur_field->second.content;
  12994. if (content.size() + n > content.max_size()) { return false; }
  12995. content.append(buf, n);
  12996. } else {
  12997. auto &content = cur_file->second.content;
  12998. if (content.size() + n > content.max_size()) { return false; }
  12999. content.append(buf, n);
  13000. }
  13001. return true;
  13002. })) {
  13003. const auto &content_type = req.get_header_value("Content-Type");
  13004. if (detail::case_ignore::equal(detail::extract_media_type(content_type),
  13005. "application/x-www-form-urlencoded")) {
  13006. if (CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH > 0 &&
  13007. req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  13008. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  13009. output_error_log(Error::ExceedMaxPayloadSize, &req);
  13010. return false;
  13011. }
  13012. detail::parse_query_text(req.body, req.params);
  13013. }
  13014. return true;
  13015. }
  13016. return false;
  13017. }
  13018. inline bool Server::read_content_with_content_receiver(
  13019. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  13020. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  13021. return read_content_core(strm, req, res, std::move(receiver),
  13022. std::move(multipart_header),
  13023. std::move(multipart_receiver));
  13024. }
  13025. inline bool Server::read_content_core(
  13026. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  13027. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  13028. detail::FormDataParser multipart_form_data_parser;
  13029. ContentReceiverWithProgress out;
  13030. if (req.is_multipart_form_data()) {
  13031. const auto &content_type = req.get_header_value("Content-Type");
  13032. std::string boundary;
  13033. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  13034. res.status = StatusCode::BadRequest_400;
  13035. output_error_log(Error::MultipartParsing, &req);
  13036. return false;
  13037. }
  13038. multipart_form_data_parser.set_boundary(std::move(boundary));
  13039. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  13040. return multipart_form_data_parser.parse(buf, n, multipart_header,
  13041. multipart_receiver);
  13042. };
  13043. } else {
  13044. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  13045. size_t /*len*/) { return receiver(buf, n); };
  13046. }
  13047. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  13048. if (!req.has_header("Content-Length") &&
  13049. !detail::is_chunked_transfer_encoding(req.headers)) {
  13050. return true;
  13051. }
  13052. // A second read would start where the first one stopped, or in the next
  13053. // request.
  13054. if (req.body_read_started_) { return false; }
  13055. // The client is waiting for this before it sends the body.
  13056. if (req.expect_100_continue_pending_) {
  13057. req.expect_100_continue_pending_ = false;
  13058. detail::write_response_line(strm, StatusCode::Continue_100);
  13059. strm.write("\r\n");
  13060. }
  13061. // Set before reading, since a receiver may also stop by throwing.
  13062. req.body_read_started_ = true;
  13063. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  13064. out, true)) {
  13065. return false;
  13066. }
  13067. req.body_consumed_ = true;
  13068. if (req.is_multipart_form_data()) {
  13069. if (!multipart_form_data_parser.is_valid()) {
  13070. res.status = StatusCode::BadRequest_400;
  13071. output_error_log(Error::MultipartParsing, &req);
  13072. return false;
  13073. }
  13074. }
  13075. return true;
  13076. }
  13077. inline bool Server::handle_file_request(Request &req, Response &res) {
  13078. if (!detail::is_valid_path(req.path)) { return false; }
  13079. for (const auto &entry : base_dirs_) {
  13080. // Prefix match, on a path segment boundary. A mount point of "/mount"
  13081. // covers "/mount" and "/mount/...", but must not swallow "/mountdir/...".
  13082. // One that already ends in '/' (the root mount among them) carries its own
  13083. // boundary; set_mount_point() guarantees the mount point is not empty.
  13084. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point) &&
  13085. (entry.mount_point.back() == '/' ||
  13086. req.path.size() == entry.mount_point.size() ||
  13087. req.path[entry.mount_point.size()] == '/')) {
  13088. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  13089. auto path = entry.base_dir + sub_path;
  13090. if (path.back() == '/') { path += "index.html"; }
  13091. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  13092. // but symlinks/junctions can still escape the base directory. A path
  13093. // that cannot be resolved, which includes one that does not exist, is
  13094. // not served from here.
  13095. std::string resolved_path;
  13096. if (!detail::canonicalize_path(path.c_str(), resolved_path)) { continue; }
  13097. if (!detail::is_path_within_base(resolved_path,
  13098. entry.resolved_base_dir)) {
  13099. res.status = StatusCode::Forbidden_403;
  13100. return true;
  13101. }
  13102. detail::FileStat stat(path);
  13103. if (stat.is_dir()) {
  13104. // Relative, so "//dir" cannot name another host; "./" keeps a ':'
  13105. // in the name from reading as a scheme.
  13106. auto name = req.path.substr(req.path.rfind('/') + 1);
  13107. res.set_redirect("./" + encode_path_component(name) + "/",
  13108. StatusCode::MovedPermanently_301);
  13109. return true;
  13110. }
  13111. if (stat.is_file()) {
  13112. for (const auto &kv : entry.headers) {
  13113. res.set_header(kv.first, kv.second);
  13114. }
  13115. auto content_type = detail::find_content_type(
  13116. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  13117. auto encoding = detail::EncodingType::None;
  13118. if (static_file_compression_) {
  13119. encoding = static_file_encoding(req, res, content_type, stat.size());
  13120. }
  13121. // The ETag names the representation actually sent, so a client that
  13122. // cached the compressed form revalidates against the compressed ETag
  13123. // and still gets a 304, while one that took identity keeps the plain
  13124. // ETag.
  13125. auto etag = detail::compute_etag(
  13126. stat, encoding == detail::EncodingType::None
  13127. ? std::string()
  13128. : std::string("-") + detail::encoding_name(encoding));
  13129. if (!etag.empty()) { res.set_header("ETag", etag); }
  13130. auto mtime = stat.mtime();
  13131. auto last_modified = detail::file_mtime_to_http_date(mtime);
  13132. if (!last_modified.empty()) {
  13133. res.set_header("Last-Modified", last_modified);
  13134. }
  13135. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  13136. check_if_range(req, etag, mtime);
  13137. auto mm = std::make_shared<detail::mmap>(path.c_str());
  13138. if (!mm->is_open()) {
  13139. output_error_log(Error::OpenFile, &req);
  13140. return false;
  13141. }
  13142. detail::set_file_content_provider(res, mm, content_type, encoding);
  13143. if (req.method != "HEAD" && file_request_handler_) {
  13144. file_request_handler_(req, res);
  13145. }
  13146. return true;
  13147. } else {
  13148. output_error_log(Error::OpenFile, &req);
  13149. }
  13150. }
  13151. }
  13152. return false;
  13153. }
  13154. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  13155. const std::string &etag,
  13156. time_t mtime) const {
  13157. // Handle conditional GET:
  13158. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  13159. // 2. If-Modified-Since is checked only when If-None-Match is absent
  13160. if (req.has_header("If-None-Match")) {
  13161. if (!etag.empty()) {
  13162. auto val =
  13163. detail::get_combined_header_value(req.headers, "If-None-Match");
  13164. // NOTE: We use exact string matching here. This works correctly
  13165. // because our server always generates weak ETags (W/"..."), and
  13166. // clients typically send back the same ETag they received.
  13167. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  13168. // If-None-Match, where W/"x" and "x" would match, but this
  13169. // simplified implementation requires exact matches.
  13170. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  13171. [&](const char *b, const char *e) {
  13172. auto seg_len = static_cast<size_t>(e - b);
  13173. return (seg_len == 1 && *b == '*') ||
  13174. (seg_len == etag.size() &&
  13175. std::equal(b, e, etag.begin()));
  13176. });
  13177. if (ret) {
  13178. res.status = StatusCode::NotModified_304;
  13179. return true;
  13180. }
  13181. }
  13182. } else if (req.has_header("If-Modified-Since")) {
  13183. auto val = req.get_header_value("If-Modified-Since");
  13184. auto t = detail::parse_http_date(val);
  13185. if (t != static_cast<time_t>(-1) && mtime <= t) {
  13186. res.status = StatusCode::NotModified_304;
  13187. return true;
  13188. }
  13189. }
  13190. return false;
  13191. }
  13192. inline bool Server::check_if_range(Request &req, const std::string &etag,
  13193. time_t mtime) const {
  13194. // Handle If-Range for partial content requests (RFC 9110
  13195. // Section 13.1.5). If-Range is only evaluated when Range header is
  13196. // present. If the validator matches, serve partial content; otherwise
  13197. // serve full content.
  13198. if (!req.ranges.empty() && req.has_header("If-Range")) {
  13199. auto val = req.get_header_value("If-Range");
  13200. auto is_valid_range = [&]() {
  13201. if (detail::is_strong_etag(val)) {
  13202. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  13203. // comparison.
  13204. return (!etag.empty() && val == etag);
  13205. } else if (detail::is_weak_etag(val)) {
  13206. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  13207. return false;
  13208. } else {
  13209. // HTTP-date comparison
  13210. auto t = detail::parse_http_date(val);
  13211. return (t != static_cast<time_t>(-1) && mtime <= t);
  13212. }
  13213. };
  13214. if (!is_valid_range()) {
  13215. // Validator doesn't match: ignore Range and serve full content
  13216. req.ranges.clear();
  13217. return false;
  13218. }
  13219. }
  13220. return true;
  13221. }
  13222. inline socket_t
  13223. Server::create_server_socket(const std::string &host, int port,
  13224. int socket_flags,
  13225. SocketOptions socket_options) const {
  13226. return detail::create_socket(
  13227. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  13228. ipv6_v6only_, std::move(socket_options),
  13229. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  13230. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  13231. output_error_log(Error::BindIPAddress, nullptr);
  13232. return false;
  13233. }
  13234. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  13235. output_error_log(Error::Listen, nullptr);
  13236. return false;
  13237. }
  13238. return true;
  13239. });
  13240. }
  13241. inline int Server::bind_internal(const std::string &host, int port,
  13242. int socket_flags) {
  13243. if (is_decommissioned) { return -1; }
  13244. if (!is_valid()) { return -1; }
  13245. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  13246. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  13247. if (port == 0) {
  13248. struct sockaddr_storage addr;
  13249. socklen_t addr_len = sizeof(addr);
  13250. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  13251. &addr_len) == -1) {
  13252. output_error_log(Error::GetSockName, nullptr);
  13253. return -1;
  13254. }
  13255. if (addr.ss_family == AF_INET) {
  13256. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  13257. } else if (addr.ss_family == AF_INET6) {
  13258. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  13259. } else {
  13260. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  13261. return -1;
  13262. }
  13263. } else {
  13264. return port;
  13265. }
  13266. }
  13267. inline bool Server::listen_internal() {
  13268. // A stop() between bind and listen leaves nothing to accept on. Report
  13269. // failure instead of returning success without ever serving, and mark the
  13270. // server decommissioned the way any failed listen does so that a concurrent
  13271. // wait_until_ready() wakes up instead of spinning forever.
  13272. if (is_decommissioned || svr_sock_ == INVALID_SOCKET) {
  13273. is_decommissioned = true;
  13274. return false;
  13275. }
  13276. auto ret = true;
  13277. is_running_ = true;
  13278. auto se = detail::scope_exit([&]() { is_running_ = false; });
  13279. if (start_handler_) { start_handler_(); }
  13280. {
  13281. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  13282. ret = keep_alive_parking_ && parking_ ? parking_loop(*task_queue)
  13283. : accept_loop(*task_queue);
  13284. task_queue->shutdown();
  13285. }
  13286. is_decommissioned = !ret;
  13287. return ret;
  13288. }
  13289. inline void Server::prepare_accepted_socket(socket_t sock) const {
  13290. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_,
  13291. read_timeout_usec_);
  13292. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_,
  13293. write_timeout_usec_);
  13294. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  13295. }
  13296. // Serves each connection on one worker thread for its whole life.
  13297. inline bool Server::accept_loop(TaskQueue &task_queue) {
  13298. auto ret = true;
  13299. while (svr_sock_ != INVALID_SOCKET) {
  13300. #ifndef _WIN32
  13301. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  13302. #endif
  13303. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  13304. idle_interval_usec_);
  13305. if (val == 0) { // Timeout
  13306. task_queue.on_idle();
  13307. continue;
  13308. }
  13309. #ifndef _WIN32
  13310. }
  13311. #endif
  13312. auto sock = detail::accept_socket(svr_sock_);
  13313. if (sock == INVALID_SOCKET) {
  13314. // NOTE: Winsock reports failures through WSAGetLastError() and never
  13315. // touches the CRT errno, so the two have to be asked platform by
  13316. // platform rather than by testing errno here.
  13317. if (detail::is_accept_resource_error()) {
  13318. // The per-process descriptor limit or the network stack's buffer
  13319. // space has been reached. Try to accept new connections after a
  13320. // short sleep.
  13321. std::this_thread::sleep_for(std::chrono::microseconds{1});
  13322. continue;
  13323. } else if (detail::is_accept_transient_error()) {
  13324. continue;
  13325. }
  13326. if (abandon_listen_socket()) { ret = false; }
  13327. break;
  13328. }
  13329. prepare_accepted_socket(sock);
  13330. if (!task_queue.enqueue(
  13331. [this, sock]() { process_and_close_socket(sock); })) {
  13332. output_error_log(Error::ResourceExhaustion, nullptr);
  13333. detail::shutdown_socket(sock);
  13334. detail::close_socket(sock);
  13335. }
  13336. }
  13337. return ret;
  13338. }
  13339. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13340. // Call from a catch block. The response is a 500 unless the exception handler
  13341. // sets another status. Returns whether the exception handler ran.
  13342. inline bool Server::handle_exception(Request &req, Response &res) {
  13343. res.status = StatusCode::InternalServerError_500;
  13344. if (!exception_handler_) { return false; }
  13345. exception_handler_(req, res, std::current_exception());
  13346. return true;
  13347. }
  13348. #endif
  13349. inline bool Server::routing(Request &req, Response &res, Stream &strm,
  13350. bool skip_pre_routing) {
  13351. if (!skip_pre_routing && pre_routing_handler_ &&
  13352. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  13353. return true;
  13354. }
  13355. // File handler
  13356. if ((req.method == "GET" || req.method == "HEAD") &&
  13357. handle_file_request(req, res)) {
  13358. return true;
  13359. }
  13360. const auto *custom = find_custom_entry(req.method);
  13361. // The second clause mirrors what expect_content() does unconditionally for
  13362. // POST/PUT/PATCH/DELETE: a content reader route fires even when the request
  13363. // carries no body. Without it a body-less PROPFIND (RFC 4918 treats one as
  13364. // `allprop`) would skip its handler and fall through to 404.
  13365. if (detail::expect_content(req) ||
  13366. (custom && !custom->handlers_for_content_reader.empty())) {
  13367. // Content reader handler
  13368. {
  13369. // Track whether the ContentReader was aborted due to the decompressed
  13370. // payload exceeding `payload_max_length_`.
  13371. // The user handler runs after the lambda returns, so we must restore the
  13372. // 413 status if the handler overwrites it.
  13373. bool content_reader_payload_too_large = false;
  13374. ContentReader reader(
  13375. [&](ContentReceiver receiver) {
  13376. auto result = read_content_with_content_receiver(
  13377. strm, req, res, std::move(receiver), nullptr, nullptr);
  13378. if (!result) {
  13379. output_error_log(Error::Read, &req);
  13380. if (res.status == StatusCode::PayloadTooLarge_413) {
  13381. content_reader_payload_too_large = true;
  13382. }
  13383. }
  13384. return result;
  13385. },
  13386. [&](FormDataHeader header, ContentReceiver receiver) {
  13387. auto result = read_content_with_content_receiver(
  13388. strm, req, res, nullptr, std::move(header),
  13389. std::move(receiver));
  13390. if (!result) {
  13391. output_error_log(Error::Read, &req);
  13392. if (res.status == StatusCode::PayloadTooLarge_413) {
  13393. content_reader_payload_too_large = true;
  13394. }
  13395. }
  13396. return result;
  13397. });
  13398. bool dispatched = false;
  13399. if (req.method == "POST") {
  13400. dispatched = dispatch_request_for_content_reader(
  13401. req, res, std::move(reader), post_handlers_for_content_reader_);
  13402. } else if (req.method == "PUT") {
  13403. dispatched = dispatch_request_for_content_reader(
  13404. req, res, std::move(reader), put_handlers_for_content_reader_);
  13405. } else if (req.method == "PATCH") {
  13406. dispatched = dispatch_request_for_content_reader(
  13407. req, res, std::move(reader), patch_handlers_for_content_reader_);
  13408. } else if (req.method == "DELETE") {
  13409. dispatched = dispatch_request_for_content_reader(
  13410. req, res, std::move(reader), delete_handlers_for_content_reader_);
  13411. } else if (custom) {
  13412. dispatched = dispatch_request_for_content_reader(
  13413. req, res, std::move(reader), custom->handlers_for_content_reader);
  13414. }
  13415. if (dispatched) {
  13416. if (content_reader_payload_too_large) {
  13417. // Enforce the limit: override any status the handler may have set
  13418. // and return false so the error path sends a plain 413 response.
  13419. res.status = StatusCode::PayloadTooLarge_413;
  13420. detail::clear_content(res);
  13421. return false;
  13422. }
  13423. return true;
  13424. }
  13425. }
  13426. // NOTE: `req.body` is not read here. For a regular handler the body is
  13427. // read inside dispatch_request(), after the route has matched and the
  13428. // pre-request handler has approved the request, so that a rejected
  13429. // request (e.g. failed authentication) never forces us to buffer a
  13430. // potentially large body.
  13431. }
  13432. // Regular handler
  13433. if (req.method == "GET" || req.method == "HEAD") {
  13434. return dispatch_request(req, res, get_handlers_, strm);
  13435. } else if (req.method == "POST") {
  13436. return dispatch_request(req, res, post_handlers_, strm);
  13437. } else if (req.method == "PUT") {
  13438. return dispatch_request(req, res, put_handlers_, strm);
  13439. } else if (req.method == "DELETE") {
  13440. return dispatch_request(req, res, delete_handlers_, strm);
  13441. } else if (req.method == "OPTIONS") {
  13442. return dispatch_request(req, res, options_handlers_, strm);
  13443. } else if (req.method == "PATCH") {
  13444. return dispatch_request(req, res, patch_handlers_, strm);
  13445. } else if (custom) {
  13446. return dispatch_request(req, res, custom->handlers, strm);
  13447. }
  13448. res.status = StatusCode::BadRequest_400;
  13449. return false;
  13450. }
  13451. inline bool Server::dispatch_request(Request &req, Response &res,
  13452. const Handlers &handlers, Stream &strm) {
  13453. for (const auto &x : handlers) {
  13454. const auto &matcher = x.first;
  13455. const auto &handler = x.second;
  13456. if (matcher->match(req)) {
  13457. req.matched_route = matcher->pattern();
  13458. // Run the pre-request handler before reading the body so a rejected
  13459. // request (e.g. failed authentication) never forces us to buffer a
  13460. // potentially large body. `req.matched_route` is available here.
  13461. if (pre_request_handler_ &&
  13462. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  13463. return true;
  13464. }
  13465. // The route matched and the request was approved; read the body now.
  13466. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  13467. output_error_log(Error::Read, &req);
  13468. return false;
  13469. }
  13470. handler(req, res);
  13471. return true;
  13472. }
  13473. }
  13474. return false;
  13475. }
  13476. // Decides the content coding for a response served straight from a file. Both
  13477. // the ETag, which has to name the representation actually sent, and
  13478. // `apply_static_file_compression()` go through this, so the two cannot drift
  13479. // apart.
  13480. inline detail::EncodingType
  13481. Server::static_file_encoding(const Request &req, const Response &res,
  13482. const std::string &content_type,
  13483. size_t length) const {
  13484. if (!static_file_compression_) { return detail::EncodingType::None; }
  13485. // Nothing to compress, and an empty file already answers with
  13486. // `Content-Length: 0`. Checked on its own so that a zero floor still cannot
  13487. // turn an empty body into a 20-byte gzip stream.
  13488. if (length == 0) { return detail::EncodingType::None; }
  13489. // A file that already fits in a single packet gains nothing from being made
  13490. // smaller, since it still travels in that one segment, and a file of a few
  13491. // bytes comes out larger than it went in.
  13492. if (length < static_file_compression_min_length_) {
  13493. return detail::EncodingType::None;
  13494. }
  13495. // RFC 9110 applies Range to the representation after content coding, so a
  13496. // compressed 206 would mean compressing the whole file and then slicing it.
  13497. // Serve ranges from the identity representation instead.
  13498. if (!req.ranges.empty()) { return detail::EncodingType::None; }
  13499. if (static_file_compression_max_length_ > 0 &&
  13500. length > static_file_compression_max_length_) {
  13501. return detail::EncodingType::None;
  13502. }
  13503. return detail::encoding_type(req, res, content_type);
  13504. }
  13505. // Compresses a file-backed content provider into `res.body`. Returns false when
  13506. // the response is left untouched.
  13507. inline bool Server::apply_static_file_compression(const Request &req,
  13508. Response &res) const {
  13509. auto type = res.content_coding_;
  13510. if (type == detail::EncodingType::None || !res.content_provider_) {
  13511. return false;
  13512. }
  13513. auto compressor = detail::make_compressor(type);
  13514. if (!compressor) { return false; }
  13515. output_pre_compression_log(req, res);
  13516. std::string compressed;
  13517. if (!detail::compress_content_provider(res.content_provider_,
  13518. res.content_length_, *compressor,
  13519. compressed)) {
  13520. return false;
  13521. }
  13522. res.body.swap(compressed);
  13523. // The provider was consumed in full, so its releaser hears about a success.
  13524. res.content_provider_success_ = true;
  13525. detail::clear_content_provider(res);
  13526. res.set_header("Content-Encoding", detail::encoding_name(type));
  13527. res.set_header("Vary", "Accept-Encoding");
  13528. return true;
  13529. }
  13530. inline void Server::apply_ranges(const Request &req, Response &res,
  13531. std::string &content_type,
  13532. std::string &boundary) const {
  13533. // A known-length content provider leaves `res.body` empty, so the compressor
  13534. // at the end of this function never runs for one (issue #2545). A file-backed
  13535. // provider is fully readable right here, so compress it and answer with an
  13536. // ordinary body: `Content-Length` and HEAD keep working, and the response
  13537. // takes the same path as `set_content()` from here on. Range requests never
  13538. // get a content coding, so `Content-Range` still names identity bytes and
  13539. // none of the range handling below applies.
  13540. if (apply_static_file_compression(req, res)) { return; }
  13541. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  13542. auto it = res.headers.find("Content-Type");
  13543. if (it != res.headers.end()) {
  13544. content_type = it->second;
  13545. res.headers.erase(it);
  13546. }
  13547. boundary = detail::make_multipart_data_boundary();
  13548. res.set_header("Content-Type",
  13549. "multipart/byteranges; boundary=" + boundary);
  13550. }
  13551. auto type =
  13552. compress_ ? detail::encoding_type(req, res) : detail::EncodingType::None;
  13553. if (res.body.empty()) {
  13554. if (res.content_length_ > 0 && req.ranges.size() == 1 &&
  13555. res.status == StatusCode::PartialContent_206) {
  13556. auto offset_and_length = detail::get_range_offset_and_length(
  13557. req.ranges[0], res.content_length_);
  13558. auto content_range = detail::make_content_range_header_field(
  13559. offset_and_length, res.content_length_);
  13560. res.set_header("Content-Range", content_range);
  13561. } else if (res.is_chunked_content_provider_) {
  13562. res.content_coding_ = type;
  13563. if (type != detail::EncodingType::None) {
  13564. res.set_header("Content-Encoding", detail::encoding_name(type));
  13565. res.set_header("Vary", "Accept-Encoding");
  13566. }
  13567. }
  13568. } else {
  13569. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  13570. ;
  13571. } else if (req.ranges.size() == 1) {
  13572. auto offset_and_length =
  13573. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  13574. auto offset = offset_and_length.first;
  13575. auto length = offset_and_length.second;
  13576. auto content_range = detail::make_content_range_header_field(
  13577. offset_and_length, res.body.size());
  13578. res.set_header("Content-Range", content_range);
  13579. assert(offset + length <= res.body.size());
  13580. res.body = res.body.substr(offset, length);
  13581. } else {
  13582. std::string data;
  13583. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  13584. res.body.size(), data);
  13585. res.body.swap(data);
  13586. }
  13587. if (type != detail::EncodingType::None) {
  13588. output_pre_compression_log(req, res);
  13589. if (auto compressor = detail::make_compressor(type)) {
  13590. std::string compressed;
  13591. if (compressor->compress(res.body.data(), res.body.size(), true,
  13592. [&](const char *data, size_t data_len) {
  13593. compressed.append(data, data_len);
  13594. return true;
  13595. })) {
  13596. res.body.swap(compressed);
  13597. res.set_header("Content-Encoding", detail::encoding_name(type));
  13598. res.set_header("Vary", "Accept-Encoding");
  13599. }
  13600. }
  13601. }
  13602. res.content_length_ = res.body.size();
  13603. }
  13604. }
  13605. inline bool Server::dispatch_request_for_content_reader(
  13606. Request &req, Response &res, ContentReader content_reader,
  13607. const HandlersForContentReader &handlers) const {
  13608. for (const auto &x : handlers) {
  13609. const auto &matcher = x.first;
  13610. const auto &handler = x.second;
  13611. if (matcher->match(req)) {
  13612. req.matched_route = matcher->pattern();
  13613. if (!pre_request_handler_ ||
  13614. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  13615. handler(req, res, content_reader);
  13616. }
  13617. return true;
  13618. }
  13619. }
  13620. return false;
  13621. }
  13622. inline std::string
  13623. get_client_ip(const std::string &x_forwarded_for,
  13624. const std::vector<std::string> &trusted_proxies) {
  13625. // X-Forwarded-For is a comma-separated list per RFC 7239
  13626. std::vector<std::string> ip_list;
  13627. detail::split(x_forwarded_for.data(),
  13628. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  13629. [&](const char *b, const char *e) {
  13630. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  13631. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  13632. });
  13633. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  13634. // no segments. Signal "no client IP derived" with an empty string so the
  13635. // caller can fall back to the connection-level remote address.
  13636. if (ip_list.empty()) { return std::string(); }
  13637. // Each hop appends the address it received the request from, so the rightmost
  13638. // entries are the ones written by our own infrastructure while the leftmost
  13639. // are whatever the original client chose to send. Walk from the right and
  13640. // skip trusted proxies; the first address that is not a trusted proxy is the
  13641. // furthest point still attributable to a real hop, i.e. the client. Scanning
  13642. // from the left instead lets a client forge an arbitrary address by following
  13643. // it with a trusted proxy's address, which the left-to-right scan then
  13644. // returned as the client.
  13645. for (size_t i = ip_list.size(); i-- > 0;) {
  13646. const auto &ip = ip_list[i];
  13647. if (!detail::is_trusted_proxy(ip, trusted_proxies)) { return ip; }
  13648. }
  13649. // Every hop was a trusted proxy; fall back to the first entry.
  13650. return ip_list.front();
  13651. }
  13652. inline bool
  13653. Server::process_request(Stream &strm, const std::string &remote_addr,
  13654. int remote_port, const std::string &local_addr,
  13655. int local_port, bool close_connection,
  13656. bool &connection_closed,
  13657. const std::function<void(Request &)> &setup_request,
  13658. bool *websocket_upgraded) {
  13659. std::array<char, 2048> buf{};
  13660. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  13661. // The read timeout bounds the request line and headers as a whole, so a
  13662. // client sending them a byte at a time cannot hold the worker any longer.
  13663. auto read_timeout_msec = read_timeout_sec_ * 1000 + read_timeout_usec_ / 1000;
  13664. strm.set_max_timeout(read_timeout_msec);
  13665. // Connection has been closed on client
  13666. if (!line_reader.getline()) { return false; }
  13667. // RFC 9112 2.2: ignore an empty line received before the request-line. Some
  13668. // clients send an extra CRLF after a request body, which would otherwise be
  13669. // parsed as the next request on a persistent connection.
  13670. if (strcmp(line_reader.ptr(), "\r\n") == 0 && !line_reader.getline()) {
  13671. return false;
  13672. }
  13673. Request req;
  13674. req.start_time_ = std::chrono::steady_clock::now();
  13675. req.remote_addr = remote_addr;
  13676. req.remote_port = remote_port;
  13677. req.local_addr = local_addr;
  13678. req.local_port = local_port;
  13679. Response res;
  13680. res.version = "HTTP/1.1";
  13681. res.headers = default_headers_;
  13682. // RFC 9112 §9.6: a server that sends the "close" connection option must
  13683. // close the connection after that response, whichever path wrote it (an
  13684. // error status, a handler, or a rejected request). Reading on would also
  13685. // parse whatever the client sent next on a connection it considers done.
  13686. auto honor_connection_close = detail::scope_exit([&] {
  13687. if (detail::has_header_token(res.headers, "Connection", "close")) {
  13688. connection_closed = true;
  13689. }
  13690. });
  13691. // Request line and headers. A rejected message leaves the rest of it (and
  13692. // any body) unread, so the connection cannot be reused: the leftover bytes
  13693. // would be parsed as the next request.
  13694. if (!parse_request_line(line_reader.ptr(), req)) {
  13695. connection_closed = true;
  13696. res.status = StatusCode::BadRequest_400;
  13697. output_error_log(Error::InvalidRequestLine, &req);
  13698. return write_response(strm, close_connection, req, res);
  13699. }
  13700. // Request headers
  13701. if (!detail::read_headers(strm, req.headers)) {
  13702. connection_closed = true;
  13703. res.status = StatusCode::BadRequest_400;
  13704. output_error_log(Error::InvalidHeaders, &req);
  13705. return write_response(strm, close_connection, req, res);
  13706. }
  13707. strm.set_max_timeout(0);
  13708. // RFC 9112 §6.3: Reject requests whose framing is invalid or ambiguous,
  13709. // which would otherwise let an intermediary and this parser disagree on
  13710. // where the body ends and enable request smuggling. Three cases: a
  13711. // Content-Length that is not a valid decimal length (e.g. "42, 42", "+42"
  13712. // or empty), which would otherwise be read as "no body"; a non-zero
  13713. // Content-Length alongside any Transfer-Encoding (Content-Length: 0 is
  13714. // tolerated for compatibility with existing clients); and a
  13715. // Transfer-Encoding whose final coding is not chunked, which leaves the body
  13716. // length undeterminable. None of them may fall through to the "no body"
  13717. // path, or the body bytes are parsed as the next request on a persistent
  13718. // connection.
  13719. auto is_invalid_content_length = false;
  13720. detail::get_header_value_u64(req.headers, "Content-Length", 0, 0,
  13721. is_invalid_content_length);
  13722. if (is_invalid_content_length ||
  13723. detail::has_conflicting_content_length(req.headers) ||
  13724. (req.has_header("Transfer-Encoding") &&
  13725. !detail::is_chunked_transfer_encoding(req.headers))) {
  13726. connection_closed = true;
  13727. res.status = StatusCode::BadRequest_400;
  13728. return write_response(strm, close_connection, req, res);
  13729. }
  13730. // RFC 9112 6.1: a lone "chunked" is the only transfer coding implemented
  13731. if (req.has_header("Transfer-Encoding") &&
  13732. (req.get_header_value_count("Transfer-Encoding") != 1 ||
  13733. !detail::case_ignore::equal(req.get_header_value("Transfer-Encoding"),
  13734. "chunked"))) {
  13735. connection_closed = true;
  13736. res.status = StatusCode::NotImplemented_501;
  13737. return write_response(strm, close_connection, req, res);
  13738. }
  13739. // RFC 9112 §6.1: a Transfer-Encoding alongside a Content-Length, or in an
  13740. // HTTP/1.0 request, is honoured, but the connection closes after the
  13741. // response.
  13742. if (detail::has_faulty_transfer_encoding(req)) { connection_closed = true; }
  13743. // RFC 9112 §3.2: Reject more than one Host field line, an invalid Host
  13744. // value, or none in HTTP/1.1, so that every recipient of the request sees
  13745. // the same authority.
  13746. auto host_count = req.get_header_value_count("Host");
  13747. if (host_count > 1 || (host_count == 0 && req.version == "HTTP/1.1") ||
  13748. !detail::fields::is_host(req.get_header_value("Host"))) {
  13749. connection_closed = true;
  13750. res.status = StatusCode::BadRequest_400;
  13751. output_error_log(Error::InvalidHeaders, &req);
  13752. return write_response(strm, close_connection, req, res);
  13753. }
  13754. // Check if the request URI doesn't exceed the limit
  13755. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  13756. connection_closed = true;
  13757. res.status = StatusCode::UriTooLong_414;
  13758. output_error_log(Error::ExceedUriMaxLength, &req);
  13759. return write_response(strm, close_connection, req, res);
  13760. }
  13761. if (detail::has_header_token(req.headers, "Connection", "close")) {
  13762. connection_closed = true;
  13763. }
  13764. if (req.version == "HTTP/1.0" &&
  13765. !detail::has_header_token(req.headers, "Connection", "keep-alive")) {
  13766. connection_closed = true;
  13767. }
  13768. // Only honor X-Forwarded-For if the peer on the actual TCP connection is
  13769. // itself a trusted proxy. Otherwise any direct client could spoof
  13770. // remote_addr simply by sending an arbitrary X-Forwarded-For header.
  13771. if (detail::is_trusted_proxy(remote_addr, trusted_proxies_) &&
  13772. req.has_header("X-Forwarded-For")) {
  13773. // Some proxies append the address they observed as a separate
  13774. // X-Forwarded-For field line instead of extending the one the client sent
  13775. // (e.g. HAProxy's "option forwardfor"), so the whole combined value has to
  13776. // be scanned. Reading only the first occurrence would hand back the
  13777. // client-supplied, and therefore forgeable, value.
  13778. auto x_forwarded_for =
  13779. detail::get_combined_header_value(req.headers, "X-Forwarded-For");
  13780. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  13781. req.remote_addr = derived.empty() ? remote_addr : derived;
  13782. } else {
  13783. req.remote_addr = remote_addr;
  13784. }
  13785. req.remote_port = remote_port;
  13786. req.local_addr = local_addr;
  13787. req.local_port = local_port;
  13788. if (req.has_header("Accept")) {
  13789. auto accept_header =
  13790. detail::get_combined_header_value(req.headers, "Accept");
  13791. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  13792. connection_closed = true;
  13793. res.status = StatusCode::BadRequest_400;
  13794. output_error_log(Error::HTTPParsing, &req);
  13795. return write_response(strm, close_connection, req, res);
  13796. }
  13797. }
  13798. // RFC 9110 14.2: range handling is defined only for GET (and so for HEAD)
  13799. if ((req.method == "GET" || req.method == "HEAD") &&
  13800. req.has_header("Range")) {
  13801. const auto &range_header_value = req.get_header_value("Range");
  13802. // RFC 9110 14.2: a range unit other than bytes must be ignored
  13803. auto unit = range_header_value.substr(0, range_header_value.find('='));
  13804. if (detail::case_ignore::equal(unit, "bytes") &&
  13805. !detail::parse_range_header(range_header_value, req.ranges)) {
  13806. connection_closed = true;
  13807. res.status = StatusCode::RangeNotSatisfiable_416;
  13808. output_error_log(Error::InvalidRangeHeader, &req);
  13809. return write_response(strm, close_connection, req, res);
  13810. }
  13811. }
  13812. if (setup_request) { setup_request(req); }
  13813. // RFC 9110 10.1.1: Expect is a comma-separated list whose value is
  13814. // case-insensitive, and a 100-continue expectation in an HTTP/1.0 request
  13815. // must be ignored. An expectation we do not recognize is left alone; the
  13816. // 417 the section allows for one is a MAY, not a requirement.
  13817. //
  13818. // `100 Continue` itself is deferred until the body is actually read (see
  13819. // read_content_core), so a request rejected by a later handler never
  13820. // invites the client to send a body nobody will read.
  13821. if (req.version != "HTTP/1.0" &&
  13822. detail::has_header_token(req.headers, "Expect", "100-continue")) {
  13823. int status = StatusCode::Continue_100;
  13824. if (expect_100_continue_handler_) {
  13825. status = expect_100_continue_handler_(req, res);
  13826. }
  13827. if (status == StatusCode::Continue_100) {
  13828. req.expect_100_continue_pending_ = true;
  13829. } else {
  13830. if (res.status == -1) { res.status = status; }
  13831. connection_closed = true;
  13832. return write_response(strm, true, req, res);
  13833. }
  13834. }
  13835. // Setup `is_connection_closed` method
  13836. auto sock = strm.socket();
  13837. req.is_connection_closed = [sock]() {
  13838. return !detail::is_socket_alive(sock);
  13839. };
  13840. // WebSocket upgrade
  13841. // Run pre_routing_handler_ and pre_request_handler_ before upgrading so
  13842. // that authentication and other middleware can reject the request with an
  13843. // HTTP response (e.g., 401) before the protocol switches.
  13844. // The response says so when this connection closes after it.
  13845. auto close_after_response = close_connection || connection_closed;
  13846. // An upgrade request has been through pre-routing before it reaches routing()
  13847. auto is_upgrade = detail::is_websocket_upgrade(req);
  13848. if (is_upgrade) {
  13849. // A response given here leaves the body unread, and it would be parsed as
  13850. // the next request.
  13851. auto close_if_answered =
  13852. close_after_response || detail::has_framed_body(req);
  13853. const WebSocketHandlerEntry *ws_route = nullptr;
  13854. std::string selected_subprotocol;
  13855. auto answer_before_upgrade = [&]() -> bool {
  13856. if (pre_routing_handler_ &&
  13857. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  13858. return true;
  13859. }
  13860. for (const auto &entry : websocket_handlers_) {
  13861. if (!entry.matcher->match(req)) { continue; }
  13862. req.matched_route = entry.matcher->pattern();
  13863. if (pre_request_handler_ &&
  13864. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  13865. return true;
  13866. }
  13867. ws_route = &entry;
  13868. if (entry.sub_protocol_selector) {
  13869. auto protocol_header = detail::get_combined_header_value(
  13870. req.headers, "Sec-WebSocket-Protocol");
  13871. if (!protocol_header.empty()) {
  13872. std::vector<std::string> protocols;
  13873. detail::split(protocol_header.data(),
  13874. protocol_header.data() + protocol_header.size(), ',',
  13875. [&](const char *b, const char *e) {
  13876. protocols.emplace_back(b, e);
  13877. });
  13878. selected_subprotocol = entry.sub_protocol_selector(protocols);
  13879. // Ignore a selection the client did not offer (RFC 6455 4.2.2)
  13880. if (std::find(protocols.begin(), protocols.end(),
  13881. selected_subprotocol) == protocols.end()) {
  13882. selected_subprotocol.clear();
  13883. }
  13884. }
  13885. }
  13886. return false;
  13887. }
  13888. return false;
  13889. };
  13890. auto answered = false;
  13891. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13892. answered = answer_before_upgrade();
  13893. #else
  13894. try {
  13895. answered = answer_before_upgrade();
  13896. } catch (...) {
  13897. if (!handle_exception(req, res)) {
  13898. return write_response(strm, close_if_answered, req, res);
  13899. }
  13900. answered = true;
  13901. }
  13902. #endif
  13903. if (answered) {
  13904. if (res.status == -1) { res.status = StatusCode::OK_200; }
  13905. return write_response_with_content(strm, close_if_answered, req, res);
  13906. }
  13907. if (ws_route) {
  13908. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  13909. auto accept_key = detail::websocket_accept_key(client_key);
  13910. // Send 101 Switching Protocols
  13911. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  13912. "Upgrade: websocket\r\n"
  13913. "Connection: Upgrade\r\n"
  13914. "Sec-WebSocket-Accept: " +
  13915. accept_key + "\r\n";
  13916. if (!selected_subprotocol.empty()) {
  13917. if (!detail::fields::is_field_value(selected_subprotocol)) {
  13918. return false;
  13919. }
  13920. handshake_response +=
  13921. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  13922. }
  13923. handshake_response += "\r\n";
  13924. if (strm.write(handshake_response.data(), handshake_response.size()) <
  13925. 0) {
  13926. return false;
  13927. }
  13928. connection_closed = true;
  13929. if (websocket_upgraded) { *websocket_upgraded = true; }
  13930. auto stopping = [this] { return is_stopping(); };
  13931. if (CPPHTTPLIB_WEBSOCKET_TCP_NODELAY) {
  13932. set_socket_opt(strm.socket(), IPPROTO_TCP, TCP_NODELAY, 1);
  13933. }
  13934. #ifdef CPPHTTPLIB_SSL_ENABLED
  13935. if (req.ssl) {
  13936. // wss: the heartbeat ping thread and the read path enter the same
  13937. // TLS session from different threads. Hand the WebSocket a stream
  13938. // that serializes every TLS call, so the shared SSLSocketStream on
  13939. // the plain HTTP/HTTPS paths stays untouched.
  13940. auto ws_strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  13941. strm.socket(), const_cast<tls::session_t>(req.ssl),
  13942. CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
  13943. write_timeout_sec_, write_timeout_usec_));
  13944. ws::WebSocket ws(std::move(ws_strm), req, true,
  13945. websocket_ping_interval_sec_,
  13946. websocket_max_missed_pongs_, stopping);
  13947. ws_route->handler(req, ws);
  13948. return true;
  13949. }
  13950. #endif
  13951. // Use WebSocket-specific read timeout instead of HTTP timeout
  13952. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
  13953. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  13954. websocket_max_missed_pongs_, stopping);
  13955. ws_route->handler(req, ws);
  13956. return true;
  13957. }
  13958. // No WebSocket route: route it as a plain HTTP request
  13959. }
  13960. // Routing
  13961. auto routed = false;
  13962. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13963. routed = routing(req, res, strm, is_upgrade);
  13964. #else
  13965. try {
  13966. routed = routing(req, res, strm, is_upgrade);
  13967. } catch (...) { routed = handle_exception(req, res); }
  13968. #endif
  13969. auto ret = false;
  13970. if (routed) {
  13971. if (res.status == -1) {
  13972. res.status = req.ranges.empty() ? StatusCode::OK_200
  13973. : StatusCode::PartialContent_206;
  13974. }
  13975. // Before the Range checks below, so they see the body's own length.
  13976. detail::prefer_assigned_body(res);
  13977. // Serve file content by using a content provider
  13978. auto file_open_error = false;
  13979. if (!res.file_content_path_.empty()) {
  13980. const auto &path = res.file_content_path_;
  13981. auto mm = std::make_shared<detail::mmap>(path.c_str());
  13982. if (!mm->is_open()) {
  13983. res.status = StatusCode::NotFound_404;
  13984. output_error_log(Error::OpenFile, &req);
  13985. file_open_error = true;
  13986. } else {
  13987. auto content_type = res.file_content_content_type_;
  13988. if (content_type.empty()) {
  13989. // One the handler set after set_file_content()
  13990. content_type = res.get_header_value("Content-Type");
  13991. }
  13992. if (content_type.empty()) {
  13993. content_type = detail::find_content_type(
  13994. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  13995. }
  13996. detail::set_file_content_provider(
  13997. res, mm, content_type,
  13998. static_file_encoding(req, res, content_type, mm->size()));
  13999. }
  14000. }
  14001. if (file_open_error) {
  14002. ret = write_response(strm, close_after_response, req, res);
  14003. } else if (detail::range_error(req, res)) {
  14004. detail::clear_content(res);
  14005. res.status = StatusCode::RangeNotSatisfiable_416;
  14006. ret = write_response(strm, close_after_response, req, res);
  14007. } else {
  14008. ret = write_response_with_content(strm, close_after_response, req, res);
  14009. }
  14010. } else {
  14011. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  14012. ret = write_response(strm, close_after_response, req, res);
  14013. }
  14014. // Drain any unconsumed framed body to prevent request smuggling on
  14015. // keep-alive. Without framing there is no body to drain — reading would
  14016. // consume the next request (issue #2450). If the response has committed the
  14017. // connection to close, there is no next request to protect. A body read in
  14018. // part cannot be drained from where it stopped, so the connection closes,
  14019. // as it does when the body is longer than the drain limit or does not
  14020. // arrive within the read timeout.
  14021. if (!req.body_consumed_ && detail::has_framed_body(req) &&
  14022. !detail::has_header_token(res.headers, "Connection", "close")) {
  14023. strm.set_max_timeout(read_timeout_msec);
  14024. int dummy_status;
  14025. if (req.body_read_started_ ||
  14026. !detail::read_content(
  14027. strm, req, CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH, dummy_status,
  14028. nullptr, [](const char *, size_t, size_t, size_t) { return true; },
  14029. false)) {
  14030. connection_closed = true;
  14031. }
  14032. }
  14033. return ret;
  14034. }
  14035. inline bool Server::is_valid() const { return !has_invalid_registration_; }
  14036. inline bool Server::process_and_close_socket(socket_t sock) {
  14037. std::string remote_addr;
  14038. int remote_port = 0;
  14039. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  14040. std::string local_addr;
  14041. int local_port = 0;
  14042. detail::get_local_ip_and_port(sock, local_addr, local_port);
  14043. bool websocket_upgraded = false;
  14044. auto ret = serve_guarded([&]() {
  14045. return detail::process_server_socket(
  14046. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  14047. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14048. write_timeout_usec_,
  14049. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  14050. return process_request(strm, remote_addr, remote_port, local_addr,
  14051. local_port, close_connection,
  14052. connection_closed, nullptr,
  14053. &websocket_upgraded);
  14054. });
  14055. });
  14056. detail::drain_and_close_socket(sock);
  14057. return ret;
  14058. }
  14059. // After accept() failed for good. Takes the descriptor out of svr_sock_
  14060. // before closing it: a later stop() would otherwise shutdown()/close() a value
  14061. // the OS may have reused, and keep_alive() watches svr_sock_ to notice the
  14062. // server is gone. The exchange also settles the race with a concurrent stop(),
  14063. // since whichever side takes the descriptor closes it exactly once. Returns
  14064. // false when stop() took it first.
  14065. inline bool Server::abandon_listen_socket() {
  14066. auto sock = svr_sock_.exchange(INVALID_SOCKET);
  14067. if (sock == INVALID_SOCKET) { return false; }
  14068. detail::close_socket(sock);
  14069. output_error_log(Error::Connection, nullptr);
  14070. return true;
  14071. }
  14072. // Like accept_loop(), but a connection waiting for its next request sits in
  14073. // the poller instead of keeping a worker. A worker serves a connection while it
  14074. // has requests to read, then gives it back to this loop.
  14075. inline bool Server::parking_loop(TaskQueue &task_queue) {
  14076. using Clock = ParkingState::Clock;
  14077. using Connection = ParkingState::Connection;
  14078. const ParkingState::Token listen_token = 0;
  14079. const auto never = (Clock::time_point::max)();
  14080. auto &st = *parking_;
  14081. auto &poller = *st.poller;
  14082. std::vector<ParkingState::Token> ready;
  14083. poller.wait(0, ready); // drops a wake() left from an earlier stop()
  14084. {
  14085. std::lock_guard<std::mutex> guard(st.mutex);
  14086. st.closed = false;
  14087. }
  14088. // Publish the listening socket before checking that stop() has not taken it,
  14089. // so that a stop() from now on leaves closing it to this loop.
  14090. auto listen_sock = svr_sock_.load();
  14091. st.listen_sock = listen_sock;
  14092. auto listening = listen_sock != INVALID_SOCKET && svr_sock_ == listen_sock;
  14093. if (listening) { detail::set_nonblocking(listen_sock, true); }
  14094. auto listen_rearm_at = Clock::now(); // `never` while it is armed
  14095. auto fatal = false;
  14096. const auto check_interval =
  14097. std::chrono::duration_cast<Clock::duration>(std::chrono::microseconds(
  14098. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND));
  14099. // Never shorter than the interval keep_alive() first waits, so that a
  14100. // request sent right after connecting is served even with a timeout of 0.
  14101. const auto keep_alive =
  14102. (std::max)(Clock::duration(std::chrono::seconds(keep_alive_timeout_sec_)),
  14103. check_interval);
  14104. // Only an interval the user asked for: Windows' default exists for the sake
  14105. // of stop(), which wake() already serves here.
  14106. const auto idle = std::chrono::microseconds(
  14107. idle_interval_set_ ? idle_interval_sec_ * 1000000 + idle_interval_usec_
  14108. : 0);
  14109. auto next_idle = idle.count() > 0 ? Clock::now() + idle : never;
  14110. auto park = [&](Connection conn, Clock::time_point now) {
  14111. if (!st.park(std::move(conn), now + keep_alive)) {
  14112. output_error_log(Error::ResourceExhaustion, nullptr);
  14113. }
  14114. };
  14115. auto dispatch = [&](const Connection &conn) {
  14116. return task_queue.enqueue([this, conn]() { resume_connection(conn); });
  14117. };
  14118. // The only way into the queue besides the backlog, which nothing overtakes.
  14119. // When the queue is full, a new connection is turned away, as accept_loop()
  14120. // does, and an established one waits in the backlog, since closing it would
  14121. // lose its request. A TaskQueue gives no sign when it has room again, so the
  14122. // backlog is retried every check_interval.
  14123. auto submit = [&](Connection conn) {
  14124. if (st.backlog.empty() && dispatch(conn)) { return; }
  14125. if (conn->opened) {
  14126. st.backlog.push_back(std::move(conn));
  14127. return;
  14128. }
  14129. conn->close_idle();
  14130. output_error_log(Error::ResourceExhaustion, nullptr);
  14131. };
  14132. std::vector<Connection> returned;
  14133. while (listening && svr_sock_ == listen_sock) {
  14134. auto now = Clock::now();
  14135. if (now >= listen_rearm_at) {
  14136. listen_rearm_at =
  14137. poller.arm(listen_sock, listen_token) ? never : now + check_interval;
  14138. }
  14139. // At most a minute, which keeps the timeout below within an int.
  14140. auto until = (std::min)({st.next_deadline(), listen_rearm_at, next_idle,
  14141. st.backlog.empty() ? never : now + check_interval,
  14142. now + std::chrono::seconds(60)});
  14143. // Rounded up, so that the wait does not end just short of the deadline.
  14144. auto timeout = std::chrono::duration_cast<std::chrono::milliseconds>(
  14145. until - now + std::chrono::microseconds(999));
  14146. poller.wait(static_cast<int>((std::max)(timeout.count(),
  14147. std::chrono::milliseconds::rep(0))),
  14148. ready);
  14149. if (svr_sock_ != listen_sock) { break; }
  14150. now = Clock::now();
  14151. {
  14152. std::lock_guard<std::mutex> guard(st.mutex);
  14153. returned.swap(st.returned);
  14154. }
  14155. for (auto &conn : returned) {
  14156. park(std::move(conn), now);
  14157. }
  14158. returned.clear();
  14159. // Connections that found the queue full go first, in their order.
  14160. while (!st.backlog.empty() && dispatch(st.backlog.front())) {
  14161. st.backlog.pop_front();
  14162. }
  14163. for (auto token : ready) {
  14164. if (token == listen_token) {
  14165. listen_rearm_at = now;
  14166. // A batch per round, so that a burst of new connections does not
  14167. // hold up the ones that are ready.
  14168. for (auto i = 0; i < 64; i++) {
  14169. auto sock = detail::accept_socket(listen_sock);
  14170. if (sock == INVALID_SOCKET) {
  14171. if (detail::is_would_block_error()) { break; }
  14172. if (detail::is_accept_resource_error()) {
  14173. // Out of descriptors: let the deadlines free some first.
  14174. listen_rearm_at = now + check_interval;
  14175. break;
  14176. }
  14177. if (detail::is_accept_transient_error()) { continue; }
  14178. fatal = true;
  14179. break;
  14180. }
  14181. // Some platforms make it non-blocking like the listening socket.
  14182. detail::set_nonblocking(sock, false);
  14183. prepare_accepted_socket(sock);
  14184. park(new_keep_alive_connection(sock), now);
  14185. if (idle.count() > 0) { next_idle = now + idle; }
  14186. }
  14187. continue;
  14188. }
  14189. submit(st.unpark(token));
  14190. }
  14191. if (fatal) { break; }
  14192. st.expire(now);
  14193. if (now >= next_idle) {
  14194. task_queue.on_idle();
  14195. next_idle = now + idle;
  14196. }
  14197. }
  14198. // A worker still serving a request closes its connection itself.
  14199. st.close_all();
  14200. poller.disarm(listen_sock);
  14201. // See ParkingState::listen_sock.
  14202. if (st.listen_sock.exchange(INVALID_SOCKET) == INVALID_SOCKET) {
  14203. // stop() handed it over.
  14204. detail::shutdown_socket(listen_sock);
  14205. detail::close_socket(listen_sock);
  14206. return true;
  14207. }
  14208. return !(fatal && abandon_listen_socket());
  14209. }
  14210. inline std::shared_ptr<Server::KeepAliveConnection>
  14211. Server::new_keep_alive_connection(socket_t sock) {
  14212. return std::make_shared<PlainConnection>(sock, *this);
  14213. }
  14214. inline void
  14215. Server::resume_connection(std::shared_ptr<KeepAliveConnection> conn) {
  14216. auto &st = *parking_;
  14217. auto &c = *conn;
  14218. auto ret = c.resume();
  14219. if (c.turn.park) {
  14220. c.release_buffers(); // it may stay idle for long
  14221. if (st.give_back(conn)) { return; }
  14222. }
  14223. c.close_served(!c.turn.websocket_upgraded && ret);
  14224. }
  14225. inline void Server::output_log(const Request &req, const Response &res) const {
  14226. if (logger_) {
  14227. std::lock_guard<std::mutex> guard(logger_mutex_);
  14228. logger_(req, res);
  14229. }
  14230. }
  14231. inline void Server::output_pre_compression_log(const Request &req,
  14232. const Response &res) const {
  14233. if (pre_compression_logger_) {
  14234. std::lock_guard<std::mutex> guard(logger_mutex_);
  14235. pre_compression_logger_(req, res);
  14236. }
  14237. }
  14238. inline void Server::output_error_log(const Error &err,
  14239. const Request *req) const {
  14240. if (error_logger_) {
  14241. std::lock_guard<std::mutex> guard(logger_mutex_);
  14242. error_logger_(err, req);
  14243. }
  14244. }
  14245. /*
  14246. * Group 5: ClientImpl and Client (Universal) implementation
  14247. */
  14248. // HTTP client implementation
  14249. inline ClientImpl::ClientImpl(const std::string &host)
  14250. : ClientImpl(host, 80, std::string(), std::string()) {}
  14251. inline ClientImpl::ClientImpl(const std::string &host, int port)
  14252. : ClientImpl(host, port, std::string(), std::string()) {}
  14253. inline ClientImpl::ClientImpl(const std::string &host, int port,
  14254. const std::string &client_cert_path,
  14255. const std::string &client_key_path)
  14256. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  14257. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  14258. inline ClientImpl::~ClientImpl() {
  14259. // Wait until all the requests in flight are handled.
  14260. size_t retry_count = 10;
  14261. while (retry_count-- > 0) {
  14262. {
  14263. std::lock_guard<std::mutex> guard(socket_mutex_);
  14264. if (socket_requests_in_flight_ == 0) { break; }
  14265. }
  14266. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  14267. }
  14268. std::lock_guard<std::mutex> guard(socket_mutex_);
  14269. shutdown_socket(socket_);
  14270. close_socket(socket_);
  14271. }
  14272. inline bool ClientImpl::is_valid() const { return true; }
  14273. inline bool
  14274. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  14275. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  14276. if (no_proxy_entries_.empty()) { return true; }
  14277. // host_ is const so its normalized form is invariant; cache it. The
  14278. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  14279. if (host == host_) {
  14280. if (!host_normalized_valid_) {
  14281. host_normalized_ = detail::normalize_target(host_);
  14282. host_normalized_valid_ = true;
  14283. }
  14284. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  14285. }
  14286. auto target = detail::normalize_target(host);
  14287. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  14288. }
  14289. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  14290. if (is_proxy_enabled_for_host(host_)) {
  14291. return detail::create_client_socket(
  14292. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  14293. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  14294. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  14295. write_timeout_sec_, write_timeout_usec_, interface_, error,
  14296. stop_interrupt());
  14297. }
  14298. // Check is custom IP or hostname specified for host_
  14299. std::string connect_host;
  14300. std::string ip;
  14301. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  14302. return detail::create_client_socket(
  14303. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  14304. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  14305. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14306. write_timeout_usec_, interface_, error, stop_interrupt());
  14307. }
  14308. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  14309. Error &error) {
  14310. auto sock = create_client_socket(error);
  14311. if (sock == INVALID_SOCKET) { return false; }
  14312. socket.sock = sock;
  14313. return true;
  14314. }
  14315. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  14316. socket_tls_settings_version_ = tls_settings_version_;
  14317. return create_and_connect_socket(socket, error);
  14318. }
  14319. inline bool ClientImpl::setup_proxy_connection(
  14320. Socket & /*socket*/,
  14321. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  14322. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  14323. return true;
  14324. }
  14325. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  14326. bool /*shutdown_gracefully*/) {
  14327. // If there are any requests in flight from threads other than us, then it's
  14328. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  14329. assert(socket_requests_in_flight_ == 0 ||
  14330. socket_requests_are_from_thread_ == std::this_thread::get_id());
  14331. }
  14332. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  14333. if (socket.sock == INVALID_SOCKET) { return; }
  14334. detail::shutdown_socket(socket.sock);
  14335. }
  14336. inline void ClientImpl::close_socket(Socket &socket) {
  14337. // If there are requests in flight in another thread, usually closing
  14338. // the socket will be fine and they will simply receive an error when
  14339. // using the closed socket, but it is still a bug since rarely the OS
  14340. // may reassign the socket id to be used for a new socket, and then
  14341. // suddenly they will be operating on a live socket that is different
  14342. // than the one they intended!
  14343. assert(socket_requests_in_flight_ == 0 ||
  14344. socket_requests_are_from_thread_ == std::this_thread::get_id());
  14345. // It is also a bug if this happens while SSL is still active
  14346. #ifdef CPPHTTPLIB_SSL_ENABLED
  14347. assert(socket.ssl == nullptr);
  14348. #endif
  14349. if (socket.sock == INVALID_SOCKET) { return; }
  14350. detail::close_socket(socket.sock);
  14351. socket.sock = INVALID_SOCKET;
  14352. }
  14353. inline void ClientImpl::disconnect(bool gracefully) {
  14354. shutdown_ssl(socket_, gracefully);
  14355. shutdown_socket(socket_);
  14356. close_socket(socket_);
  14357. }
  14358. inline bool ClientImpl::socket_reusable() {
  14359. if (!socket_.is_open()) { return false; }
  14360. // RFC 9112 9.2: data with no request outstanding is not a response
  14361. if (detail::select_read(socket_.sock, 0, 0) != 0) {
  14362. disconnect(/*gracefully=*/false);
  14363. return false;
  14364. }
  14365. if (is_ssl() && socket_tls_settings_version_ != tls_settings_version_) {
  14366. disconnect(/*gracefully=*/true);
  14367. return false;
  14368. }
  14369. return true;
  14370. }
  14371. inline bool ClientImpl::prepare_socket(
  14372. std::unique_lock<std::mutex> &guard,
  14373. std::chrono::time_point<std::chrono::steady_clock> start_time,
  14374. Response &res, bool &success, Error &error) {
  14375. auto opened = true;
  14376. if (!socket_reusable()) {
  14377. Socket socket;
  14378. guard.unlock();
  14379. opened = ensure_socket_connection(socket, error);
  14380. if (opened) {
  14381. opened = setup_proxy_connection(socket, start_time, res, success, error);
  14382. } else {
  14383. success = false;
  14384. }
  14385. guard.lock();
  14386. socket_ = socket;
  14387. }
  14388. if (stop_requested_) {
  14389. disconnect(/*gracefully=*/false);
  14390. error = Error::Canceled;
  14391. success = false;
  14392. return false;
  14393. }
  14394. return opened;
  14395. }
  14396. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  14397. Response &res,
  14398. bool skip_100_continue) const {
  14399. std::array<char, 2048> buf{};
  14400. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  14401. if (!line_reader.getline()) { return false; }
  14402. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  14403. res.reason)) {
  14404. return req.method == "CONNECT";
  14405. }
  14406. // Skip interim (1xx) responses along with their header fields, except a 100
  14407. // Continue the caller handles itself for Expect: 100-continue. 101 ends
  14408. // HTTP on the connection, so it is final. A server sending them without end
  14409. // would hold the client, so there may be only so many.
  14410. size_t interim_count = 0;
  14411. while (100 <= res.status && res.status < 200 &&
  14412. res.status != StatusCode::SwitchingProtocol_101 &&
  14413. (skip_100_continue || res.status != StatusCode::Continue_100)) {
  14414. if (++interim_count > CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT) {
  14415. return false;
  14416. }
  14417. Headers interim_headers;
  14418. if (!detail::read_headers(strm, interim_headers)) { return false; }
  14419. if (!line_reader.getline()) { return false; } // next response line
  14420. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  14421. res.reason)) {
  14422. return false;
  14423. }
  14424. }
  14425. return true;
  14426. }
  14427. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  14428. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  14429. // A same-origin redirect and a digest retry send through here again. Only
  14430. // the call the caller made reports a failure, once, with its request.
  14431. auto outermost = send_depth_++ == 0;
  14432. auto se = detail::scope_exit([&] { send_depth_--; });
  14433. if (outermost) {
  14434. error = Error::Success;
  14435. stop_requested_ = false;
  14436. }
  14437. auto ret = send_(req, res, error);
  14438. if (error == Error::SSLPeerCouldBeClosed_) {
  14439. assert(!ret);
  14440. ret = send_(req, res, error);
  14441. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  14442. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  14443. }
  14444. // Also an answer that carries an error, such as a proxy's 407
  14445. if (outermost && error != Error::Success) { output_error_log(error, &req); }
  14446. return ret;
  14447. }
  14448. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  14449. #ifdef CPPHTTPLIB_SSL_ENABLED
  14450. // Don't let an earlier attempt's TLS error show up in this one's Result. A
  14451. // client that failed to set up its TLS context keeps reporting why.
  14452. if (is_valid()) {
  14453. last_ssl_error_ = 0;
  14454. last_backend_error_ = 0;
  14455. }
  14456. #endif
  14457. {
  14458. std::unique_lock<std::mutex> guard(socket_mutex_);
  14459. // Set this to false immediately - if it ever gets set to true by the end
  14460. // of the request, we know another thread instructed us to close the
  14461. // socket.
  14462. socket_should_be_closed_when_request_is_done_ = false;
  14463. auto success = true;
  14464. if (!prepare_socket(guard, req.start_time_, res, success, error)) {
  14465. return success;
  14466. }
  14467. // Mark the current socket as being in use so that it cannot be closed by
  14468. // anyone else while this request is ongoing, even though we will be
  14469. // releasing the mutex.
  14470. if (socket_requests_in_flight_ > 1) {
  14471. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  14472. }
  14473. socket_requests_in_flight_ += 1;
  14474. socket_requests_are_from_thread_ = std::this_thread::get_id();
  14475. }
  14476. for (const auto &header : default_headers_) {
  14477. if (req.headers.find(header.first) == req.headers.end()) {
  14478. req.headers.insert(header);
  14479. }
  14480. }
  14481. auto ret = false;
  14482. auto close_connection = !keep_alive_;
  14483. auto se = detail::scope_exit([&]() {
  14484. // Briefly lock mutex in order to mark that a request is no longer ongoing
  14485. std::lock_guard<std::mutex> guard(socket_mutex_);
  14486. socket_requests_in_flight_ -= 1;
  14487. if (socket_requests_in_flight_ <= 0) {
  14488. assert(socket_requests_in_flight_ == 0);
  14489. socket_requests_are_from_thread_ = std::thread::id();
  14490. }
  14491. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  14492. !ret) {
  14493. disconnect(/*gracefully=*/true);
  14494. }
  14495. });
  14496. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  14497. strm.set_read_interrupt(stop_interrupt());
  14498. return handle_request(strm, req, res, close_connection, error);
  14499. });
  14500. if (!ret) {
  14501. if (error == Error::Success) { error = Error::Unknown; }
  14502. }
  14503. return ret;
  14504. }
  14505. inline Result ClientImpl::send(const Request &req) {
  14506. auto req2 = req;
  14507. return send_(std::move(req2));
  14508. }
  14509. inline Result ClientImpl::send_(Request &&req) {
  14510. auto res = detail::make_unique<Response>();
  14511. auto error = Error::Success;
  14512. #ifdef CPPHTTPLIB_SSL_ENABLED
  14513. // Hold the request lock until the Result has read this request's TLS error
  14514. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  14515. #endif
  14516. auto ret = send(req, *res, error);
  14517. #ifdef CPPHTTPLIB_SSL_ENABLED
  14518. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  14519. last_ssl_error_, last_backend_error_};
  14520. #else
  14521. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  14522. #endif
  14523. }
  14524. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  14525. const std::string &ct) {
  14526. (void)for_stream;
  14527. // Default headers are meant for the origin and may carry its credentials, so
  14528. // keep them off the CONNECT request the proxy reads.
  14529. if (r.method != "CONNECT") {
  14530. for (const auto &header : default_headers_) {
  14531. if (!r.has_header(header.first)) { r.headers.insert(header); }
  14532. }
  14533. }
  14534. // RFC 9110 5.3 recommends sending control data such as Host first, so
  14535. // prepend it rather than appending it after the caller's own fields.
  14536. if (!r.has_header("Host")) {
  14537. r.headers.emplace_front(
  14538. "Host", detail::make_default_host_header_value(host_, port_, is_ssl(),
  14539. address_family_));
  14540. }
  14541. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  14542. if (!r.content_receiver) {
  14543. if (!r.has_header("Accept-Encoding")) {
  14544. std::string accept_encoding;
  14545. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14546. accept_encoding = "br";
  14547. #endif
  14548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14549. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  14550. accept_encoding += "gzip, deflate";
  14551. #endif
  14552. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14553. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  14554. accept_encoding += "zstd";
  14555. #endif
  14556. r.set_header("Accept-Encoding", accept_encoding);
  14557. }
  14558. detail::add_default_user_agent_header(r);
  14559. }
  14560. if (!r.body.empty()) {
  14561. if (!ct.empty() && !r.has_header("Content-Type")) {
  14562. r.headers.emplace("Content-Type", ct);
  14563. }
  14564. if (!r.has_header("Content-Length")) {
  14565. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  14566. }
  14567. }
  14568. }
  14569. inline ClientImpl::StreamHandle
  14570. ClientImpl::open_stream(const std::string &method, const std::string &path,
  14571. const Params &params, const Headers &headers,
  14572. const std::string &body,
  14573. const std::string &content_type) {
  14574. // Encode the target exactly like the buffered send path does, so that the
  14575. // same `path` produces the same request line through either API.
  14576. auto raw_query_path =
  14577. params.empty() ? path : append_query_params(path, params);
  14578. Request req;
  14579. req.method = method;
  14580. req.path = detail::encode_request_target(raw_query_path, path_encode_);
  14581. req.headers = headers;
  14582. req.body = body;
  14583. prepare_default_headers(req, true, content_type);
  14584. auto handle = open_stream_(req);
  14585. // Like a buffered request, a stream that fails to open is reported once
  14586. if (handle.error != Error::Success) { output_error_log(handle.error, &req); }
  14587. return handle;
  14588. }
  14589. inline ClientImpl::StreamHandle ClientImpl::open_stream_(Request &req) {
  14590. StreamHandle handle;
  14591. handle.response = detail::make_unique<Response>();
  14592. handle.error = Error::Success;
  14593. handle.connection_ = detail::make_unique<ClientConnection>();
  14594. {
  14595. // A request in flight uses socket_ without holding socket_mutex_
  14596. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  14597. if (send_depth_ == 0) { stop_requested_ = false; }
  14598. std::unique_lock<std::mutex> guard(socket_mutex_);
  14599. auto success = true;
  14600. if (!prepare_socket(guard, std::chrono::steady_clock::now(),
  14601. *handle.response, success, handle.error)) {
  14602. if (!success) { handle.response.reset(); }
  14603. return handle;
  14604. }
  14605. transfer_socket_ownership_to_handle(handle);
  14606. }
  14607. #ifdef CPPHTTPLIB_SSL_ENABLED
  14608. if (is_ssl() && handle.connection_->session) {
  14609. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  14610. handle.connection_->sock, handle.connection_->session,
  14611. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14612. write_timeout_usec_);
  14613. } else {
  14614. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  14615. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  14616. write_timeout_sec_, write_timeout_usec_);
  14617. }
  14618. #else
  14619. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  14620. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  14621. write_timeout_sec_, write_timeout_usec_);
  14622. #endif
  14623. handle.stream_ = handle.socket_stream_.get();
  14624. auto &strm = *handle.stream_;
  14625. // Only for the head, as the handle may outlive this client
  14626. strm.set_read_interrupt(stop_interrupt());
  14627. auto release_interrupt =
  14628. detail::scope_exit([&] { strm.set_read_interrupt(nullptr); });
  14629. // After connecting, as for a buffered request
  14630. add_credential_headers(req);
  14631. // Build the request line and headers in memory first, like write_request()
  14632. // does, so that a rejected header leaves nothing on the wire.
  14633. {
  14634. detail::BufferStream bstrm;
  14635. // The path follows the authority in absolute-form, so one that does not
  14636. // begin with '/' (e.g. "@evil.example/x") would name another host.
  14637. auto prefix = proxy_target_prefix();
  14638. if ((!prefix.empty() && req.path[0] != '/') ||
  14639. detail::write_request_line(bstrm, req.method, prefix + req.path) < 0) {
  14640. handle.error = Error::Write;
  14641. handle.response.reset();
  14642. return handle;
  14643. }
  14644. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  14645. handle.error)) {
  14646. handle.response.reset();
  14647. return handle;
  14648. }
  14649. const auto &data = bstrm.get_buffer();
  14650. if (!detail::write_data(strm, data.data(), data.size())) {
  14651. handle.error = Error::Write;
  14652. handle.response.reset();
  14653. return handle;
  14654. }
  14655. }
  14656. if (!req.body.empty()) {
  14657. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  14658. handle.error = Error::Write;
  14659. handle.response.reset();
  14660. return handle;
  14661. }
  14662. }
  14663. if (!read_response_line(strm, req, *handle.response) ||
  14664. !detail::read_headers(strm, handle.response->headers)) {
  14665. handle.error = Error::Read;
  14666. handle.response.reset();
  14667. return handle;
  14668. }
  14669. handle.body_reader_.stream = handle.stream_;
  14670. handle.body_reader_.payload_max_length = payload_max_length_;
  14671. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  14672. // header section, so none of its framing or coding headers apply.
  14673. if (req.method == "HEAD" ||
  14674. handle.response->status == StatusCode::NoContent_204 ||
  14675. handle.response->status == StatusCode::NotModified_304) {
  14676. handle.body_reader_.eof = true;
  14677. return handle;
  14678. }
  14679. // Same framing check as ClientImpl::process_request()
  14680. if (detail::has_conflicting_content_length(handle.response->headers)) {
  14681. handle.error = Error::Read;
  14682. handle.response.reset();
  14683. return handle;
  14684. }
  14685. if (handle.response->has_header("Content-Length")) {
  14686. bool is_invalid = false;
  14687. auto content_length = detail::get_header_value_u64(
  14688. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  14689. if (is_invalid) {
  14690. handle.error = Error::Read;
  14691. handle.response.reset();
  14692. return handle;
  14693. }
  14694. handle.body_reader_.has_content_length = true;
  14695. handle.body_reader_.content_length = content_length;
  14696. }
  14697. handle.body_reader_.chunked =
  14698. detail::is_chunked_transfer_encoding(handle.response->headers);
  14699. auto content_encoding = detail::get_combined_header_value(
  14700. handle.response->headers, "Content-Encoding");
  14701. if (decompress_ && !content_encoding.empty()) {
  14702. // Same policy as prepare_content_receiver(): reject a coding we know about
  14703. // but were not built with, pass an unrecognized one through as-is.
  14704. handle.decompressor_ = detail::create_decompressor(content_encoding);
  14705. if (!handle.decompressor_) {
  14706. if (detail::is_known_content_encoding(content_encoding)) {
  14707. handle.error = Error::UnsupportedContentEncoding;
  14708. handle.response.reset();
  14709. return handle;
  14710. }
  14711. } else if (!handle.decompressor_->is_valid()) {
  14712. handle.error = Error::Compression;
  14713. handle.response.reset();
  14714. return handle;
  14715. }
  14716. }
  14717. return handle;
  14718. }
  14719. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  14720. if (!is_valid() || !response) { return -1; }
  14721. auto n = decompressor_
  14722. ? read_with_decompression(buf, len)
  14723. : detail::read_body_content(stream_, body_reader_, buf, len);
  14724. if (n == 0) { parse_trailers_if_needed(); }
  14725. return n;
  14726. }
  14727. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  14728. size_t len) {
  14729. if (decompress_offset_ < decompress_buffer_.size()) {
  14730. auto available = decompress_buffer_.size() - decompress_offset_;
  14731. auto to_copy = (std::min)(len, available);
  14732. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  14733. decompress_offset_ += to_copy;
  14734. decompressed_bytes_read_ += to_copy;
  14735. return static_cast<ssize_t>(to_copy);
  14736. }
  14737. decompress_buffer_.clear();
  14738. decompress_offset_ = 0;
  14739. constexpr size_t kDecompressionBufferSize = 8192;
  14740. char compressed_buf[kDecompressionBufferSize];
  14741. while (true) {
  14742. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  14743. sizeof(compressed_buf));
  14744. if (n <= 0) { return n; }
  14745. auto exceeded = false;
  14746. bool decompress_ok = decompressor_->decompress(
  14747. compressed_buf, static_cast<size_t>(n),
  14748. [&](const char *data, size_t data_len) {
  14749. decompress_buffer_.append(data, data_len);
  14750. auto limit = body_reader_.payload_max_length;
  14751. exceeded =
  14752. limit > 0 &&
  14753. decompressed_bytes_read_ + decompress_buffer_.size() > limit;
  14754. return !exceeded;
  14755. });
  14756. if (!decompress_ok) {
  14757. body_reader_.last_error =
  14758. exceeded ? Error::ExceedMaxPayloadSize : Error::Read;
  14759. return -1;
  14760. }
  14761. if (!decompress_buffer_.empty()) { break; }
  14762. }
  14763. auto to_copy = (std::min)(len, decompress_buffer_.size());
  14764. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  14765. decompress_offset_ = to_copy;
  14766. decompressed_bytes_read_ += to_copy;
  14767. return static_cast<ssize_t>(to_copy);
  14768. }
  14769. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  14770. // The trailers follow the last chunk, so there are none before it
  14771. auto &decoder = body_reader_.chunked_decoder;
  14772. if (!response || trailers_parsed_ || !decoder || !decoder->finished) {
  14773. return;
  14774. }
  14775. trailers_parsed_ = true;
  14776. decoder->parse_trailers_into(response->trailers, response->headers);
  14777. }
  14778. namespace detail {
  14779. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  14780. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  14781. size_t &out_chunk_offset,
  14782. size_t &out_chunk_total) {
  14783. if (finished) { return 0; }
  14784. if (chunk_remaining == 0) {
  14785. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  14786. if (!lr.getline()) { return -1; }
  14787. // Everything below is bounded by eol rather than by the buffer's NUL, so
  14788. // the line terminator is never mistaken for line content.
  14789. const char *eol = lr.ptr() + lr.size();
  14790. if (lr.end_with_crlf()) {
  14791. eol -= 2;
  14792. } else if (eol != lr.ptr() && eol[-1] == '\n') {
  14793. // Only reachable under CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR, where
  14794. // getline() ends the line on a bare LF. That LF is the terminator, so it
  14795. // has to come off here or the check below would reject the line.
  14796. eol -= 1;
  14797. }
  14798. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  14799. const char *p = lr.ptr();
  14800. int v = 0;
  14801. if (p == eol || !is_hex(*p, v)) { return -1; }
  14802. size_t chunk_len = 0;
  14803. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  14804. for (; p < eol && is_hex(*p, v); ++p) {
  14805. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  14806. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  14807. }
  14808. while (p < eol && is_space_or_tab(*p)) {
  14809. ++p;
  14810. }
  14811. // RFC 9112 §7.1.1: only a chunk-ext may sit between the size and the line
  14812. // terminator, and it is built from tokens and quoted-strings, so it never
  14813. // holds a CR, LF or any other control character. getline() reads up to the
  14814. // CRLF, so a bare LF left in here would be swallowed as extension text
  14815. // while an intermediary that ends the line on it delimits the chunks
  14816. // differently, and the two disagree on where the body ends (request
  14817. // smuggling).
  14818. if (p < eol && *p != ';') { return -1; }
  14819. for (; p < eol; ++p) {
  14820. if (!is_space_or_tab(*p) && !fields::is_field_vchar(*p)) { return -1; }
  14821. }
  14822. // The bytes around the data are no payload, so they are counted on their
  14823. // own, as Go does: each chunk may spend 16 bytes and twice its data on
  14824. // them, which lets a stream send a byte at a time, and what goes past that
  14825. // in padding, leading zeros and extensions builds up to one header field.
  14826. overhead += lr.size() + 2;
  14827. overhead = overhead > 16 ? overhead - 16 : 0;
  14828. overhead = chunk_len > overhead / 2 ? 0 : overhead - 2 * chunk_len;
  14829. if (overhead > CPPHTTPLIB_HEADER_MAX_LENGTH) { return -1; }
  14830. if (chunk_len == 0) {
  14831. chunk_remaining = 0;
  14832. finished = true;
  14833. out_chunk_offset = 0;
  14834. out_chunk_total = 0;
  14835. return 0;
  14836. }
  14837. chunk_remaining = chunk_len;
  14838. last_chunk_total = chunk_remaining;
  14839. last_chunk_offset = 0;
  14840. }
  14841. auto to_read = (std::min)(chunk_remaining, len);
  14842. auto n = strm.read(buf, to_read);
  14843. if (n <= 0) { return -1; }
  14844. auto offset_before = last_chunk_offset;
  14845. last_chunk_offset += static_cast<size_t>(n);
  14846. chunk_remaining -= static_cast<size_t>(n);
  14847. out_chunk_offset = offset_before;
  14848. out_chunk_total = last_chunk_total;
  14849. if (chunk_remaining == 0) {
  14850. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  14851. if (!lr.getline()) { return -1; }
  14852. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  14853. }
  14854. return n;
  14855. }
  14856. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  14857. const Headers &src_headers) {
  14858. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  14859. if (!lr.getline()) { return false; }
  14860. return parse_trailers(lr, dest, src_headers);
  14861. }
  14862. // Only 301, 302, 303, 307 and 308 redirect. Any other 3xx, such as a 304, or
  14863. // a redirect without a Location, is a final response.
  14864. inline bool is_redirect(const Response &res) {
  14865. switch (res.status) {
  14866. case StatusCode::MovedPermanently_301:
  14867. case StatusCode::Found_302:
  14868. case StatusCode::SeeOther_303:
  14869. case StatusCode::TemporaryRedirect_307:
  14870. case StatusCode::PermanentRedirect_308:
  14871. return !res.get_header_value("Location").empty();
  14872. default: return false;
  14873. }
  14874. }
  14875. } // namespace detail
  14876. inline void
  14877. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  14878. handle.connection_->sock = socket_.sock;
  14879. #ifdef CPPHTTPLIB_SSL_ENABLED
  14880. handle.connection_->session = socket_.ssl;
  14881. socket_.ssl = nullptr;
  14882. #endif
  14883. socket_.sock = INVALID_SOCKET;
  14884. }
  14885. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2)
  14886. inline std::string ClientImpl::proxy_target_prefix() const {
  14887. if (is_ssl() || !is_proxy_enabled_for_host(host_)) { return std::string(); }
  14888. return "http://" + detail::make_host_and_port_string(host_, port_, false);
  14889. }
  14890. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  14891. Response &res, bool close_connection,
  14892. Error &error) {
  14893. if (req.path.empty()) {
  14894. error = Error::Connection;
  14895. return false;
  14896. }
  14897. auto req_save = req;
  14898. bool ret;
  14899. auto prefix = proxy_target_prefix();
  14900. if (!prefix.empty()) {
  14901. // The path follows the authority in absolute-form, so one that does not
  14902. // begin with '/' (e.g. "@evil.example/x") would name another host.
  14903. if (req.path[0] != '/') {
  14904. error = Error::Write;
  14905. return false;
  14906. }
  14907. auto req2 = req;
  14908. req2.path = prefix + req.path;
  14909. ret = process_request(strm, req2, res, close_connection, error);
  14910. req = std::move(req2);
  14911. req.path = req_save.path;
  14912. } else {
  14913. ret = process_request(strm, req, res, close_connection, error);
  14914. }
  14915. if (!ret) { return false; }
  14916. {
  14917. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  14918. // for this to be safe.
  14919. // This is safe to call because handle_request is only called by send_
  14920. // which locks the request mutex during the process. It would be a bug
  14921. // to call it from a different thread since it's a thread-safety issue
  14922. // to do these things to the socket if another thread is using the socket.
  14923. std::lock_guard<std::mutex> guard(socket_mutex_);
  14924. // Also when the request asked for it (e.g. a body that was never sent,
  14925. // or "Connection: close") or bytes follow the response (RFC 9112 9.2), so
  14926. // that a redirect or an auth retry below does not reuse the socket.
  14927. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  14928. strm.is_readable() ||
  14929. detail::has_header_token(res.headers, "Connection", "close") ||
  14930. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  14931. disconnect(/*gracefully=*/true);
  14932. }
  14933. }
  14934. if (follow_location_ && detail::is_redirect(res)) {
  14935. req = std::move(req_save);
  14936. // The client that followed the redirect has answered any challenge it
  14937. // could. Retrying below would sign another host's challenge and send it
  14938. // here.
  14939. return redirect(req, res, error);
  14940. }
  14941. #ifdef CPPHTTPLIB_SSL_ENABLED
  14942. if ((res.status == StatusCode::Unauthorized_401 ||
  14943. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  14944. req.authorization_count_ < 5) {
  14945. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  14946. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  14947. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  14948. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  14949. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  14950. return ret;
  14951. }
  14952. const auto &username =
  14953. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  14954. const auto &password =
  14955. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  14956. if (!username.empty() && !password.empty()) {
  14957. std::map<std::string, std::string> auth;
  14958. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  14959. Request new_req = req;
  14960. new_req.authorization_count_ += 1;
  14961. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  14962. : "Authorization");
  14963. new_req.headers.insert(detail::make_digest_authentication_header(
  14964. req, make_request_target(req), auth, new_req.authorization_count_,
  14965. detail::random_string(10), username, password, is_proxy));
  14966. Response new_res;
  14967. ret = send(new_req, new_res, error);
  14968. if (ret) { res = std::move(new_res); }
  14969. }
  14970. }
  14971. }
  14972. #endif
  14973. return ret;
  14974. }
  14975. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  14976. if (req.redirect_count_ == 0) {
  14977. error = Error::ExceedRedirectCount;
  14978. return false;
  14979. }
  14980. auto location = res.get_header_value("location");
  14981. if (location.empty()) { return false; }
  14982. auto next_url = detail::resolve_relative_location(location, req.path);
  14983. detail::UrlComponents uc;
  14984. if (!detail::parse_url(next_url, uc)) { return false; }
  14985. // Follow only http/https URLs and references starting with '/'
  14986. if (next_url[0] != '/' && uc.scheme != "http" && uc.scheme != "https") {
  14987. return false;
  14988. }
  14989. auto scheme = is_ssl() ? "https" : "http";
  14990. auto next_scheme = std::move(uc.scheme);
  14991. auto next_host = std::move(uc.host);
  14992. auto port_str = std::move(uc.port);
  14993. auto next_path = std::move(uc.path);
  14994. auto next_query = std::move(uc.query);
  14995. auto next_port = port_;
  14996. if (!port_str.empty()) {
  14997. if (!detail::parse_port(port_str, next_port)) { return false; }
  14998. } else if (!next_scheme.empty()) {
  14999. next_port = next_scheme == "https" ? 443 : 80;
  15000. }
  15001. if (next_scheme.empty()) { next_scheme = scheme; }
  15002. if (next_host.empty()) { next_host = host_; }
  15003. if (next_path.empty()) { next_path = "/"; }
  15004. // An absolute or absolute-path location can have dot segments too.
  15005. if (next_path[0] == '/') {
  15006. next_path = detail::remove_dot_segments(next_path);
  15007. }
  15008. auto path = std::move(next_path) + next_query;
  15009. // A Unix socket client sends "Host: localhost", so a Location naming
  15010. // localhost names this client too.
  15011. auto is_same_host = next_host == host_ ||
  15012. (address_family_ == AF_UNIX && next_host == "localhost");
  15013. // Same host redirect - use current client
  15014. if (next_scheme == scheme && is_same_host && next_port == port_) {
  15015. return detail::redirect(*this, req, res, path, location, error);
  15016. }
  15017. // Cross-host/scheme redirect - create new client with robust setup
  15018. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  15019. path, location, error);
  15020. }
  15021. // New method for robust redirect client creation
  15022. inline bool ClientImpl::create_redirect_client(
  15023. const std::string &scheme, const std::string &host, int port, Request &req,
  15024. Response &res, const std::string &path, const std::string &location,
  15025. Error &error) {
  15026. // Determine if we need SSL
  15027. auto need_ssl = (scheme == "https");
  15028. // Clean up request headers that are host/client specific
  15029. // Remove headers that should not be carried over to new host
  15030. auto headers_to_remove = std::vector<std::string>{
  15031. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  15032. for (const auto &header_name : headers_to_remove) {
  15033. auto it = req.headers.find(header_name);
  15034. while (it != req.headers.end()) {
  15035. it = req.headers.erase(it);
  15036. it = req.headers.find(header_name);
  15037. }
  15038. }
  15039. // Create appropriate client type and handle redirect
  15040. if (need_ssl) {
  15041. #ifdef CPPHTTPLIB_SSL_ENABLED
  15042. // Create SSL client for HTTPS redirect
  15043. SSLClient redirect_client(host, port);
  15044. // Setup basic client configuration first
  15045. setup_redirect_client(redirect_client);
  15046. redirect_client.enable_server_certificate_verification(
  15047. server_certificate_verification_);
  15048. redirect_client.enable_server_hostname_verification(
  15049. server_hostname_verification_);
  15050. redirect_client.system_ca_mode_ = system_ca_mode_;
  15051. // Transfer CA certificate to redirect client
  15052. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  15053. if (is_ssl()) {
  15054. auto &self = static_cast<SSLClient &>(*this);
  15055. // A store given to set_ca_cert_store() lives only in this client's
  15056. // context, which then holds all that is trusted.
  15057. if (self.ca_cert_store_set_) {
  15058. std::string pem;
  15059. {
  15060. std::lock_guard<std::mutex> guard(self.ctx_mutex_);
  15061. pem = detail::ca_certs_to_pem(self.ctx_);
  15062. }
  15063. redirect_client.load_ca_cert_store(pem.data(), pem.size());
  15064. redirect_client.ca_cert_store_set_ = true;
  15065. } else if (self.custom_ca_loaded_) {
  15066. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  15067. ca_cert_pem_.size());
  15068. }
  15069. redirect_client.set_session_verifier(self.session_verifier_);
  15070. if (self.server_certificate_verifier_) {
  15071. redirect_client.set_server_certificate_verifier(
  15072. self.server_certificate_verifier_);
  15073. }
  15074. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15075. redirect_client.enable_windows_cert_verification_ =
  15076. self.enable_windows_cert_verification_;
  15077. #endif
  15078. }
  15079. // Client certificates are set through constructor for SSLClient
  15080. // NOTE: SSLClient constructor already takes client_cert_path and
  15081. // client_key_path so we need to create it properly if client certs are
  15082. // needed
  15083. // Execute the redirect
  15084. return detail::redirect(redirect_client, req, res, path, location, error);
  15085. #else
  15086. // SSL not supported - set appropriate error
  15087. error = Error::SSLConnection;
  15088. return false;
  15089. #endif
  15090. } else {
  15091. // HTTP redirect
  15092. ClientImpl redirect_client(host, port);
  15093. // Setup client with robust configuration
  15094. setup_redirect_client(redirect_client);
  15095. // Execute the redirect
  15096. return detail::redirect(redirect_client, req, res, path, location, error);
  15097. }
  15098. }
  15099. // New method for robust client setup (based on basic_manual_redirect.cpp
  15100. // logic)
  15101. template <typename ClientType>
  15102. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  15103. // Copy basic settings first
  15104. client.set_connection_timeout(connection_timeout_sec_,
  15105. connection_timeout_usec_);
  15106. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  15107. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  15108. client.set_max_timeout(max_timeout_msec_);
  15109. if (has_payload_max_length_) {
  15110. client.set_payload_max_length(payload_max_length_);
  15111. }
  15112. client.set_keep_alive(keep_alive_);
  15113. client.set_follow_location(
  15114. true); // Enable redirects to handle multi-step redirects
  15115. client.set_path_encode(path_encode_);
  15116. client.set_compress(compress_);
  15117. client.set_decompress(decompress_);
  15118. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  15119. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  15120. // 15.4, credentials must not be forwarded when redirecting to a different
  15121. // host. This function is only called for cross-host redirects; same-host
  15122. // redirects are handled directly in ClientImpl::redirect().
  15123. // Copy the proxy configuration unconditionally; the per-target bypass is
  15124. // re-evaluated at send time, so a later hop to a non-bypassed host can
  15125. // still use the proxy.
  15126. client.no_proxy_entries_ = no_proxy_entries_;
  15127. if (!proxy_host_.empty() && proxy_port_ != -1) {
  15128. client.set_proxy(proxy_host_, proxy_port_);
  15129. if (!proxy_basic_auth_username_.empty() ||
  15130. !proxy_basic_auth_password_.empty()) {
  15131. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  15132. proxy_basic_auth_password_);
  15133. }
  15134. if (!proxy_bearer_token_auth_token_.empty()) {
  15135. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  15136. }
  15137. #ifdef CPPHTTPLIB_SSL_ENABLED
  15138. if (!proxy_digest_auth_username_.empty()) {
  15139. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  15140. proxy_digest_auth_password_);
  15141. }
  15142. #endif
  15143. }
  15144. // Copy network and socket settings
  15145. client.addr_map_ = addr_map_;
  15146. client.tunnel_addr_map_ = tunnel_addr_map_;
  15147. // A Unix socket client reaches every host through its own socket, as curl's
  15148. // --unix-socket does, unless the caller mapped that host elsewhere. The
  15149. // Location's host is never taken as a socket path.
  15150. if (address_family_ == AF_UNIX) {
  15151. auto &target = client.addr_map_[client.host()];
  15152. if (target.empty()) { target = detail::addr_map_target(addr_map_, host_); }
  15153. }
  15154. client.set_address_family(address_family_);
  15155. client.set_tcp_nodelay(tcp_nodelay_);
  15156. client.set_ipv6_v6only(ipv6_v6only_);
  15157. if (socket_options_) { client.set_socket_options(socket_options_); }
  15158. if (!interface_.empty()) { client.set_interface(interface_); }
  15159. // Copy logging and headers. Not the error logger: a failure comes back to
  15160. // this client's send(), which reports it with the caller's request.
  15161. if (logger_) { client.set_logger(logger_); }
  15162. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  15163. // Each new client should generate its own headers based on its target host
  15164. }
  15165. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  15166. const Request &req,
  15167. Error &error) const {
  15168. auto is_shutting_down = []() { return false; };
  15169. if (req.is_chunked_content_provider_) {
  15170. auto compressor = compress_ ? detail::create_compressor().first
  15171. : std::unique_ptr<detail::compressor>();
  15172. if (!compressor) {
  15173. compressor = detail::make_unique<detail::nocompressor>();
  15174. }
  15175. return detail::write_content_chunked(strm, req.content_provider_,
  15176. is_shutting_down, *compressor, error);
  15177. } else {
  15178. return detail::write_content_with_progress(
  15179. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  15180. req.upload_progress, error);
  15181. }
  15182. }
  15183. // What goes on the request line for req: its path, encoded and without the
  15184. // fragment, with `req.params` as the query when the path has none.
  15185. inline std::string ClientImpl::make_request_target(const Request &req) const {
  15186. auto target = detail::encode_request_target(req.path, path_encode_);
  15187. if (detail::query_of(req.path).empty() && !req.params.empty()) {
  15188. target = append_query_params(target, req.params);
  15189. }
  15190. return target;
  15191. }
  15192. inline void ClientImpl::add_credential_headers(Request &req) {
  15193. // A CONNECT request is read by the proxy; everything sent through the tunnel
  15194. // it opens is read by the origin. Each credential goes only to its own hop.
  15195. auto is_connect = req.method == "CONNECT";
  15196. if (!is_connect) {
  15197. detail::add_authorization_header(req, basic_auth_username_,
  15198. basic_auth_password_,
  15199. bearer_token_auth_token_, false);
  15200. }
  15201. // Proxy-Authorization is only sent when the proxy reads this message —
  15202. // otherwise NO_PROXY-matched requests, and requests inside a TLS tunnel,
  15203. // would leak proxy credentials to the destination server.
  15204. if (is_proxy_enabled_for_host(host_) && (!is_ssl() || is_connect)) {
  15205. detail::add_authorization_header(req, proxy_basic_auth_username_,
  15206. proxy_basic_auth_password_,
  15207. proxy_bearer_token_auth_token_, true);
  15208. }
  15209. }
  15210. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  15211. bool close_connection, Error &error,
  15212. bool skip_body, bool &rejected_locally) {
  15213. rejected_locally = false;
  15214. // Prepare additional headers
  15215. if (close_connection) {
  15216. if (!req.has_header("Connection")) {
  15217. req.set_header("Connection", "close");
  15218. }
  15219. }
  15220. std::string ct_for_defaults;
  15221. if (!req.has_header("Content-Type") && !req.body.empty()) {
  15222. ct_for_defaults = "text/plain";
  15223. }
  15224. prepare_default_headers(req, false, ct_for_defaults);
  15225. if (req.body.empty()) {
  15226. if (req.content_provider_) {
  15227. if (!req.is_chunked_content_provider_) {
  15228. if (!req.has_header("Content-Length")) {
  15229. auto length = std::to_string(req.content_length_);
  15230. req.set_header("Content-Length", length);
  15231. }
  15232. }
  15233. } else {
  15234. if (req.method == "POST" || req.method == "PUT" ||
  15235. req.method == "PATCH") {
  15236. req.set_header("Content-Length", "0");
  15237. }
  15238. }
  15239. }
  15240. add_credential_headers(req);
  15241. // Request line and headers
  15242. {
  15243. detail::BufferStream bstrm;
  15244. auto path_with_query = make_request_target(req);
  15245. // The query already came in through `req.path`; still populate
  15246. // `req.params` for handlers/users who read them.
  15247. auto query_part = detail::query_of(req.path);
  15248. if (!query_part.empty()) {
  15249. detail::parse_query_text(query_part, req.params);
  15250. }
  15251. // Write request line and headers
  15252. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  15253. // A rejected method (not a token, e.g. carrying CR/LF) or target (e.g.
  15254. // CR/LF in a caller-supplied path under set_path_encode(false)) must
  15255. // fail the request cleanly instead of emitting a request-line-less,
  15256. // header-injecting request.
  15257. error = Error::Write;
  15258. rejected_locally = true;
  15259. return false;
  15260. }
  15261. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  15262. error)) {
  15263. rejected_locally = true;
  15264. return false;
  15265. }
  15266. // Flush buffer
  15267. auto &data = bstrm.get_buffer();
  15268. if (!detail::write_data(strm, data.data(), data.size())) {
  15269. error = Error::Write;
  15270. return false;
  15271. }
  15272. }
  15273. // After sending request line and headers, wait briefly for an early server
  15274. // response (e.g. 4xx) and avoid sending a potentially large request body
  15275. // unnecessarily. This workaround is only enabled on Windows because Unix
  15276. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  15277. // buffering can accept large writes even when the peer already responded.
  15278. // Check the stream first (which covers SSL via `is_readable()`), then
  15279. // fall back to select on the socket. Only perform the wait for very large
  15280. // request bodies to avoid interfering with normal small requests and
  15281. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  15282. // response. Skip this check when using Expect: 100-continue, as the protocol
  15283. // handles early responses properly.
  15284. #if defined(_WIN32)
  15285. if (!skip_body &&
  15286. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  15287. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  15288. auto start = std::chrono::high_resolution_clock::now();
  15289. for (;;) {
  15290. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  15291. // from SSL internals. If the underlying socket is readable, assume an
  15292. // early response may be present.
  15293. auto sock = strm.socket();
  15294. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  15295. return false;
  15296. }
  15297. // Fallback to stream-level check for non-socket streams or when the
  15298. // socket isn't reporting readable. Avoid using `is_readable()` for
  15299. // SSL, since `SSL_pending()` may report buffered records that do not
  15300. // indicate a complete application-level response yet.
  15301. if (!is_ssl() && strm.is_readable()) { return false; }
  15302. auto now = std::chrono::high_resolution_clock::now();
  15303. auto elapsed =
  15304. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  15305. .count();
  15306. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  15307. break;
  15308. }
  15309. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  15310. }
  15311. }
  15312. #endif
  15313. // Body
  15314. if (skip_body) { return true; }
  15315. return write_request_body(strm, req, error);
  15316. }
  15317. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  15318. Error &error) {
  15319. if (req.body.empty()) {
  15320. return write_content_with_provider(strm, req, error);
  15321. }
  15322. if (req.upload_progress) {
  15323. auto body_size = req.body.size();
  15324. size_t written = 0;
  15325. auto data = req.body.data();
  15326. while (written < body_size) {
  15327. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  15328. if (!detail::write_data(strm, data + written, to_write)) {
  15329. error = Error::Write;
  15330. return false;
  15331. }
  15332. written += to_write;
  15333. if (!req.upload_progress(written, body_size)) {
  15334. error = Error::Canceled;
  15335. return false;
  15336. }
  15337. }
  15338. } else {
  15339. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  15340. error = Error::Write;
  15341. return false;
  15342. }
  15343. }
  15344. return true;
  15345. }
  15346. inline std::unique_ptr<Response>
  15347. ClientImpl::send_with_content_provider_and_receiver(
  15348. Request &req, const char *body, size_t content_length,
  15349. ContentProvider content_provider,
  15350. ContentProviderWithoutLength content_provider_without_length,
  15351. const std::string &content_type, ContentReceiver content_receiver,
  15352. Error &error) {
  15353. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  15354. auto enc = compress_
  15355. ? detail::create_compressor()
  15356. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  15357. nullptr, nullptr);
  15358. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  15359. // A compressed or chunked body is framed by the library, not the caller
  15360. if (enc.second || content_provider_without_length) {
  15361. req.headers.erase("Content-Length");
  15362. }
  15363. if (enc.first && !content_provider_without_length) {
  15364. auto &compressor = enc.first;
  15365. if (content_provider) {
  15366. auto ok = true;
  15367. auto finished = false;
  15368. size_t offset = 0;
  15369. DataSink data_sink;
  15370. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  15371. if (ok) {
  15372. auto last = offset + data_len == content_length;
  15373. auto ret = compressor->compress(
  15374. data, data_len, last,
  15375. [&](const char *compressed_data, size_t compressed_data_len) {
  15376. req.body.append(compressed_data, compressed_data_len);
  15377. return true;
  15378. });
  15379. if (ret) {
  15380. offset += data_len;
  15381. } else {
  15382. ok = false;
  15383. }
  15384. }
  15385. return ok;
  15386. };
  15387. // As in detail::write_content_with_progress(): the body is framed by
  15388. // content_length, so a provider that finishes early has truncated it.
  15389. // Stop and report that instead of calling the provider forever.
  15390. data_sink.done = [&]() { finished = true; };
  15391. while (ok && !finished && offset < content_length) {
  15392. if (!content_provider(offset, content_length - offset, data_sink)) {
  15393. error = Error::Canceled;
  15394. output_error_log(error, &req);
  15395. return nullptr;
  15396. }
  15397. }
  15398. // A short body here means either the provider stopped early or the
  15399. // compressor gave up. The branch below reports a failing compressor as
  15400. // Error::Compression, so keep the two distinguishable.
  15401. if (offset < content_length) {
  15402. error = ok ? Error::Write : Error::Compression;
  15403. output_error_log(error, &req);
  15404. return nullptr;
  15405. }
  15406. } else {
  15407. if (!compressor->compress(body, content_length, true,
  15408. [&](const char *data, size_t data_len) {
  15409. req.body.append(data, data_len);
  15410. return true;
  15411. })) {
  15412. error = Error::Compression;
  15413. output_error_log(error, &req);
  15414. return nullptr;
  15415. }
  15416. }
  15417. } else {
  15418. if (content_provider) {
  15419. req.content_length_ = content_length;
  15420. req.content_provider_ = std::move(content_provider);
  15421. req.is_chunked_content_provider_ = false;
  15422. } else if (content_provider_without_length) {
  15423. req.content_length_ = 0;
  15424. req.content_provider_ = detail::ContentProviderAdapter(
  15425. std::move(content_provider_without_length));
  15426. req.is_chunked_content_provider_ = true;
  15427. req.set_header("Transfer-Encoding", "chunked");
  15428. } else {
  15429. req.body.assign(body, content_length);
  15430. }
  15431. }
  15432. if (content_receiver) {
  15433. req.content_receiver =
  15434. [content_receiver](const char *data, size_t data_length,
  15435. size_t /*offset*/, size_t /*total_length*/) {
  15436. return content_receiver(data, data_length);
  15437. };
  15438. }
  15439. auto res = detail::make_unique<Response>();
  15440. return send(req, *res, error) ? std::move(res) : nullptr;
  15441. }
  15442. inline Result ClientImpl::send_with_content_provider_and_receiver(
  15443. const std::string &method, const std::string &path, const Headers &headers,
  15444. const char *body, size_t content_length, ContentProvider content_provider,
  15445. ContentProviderWithoutLength content_provider_without_length,
  15446. const std::string &content_type, ContentReceiver content_receiver,
  15447. UploadProgress progress) {
  15448. Request req;
  15449. req.method = method;
  15450. req.headers = headers;
  15451. req.path = path;
  15452. req.upload_progress = std::move(progress);
  15453. if (max_timeout_msec_ > 0) {
  15454. req.start_time_ = std::chrono::steady_clock::now();
  15455. }
  15456. auto error = Error::Success;
  15457. #ifdef CPPHTTPLIB_SSL_ENABLED
  15458. // Hold the request lock until the Result has read this request's TLS error
  15459. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  15460. #endif
  15461. auto res = send_with_content_provider_and_receiver(
  15462. req, body, content_length, std::move(content_provider),
  15463. std::move(content_provider_without_length), content_type,
  15464. std::move(content_receiver), error);
  15465. #ifdef CPPHTTPLIB_SSL_ENABLED
  15466. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  15467. last_backend_error_};
  15468. #else
  15469. return Result{std::move(res), error, std::move(req.headers)};
  15470. #endif
  15471. }
  15472. inline void ClientImpl::output_log(const Request &req,
  15473. const Response &res) const {
  15474. if (logger_) {
  15475. std::lock_guard<std::mutex> guard(logger_mutex_);
  15476. logger_(req, res);
  15477. }
  15478. }
  15479. inline void ClientImpl::output_error_log(const Error &err,
  15480. const Request *req) const {
  15481. if (error_logger_) {
  15482. std::lock_guard<std::mutex> guard(logger_mutex_);
  15483. error_logger_(err, req);
  15484. }
  15485. }
  15486. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  15487. Response &res, bool close_connection,
  15488. Error &error) {
  15489. // Auto-add Expect: 100-continue for large bodies
  15490. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  15491. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  15492. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  15493. req.set_header("Expect", "100-continue");
  15494. }
  15495. }
  15496. // Check for Expect: 100-continue
  15497. auto expect_100_continue =
  15498. detail::has_header_token(req.headers, "Expect", "100-continue");
  15499. // Send request (skip body if using Expect: 100-continue)
  15500. auto rejected_locally = false;
  15501. auto write_request_success =
  15502. write_request(strm, req, close_connection, error, expect_100_continue,
  15503. rejected_locally);
  15504. // A failed write normally still reads the response below, since the server
  15505. // may have answered early (e.g. 413/414) and closed while the body was being
  15506. // sent. A request rejected before any byte reached the socket gets no such
  15507. // response, and waiting for one would block until the read timeout.
  15508. if (rejected_locally) { return false; }
  15509. #ifdef CPPHTTPLIB_SSL_ENABLED
  15510. if (is_ssl() && !expect_100_continue) {
  15511. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  15512. if (!is_proxy_enabled) {
  15513. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  15514. error = Error::SSLPeerCouldBeClosed_;
  15515. return false;
  15516. }
  15517. }
  15518. }
  15519. #endif
  15520. // Handle Expect: 100-continue.
  15521. //
  15522. // Wait for an interim/early response by attempting to read the status line
  15523. // under a short timeout, instead of trusting raw socket readability. Over
  15524. // TLS, post-handshake records (e.g. session tickets) make the socket
  15525. // readable without any HTTP response being available; relying on
  15526. // `select_read` there caused the body to be withheld forever and the
  15527. // request to fail with `Read` (#2458). If no status line arrives within the
  15528. // timeout, send the body anyway (matching curl's behavior).
  15529. auto status_line_read = false;
  15530. if (expect_100_continue && write_request_success) {
  15531. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  15532. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  15533. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  15534. strm.set_read_timeout(sec, usec);
  15535. status_line_read = read_response_line(strm, req, res, false);
  15536. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  15537. }
  15538. if (!status_line_read) {
  15539. // No interim response within the timeout: send the body and handle the
  15540. // response as usual.
  15541. if (!write_request_body(strm, req, error)) { return false; }
  15542. expect_100_continue = false; // Switch to normal response handling
  15543. }
  15544. }
  15545. // Receive response and headers
  15546. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  15547. if ((!status_line_read &&
  15548. !read_response_line(strm, req, res, !expect_100_continue)) ||
  15549. !detail::read_headers(strm, res.headers)) {
  15550. if (write_request_success) { error = Error::Read; }
  15551. return false;
  15552. }
  15553. if (!write_request_success) { return false; }
  15554. // Handle Expect: 100-continue response
  15555. if (expect_100_continue) {
  15556. if (res.status == StatusCode::Continue_100) {
  15557. // Server accepted, send the body
  15558. if (!write_request_body(strm, req, error)) { return false; }
  15559. // Read the actual response
  15560. res.headers.clear();
  15561. res.body.clear();
  15562. if (!read_response_line(strm, req, res) ||
  15563. !detail::read_headers(strm, res.headers)) {
  15564. error = Error::Read;
  15565. return false;
  15566. }
  15567. } else {
  15568. // A final response came first, so the body this request declared was
  15569. // never sent, and the server may still be waiting for it. The
  15570. // connection cannot carry another request.
  15571. std::lock_guard<std::mutex> guard(socket_mutex_);
  15572. socket_should_be_closed_when_request_is_done_ = true;
  15573. }
  15574. }
  15575. // Body
  15576. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  15577. req.method != "CONNECT") {
  15578. // Reject ambiguous framing (RFC 9112 §6.3). Unlike a request, a response
  15579. // whose final transfer coding is not chunked is not ambiguous: its body
  15580. // runs until the server closes the connection, so it is not rejected.
  15581. // HEAD/204 are excluded above and a 304 carries no body.
  15582. if (res.status != StatusCode::NotModified_304) {
  15583. if (detail::has_conflicting_content_length(res.headers)) {
  15584. error = Error::Read;
  15585. return false;
  15586. }
  15587. if (detail::has_faulty_transfer_encoding(res)) {
  15588. std::lock_guard<std::mutex> guard(socket_mutex_);
  15589. socket_should_be_closed_when_request_is_done_ = true;
  15590. }
  15591. }
  15592. auto redirect = follow_location_ && detail::is_redirect(res);
  15593. if (req.response_handler && !redirect) {
  15594. if (!req.response_handler(res)) {
  15595. error = Error::Canceled;
  15596. return false;
  15597. }
  15598. }
  15599. auto out =
  15600. req.content_receiver
  15601. ? static_cast<ContentReceiverWithProgress>(
  15602. [&](const char *buf, size_t n, size_t off, size_t len) {
  15603. if (redirect) { return true; }
  15604. auto ret = req.content_receiver(buf, n, off, len);
  15605. if (!ret) { error = Error::Canceled; }
  15606. return ret;
  15607. })
  15608. : static_cast<ContentReceiverWithProgress>(
  15609. [&](const char *buf, size_t n, size_t /*off*/,
  15610. size_t /*len*/) {
  15611. assert(res.body.size() + n <= res.body.max_size());
  15612. if (payload_max_length_ > 0 &&
  15613. (res.body.size() >= payload_max_length_ ||
  15614. n > payload_max_length_ - res.body.size())) {
  15615. return false;
  15616. }
  15617. res.body.append(buf, n);
  15618. return true;
  15619. });
  15620. auto progress = [&](size_t current, size_t total) {
  15621. if (!req.download_progress || redirect) { return true; }
  15622. auto ret = req.download_progress(current, total);
  15623. if (!ret) { error = Error::Canceled; }
  15624. return ret;
  15625. };
  15626. if (res.has_header("Content-Length")) {
  15627. if (!req.content_receiver) {
  15628. auto len = res.get_header_value_u64("Content-Length");
  15629. if (len > res.body.max_size()) {
  15630. error = Error::Read;
  15631. return false;
  15632. }
  15633. // Content-Length is only the server's claim, so reserve no more than
  15634. // payload_max_length_ allows, nor more than 1 MiB before any of the
  15635. // body has arrived. A longer body grows as it is read.
  15636. auto reserve_len =
  15637. (std::min)(static_cast<size_t>(len), size_t(1024 * 1024));
  15638. if (payload_max_length_ > 0) {
  15639. reserve_len = (std::min)(reserve_len, payload_max_length_);
  15640. }
  15641. res.body.reserve(reserve_len);
  15642. }
  15643. }
  15644. if (res.status != StatusCode::NotModified_304) {
  15645. auto content_status = 0;
  15646. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  15647. ? (std::numeric_limits<size_t>::max)()
  15648. : payload_max_length_;
  15649. if (!detail::read_content(strm, res, max_length, content_status,
  15650. std::move(progress), std::move(out),
  15651. decompress_)) {
  15652. if (error != Error::Canceled) {
  15653. // Tell the caller apart from a plain read failure when the body was
  15654. // over the payload limit or could not be decoded because of its
  15655. // Content-Encoding.
  15656. switch (content_status) {
  15657. case StatusCode::PayloadTooLarge_413:
  15658. error = Error::ExceedMaxPayloadSize;
  15659. break;
  15660. case StatusCode::UnsupportedMediaType_415:
  15661. error = Error::UnsupportedContentEncoding;
  15662. break;
  15663. case StatusCode::InternalServerError_500:
  15664. error = Error::Compression;
  15665. break;
  15666. default: error = Error::Read; break;
  15667. }
  15668. }
  15669. return false;
  15670. }
  15671. }
  15672. }
  15673. // Log
  15674. output_log(req, res);
  15675. return true;
  15676. }
  15677. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  15678. const std::string &boundary, const UploadFormDataItems &items,
  15679. const FormDataProviderItems &provider_items) const {
  15680. size_t cur_item = 0;
  15681. size_t cur_start = 0;
  15682. // cur_item and cur_start are copied to within the std::function and
  15683. // maintain state between successive calls
  15684. return [&, cur_item, cur_start](size_t offset,
  15685. DataSink &sink) mutable -> bool {
  15686. if (!offset && !items.empty()) {
  15687. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  15688. return true;
  15689. } else if (cur_item < provider_items.size()) {
  15690. if (!cur_start) {
  15691. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  15692. provider_items[cur_item], boundary);
  15693. offset += begin.size();
  15694. cur_start = offset;
  15695. sink.os << begin;
  15696. }
  15697. DataSink cur_sink;
  15698. auto has_data = true;
  15699. cur_sink.write = sink.write;
  15700. // Forward is_writable so a provider item asking whether it may keep
  15701. // going gets the outer sink's answer rather than the default `true`.
  15702. cur_sink.is_writable = sink.is_writable;
  15703. cur_sink.done = [&]() { has_data = false; };
  15704. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  15705. return false;
  15706. }
  15707. if (!has_data) {
  15708. sink.os << detail::serialize_multipart_formdata_item_end();
  15709. cur_item++;
  15710. cur_start = 0;
  15711. }
  15712. return true;
  15713. } else {
  15714. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  15715. sink.done();
  15716. return true;
  15717. }
  15718. };
  15719. }
  15720. inline bool ClientImpl::process_socket(
  15721. const Socket &socket,
  15722. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15723. std::function<bool(Stream &strm)> callback) {
  15724. return detail::process_client_socket(
  15725. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  15726. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  15727. }
  15728. inline bool ClientImpl::is_ssl() const { return false; }
  15729. inline Result ClientImpl::Get(const std::string &path,
  15730. DownloadProgress progress) {
  15731. return Get(path, Headers(), std::move(progress));
  15732. }
  15733. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15734. DownloadProgress progress) {
  15735. return Get(path, params, Headers(), std::move(progress));
  15736. }
  15737. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15738. const Headers &headers,
  15739. DownloadProgress progress) {
  15740. if (params.empty()) { return Get(path, headers); }
  15741. std::string path_with_query = append_query_params(path, params);
  15742. return Get(path_with_query, headers, std::move(progress));
  15743. }
  15744. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  15745. DownloadProgress progress) {
  15746. Request req;
  15747. req.method = "GET";
  15748. req.path = path;
  15749. req.headers = headers;
  15750. req.download_progress = std::move(progress);
  15751. if (max_timeout_msec_ > 0) {
  15752. req.start_time_ = std::chrono::steady_clock::now();
  15753. }
  15754. return send_(std::move(req));
  15755. }
  15756. inline Result ClientImpl::Get(const std::string &path,
  15757. ContentReceiver content_receiver,
  15758. DownloadProgress progress) {
  15759. return Get(path, Headers(), nullptr, std::move(content_receiver),
  15760. std::move(progress));
  15761. }
  15762. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  15763. ContentReceiver content_receiver,
  15764. DownloadProgress progress) {
  15765. return Get(path, headers, nullptr, std::move(content_receiver),
  15766. std::move(progress));
  15767. }
  15768. inline Result ClientImpl::Get(const std::string &path,
  15769. ResponseHandler response_handler,
  15770. ContentReceiver content_receiver,
  15771. DownloadProgress progress) {
  15772. return Get(path, Headers(), std::move(response_handler),
  15773. std::move(content_receiver), std::move(progress));
  15774. }
  15775. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  15776. ResponseHandler response_handler,
  15777. ContentReceiver content_receiver,
  15778. DownloadProgress progress) {
  15779. Request req;
  15780. req.method = "GET";
  15781. req.path = path;
  15782. req.headers = headers;
  15783. req.response_handler = std::move(response_handler);
  15784. req.content_receiver =
  15785. [content_receiver](const char *data, size_t data_length,
  15786. size_t /*offset*/, size_t /*total_length*/) {
  15787. return content_receiver(data, data_length);
  15788. };
  15789. req.download_progress = std::move(progress);
  15790. if (max_timeout_msec_ > 0) {
  15791. req.start_time_ = std::chrono::steady_clock::now();
  15792. }
  15793. return send_(std::move(req));
  15794. }
  15795. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15796. const Headers &headers,
  15797. ContentReceiver content_receiver,
  15798. DownloadProgress progress) {
  15799. return Get(path, params, headers, nullptr, std::move(content_receiver),
  15800. std::move(progress));
  15801. }
  15802. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  15803. const Headers &headers,
  15804. ResponseHandler response_handler,
  15805. ContentReceiver content_receiver,
  15806. DownloadProgress progress) {
  15807. if (params.empty()) {
  15808. return Get(path, headers, std::move(response_handler),
  15809. std::move(content_receiver), std::move(progress));
  15810. }
  15811. std::string path_with_query = append_query_params(path, params);
  15812. return Get(path_with_query, headers, std::move(response_handler),
  15813. std::move(content_receiver), std::move(progress));
  15814. }
  15815. inline Result ClientImpl::Head(const std::string &path) {
  15816. return Head(path, Headers());
  15817. }
  15818. inline Result ClientImpl::Head(const std::string &path,
  15819. const Headers &headers) {
  15820. Request req;
  15821. req.method = "HEAD";
  15822. req.headers = headers;
  15823. req.path = path;
  15824. if (max_timeout_msec_ > 0) {
  15825. req.start_time_ = std::chrono::steady_clock::now();
  15826. }
  15827. return send_(std::move(req));
  15828. }
  15829. inline Result ClientImpl::Post(const std::string &path) {
  15830. return Post(path, std::string(), std::string());
  15831. }
  15832. inline Result ClientImpl::Post(const std::string &path,
  15833. const Headers &headers) {
  15834. return Post(path, headers, nullptr, 0, std::string());
  15835. }
  15836. inline Result ClientImpl::Post(const std::string &path, const char *body,
  15837. size_t content_length,
  15838. const std::string &content_type,
  15839. UploadProgress progress) {
  15840. return Post(path, Headers(), body, content_length, content_type, progress);
  15841. }
  15842. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  15843. const std::string &content_type,
  15844. UploadProgress progress) {
  15845. return Post(path, Headers(), body, content_type, progress);
  15846. }
  15847. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  15848. return Post(path, Headers(), params);
  15849. }
  15850. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  15851. ContentProvider content_provider,
  15852. const std::string &content_type,
  15853. UploadProgress progress) {
  15854. return Post(path, Headers(), content_length, std::move(content_provider),
  15855. content_type, progress);
  15856. }
  15857. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  15858. ContentProvider content_provider,
  15859. const std::string &content_type,
  15860. ContentReceiver content_receiver,
  15861. UploadProgress progress) {
  15862. return Post(path, Headers(), content_length, std::move(content_provider),
  15863. content_type, std::move(content_receiver), progress);
  15864. }
  15865. inline Result ClientImpl::Post(const std::string &path,
  15866. ContentProviderWithoutLength content_provider,
  15867. const std::string &content_type,
  15868. UploadProgress progress) {
  15869. return Post(path, Headers(), std::move(content_provider), content_type,
  15870. progress);
  15871. }
  15872. inline Result ClientImpl::Post(const std::string &path,
  15873. ContentProviderWithoutLength content_provider,
  15874. const std::string &content_type,
  15875. ContentReceiver content_receiver,
  15876. UploadProgress progress) {
  15877. return Post(path, Headers(), std::move(content_provider), content_type,
  15878. std::move(content_receiver), progress);
  15879. }
  15880. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15881. const Params &params) {
  15882. auto query = detail::params_to_query_str(params);
  15883. return Post(path, headers, query, "application/x-www-form-urlencoded");
  15884. }
  15885. inline Result ClientImpl::Post(const std::string &path,
  15886. const UploadFormDataItems &items,
  15887. UploadProgress progress) {
  15888. return Post(path, Headers(), items, progress);
  15889. }
  15890. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15891. const UploadFormDataItems &items,
  15892. UploadProgress progress) {
  15893. const auto &boundary = detail::make_multipart_data_boundary();
  15894. const auto &content_type =
  15895. detail::serialize_multipart_formdata_get_content_type(boundary);
  15896. auto content_length = detail::get_multipart_content_length(items, boundary);
  15897. return Post(path, headers, content_length,
  15898. detail::make_multipart_content_provider(items, boundary),
  15899. content_type, progress);
  15900. }
  15901. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15902. const UploadFormDataItems &items,
  15903. const std::string &boundary,
  15904. UploadProgress progress) {
  15905. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  15906. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  15907. }
  15908. const auto &content_type =
  15909. detail::serialize_multipart_formdata_get_content_type(boundary);
  15910. auto content_length = detail::get_multipart_content_length(items, boundary);
  15911. return Post(path, headers, content_length,
  15912. detail::make_multipart_content_provider(items, boundary),
  15913. content_type, progress);
  15914. }
  15915. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15916. const char *body, size_t content_length,
  15917. const std::string &content_type,
  15918. UploadProgress progress) {
  15919. return send_with_content_provider_and_receiver(
  15920. "POST", path, headers, body, content_length, nullptr, nullptr,
  15921. content_type, nullptr, progress);
  15922. }
  15923. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15924. const std::string &body,
  15925. const std::string &content_type,
  15926. UploadProgress progress) {
  15927. return send_with_content_provider_and_receiver(
  15928. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  15929. content_type, nullptr, progress);
  15930. }
  15931. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15932. size_t content_length,
  15933. ContentProvider content_provider,
  15934. const std::string &content_type,
  15935. UploadProgress progress) {
  15936. return send_with_content_provider_and_receiver(
  15937. "POST", path, headers, nullptr, content_length,
  15938. std::move(content_provider), nullptr, content_type, nullptr, progress);
  15939. }
  15940. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15941. size_t content_length,
  15942. ContentProvider content_provider,
  15943. const std::string &content_type,
  15944. ContentReceiver content_receiver,
  15945. DownloadProgress progress) {
  15946. return send_with_content_provider_and_receiver(
  15947. "POST", path, headers, nullptr, content_length,
  15948. std::move(content_provider), nullptr, content_type,
  15949. std::move(content_receiver), std::move(progress));
  15950. }
  15951. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15952. ContentProviderWithoutLength content_provider,
  15953. const std::string &content_type,
  15954. UploadProgress progress) {
  15955. return send_with_content_provider_and_receiver(
  15956. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  15957. content_type, nullptr, progress);
  15958. }
  15959. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15960. ContentProviderWithoutLength content_provider,
  15961. const std::string &content_type,
  15962. ContentReceiver content_receiver,
  15963. DownloadProgress progress) {
  15964. return send_with_content_provider_and_receiver(
  15965. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  15966. content_type, std::move(content_receiver), std::move(progress));
  15967. }
  15968. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15969. const UploadFormDataItems &items,
  15970. const FormDataProviderItems &provider_items,
  15971. UploadProgress progress) {
  15972. const auto &boundary = detail::make_multipart_data_boundary();
  15973. const auto &content_type =
  15974. detail::serialize_multipart_formdata_get_content_type(boundary);
  15975. return send_with_content_provider_and_receiver(
  15976. "POST", path, headers, nullptr, 0, nullptr,
  15977. get_multipart_content_provider(boundary, items, provider_items),
  15978. content_type, nullptr, progress);
  15979. }
  15980. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  15981. const std::string &body,
  15982. const std::string &content_type,
  15983. ContentReceiver content_receiver,
  15984. DownloadProgress progress) {
  15985. Request req;
  15986. req.method = "POST";
  15987. req.path = path;
  15988. req.headers = headers;
  15989. req.body = body;
  15990. req.content_receiver =
  15991. [content_receiver](const char *data, size_t data_length,
  15992. size_t /*offset*/, size_t /*total_length*/) {
  15993. return content_receiver(data, data_length);
  15994. };
  15995. req.download_progress = std::move(progress);
  15996. if (max_timeout_msec_ > 0) {
  15997. req.start_time_ = std::chrono::steady_clock::now();
  15998. }
  15999. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16000. return send_(std::move(req));
  16001. }
  16002. inline Result ClientImpl::Put(const std::string &path) {
  16003. return Put(path, std::string(), std::string());
  16004. }
  16005. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  16006. return Put(path, headers, nullptr, 0, std::string());
  16007. }
  16008. inline Result ClientImpl::Put(const std::string &path, const char *body,
  16009. size_t content_length,
  16010. const std::string &content_type,
  16011. UploadProgress progress) {
  16012. return Put(path, Headers(), body, content_length, content_type, progress);
  16013. }
  16014. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  16015. const std::string &content_type,
  16016. UploadProgress progress) {
  16017. return Put(path, Headers(), body, content_type, progress);
  16018. }
  16019. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  16020. return Put(path, Headers(), params);
  16021. }
  16022. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  16023. ContentProvider content_provider,
  16024. const std::string &content_type,
  16025. UploadProgress progress) {
  16026. return Put(path, Headers(), content_length, std::move(content_provider),
  16027. content_type, progress);
  16028. }
  16029. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  16030. ContentProvider content_provider,
  16031. const std::string &content_type,
  16032. ContentReceiver content_receiver,
  16033. UploadProgress progress) {
  16034. return Put(path, Headers(), content_length, std::move(content_provider),
  16035. content_type, std::move(content_receiver), progress);
  16036. }
  16037. inline Result ClientImpl::Put(const std::string &path,
  16038. ContentProviderWithoutLength content_provider,
  16039. const std::string &content_type,
  16040. UploadProgress progress) {
  16041. return Put(path, Headers(), std::move(content_provider), content_type,
  16042. progress);
  16043. }
  16044. inline Result ClientImpl::Put(const std::string &path,
  16045. ContentProviderWithoutLength content_provider,
  16046. const std::string &content_type,
  16047. ContentReceiver content_receiver,
  16048. UploadProgress progress) {
  16049. return Put(path, Headers(), std::move(content_provider), content_type,
  16050. std::move(content_receiver), progress);
  16051. }
  16052. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16053. const Params &params) {
  16054. auto query = detail::params_to_query_str(params);
  16055. return Put(path, headers, query, "application/x-www-form-urlencoded");
  16056. }
  16057. inline Result ClientImpl::Put(const std::string &path,
  16058. const UploadFormDataItems &items,
  16059. UploadProgress progress) {
  16060. return Put(path, Headers(), items, progress);
  16061. }
  16062. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16063. const UploadFormDataItems &items,
  16064. UploadProgress progress) {
  16065. const auto &boundary = detail::make_multipart_data_boundary();
  16066. const auto &content_type =
  16067. detail::serialize_multipart_formdata_get_content_type(boundary);
  16068. auto content_length = detail::get_multipart_content_length(items, boundary);
  16069. return Put(path, headers, content_length,
  16070. detail::make_multipart_content_provider(items, boundary),
  16071. content_type, progress);
  16072. }
  16073. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16074. const UploadFormDataItems &items,
  16075. const std::string &boundary,
  16076. UploadProgress progress) {
  16077. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  16078. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  16079. }
  16080. const auto &content_type =
  16081. detail::serialize_multipart_formdata_get_content_type(boundary);
  16082. auto content_length = detail::get_multipart_content_length(items, boundary);
  16083. return Put(path, headers, content_length,
  16084. detail::make_multipart_content_provider(items, boundary),
  16085. content_type, progress);
  16086. }
  16087. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16088. const char *body, size_t content_length,
  16089. const std::string &content_type,
  16090. UploadProgress progress) {
  16091. return send_with_content_provider_and_receiver(
  16092. "PUT", path, headers, body, content_length, nullptr, nullptr,
  16093. content_type, nullptr, progress);
  16094. }
  16095. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16096. const std::string &body,
  16097. const std::string &content_type,
  16098. UploadProgress progress) {
  16099. return send_with_content_provider_and_receiver(
  16100. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  16101. content_type, nullptr, progress);
  16102. }
  16103. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16104. size_t content_length,
  16105. ContentProvider content_provider,
  16106. const std::string &content_type,
  16107. UploadProgress progress) {
  16108. return send_with_content_provider_and_receiver(
  16109. "PUT", path, headers, nullptr, content_length,
  16110. std::move(content_provider), nullptr, content_type, nullptr, progress);
  16111. }
  16112. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16113. size_t content_length,
  16114. ContentProvider content_provider,
  16115. const std::string &content_type,
  16116. ContentReceiver content_receiver,
  16117. UploadProgress progress) {
  16118. return send_with_content_provider_and_receiver(
  16119. "PUT", path, headers, nullptr, content_length,
  16120. std::move(content_provider), nullptr, content_type,
  16121. std::move(content_receiver), progress);
  16122. }
  16123. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16124. ContentProviderWithoutLength content_provider,
  16125. const std::string &content_type,
  16126. UploadProgress progress) {
  16127. return send_with_content_provider_and_receiver(
  16128. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16129. content_type, nullptr, progress);
  16130. }
  16131. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16132. ContentProviderWithoutLength content_provider,
  16133. const std::string &content_type,
  16134. ContentReceiver content_receiver,
  16135. UploadProgress progress) {
  16136. return send_with_content_provider_and_receiver(
  16137. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16138. content_type, std::move(content_receiver), progress);
  16139. }
  16140. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16141. const UploadFormDataItems &items,
  16142. const FormDataProviderItems &provider_items,
  16143. UploadProgress progress) {
  16144. const auto &boundary = detail::make_multipart_data_boundary();
  16145. const auto &content_type =
  16146. detail::serialize_multipart_formdata_get_content_type(boundary);
  16147. return send_with_content_provider_and_receiver(
  16148. "PUT", path, headers, nullptr, 0, nullptr,
  16149. get_multipart_content_provider(boundary, items, provider_items),
  16150. content_type, nullptr, progress);
  16151. }
  16152. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  16153. const std::string &body,
  16154. const std::string &content_type,
  16155. ContentReceiver content_receiver,
  16156. DownloadProgress progress) {
  16157. Request req;
  16158. req.method = "PUT";
  16159. req.path = path;
  16160. req.headers = headers;
  16161. req.body = body;
  16162. req.content_receiver =
  16163. [content_receiver](const char *data, size_t data_length,
  16164. size_t /*offset*/, size_t /*total_length*/) {
  16165. return content_receiver(data, data_length);
  16166. };
  16167. req.download_progress = std::move(progress);
  16168. if (max_timeout_msec_ > 0) {
  16169. req.start_time_ = std::chrono::steady_clock::now();
  16170. }
  16171. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16172. return send_(std::move(req));
  16173. }
  16174. inline Result ClientImpl::Patch(const std::string &path) {
  16175. return Patch(path, std::string(), std::string());
  16176. }
  16177. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16178. UploadProgress progress) {
  16179. return Patch(path, headers, nullptr, 0, std::string(), progress);
  16180. }
  16181. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  16182. size_t content_length,
  16183. const std::string &content_type,
  16184. UploadProgress progress) {
  16185. return Patch(path, Headers(), body, content_length, content_type, progress);
  16186. }
  16187. inline Result ClientImpl::Patch(const std::string &path,
  16188. const std::string &body,
  16189. const std::string &content_type,
  16190. UploadProgress progress) {
  16191. return Patch(path, Headers(), body, content_type, progress);
  16192. }
  16193. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  16194. return Patch(path, Headers(), params);
  16195. }
  16196. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  16197. ContentProvider content_provider,
  16198. const std::string &content_type,
  16199. UploadProgress progress) {
  16200. return Patch(path, Headers(), content_length, std::move(content_provider),
  16201. content_type, progress);
  16202. }
  16203. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  16204. ContentProvider content_provider,
  16205. const std::string &content_type,
  16206. ContentReceiver content_receiver,
  16207. UploadProgress progress) {
  16208. return Patch(path, Headers(), content_length, std::move(content_provider),
  16209. content_type, std::move(content_receiver), progress);
  16210. }
  16211. inline Result ClientImpl::Patch(const std::string &path,
  16212. ContentProviderWithoutLength content_provider,
  16213. const std::string &content_type,
  16214. UploadProgress progress) {
  16215. return Patch(path, Headers(), std::move(content_provider), content_type,
  16216. progress);
  16217. }
  16218. inline Result ClientImpl::Patch(const std::string &path,
  16219. ContentProviderWithoutLength content_provider,
  16220. const std::string &content_type,
  16221. ContentReceiver content_receiver,
  16222. UploadProgress progress) {
  16223. return Patch(path, Headers(), std::move(content_provider), content_type,
  16224. std::move(content_receiver), progress);
  16225. }
  16226. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16227. const Params &params) {
  16228. auto query = detail::params_to_query_str(params);
  16229. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  16230. }
  16231. inline Result ClientImpl::Patch(const std::string &path,
  16232. const UploadFormDataItems &items,
  16233. UploadProgress progress) {
  16234. return Patch(path, Headers(), items, progress);
  16235. }
  16236. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16237. const UploadFormDataItems &items,
  16238. UploadProgress progress) {
  16239. const auto &boundary = detail::make_multipart_data_boundary();
  16240. const auto &content_type =
  16241. detail::serialize_multipart_formdata_get_content_type(boundary);
  16242. auto content_length = detail::get_multipart_content_length(items, boundary);
  16243. return Patch(path, headers, content_length,
  16244. detail::make_multipart_content_provider(items, boundary),
  16245. content_type, progress);
  16246. }
  16247. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16248. const UploadFormDataItems &items,
  16249. const std::string &boundary,
  16250. UploadProgress progress) {
  16251. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  16252. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  16253. }
  16254. const auto &content_type =
  16255. detail::serialize_multipart_formdata_get_content_type(boundary);
  16256. auto content_length = detail::get_multipart_content_length(items, boundary);
  16257. return Patch(path, headers, content_length,
  16258. detail::make_multipart_content_provider(items, boundary),
  16259. content_type, progress);
  16260. }
  16261. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16262. const char *body, size_t content_length,
  16263. const std::string &content_type,
  16264. UploadProgress progress) {
  16265. return send_with_content_provider_and_receiver(
  16266. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  16267. content_type, nullptr, progress);
  16268. }
  16269. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16270. const std::string &body,
  16271. const std::string &content_type,
  16272. UploadProgress progress) {
  16273. return send_with_content_provider_and_receiver(
  16274. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  16275. content_type, nullptr, progress);
  16276. }
  16277. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16278. size_t content_length,
  16279. ContentProvider content_provider,
  16280. const std::string &content_type,
  16281. UploadProgress progress) {
  16282. return send_with_content_provider_and_receiver(
  16283. "PATCH", path, headers, nullptr, content_length,
  16284. std::move(content_provider), nullptr, content_type, nullptr, progress);
  16285. }
  16286. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16287. size_t content_length,
  16288. ContentProvider content_provider,
  16289. const std::string &content_type,
  16290. ContentReceiver content_receiver,
  16291. UploadProgress progress) {
  16292. return send_with_content_provider_and_receiver(
  16293. "PATCH", path, headers, nullptr, content_length,
  16294. std::move(content_provider), nullptr, content_type,
  16295. std::move(content_receiver), progress);
  16296. }
  16297. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16298. ContentProviderWithoutLength content_provider,
  16299. const std::string &content_type,
  16300. UploadProgress progress) {
  16301. return send_with_content_provider_and_receiver(
  16302. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16303. content_type, nullptr, progress);
  16304. }
  16305. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16306. ContentProviderWithoutLength content_provider,
  16307. const std::string &content_type,
  16308. ContentReceiver content_receiver,
  16309. UploadProgress progress) {
  16310. return send_with_content_provider_and_receiver(
  16311. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  16312. content_type, std::move(content_receiver), progress);
  16313. }
  16314. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16315. const UploadFormDataItems &items,
  16316. const FormDataProviderItems &provider_items,
  16317. UploadProgress progress) {
  16318. const auto &boundary = detail::make_multipart_data_boundary();
  16319. const auto &content_type =
  16320. detail::serialize_multipart_formdata_get_content_type(boundary);
  16321. return send_with_content_provider_and_receiver(
  16322. "PATCH", path, headers, nullptr, 0, nullptr,
  16323. get_multipart_content_provider(boundary, items, provider_items),
  16324. content_type, nullptr, progress);
  16325. }
  16326. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  16327. const std::string &body,
  16328. const std::string &content_type,
  16329. ContentReceiver content_receiver,
  16330. DownloadProgress progress) {
  16331. Request req;
  16332. req.method = "PATCH";
  16333. req.path = path;
  16334. req.headers = headers;
  16335. req.body = body;
  16336. req.content_receiver =
  16337. [content_receiver](const char *data, size_t data_length,
  16338. size_t /*offset*/, size_t /*total_length*/) {
  16339. return content_receiver(data, data_length);
  16340. };
  16341. req.download_progress = std::move(progress);
  16342. if (max_timeout_msec_ > 0) {
  16343. req.start_time_ = std::chrono::steady_clock::now();
  16344. }
  16345. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16346. return send_(std::move(req));
  16347. }
  16348. inline Result ClientImpl::Delete(const std::string &path,
  16349. DownloadProgress progress) {
  16350. return Delete(path, Headers(), std::string(), std::string(), progress);
  16351. }
  16352. inline Result ClientImpl::Delete(const std::string &path,
  16353. const Headers &headers,
  16354. DownloadProgress progress) {
  16355. return Delete(path, headers, std::string(), std::string(), progress);
  16356. }
  16357. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  16358. size_t content_length,
  16359. const std::string &content_type,
  16360. DownloadProgress progress) {
  16361. return Delete(path, Headers(), body, content_length, content_type, progress);
  16362. }
  16363. inline Result ClientImpl::Delete(const std::string &path,
  16364. const std::string &body,
  16365. const std::string &content_type,
  16366. DownloadProgress progress) {
  16367. return Delete(path, Headers(), body.data(), body.size(), content_type,
  16368. progress);
  16369. }
  16370. inline Result ClientImpl::Delete(const std::string &path,
  16371. const Headers &headers,
  16372. const std::string &body,
  16373. const std::string &content_type,
  16374. DownloadProgress progress) {
  16375. return Delete(path, headers, body.data(), body.size(), content_type,
  16376. progress);
  16377. }
  16378. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  16379. DownloadProgress progress) {
  16380. return Delete(path, Headers(), params, progress);
  16381. }
  16382. inline Result ClientImpl::Delete(const std::string &path,
  16383. const Headers &headers, const Params &params,
  16384. DownloadProgress progress) {
  16385. auto query = detail::params_to_query_str(params);
  16386. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  16387. progress);
  16388. }
  16389. inline Result ClientImpl::Delete(const std::string &path,
  16390. const Headers &headers, const char *body,
  16391. size_t content_length,
  16392. const std::string &content_type,
  16393. DownloadProgress progress) {
  16394. Request req;
  16395. req.method = "DELETE";
  16396. req.headers = headers;
  16397. req.path = path;
  16398. req.download_progress = std::move(progress);
  16399. if (max_timeout_msec_ > 0) {
  16400. req.start_time_ = std::chrono::steady_clock::now();
  16401. }
  16402. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  16403. req.body.assign(body, content_length);
  16404. return send_(std::move(req));
  16405. }
  16406. inline Result ClientImpl::Options(const std::string &path) {
  16407. return Options(path, Headers());
  16408. }
  16409. inline Result ClientImpl::Options(const std::string &path,
  16410. const Headers &headers) {
  16411. Request req;
  16412. req.method = "OPTIONS";
  16413. req.headers = headers;
  16414. req.path = path;
  16415. if (max_timeout_msec_ > 0) {
  16416. req.start_time_ = std::chrono::steady_clock::now();
  16417. }
  16418. return send_(std::move(req));
  16419. }
  16420. inline void ClientImpl::stop() {
  16421. std::lock_guard<std::mutex> guard(socket_mutex_);
  16422. stop_requested_ = true;
  16423. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  16424. // do is to shutdown_socket, so that threads using this socket suddenly
  16425. // discover they can't read/write any more and error out. Everything else
  16426. // (closing the socket, shutting ssl down) is unsafe because these actions
  16427. // are not thread-safe.
  16428. if (socket_requests_in_flight_ > 0) {
  16429. shutdown_socket(socket_);
  16430. // Aside from that, we set a flag for the socket to be closed when we're
  16431. // done.
  16432. socket_should_be_closed_when_request_is_done_ = true;
  16433. return;
  16434. }
  16435. disconnect(/*gracefully=*/true);
  16436. }
  16437. inline std::string ClientImpl::host() const { return host_; }
  16438. inline int ClientImpl::port() const { return port_; }
  16439. inline size_t ClientImpl::is_socket_open() const {
  16440. std::lock_guard<std::mutex> guard(socket_mutex_);
  16441. return socket_.is_open();
  16442. }
  16443. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  16444. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  16445. connection_timeout_sec_ = sec;
  16446. connection_timeout_usec_ = usec;
  16447. }
  16448. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  16449. read_timeout_sec_ = sec;
  16450. read_timeout_usec_ = usec;
  16451. }
  16452. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  16453. write_timeout_sec_ = sec;
  16454. write_timeout_usec_ = usec;
  16455. }
  16456. inline void ClientImpl::set_max_timeout(time_t msec) {
  16457. max_timeout_msec_ = msec;
  16458. }
  16459. inline void ClientImpl::set_basic_auth(const std::string &username,
  16460. const std::string &password) {
  16461. basic_auth_username_ = username;
  16462. basic_auth_password_ = password;
  16463. }
  16464. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  16465. bearer_token_auth_token_ = token;
  16466. }
  16467. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  16468. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  16469. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  16470. inline void
  16471. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  16472. set_direct_hostname_addr_map(std::move(addr_map));
  16473. }
  16474. inline void ClientImpl::set_direct_hostname_addr_map(
  16475. std::map<std::string, std::string> addr_map) {
  16476. addr_map_ = std::move(addr_map);
  16477. }
  16478. inline void ClientImpl::set_tunnel_hostname_addr_map(
  16479. std::map<std::string, std::string> addr_map) {
  16480. tunnel_addr_map_ = std::move(addr_map);
  16481. }
  16482. inline void ClientImpl::set_default_headers(Headers headers) {
  16483. default_headers_ = std::move(headers);
  16484. }
  16485. inline void ClientImpl::set_header_writer(
  16486. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  16487. header_writer_ = writer;
  16488. }
  16489. inline void ClientImpl::set_address_family(int family) {
  16490. address_family_ = family;
  16491. }
  16492. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  16493. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  16494. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  16495. socket_options_ = std::move(socket_options);
  16496. }
  16497. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  16498. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  16499. inline void ClientImpl::set_payload_max_length(size_t length) {
  16500. payload_max_length_ = length;
  16501. has_payload_max_length_ = true;
  16502. }
  16503. inline void ClientImpl::set_interface(const std::string &intf) {
  16504. interface_ = intf;
  16505. }
  16506. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  16507. proxy_host_ = host;
  16508. proxy_port_ = port;
  16509. std::lock_guard<std::mutex> guard(socket_mutex_);
  16510. disconnect(/*gracefully=*/true);
  16511. }
  16512. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  16513. const std::string &password) {
  16514. proxy_basic_auth_username_ = username;
  16515. proxy_basic_auth_password_ = password;
  16516. }
  16517. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  16518. proxy_bearer_token_auth_token_ = token;
  16519. }
  16520. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  16521. no_proxy_entries_ = detail::parse_no_proxy_entries(patterns);
  16522. std::lock_guard<std::mutex> guard(socket_mutex_);
  16523. disconnect(/*gracefully=*/true);
  16524. }
  16525. #ifdef CPPHTTPLIB_SSL_ENABLED
  16526. inline void ClientImpl::set_digest_auth(const std::string &username,
  16527. const std::string &password) {
  16528. digest_auth_username_ = username;
  16529. digest_auth_password_ = password;
  16530. }
  16531. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  16532. const std::string &ca_cert_dir_path) {
  16533. ca_cert_file_path_ = ca_cert_file_path;
  16534. ca_cert_dir_path_ = ca_cert_dir_path;
  16535. }
  16536. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  16537. const std::string &password) {
  16538. proxy_digest_auth_username_ = username;
  16539. proxy_digest_auth_password_ = password;
  16540. }
  16541. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  16542. if (server_certificate_verification_ == enabled) { return; }
  16543. server_certificate_verification_ = enabled;
  16544. tls_settings_changed();
  16545. }
  16546. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  16547. if (server_hostname_verification_ == enabled) { return; }
  16548. server_hostname_verification_ = enabled;
  16549. tls_settings_changed();
  16550. }
  16551. inline void ClientImpl::enable_system_ca(bool enabled) {
  16552. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  16553. }
  16554. #endif
  16555. inline void ClientImpl::set_logger(Logger logger) {
  16556. logger_ = std::move(logger);
  16557. }
  16558. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  16559. error_logger_ = std::move(error_logger);
  16560. }
  16561. /*
  16562. * SSL/TLS Common Implementation
  16563. */
  16564. inline ClientConnection::~ClientConnection() {
  16565. #ifdef CPPHTTPLIB_SSL_ENABLED
  16566. if (session) {
  16567. tls::shutdown(session, true);
  16568. tls::free_session(session);
  16569. session = nullptr;
  16570. }
  16571. #endif
  16572. if (sock != INVALID_SOCKET) {
  16573. detail::close_socket(sock);
  16574. sock = INVALID_SOCKET;
  16575. }
  16576. }
  16577. // Universal client implementation
  16578. inline Client::Client(const std::string &scheme_host_port)
  16579. : Client(scheme_host_port, std::string(), std::string()) {}
  16580. inline Client::Client(const std::string &scheme_host_port,
  16581. const std::string &client_cert_path,
  16582. const std::string &client_key_path) {
  16583. detail::UrlComponents uc;
  16584. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  16585. auto &scheme = uc.scheme;
  16586. #ifdef CPPHTTPLIB_SSL_ENABLED
  16587. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  16588. #else
  16589. if (!scheme.empty() && scheme != "http") {
  16590. #endif
  16591. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  16592. std::string msg = "'" + scheme + "' scheme is not supported.";
  16593. throw std::invalid_argument(msg);
  16594. #endif
  16595. cli_ = detail::make_unique<detail::InvalidClientImpl>();
  16596. return;
  16597. }
  16598. auto is_ssl = scheme == "https";
  16599. auto host = std::move(uc.host);
  16600. auto port = is_ssl ? 443 : 80;
  16601. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) {
  16602. cli_ = detail::make_unique<detail::InvalidClientImpl>();
  16603. return;
  16604. }
  16605. if (is_ssl) {
  16606. #ifdef CPPHTTPLIB_SSL_ENABLED
  16607. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  16608. client_key_path);
  16609. is_ssl_ = is_ssl;
  16610. #endif
  16611. } else {
  16612. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  16613. client_key_path);
  16614. }
  16615. } else if (scheme_host_port.compare(0, 2, "//") == 0 ||
  16616. scheme_host_port.find("://") < scheme_host_port.find('/')) {
  16617. // A URL, but not one this client can use, such as one with userinfo. A
  16618. // Unix socket path may have "//" further on.
  16619. cli_ = detail::make_unique<detail::InvalidClientImpl>();
  16620. } else {
  16621. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  16622. // if port param below changes.
  16623. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  16624. client_cert_path, client_key_path);
  16625. }
  16626. }
  16627. inline Client::Client(const std::string &host, int port)
  16628. : Client(host, port, std::string(), std::string()) {}
  16629. inline Client::Client(const std::string &host, int port,
  16630. const std::string &client_cert_path,
  16631. const std::string &client_key_path)
  16632. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  16633. client_key_path)) {}
  16634. inline Client::~Client() = default;
  16635. inline bool Client::is_valid() const {
  16636. return cli_ != nullptr && cli_->is_valid();
  16637. }
  16638. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  16639. return cli_->Get(path, std::move(progress));
  16640. }
  16641. inline Result Client::Get(const std::string &path, const Headers &headers,
  16642. DownloadProgress progress) {
  16643. return cli_->Get(path, headers, std::move(progress));
  16644. }
  16645. inline Result Client::Get(const std::string &path,
  16646. ContentReceiver content_receiver,
  16647. DownloadProgress progress) {
  16648. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  16649. }
  16650. inline Result Client::Get(const std::string &path, const Headers &headers,
  16651. ContentReceiver content_receiver,
  16652. DownloadProgress progress) {
  16653. return cli_->Get(path, headers, std::move(content_receiver),
  16654. std::move(progress));
  16655. }
  16656. inline Result Client::Get(const std::string &path,
  16657. ResponseHandler response_handler,
  16658. ContentReceiver content_receiver,
  16659. DownloadProgress progress) {
  16660. return cli_->Get(path, std::move(response_handler),
  16661. std::move(content_receiver), std::move(progress));
  16662. }
  16663. inline Result Client::Get(const std::string &path, const Headers &headers,
  16664. ResponseHandler response_handler,
  16665. ContentReceiver content_receiver,
  16666. DownloadProgress progress) {
  16667. return cli_->Get(path, headers, std::move(response_handler),
  16668. std::move(content_receiver), std::move(progress));
  16669. }
  16670. inline Result Client::Get(const std::string &path, const Params &params,
  16671. DownloadProgress progress) {
  16672. return cli_->Get(path, params, std::move(progress));
  16673. }
  16674. inline Result Client::Get(const std::string &path, const Params &params,
  16675. const Headers &headers, DownloadProgress progress) {
  16676. return cli_->Get(path, params, headers, std::move(progress));
  16677. }
  16678. inline Result Client::Get(const std::string &path, const Params &params,
  16679. const Headers &headers,
  16680. ContentReceiver content_receiver,
  16681. DownloadProgress progress) {
  16682. return cli_->Get(path, params, headers, std::move(content_receiver),
  16683. std::move(progress));
  16684. }
  16685. inline Result Client::Get(const std::string &path, const Params &params,
  16686. const Headers &headers,
  16687. ResponseHandler response_handler,
  16688. ContentReceiver content_receiver,
  16689. DownloadProgress progress) {
  16690. return cli_->Get(path, params, headers, std::move(response_handler),
  16691. std::move(content_receiver), std::move(progress));
  16692. }
  16693. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  16694. inline Result Client::Head(const std::string &path, const Headers &headers) {
  16695. return cli_->Head(path, headers);
  16696. }
  16697. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  16698. inline Result Client::Post(const std::string &path, const Headers &headers) {
  16699. return cli_->Post(path, headers);
  16700. }
  16701. inline Result Client::Post(const std::string &path, const char *body,
  16702. size_t content_length,
  16703. const std::string &content_type,
  16704. UploadProgress progress) {
  16705. return cli_->Post(path, body, content_length, content_type, progress);
  16706. }
  16707. inline Result Client::Post(const std::string &path, const Headers &headers,
  16708. const char *body, size_t content_length,
  16709. const std::string &content_type,
  16710. UploadProgress progress) {
  16711. return cli_->Post(path, headers, body, content_length, content_type,
  16712. progress);
  16713. }
  16714. inline Result Client::Post(const std::string &path, const std::string &body,
  16715. const std::string &content_type,
  16716. UploadProgress progress) {
  16717. return cli_->Post(path, body, content_type, progress);
  16718. }
  16719. inline Result Client::Post(const std::string &path, const Headers &headers,
  16720. const std::string &body,
  16721. const std::string &content_type,
  16722. UploadProgress progress) {
  16723. return cli_->Post(path, headers, body, content_type, progress);
  16724. }
  16725. inline Result Client::Post(const std::string &path, size_t content_length,
  16726. ContentProvider content_provider,
  16727. const std::string &content_type,
  16728. UploadProgress progress) {
  16729. return cli_->Post(path, content_length, std::move(content_provider),
  16730. content_type, progress);
  16731. }
  16732. inline Result Client::Post(const std::string &path, size_t content_length,
  16733. ContentProvider content_provider,
  16734. const std::string &content_type,
  16735. ContentReceiver content_receiver,
  16736. UploadProgress progress) {
  16737. return cli_->Post(path, content_length, std::move(content_provider),
  16738. content_type, std::move(content_receiver), progress);
  16739. }
  16740. inline Result Client::Post(const std::string &path,
  16741. ContentProviderWithoutLength content_provider,
  16742. const std::string &content_type,
  16743. UploadProgress progress) {
  16744. return cli_->Post(path, std::move(content_provider), content_type, progress);
  16745. }
  16746. inline Result Client::Post(const std::string &path,
  16747. ContentProviderWithoutLength content_provider,
  16748. const std::string &content_type,
  16749. ContentReceiver content_receiver,
  16750. UploadProgress progress) {
  16751. return cli_->Post(path, std::move(content_provider), content_type,
  16752. std::move(content_receiver), progress);
  16753. }
  16754. inline Result Client::Post(const std::string &path, const Headers &headers,
  16755. size_t content_length,
  16756. ContentProvider content_provider,
  16757. const std::string &content_type,
  16758. UploadProgress progress) {
  16759. return cli_->Post(path, headers, content_length, std::move(content_provider),
  16760. content_type, progress);
  16761. }
  16762. inline Result Client::Post(const std::string &path, const Headers &headers,
  16763. size_t content_length,
  16764. ContentProvider content_provider,
  16765. const std::string &content_type,
  16766. ContentReceiver content_receiver,
  16767. DownloadProgress progress) {
  16768. return cli_->Post(path, headers, content_length, std::move(content_provider),
  16769. content_type, std::move(content_receiver), progress);
  16770. }
  16771. inline Result Client::Post(const std::string &path, const Headers &headers,
  16772. ContentProviderWithoutLength content_provider,
  16773. const std::string &content_type,
  16774. UploadProgress progress) {
  16775. return cli_->Post(path, headers, std::move(content_provider), content_type,
  16776. progress);
  16777. }
  16778. inline Result Client::Post(const std::string &path, const Headers &headers,
  16779. ContentProviderWithoutLength content_provider,
  16780. const std::string &content_type,
  16781. ContentReceiver content_receiver,
  16782. DownloadProgress progress) {
  16783. return cli_->Post(path, headers, std::move(content_provider), content_type,
  16784. std::move(content_receiver), progress);
  16785. }
  16786. inline Result Client::Post(const std::string &path, const Params &params) {
  16787. return cli_->Post(path, params);
  16788. }
  16789. inline Result Client::Post(const std::string &path, const Headers &headers,
  16790. const Params &params) {
  16791. return cli_->Post(path, headers, params);
  16792. }
  16793. inline Result Client::Post(const std::string &path,
  16794. const UploadFormDataItems &items,
  16795. UploadProgress progress) {
  16796. return cli_->Post(path, items, progress);
  16797. }
  16798. inline Result Client::Post(const std::string &path, const Headers &headers,
  16799. const UploadFormDataItems &items,
  16800. UploadProgress progress) {
  16801. return cli_->Post(path, headers, items, progress);
  16802. }
  16803. inline Result Client::Post(const std::string &path, const Headers &headers,
  16804. const UploadFormDataItems &items,
  16805. const std::string &boundary,
  16806. UploadProgress progress) {
  16807. return cli_->Post(path, headers, items, boundary, progress);
  16808. }
  16809. inline Result Client::Post(const std::string &path, const Headers &headers,
  16810. const UploadFormDataItems &items,
  16811. const FormDataProviderItems &provider_items,
  16812. UploadProgress progress) {
  16813. return cli_->Post(path, headers, items, provider_items, progress);
  16814. }
  16815. inline Result Client::Post(const std::string &path, const Headers &headers,
  16816. const std::string &body,
  16817. const std::string &content_type,
  16818. ContentReceiver content_receiver,
  16819. DownloadProgress progress) {
  16820. return cli_->Post(path, headers, body, content_type,
  16821. std::move(content_receiver), progress);
  16822. }
  16823. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  16824. inline Result Client::Put(const std::string &path, const Headers &headers) {
  16825. return cli_->Put(path, headers);
  16826. }
  16827. inline Result Client::Put(const std::string &path, const char *body,
  16828. size_t content_length,
  16829. const std::string &content_type,
  16830. UploadProgress progress) {
  16831. return cli_->Put(path, body, content_length, content_type, progress);
  16832. }
  16833. inline Result Client::Put(const std::string &path, const Headers &headers,
  16834. const char *body, size_t content_length,
  16835. const std::string &content_type,
  16836. UploadProgress progress) {
  16837. return cli_->Put(path, headers, body, content_length, content_type, progress);
  16838. }
  16839. inline Result Client::Put(const std::string &path, const std::string &body,
  16840. const std::string &content_type,
  16841. UploadProgress progress) {
  16842. return cli_->Put(path, body, content_type, progress);
  16843. }
  16844. inline Result Client::Put(const std::string &path, const Headers &headers,
  16845. const std::string &body,
  16846. const std::string &content_type,
  16847. UploadProgress progress) {
  16848. return cli_->Put(path, headers, body, content_type, progress);
  16849. }
  16850. inline Result Client::Put(const std::string &path, size_t content_length,
  16851. ContentProvider content_provider,
  16852. const std::string &content_type,
  16853. UploadProgress progress) {
  16854. return cli_->Put(path, content_length, std::move(content_provider),
  16855. content_type, progress);
  16856. }
  16857. inline Result Client::Put(const std::string &path, size_t content_length,
  16858. ContentProvider content_provider,
  16859. const std::string &content_type,
  16860. ContentReceiver content_receiver,
  16861. UploadProgress progress) {
  16862. return cli_->Put(path, content_length, std::move(content_provider),
  16863. content_type, std::move(content_receiver), progress);
  16864. }
  16865. inline Result Client::Put(const std::string &path,
  16866. ContentProviderWithoutLength content_provider,
  16867. const std::string &content_type,
  16868. UploadProgress progress) {
  16869. return cli_->Put(path, std::move(content_provider), content_type, progress);
  16870. }
  16871. inline Result Client::Put(const std::string &path,
  16872. ContentProviderWithoutLength content_provider,
  16873. const std::string &content_type,
  16874. ContentReceiver content_receiver,
  16875. UploadProgress progress) {
  16876. return cli_->Put(path, std::move(content_provider), content_type,
  16877. std::move(content_receiver), progress);
  16878. }
  16879. inline Result Client::Put(const std::string &path, const Headers &headers,
  16880. size_t content_length,
  16881. ContentProvider content_provider,
  16882. const std::string &content_type,
  16883. UploadProgress progress) {
  16884. return cli_->Put(path, headers, content_length, std::move(content_provider),
  16885. content_type, progress);
  16886. }
  16887. inline Result Client::Put(const std::string &path, const Headers &headers,
  16888. size_t content_length,
  16889. ContentProvider content_provider,
  16890. const std::string &content_type,
  16891. ContentReceiver content_receiver,
  16892. UploadProgress progress) {
  16893. return cli_->Put(path, headers, content_length, std::move(content_provider),
  16894. content_type, std::move(content_receiver), progress);
  16895. }
  16896. inline Result Client::Put(const std::string &path, const Headers &headers,
  16897. ContentProviderWithoutLength content_provider,
  16898. const std::string &content_type,
  16899. UploadProgress progress) {
  16900. return cli_->Put(path, headers, std::move(content_provider), content_type,
  16901. progress);
  16902. }
  16903. inline Result Client::Put(const std::string &path, const Headers &headers,
  16904. ContentProviderWithoutLength content_provider,
  16905. const std::string &content_type,
  16906. ContentReceiver content_receiver,
  16907. UploadProgress progress) {
  16908. return cli_->Put(path, headers, std::move(content_provider), content_type,
  16909. std::move(content_receiver), progress);
  16910. }
  16911. inline Result Client::Put(const std::string &path, const Params &params) {
  16912. return cli_->Put(path, params);
  16913. }
  16914. inline Result Client::Put(const std::string &path, const Headers &headers,
  16915. const Params &params) {
  16916. return cli_->Put(path, headers, params);
  16917. }
  16918. inline Result Client::Put(const std::string &path,
  16919. const UploadFormDataItems &items,
  16920. UploadProgress progress) {
  16921. return cli_->Put(path, items, progress);
  16922. }
  16923. inline Result Client::Put(const std::string &path, const Headers &headers,
  16924. const UploadFormDataItems &items,
  16925. UploadProgress progress) {
  16926. return cli_->Put(path, headers, items, progress);
  16927. }
  16928. inline Result Client::Put(const std::string &path, const Headers &headers,
  16929. const UploadFormDataItems &items,
  16930. const std::string &boundary,
  16931. UploadProgress progress) {
  16932. return cli_->Put(path, headers, items, boundary, progress);
  16933. }
  16934. inline Result Client::Put(const std::string &path, const Headers &headers,
  16935. const UploadFormDataItems &items,
  16936. const FormDataProviderItems &provider_items,
  16937. UploadProgress progress) {
  16938. return cli_->Put(path, headers, items, provider_items, progress);
  16939. }
  16940. inline Result Client::Put(const std::string &path, const Headers &headers,
  16941. const std::string &body,
  16942. const std::string &content_type,
  16943. ContentReceiver content_receiver,
  16944. DownloadProgress progress) {
  16945. return cli_->Put(path, headers, body, content_type, content_receiver,
  16946. progress);
  16947. }
  16948. inline Result Client::Patch(const std::string &path) {
  16949. return cli_->Patch(path);
  16950. }
  16951. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  16952. return cli_->Patch(path, headers);
  16953. }
  16954. inline Result Client::Patch(const std::string &path, const char *body,
  16955. size_t content_length,
  16956. const std::string &content_type,
  16957. UploadProgress progress) {
  16958. return cli_->Patch(path, body, content_length, content_type, progress);
  16959. }
  16960. inline Result Client::Patch(const std::string &path, const Headers &headers,
  16961. const char *body, size_t content_length,
  16962. const std::string &content_type,
  16963. UploadProgress progress) {
  16964. return cli_->Patch(path, headers, body, content_length, content_type,
  16965. progress);
  16966. }
  16967. inline Result Client::Patch(const std::string &path, const std::string &body,
  16968. const std::string &content_type,
  16969. UploadProgress progress) {
  16970. return cli_->Patch(path, body, content_type, progress);
  16971. }
  16972. inline Result Client::Patch(const std::string &path, const Headers &headers,
  16973. const std::string &body,
  16974. const std::string &content_type,
  16975. UploadProgress progress) {
  16976. return cli_->Patch(path, headers, body, content_type, progress);
  16977. }
  16978. inline Result Client::Patch(const std::string &path, size_t content_length,
  16979. ContentProvider content_provider,
  16980. const std::string &content_type,
  16981. UploadProgress progress) {
  16982. return cli_->Patch(path, content_length, std::move(content_provider),
  16983. content_type, progress);
  16984. }
  16985. inline Result Client::Patch(const std::string &path, size_t content_length,
  16986. ContentProvider content_provider,
  16987. const std::string &content_type,
  16988. ContentReceiver content_receiver,
  16989. UploadProgress progress) {
  16990. return cli_->Patch(path, content_length, std::move(content_provider),
  16991. content_type, std::move(content_receiver), progress);
  16992. }
  16993. inline Result Client::Patch(const std::string &path,
  16994. ContentProviderWithoutLength content_provider,
  16995. const std::string &content_type,
  16996. UploadProgress progress) {
  16997. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  16998. }
  16999. inline Result Client::Patch(const std::string &path,
  17000. ContentProviderWithoutLength content_provider,
  17001. const std::string &content_type,
  17002. ContentReceiver content_receiver,
  17003. UploadProgress progress) {
  17004. return cli_->Patch(path, std::move(content_provider), content_type,
  17005. std::move(content_receiver), progress);
  17006. }
  17007. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17008. size_t content_length,
  17009. ContentProvider content_provider,
  17010. const std::string &content_type,
  17011. UploadProgress progress) {
  17012. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  17013. content_type, progress);
  17014. }
  17015. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17016. size_t content_length,
  17017. ContentProvider content_provider,
  17018. const std::string &content_type,
  17019. ContentReceiver content_receiver,
  17020. UploadProgress progress) {
  17021. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  17022. content_type, std::move(content_receiver), progress);
  17023. }
  17024. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17025. ContentProviderWithoutLength content_provider,
  17026. const std::string &content_type,
  17027. UploadProgress progress) {
  17028. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  17029. progress);
  17030. }
  17031. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17032. ContentProviderWithoutLength content_provider,
  17033. const std::string &content_type,
  17034. ContentReceiver content_receiver,
  17035. UploadProgress progress) {
  17036. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  17037. std::move(content_receiver), progress);
  17038. }
  17039. inline Result Client::Patch(const std::string &path, const Params &params) {
  17040. return cli_->Patch(path, params);
  17041. }
  17042. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17043. const Params &params) {
  17044. return cli_->Patch(path, headers, params);
  17045. }
  17046. inline Result Client::Patch(const std::string &path,
  17047. const UploadFormDataItems &items,
  17048. UploadProgress progress) {
  17049. return cli_->Patch(path, items, progress);
  17050. }
  17051. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17052. const UploadFormDataItems &items,
  17053. UploadProgress progress) {
  17054. return cli_->Patch(path, headers, items, progress);
  17055. }
  17056. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17057. const UploadFormDataItems &items,
  17058. const std::string &boundary,
  17059. UploadProgress progress) {
  17060. return cli_->Patch(path, headers, items, boundary, progress);
  17061. }
  17062. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17063. const UploadFormDataItems &items,
  17064. const FormDataProviderItems &provider_items,
  17065. UploadProgress progress) {
  17066. return cli_->Patch(path, headers, items, provider_items, progress);
  17067. }
  17068. inline Result Client::Patch(const std::string &path, const Headers &headers,
  17069. const std::string &body,
  17070. const std::string &content_type,
  17071. ContentReceiver content_receiver,
  17072. DownloadProgress progress) {
  17073. return cli_->Patch(path, headers, body, content_type, content_receiver,
  17074. progress);
  17075. }
  17076. inline Result Client::Delete(const std::string &path,
  17077. DownloadProgress progress) {
  17078. return cli_->Delete(path, progress);
  17079. }
  17080. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17081. DownloadProgress progress) {
  17082. return cli_->Delete(path, headers, progress);
  17083. }
  17084. inline Result Client::Delete(const std::string &path, const char *body,
  17085. size_t content_length,
  17086. const std::string &content_type,
  17087. DownloadProgress progress) {
  17088. return cli_->Delete(path, body, content_length, content_type, progress);
  17089. }
  17090. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17091. const char *body, size_t content_length,
  17092. const std::string &content_type,
  17093. DownloadProgress progress) {
  17094. return cli_->Delete(path, headers, body, content_length, content_type,
  17095. progress);
  17096. }
  17097. inline Result Client::Delete(const std::string &path, const std::string &body,
  17098. const std::string &content_type,
  17099. DownloadProgress progress) {
  17100. return cli_->Delete(path, body, content_type, progress);
  17101. }
  17102. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17103. const std::string &body,
  17104. const std::string &content_type,
  17105. DownloadProgress progress) {
  17106. return cli_->Delete(path, headers, body, content_type, progress);
  17107. }
  17108. inline Result Client::Delete(const std::string &path, const Params &params,
  17109. DownloadProgress progress) {
  17110. return cli_->Delete(path, params, progress);
  17111. }
  17112. inline Result Client::Delete(const std::string &path, const Headers &headers,
  17113. const Params &params, DownloadProgress progress) {
  17114. return cli_->Delete(path, headers, params, progress);
  17115. }
  17116. inline Result Client::Options(const std::string &path) {
  17117. return cli_->Options(path);
  17118. }
  17119. inline Result Client::Options(const std::string &path, const Headers &headers) {
  17120. return cli_->Options(path, headers);
  17121. }
  17122. inline ClientImpl::StreamHandle
  17123. Client::open_stream(const std::string &method, const std::string &path,
  17124. const Params &params, const Headers &headers,
  17125. const std::string &body, const std::string &content_type) {
  17126. return cli_->open_stream(method, path, params, headers, body, content_type);
  17127. }
  17128. inline bool Client::send(Request &req, Response &res, Error &error) {
  17129. return cli_->send(req, res, error);
  17130. }
  17131. inline Result Client::send(const Request &req) { return cli_->send(req); }
  17132. inline void Client::stop() { cli_->stop(); }
  17133. inline std::string Client::host() const { return cli_->host(); }
  17134. inline int Client::port() const { return cli_->port(); }
  17135. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  17136. inline socket_t Client::socket() const { return cli_->socket(); }
  17137. inline void
  17138. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  17139. cli_->set_direct_hostname_addr_map(std::move(addr_map));
  17140. }
  17141. inline void Client::set_direct_hostname_addr_map(
  17142. std::map<std::string, std::string> addr_map) {
  17143. cli_->set_direct_hostname_addr_map(std::move(addr_map));
  17144. }
  17145. inline void Client::set_tunnel_hostname_addr_map(
  17146. std::map<std::string, std::string> addr_map) {
  17147. cli_->set_tunnel_hostname_addr_map(std::move(addr_map));
  17148. }
  17149. inline void Client::set_default_headers(Headers headers) {
  17150. cli_->set_default_headers(std::move(headers));
  17151. }
  17152. inline void Client::set_header_writer(
  17153. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  17154. cli_->set_header_writer(writer);
  17155. }
  17156. inline void Client::set_address_family(int family) {
  17157. cli_->set_address_family(family);
  17158. }
  17159. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  17160. inline void Client::set_socket_options(SocketOptions socket_options) {
  17161. cli_->set_socket_options(std::move(socket_options));
  17162. }
  17163. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  17164. cli_->set_connection_timeout(sec, usec);
  17165. }
  17166. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  17167. cli_->set_read_timeout(sec, usec);
  17168. }
  17169. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  17170. cli_->set_write_timeout(sec, usec);
  17171. }
  17172. inline void Client::set_basic_auth(const std::string &username,
  17173. const std::string &password) {
  17174. cli_->set_basic_auth(username, password);
  17175. }
  17176. inline void Client::set_bearer_token_auth(const std::string &token) {
  17177. cli_->set_bearer_token_auth(token);
  17178. }
  17179. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  17180. inline void Client::set_follow_location(bool on) {
  17181. cli_->set_follow_location(on);
  17182. }
  17183. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  17184. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  17185. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  17186. inline void Client::set_payload_max_length(size_t length) {
  17187. cli_->set_payload_max_length(length);
  17188. }
  17189. inline void Client::set_interface(const std::string &intf) {
  17190. cli_->set_interface(intf);
  17191. }
  17192. inline void Client::set_proxy(const std::string &host, int port) {
  17193. cli_->set_proxy(host, port);
  17194. }
  17195. inline void Client::set_proxy_basic_auth(const std::string &username,
  17196. const std::string &password) {
  17197. cli_->set_proxy_basic_auth(username, password);
  17198. }
  17199. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  17200. cli_->set_proxy_bearer_token_auth(token);
  17201. }
  17202. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  17203. cli_->set_no_proxy(patterns);
  17204. }
  17205. inline void Client::set_logger(Logger logger) {
  17206. cli_->set_logger(std::move(logger));
  17207. }
  17208. inline void Client::set_error_logger(ErrorLogger error_logger) {
  17209. cli_->set_error_logger(std::move(error_logger));
  17210. }
  17211. /*
  17212. * Group 6: SSL Server and Client implementation
  17213. */
  17214. #ifdef CPPHTTPLIB_SSL_ENABLED
  17215. // SSL HTTP server implementation
  17216. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  17217. const char *client_ca_cert_file_path,
  17218. const char *client_ca_cert_dir_path,
  17219. const char *private_key_password) {
  17220. using namespace tls;
  17221. ctx_ = create_server_context();
  17222. if (!ctx_) { return; }
  17223. // Load server certificate and private key
  17224. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  17225. private_key_password)) {
  17226. last_ssl_error_ = static_cast<int>(get_error());
  17227. free_context(ctx_);
  17228. ctx_ = nullptr;
  17229. return;
  17230. }
  17231. // Load client CA certificates for client authentication
  17232. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  17233. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  17234. client_ca_cert_dir_path)) {
  17235. last_ssl_error_ = static_cast<int>(get_error());
  17236. free_context(ctx_);
  17237. ctx_ = nullptr;
  17238. return;
  17239. }
  17240. // Enable client certificate verification
  17241. set_verify_client(ctx_, true);
  17242. }
  17243. }
  17244. inline SSLServer::SSLServer(const PemMemory &pem) {
  17245. using namespace tls;
  17246. ctx_ = create_server_context();
  17247. if (ctx_) {
  17248. std::string cert_buf, key_buf;
  17249. if (!set_server_cert_pem(
  17250. ctx_, detail::pem_c_str(pem.cert_pem, pem.cert_pem_len, cert_buf),
  17251. detail::pem_c_str(pem.key_pem, pem.key_pem_len, key_buf),
  17252. pem.private_key_password)) {
  17253. last_ssl_error_ = static_cast<int>(get_error());
  17254. free_context(ctx_);
  17255. ctx_ = nullptr;
  17256. } else if (pem.client_ca_pem) {
  17257. auto ca_len = pem.client_ca_pem_len ? pem.client_ca_pem_len
  17258. : strlen(pem.client_ca_pem);
  17259. if (!load_ca_pem(ctx_, pem.client_ca_pem, ca_len)) {
  17260. last_ssl_error_ = static_cast<int>(get_error());
  17261. free_context(ctx_);
  17262. ctx_ = nullptr;
  17263. } else {
  17264. set_verify_client(ctx_, true);
  17265. }
  17266. }
  17267. }
  17268. }
  17269. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  17270. using namespace tls;
  17271. ctx_ = create_server_context();
  17272. if (ctx_) {
  17273. if (!setup_callback(ctx_)) {
  17274. free_context(ctx_);
  17275. ctx_ = nullptr;
  17276. }
  17277. }
  17278. }
  17279. inline SSLServer::~SSLServer() {
  17280. if (ctx_) { tls::free_context(ctx_); }
  17281. }
  17282. inline bool SSLServer::is_valid() const {
  17283. return ctx_ != nullptr && Server::is_valid();
  17284. }
  17285. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17286. namespace detail {
  17287. // Before these, SSL_free_buffers() could free a buffer that a record whose
  17288. // body has not arrived yet still uses (CVE-2024-4741). `version` is
  17289. // OpenSSL_version_num().
  17290. inline bool ssl_free_buffers_is_safe(unsigned long version) {
  17291. if (version >= 0x30400000UL) { return true; }
  17292. if (version >= 0x30300000UL) { return version >= 0x30300010UL; } // 3.3.1
  17293. if (version >= 0x30200000UL) { return version >= 0x30200020UL; } // 3.2.2
  17294. if (version >= 0x30100000UL) { return version >= 0x30100060UL; } // 3.1.6
  17295. return version >= 0x300000e0UL; // 3.0.14
  17296. }
  17297. } // namespace detail
  17298. #endif
  17299. // A connection that keep-alive parking keeps for SSLServer. The worker that
  17300. // first resumes it runs the handshake, so one that has not sent its
  17301. // ClientHello yet waits in the event loop like an idle connection.
  17302. struct SSLServer::TlsConnection final : Server::KeepAliveConnection {
  17303. TlsConnection(socket_t s, SSLServer &server)
  17304. : KeepAliveConnection(s, server), ssl_svr(server) {}
  17305. ~TlsConnection() override { tls::free_session(session); }
  17306. bool open() override {
  17307. // A handshake would hold up the stop() that is under way.
  17308. if (ssl_svr.is_stopping()) { return false; }
  17309. session = ssl_svr.start_session(sock);
  17310. if (!session) { return false; }
  17311. // The handshake has read what the event loop saw, so a client that sends
  17312. // nothing after it is parked instead of being waited for.
  17313. turn.woken = false;
  17314. return true;
  17315. }
  17316. // The session, not the stream, holds what a pipelined request has left.
  17317. bool serve() override {
  17318. detail::SSLSocketStream strm(
  17319. sock, session, ssl_svr.read_timeout_sec_, ssl_svr.read_timeout_usec_,
  17320. ssl_svr.write_timeout_sec_, ssl_svr.write_timeout_usec_);
  17321. return serve_on(strm, [this](Request &req) { req.ssl = session; });
  17322. }
  17323. void release_buffers() override {
  17324. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  17325. !defined(LIBRESSL_VERSION_NUMBER)
  17326. // The record buffers are most of an idle session's memory, and the next
  17327. // read makes new ones. The library that runs decides whether that is safe.
  17328. static const auto safe =
  17329. detail::ssl_free_buffers_is_safe(OpenSSL_version_num());
  17330. if (safe) { SSL_free_buffers(static_cast<SSL *>(session)); }
  17331. #endif
  17332. }
  17333. void shut_down(bool graceful) override { tls::shutdown(session, graceful); }
  17334. SSLServer &ssl_svr;
  17335. tls::session_t session = nullptr;
  17336. };
  17337. inline std::shared_ptr<Server::KeepAliveConnection>
  17338. SSLServer::new_keep_alive_connection(socket_t sock) {
  17339. return std::make_shared<TlsConnection>(sock, *this);
  17340. }
  17341. inline tls::session_t SSLServer::start_session(socket_t sock) {
  17342. using namespace tls;
  17343. session_t session = nullptr;
  17344. {
  17345. std::unique_lock<std::mutex> lock(ctx_mutex_);
  17346. ctx_cv_.wait(lock, [&] { return updates_pending_ == 0; });
  17347. session = create_session(static_cast<ctx_t>(ctx_), sock);
  17348. if (session) { handshakes_in_progress_++; }
  17349. }
  17350. if (!session) {
  17351. last_ssl_error_ = static_cast<int>(get_error());
  17352. return nullptr;
  17353. }
  17354. // Frees the session on all paths but success (including exceptions)
  17355. auto accepted = false;
  17356. auto cleanup = detail::scope_exit([&] {
  17357. if (!accepted) { free_session(session); }
  17358. });
  17359. // Perform TLS accept handshake with timeout
  17360. TlsError tls_err;
  17361. {
  17362. auto handshake_left = detail::scope_exit([&] {
  17363. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17364. if (--handshakes_in_progress_ == 0) { ctx_cv_.notify_all(); }
  17365. });
  17366. accepted = accept_nonblocking(session, sock, read_timeout_sec_,
  17367. read_timeout_usec_, &tls_err);
  17368. }
  17369. if (!accepted) {
  17370. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17371. // Map TlsError to legacy ssl_error for backward compatibility
  17372. if (tls_err.code == ErrorCode::WantRead) {
  17373. last_ssl_error_ = SSL_ERROR_WANT_READ;
  17374. } else if (tls_err.code == ErrorCode::WantWrite) {
  17375. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  17376. } else {
  17377. last_ssl_error_ = SSL_ERROR_SSL;
  17378. }
  17379. #else
  17380. last_ssl_error_ = static_cast<int>(get_error());
  17381. #endif
  17382. return nullptr;
  17383. }
  17384. return session;
  17385. }
  17386. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  17387. auto session = start_session(sock);
  17388. if (!session) {
  17389. detail::shutdown_socket(sock);
  17390. detail::close_socket(sock);
  17391. return false;
  17392. }
  17393. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  17394. bool ret = false;
  17395. bool websocket_upgraded = false;
  17396. auto cleanup = detail::scope_exit([&] {
  17397. tls::shutdown(session, !websocket_upgraded && ret);
  17398. tls::free_session(session);
  17399. detail::drain_and_close_socket(sock);
  17400. });
  17401. std::string remote_addr;
  17402. int remote_port = 0;
  17403. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  17404. std::string local_addr;
  17405. int local_port = 0;
  17406. detail::get_local_ip_and_port(sock, local_addr, local_port);
  17407. ret = serve_guarded([&]() {
  17408. return detail::process_server_socket_ssl(
  17409. svr_sock_, session, sock, keep_alive_max_count_,
  17410. keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
  17411. write_timeout_sec_, write_timeout_usec_,
  17412. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  17413. return process_request(
  17414. strm, remote_addr, remote_port, local_addr, local_port,
  17415. close_connection, connection_closed,
  17416. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  17417. });
  17418. });
  17419. return ret;
  17420. }
  17421. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  17422. const char *key_pem,
  17423. const char *client_ca_pem,
  17424. const char *password) {
  17425. if (!ctx_) { return false; }
  17426. std::unique_lock<std::mutex> lock(ctx_mutex_);
  17427. updates_pending_++;
  17428. auto se = detail::scope_exit([&] {
  17429. if (--updates_pending_ == 0) { ctx_cv_.notify_all(); }
  17430. });
  17431. ctx_cv_.wait(lock, [&] { return handshakes_in_progress_ == 0; });
  17432. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  17433. return false;
  17434. }
  17435. if (client_ca_pem) {
  17436. if (!tls::update_server_client_ca(ctx_, client_ca_pem)) { return false; }
  17437. // As in the constructors, a client CA makes client certificates required
  17438. tls::set_verify_client(ctx_, true);
  17439. }
  17440. return true;
  17441. }
  17442. // SSL HTTP client implementation
  17443. inline SSLClient::~SSLClient() {
  17444. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  17445. // base function rather than the derived function once we get to the
  17446. // base class destructor, and won't free the SSL (causing a leak).
  17447. // This must happen before the context is freed below: some backends
  17448. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  17449. // context, so freeing the context first leaves close_notify reading
  17450. // freed memory.
  17451. shutdown_ssl_impl(socket_, true);
  17452. if (ctx_) {
  17453. tls::free_context(ctx_);
  17454. ctx_ = nullptr;
  17455. }
  17456. }
  17457. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  17458. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  17459. shutdown_ssl_impl(socket, shutdown_gracefully);
  17460. }
  17461. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  17462. bool shutdown_gracefully) {
  17463. if (socket.sock == INVALID_SOCKET) {
  17464. assert(socket.ssl == nullptr);
  17465. return;
  17466. }
  17467. if (socket.ssl) {
  17468. tls::shutdown(socket.ssl, shutdown_gracefully);
  17469. {
  17470. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17471. tls::free_session(socket.ssl);
  17472. }
  17473. socket.ssl = nullptr;
  17474. }
  17475. assert(socket.ssl == nullptr);
  17476. }
  17477. inline bool SSLClient::process_socket(
  17478. const Socket &socket,
  17479. std::chrono::time_point<std::chrono::steady_clock> start_time,
  17480. std::function<bool(Stream &strm)> callback) {
  17481. assert(socket.ssl);
  17482. return detail::process_client_socket_ssl(
  17483. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  17484. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  17485. [&](detail::SSLSocketStream &strm) {
  17486. auto ret = callback(strm);
  17487. // A request that failed after the handshake reports Error::Read or
  17488. // Error::Write; keep the TLS error behind it, such as a fatal alert
  17489. // from the server, for Result::ssl_error() and ssl_backend_error()
  17490. const auto &tls_error = strm.tls_error();
  17491. if (!ret && tls_error.code != tls::ErrorCode::Success) {
  17492. last_ssl_error_ = static_cast<int>(tls_error.code);
  17493. last_backend_error_ = tls_error.backend_code;
  17494. }
  17495. return ret;
  17496. });
  17497. }
  17498. inline bool SSLClient::is_ssl() const { return true; }
  17499. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  17500. if (!is_valid()) {
  17501. error = Error::SSLConnection;
  17502. return false;
  17503. }
  17504. return ClientImpl::create_and_connect_socket(socket, error);
  17505. }
  17506. inline bool SSLClient::setup_proxy_connection(
  17507. Socket &socket,
  17508. std::chrono::time_point<std::chrono::steady_clock> start_time,
  17509. Response &res, bool &success, Error &error) {
  17510. if (!is_proxy_enabled_for_host(host_)) { return true; }
  17511. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  17512. return false;
  17513. }
  17514. if (!initialize_ssl(socket, error)) {
  17515. shutdown_socket(socket);
  17516. close_socket(socket);
  17517. success = false;
  17518. return false;
  17519. }
  17520. return true;
  17521. }
  17522. // Assumes that socket is a connection being opened, which no other thread uses
  17523. inline bool SSLClient::connect_with_proxy(
  17524. Socket &socket,
  17525. std::chrono::time_point<std::chrono::steady_clock> start_time,
  17526. Response &res, bool &success, Error &error) {
  17527. success = true;
  17528. auto connect_target =
  17529. detail::make_connect_request_target(tunnel_addr_map_, host_, port_);
  17530. auto retargeted = connect_target !=
  17531. detail::make_host_and_port_string_always_port(host_, port_);
  17532. Response proxy_res;
  17533. if (!detail::process_client_socket(
  17534. socket.sock, read_timeout_sec_, read_timeout_usec_,
  17535. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  17536. start_time, [&](Stream &strm) {
  17537. strm.set_read_interrupt(stop_interrupt());
  17538. Request req2;
  17539. req2.method = "CONNECT";
  17540. req2.path = connect_target;
  17541. if (retargeted) { req2.set_header("Host", connect_target); }
  17542. if (max_timeout_msec_ > 0) {
  17543. req2.start_time_ = std::chrono::steady_clock::now();
  17544. }
  17545. return process_request(strm, req2, proxy_res, false, error);
  17546. })) {
  17547. // Thread-safe to close everything because we are assuming there are no
  17548. // requests in flight
  17549. shutdown_ssl(socket, true);
  17550. shutdown_socket(socket);
  17551. close_socket(socket);
  17552. success = false;
  17553. return false;
  17554. }
  17555. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  17556. if (!proxy_digest_auth_username_.empty() &&
  17557. !proxy_digest_auth_password_.empty()) {
  17558. std::map<std::string, std::string> auth;
  17559. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  17560. // Close the current socket and create a new one for the authenticated
  17561. // request
  17562. shutdown_ssl(socket, true);
  17563. shutdown_socket(socket);
  17564. close_socket(socket);
  17565. // Create a new socket for the authenticated CONNECT request
  17566. if (!ensure_socket_connection(socket, error)) {
  17567. success = false;
  17568. return false;
  17569. }
  17570. proxy_res = Response();
  17571. if (!detail::process_client_socket(
  17572. socket.sock, read_timeout_sec_, read_timeout_usec_,
  17573. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  17574. start_time, [&](Stream &strm) {
  17575. strm.set_read_interrupt(stop_interrupt());
  17576. Request req3;
  17577. req3.method = "CONNECT";
  17578. req3.path = connect_target;
  17579. if (retargeted) { req3.set_header("Host", connect_target); }
  17580. req3.headers.insert(detail::make_digest_authentication_header(
  17581. req3, make_request_target(req3), auth, 1,
  17582. detail::random_string(10), proxy_digest_auth_username_,
  17583. proxy_digest_auth_password_, true));
  17584. if (max_timeout_msec_ > 0) {
  17585. req3.start_time_ = std::chrono::steady_clock::now();
  17586. }
  17587. return process_request(strm, req3, proxy_res, false, error);
  17588. })) {
  17589. // Thread-safe to close everything because we are assuming there are
  17590. // no requests in flight
  17591. shutdown_ssl(socket, true);
  17592. shutdown_socket(socket);
  17593. close_socket(socket);
  17594. success = false;
  17595. return false;
  17596. }
  17597. }
  17598. }
  17599. }
  17600. // If status code is not 200, proxy request is failed.
  17601. // Set error to ProxyConnection. A 407 is returned as the response of the
  17602. // request, so the caller sees the proxy asks for credentials; any other
  17603. // status would read as the answer of the origin, which it never reached.
  17604. if (proxy_res.status != StatusCode::OK_200) {
  17605. error = Error::ProxyConnection;
  17606. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  17607. res = std::move(proxy_res);
  17608. } else {
  17609. success = false;
  17610. }
  17611. // Thread-safe to close everything because we are assuming there are
  17612. // no requests in flight
  17613. shutdown_ssl(socket, true);
  17614. shutdown_socket(socket);
  17615. close_socket(socket);
  17616. return false;
  17617. }
  17618. return true;
  17619. }
  17620. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  17621. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  17622. if (is_proxy_enabled_for_host(host_)) { return true; }
  17623. if (!initialize_ssl(socket, error)) {
  17624. shutdown_socket(socket);
  17625. close_socket(socket);
  17626. return false;
  17627. }
  17628. return true;
  17629. }
  17630. // SSL HTTP client implementation
  17631. inline SSLClient::SSLClient(const std::string &host)
  17632. : SSLClient(host, 443, std::string(), std::string()) {}
  17633. inline SSLClient::SSLClient(const std::string &host, int port)
  17634. : SSLClient(host, port, std::string(), std::string()) {}
  17635. inline void SSLClient::init_ctx() {
  17636. ctx_ = tls::create_client_context();
  17637. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  17638. }
  17639. inline void SSLClient::reset_ctx_on_error() {
  17640. last_backend_error_ = tls::get_error();
  17641. tls::free_context(ctx_);
  17642. ctx_ = nullptr;
  17643. }
  17644. inline SSLClient::SSLClient(const std::string &host, int port,
  17645. const std::string &client_cert_path,
  17646. const std::string &client_key_path,
  17647. const std::string &private_key_password)
  17648. : ClientImpl(host, port, client_cert_path, client_key_path) {
  17649. init_ctx();
  17650. if (!ctx_) { return; }
  17651. if (!client_cert_path.empty() && !client_key_path.empty()) {
  17652. const char *password =
  17653. private_key_password.empty() ? nullptr : private_key_password.c_str();
  17654. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  17655. client_key_path.c_str(), password)) {
  17656. reset_ctx_on_error();
  17657. }
  17658. }
  17659. }
  17660. inline SSLClient::SSLClient(const std::string &host, int port,
  17661. const PemMemory &pem)
  17662. : ClientImpl(host, port) {
  17663. init_ctx();
  17664. if (!ctx_) { return; }
  17665. if (pem.cert_pem && pem.key_pem) {
  17666. std::string cert_buf, key_buf;
  17667. if (!tls::set_client_cert_pem(
  17668. ctx_, detail::pem_c_str(pem.cert_pem, pem.cert_pem_len, cert_buf),
  17669. detail::pem_c_str(pem.key_pem, pem.key_pem_len, key_buf),
  17670. pem.private_key_password)) {
  17671. reset_ctx_on_error();
  17672. }
  17673. }
  17674. }
  17675. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  17676. if (ca_cert_store && ctx_) {
  17677. // set_ca_store takes ownership of ca_cert_store
  17678. tls::set_ca_store(ctx_, ca_cert_store);
  17679. ca_cert_store_set_ = true;
  17680. } else if (ca_cert_store) {
  17681. tls::free_ca_store(ca_cert_store);
  17682. }
  17683. custom_ca_loaded_ = true;
  17684. tls_settings_changed();
  17685. }
  17686. inline void
  17687. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  17688. if (!ctx_) { return; }
  17689. server_certificate_verifier_ = verifier;
  17690. {
  17691. // Under the lock that creating a session from ctx_ takes
  17692. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17693. tls::set_verify_callback(ctx_, std::move(verifier));
  17694. }
  17695. tls_settings_changed();
  17696. }
  17697. inline void SSLClient::set_session_verifier(
  17698. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  17699. session_verifier_ = std::move(verifier);
  17700. tls_settings_changed();
  17701. }
  17702. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  17703. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  17704. if (enable_windows_cert_verification_ == enabled) { return; }
  17705. enable_windows_cert_verification_ = enabled;
  17706. tls_settings_changed();
  17707. }
  17708. #endif
  17709. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  17710. std::size_t size) {
  17711. if (ctx_ && ca_cert && size > 0) {
  17712. // Every PEM loaded, for redirect transfer
  17713. if (!ca_cert_pem_.empty() && ca_cert_pem_.back() != '\n') {
  17714. ca_cert_pem_ += '\n';
  17715. }
  17716. ca_cert_pem_.append(ca_cert, size);
  17717. tls::load_ca_pem(ctx_, ca_cert, size);
  17718. }
  17719. custom_ca_loaded_ = true;
  17720. tls_settings_changed();
  17721. }
  17722. inline bool SSLClient::load_certs() {
  17723. auto ret = true;
  17724. // call_once rather than the plain flag WebSocketClient::create_stream() uses:
  17725. // one client is shared across concurrent requests here.
  17726. std::call_once(initialize_cert_, [&]() {
  17727. std::lock_guard<std::mutex> guard(ctx_mutex_);
  17728. ret = detail::load_client_ca_config(ctx_, ca_cert_file_path_,
  17729. ca_cert_dir_path_, custom_ca_loaded_,
  17730. system_ca_mode_, last_backend_error_);
  17731. });
  17732. return ret;
  17733. }
  17734. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  17735. // Load CA certificates if server verification is enabled
  17736. if (server_certificate_verification_) {
  17737. if (!load_certs()) {
  17738. error = Error::SSLLoadingCerts;
  17739. return false;
  17740. }
  17741. }
  17742. detail::ClientTlsSessionOptions options;
  17743. options.server_hostname_verification = server_hostname_verification_;
  17744. options.session_verifier = session_verifier_;
  17745. options.interrupted = stop_interrupt();
  17746. options.ctx_mutex = &ctx_mutex_;
  17747. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  17748. options.windows_cert_verification = detail::use_windows_cert_verification(
  17749. enable_windows_cert_verification_, ca_cert_file_path_, ca_cert_dir_path_,
  17750. custom_ca_loaded_, system_ca_mode_);
  17751. // Only a verifier set through set_server_certificate_verifier() is seen
  17752. // here, not one installed with tls::set_verify_callback() directly.
  17753. options.server_certificate_verifier_set =
  17754. static_cast<bool>(server_certificate_verifier_);
  17755. #endif
  17756. tls::session_t session = nullptr;
  17757. // Use scope_exit to ensure session is freed on error paths
  17758. bool success = false;
  17759. auto session_guard = detail::scope_exit([&] {
  17760. if (!success) { tls::free_session(session); }
  17761. });
  17762. detail::ClientTlsSessionError tls_error;
  17763. if (!detail::setup_client_tls_session(
  17764. host_, ctx_, session, socket.sock, server_certificate_verification_,
  17765. connection_timeout_sec_, connection_timeout_usec_, &tls_error,
  17766. options)) {
  17767. error = tls_error.error;
  17768. last_ssl_error_ = tls_error.ssl_error;
  17769. last_backend_error_ = tls_error.backend_error;
  17770. return false;
  17771. }
  17772. success = true;
  17773. socket.ssl = session;
  17774. return true;
  17775. }
  17776. inline void Client::set_digest_auth(const std::string &username,
  17777. const std::string &password) {
  17778. cli_->set_digest_auth(username, password);
  17779. }
  17780. inline void Client::set_proxy_digest_auth(const std::string &username,
  17781. const std::string &password) {
  17782. cli_->set_proxy_digest_auth(username, password);
  17783. }
  17784. inline void Client::enable_server_certificate_verification(bool enabled) {
  17785. cli_->enable_server_certificate_verification(enabled);
  17786. }
  17787. inline void Client::enable_server_hostname_verification(bool enabled) {
  17788. cli_->enable_server_hostname_verification(enabled);
  17789. }
  17790. inline void Client::enable_system_ca(bool enabled) {
  17791. cli_->enable_system_ca(enabled);
  17792. }
  17793. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  17794. inline void Client::enable_windows_certificate_verification(bool enabled) {
  17795. if (is_ssl_) {
  17796. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  17797. enabled);
  17798. }
  17799. }
  17800. #endif
  17801. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  17802. const std::string &ca_cert_dir_path) {
  17803. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  17804. }
  17805. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  17806. if (is_ssl_) {
  17807. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  17808. } else if (ca_cert_store) {
  17809. tls::free_ca_store(ca_cert_store);
  17810. }
  17811. }
  17812. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  17813. if (is_ssl_) {
  17814. // Use the PEM-based path so the CA data is retained for redirect transfer
  17815. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  17816. }
  17817. }
  17818. inline void
  17819. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  17820. if (is_ssl_) {
  17821. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  17822. std::move(verifier));
  17823. }
  17824. }
  17825. inline void Client::set_session_verifier(
  17826. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  17827. if (is_ssl_) {
  17828. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  17829. }
  17830. }
  17831. inline tls::ctx_t Client::tls_context() const {
  17832. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  17833. return nullptr;
  17834. }
  17835. #endif // CPPHTTPLIB_SSL_ENABLED
  17836. /*
  17837. * Group 7: TLS abstraction layer - Common API
  17838. */
  17839. #ifdef CPPHTTPLIB_SSL_ENABLED
  17840. namespace tls {
  17841. // Helper for PeerCert construction
  17842. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  17843. return PeerCert(get_peer_cert(session));
  17844. }
  17845. namespace impl {
  17846. // set_verify_callback() can replace a callback while handshakes on other
  17847. // threads run it, so they share it, and take their reference under this lock.
  17848. inline std::mutex &verify_callback_mutex() {
  17849. static std::mutex mutex;
  17850. return mutex;
  17851. }
  17852. // The TLS libraries are C, so an exception from a verify callback must not
  17853. // unwind through them. It rejects the certificate instead.
  17854. inline bool run_verify_callback(const VerifyCallback &callback,
  17855. const VerifyContext &ctx) {
  17856. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17857. return callback(ctx);
  17858. #else
  17859. try {
  17860. return callback(ctx);
  17861. } catch (...) { return false; }
  17862. #endif
  17863. }
  17864. // Check if a string is an IPv4 address
  17865. inline bool is_ipv4_address(const std::string &str) {
  17866. int dots = 0;
  17867. for (char c : str) {
  17868. if (c == '.') {
  17869. dots++;
  17870. } else if (!detail::is_ascii_digit(c)) {
  17871. return false;
  17872. }
  17873. }
  17874. return dots == 3;
  17875. }
  17876. // Parse IPv4 address string to bytes
  17877. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  17878. const char *p = str.c_str();
  17879. for (int i = 0; i < 4; i++) {
  17880. if (i > 0) {
  17881. if (*p != '.') { return false; }
  17882. p++;
  17883. }
  17884. int val = 0;
  17885. int digits = 0;
  17886. while (detail::is_ascii_digit(*p)) {
  17887. val = val * 10 + (*p - '0');
  17888. if (val > 255) { return false; }
  17889. p++;
  17890. digits++;
  17891. }
  17892. if (digits == 0) { return false; }
  17893. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  17894. if (digits > 1 && *(p - digits) == '0') { return false; }
  17895. out[i] = static_cast<unsigned char>(val);
  17896. }
  17897. return *p == '\0';
  17898. }
  17899. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  17900. // `out` must have room for at least 16 bytes. Returns the address length
  17901. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  17902. // literal. Used to match a host against iPAddress SANs the same way the
  17903. // OpenSSL backend does via X509_check_ip.
  17904. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  17905. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  17906. struct in6_addr addr6 = {};
  17907. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  17908. memcpy(out, &addr6, 16);
  17909. return 16;
  17910. }
  17911. return 0;
  17912. }
  17913. #ifdef _WIN32
  17914. // Enumerate Windows system certificates and call callback with DER data
  17915. template <typename Callback>
  17916. inline bool enumerate_windows_system_certs(Callback cb) {
  17917. bool loaded = false;
  17918. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  17919. for (auto store_name : store_names) {
  17920. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  17921. if (hStore) {
  17922. PCCERT_CONTEXT pContext = nullptr;
  17923. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  17924. nullptr) {
  17925. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  17926. loaded = true;
  17927. }
  17928. }
  17929. CertCloseStore(hStore, 0);
  17930. }
  17931. }
  17932. return loaded;
  17933. }
  17934. #endif
  17935. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  17936. // The trust a certificate's Trust Settings give it for SSL server
  17937. // verification (SecTrustSettings.h). An empty array trusts it as a root.
  17938. // Otherwise the first usage-constraints dictionary that applies decides: one
  17939. // naming a policy other than SSL, a host name or an application does not
  17940. // apply, and a result left out means TrustRoot. Keychain Access writes "Never
  17941. // Trust" as kSecTrustSettingsResultDeny.
  17942. inline SecTrustSettingsResult
  17943. macos_ssl_trust_settings_result(CFArrayRef trust_settings) {
  17944. auto count = CFArrayGetCount(trust_settings);
  17945. if (count == 0) { return kSecTrustSettingsResultTrustRoot; }
  17946. for (CFIndex i = 0; i < count; i++) {
  17947. auto value = CFArrayGetValueAtIndex(trust_settings, i);
  17948. if (!value || CFGetTypeID(value) != CFDictionaryGetTypeID()) { continue; }
  17949. auto constraint = static_cast<CFDictionaryRef>(value);
  17950. auto policy_value =
  17951. CFDictionaryGetValue(constraint, kSecTrustSettingsPolicy);
  17952. if (policy_value) {
  17953. auto policy = static_cast<SecPolicyRef>(const_cast<void *>(policy_value));
  17954. auto is_ssl = false;
  17955. if (auto properties = SecPolicyCopyProperties(policy)) {
  17956. auto oid = CFDictionaryGetValue(properties, kSecPolicyOid);
  17957. is_ssl = oid && CFEqual(oid, kSecPolicyAppleSSL);
  17958. CFRelease(properties);
  17959. }
  17960. if (!is_ssl) { continue; }
  17961. }
  17962. if (CFDictionaryContainsKey(constraint, kSecTrustSettingsPolicyString) ||
  17963. CFDictionaryContainsKey(constraint, kSecTrustSettingsApplication)) {
  17964. continue;
  17965. }
  17966. auto result = kSecTrustSettingsResultTrustRoot;
  17967. auto number = static_cast<CFNumberRef>(
  17968. CFDictionaryGetValue(constraint, kSecTrustSettingsResult));
  17969. if (number) {
  17970. SInt32 number_value = 0;
  17971. if (!CFNumberGetValue(number, kCFNumberSInt32Type, &number_value)) {
  17972. continue;
  17973. }
  17974. result = static_cast<SecTrustSettingsResult>(number_value);
  17975. }
  17976. if (result == kSecTrustSettingsResultTrustRoot ||
  17977. result == kSecTrustSettingsResultTrustAsRoot ||
  17978. result == kSecTrustSettingsResultDeny) {
  17979. return result;
  17980. }
  17981. }
  17982. return kSecTrustSettingsResultUnspecified;
  17983. }
  17984. // Enumerate the macOS Keychain certificates trusted for SSL and call callback
  17985. // with DER data. A certificate with Trust Settings is not trusted just by
  17986. // having them: the settings say whether it is, and a per-user setting
  17987. // overrides the admin domain's, which overrides the system domain's (whose
  17988. // roots are all trusted). So a system root the user set to "Never Trust" is
  17989. // left out, as is one trusted only for S/MIME or code signing.
  17990. template <typename Callback>
  17991. inline bool enumerate_macos_keychain_certs(Callback cb) {
  17992. const SecTrustSettingsDomain domains[] = {
  17993. kSecTrustSettingsDomainUser,
  17994. kSecTrustSettingsDomainAdmin,
  17995. kSecTrustSettingsDomainSystem,
  17996. };
  17997. std::set<std::string> decided;
  17998. std::vector<std::string> trusted;
  17999. for (auto domain : domains) {
  18000. CFArrayRef certs = nullptr;
  18001. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  18002. if (status != errSecSuccess || !certs) {
  18003. if (certs) CFRelease(certs);
  18004. continue;
  18005. }
  18006. CFIndex count = CFArrayGetCount(certs);
  18007. for (CFIndex i = 0; i < count; i++) {
  18008. SecCertificateRef cert =
  18009. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  18010. CFDataRef data = SecCertificateCopyData(cert);
  18011. if (!data) { continue; }
  18012. std::string der(reinterpret_cast<const char *>(CFDataGetBytePtr(data)),
  18013. static_cast<size_t>(CFDataGetLength(data)));
  18014. CFRelease(data);
  18015. // Decided by a domain that overrides this one
  18016. if (decided.find(der) != decided.end()) { continue; }
  18017. auto result = kSecTrustSettingsResultTrustRoot;
  18018. if (domain != kSecTrustSettingsDomainSystem) {
  18019. result = kSecTrustSettingsResultUnspecified;
  18020. CFArrayRef trust_settings = nullptr;
  18021. if (SecTrustSettingsCopyTrustSettings(cert, domain, &trust_settings) ==
  18022. errSecSuccess &&
  18023. trust_settings) {
  18024. result = macos_ssl_trust_settings_result(trust_settings);
  18025. }
  18026. if (trust_settings) CFRelease(trust_settings);
  18027. }
  18028. // Neither trusted nor distrusted here; a domain below may decide
  18029. if (result == kSecTrustSettingsResultUnspecified) { continue; }
  18030. decided.insert(der);
  18031. if (result == kSecTrustSettingsResultTrustRoot ||
  18032. result == kSecTrustSettingsResultTrustAsRoot) {
  18033. trusted.push_back(std::move(der));
  18034. }
  18035. }
  18036. CFRelease(certs);
  18037. }
  18038. bool loaded = false;
  18039. for (const auto &der : trusted) {
  18040. if (cb(reinterpret_cast<const unsigned char *>(der.data()), der.size())) {
  18041. loaded = true;
  18042. }
  18043. }
  18044. return loaded;
  18045. }
  18046. #endif
  18047. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  18048. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  18049. // Common CA certificate file paths on Linux/Unix
  18050. inline const char **system_ca_paths() {
  18051. static const char *paths[] = {
  18052. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  18053. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  18054. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  18055. "/etc/pki/tls/cacert.pem", // OpenELEC
  18056. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  18057. nullptr};
  18058. return paths;
  18059. }
  18060. // Common CA certificate directory paths on Linux/Unix
  18061. inline const char **system_ca_dirs() {
  18062. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  18063. "/etc/pki/tls/certs", // RHEL/CentOS
  18064. "/usr/share/ca-certificates", // Other
  18065. nullptr};
  18066. return dirs;
  18067. }
  18068. #endif
  18069. } // namespace impl
  18070. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  18071. const char *ca_dir) {
  18072. if (!ctx) { return false; }
  18073. bool success = true;
  18074. if (ca_file && *ca_file) {
  18075. if (!load_ca_file(ctx, ca_file)) { success = false; }
  18076. }
  18077. if (ca_dir && *ca_dir) {
  18078. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  18079. }
  18080. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18081. // Set CA list for client certificate request (CertificateRequest message)
  18082. if (ca_file && *ca_file) {
  18083. auto list = SSL_load_client_CA_file(ca_file);
  18084. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  18085. }
  18086. #endif
  18087. return success;
  18088. }
  18089. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  18090. const char *password) {
  18091. return set_client_cert_pem(ctx, cert, key, password);
  18092. }
  18093. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  18094. const char *key_path, const char *password) {
  18095. return set_client_cert_file(ctx, cert_path, key_path, password);
  18096. }
  18097. // PeerCert implementation
  18098. inline PeerCert::PeerCert() = default;
  18099. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  18100. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  18101. other.cert_ = nullptr;
  18102. }
  18103. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  18104. if (this != &other) {
  18105. if (cert_) { free_cert(cert_); }
  18106. cert_ = other.cert_;
  18107. other.cert_ = nullptr;
  18108. }
  18109. return *this;
  18110. }
  18111. inline PeerCert::~PeerCert() {
  18112. if (cert_) { free_cert(cert_); }
  18113. }
  18114. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  18115. inline std::string PeerCert::subject_cn() const {
  18116. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  18117. }
  18118. inline std::string PeerCert::issuer_name() const {
  18119. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  18120. }
  18121. inline bool PeerCert::check_hostname(const char *hostname) const {
  18122. return cert_ ? verify_hostname(cert_, hostname) : false;
  18123. }
  18124. inline std::vector<SanEntry> PeerCert::sans() const {
  18125. std::vector<SanEntry> result;
  18126. if (cert_) { get_cert_sans(cert_, result); }
  18127. return result;
  18128. }
  18129. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  18130. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  18131. }
  18132. inline std::string PeerCert::serial() const {
  18133. return cert_ ? get_cert_serial(cert_) : std::string();
  18134. }
  18135. // VerifyContext method implementations
  18136. inline std::string VerifyContext::subject_cn() const {
  18137. return cert ? get_cert_subject_cn(cert) : std::string();
  18138. }
  18139. inline std::string VerifyContext::issuer_name() const {
  18140. return cert ? get_cert_issuer_name(cert) : std::string();
  18141. }
  18142. inline bool VerifyContext::check_hostname(const char *hostname) const {
  18143. return cert ? verify_hostname(cert, hostname) : false;
  18144. }
  18145. inline std::vector<SanEntry> VerifyContext::sans() const {
  18146. std::vector<SanEntry> result;
  18147. if (cert) { get_cert_sans(cert, result); }
  18148. return result;
  18149. }
  18150. inline bool VerifyContext::validity(time_t &not_before,
  18151. time_t &not_after) const {
  18152. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  18153. }
  18154. inline std::string VerifyContext::serial() const {
  18155. return cert ? get_cert_serial(cert) : std::string();
  18156. }
  18157. // TlsError static method implementation
  18158. inline std::string TlsError::verify_error_to_string(long error_code) {
  18159. return verify_error_string(error_code);
  18160. }
  18161. } // namespace tls
  18162. // Request::peer_cert() implementation
  18163. inline tls::PeerCert Request::peer_cert() const {
  18164. return tls::get_peer_cert_from_session(ssl);
  18165. }
  18166. // Request::sni() implementation
  18167. inline std::string Request::sni() const {
  18168. if (!ssl) { return std::string(); }
  18169. const char *s = tls::get_sni(ssl);
  18170. return s ? std::string(s) : std::string();
  18171. }
  18172. #endif // CPPHTTPLIB_SSL_ENABLED
  18173. /*
  18174. * Group 8: TLS abstraction layer - OpenSSL backend
  18175. */
  18176. /*
  18177. * OpenSSL Backend Implementation
  18178. */
  18179. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18180. namespace tls {
  18181. namespace impl {
  18182. // Helper to map OpenSSL SSL_get_error to ErrorCode
  18183. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  18184. switch (ssl_error) {
  18185. case SSL_ERROR_NONE: return ErrorCode::Success;
  18186. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  18187. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  18188. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  18189. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  18190. case SSL_ERROR_SSL:
  18191. default: return ErrorCode::Fatal;
  18192. }
  18193. }
  18194. // Fills in a failed SSL_connect(). One that the server certificate's
  18195. // verification stopped reports the verify result, as the other backends and
  18196. // a check after the handshake do.
  18197. inline void fill_connect_error(SSL *ssl, int ret, TlsError &err) {
  18198. auto ssl_err = SSL_get_error(ssl, ret);
  18199. auto error = ERR_get_error();
  18200. err.code = map_ssl_error(ssl_err, err.sys_errno);
  18201. err.backend_code = error;
  18202. if (ssl_err != SSL_ERROR_SSL || ERR_GET_LIB(error) != ERR_LIB_SSL ||
  18203. ERR_GET_REASON(error) != SSL_R_CERTIFICATE_VERIFY_FAILED) {
  18204. return;
  18205. }
  18206. // A certificate only a verify callback turned down carries no verdict of
  18207. // its own, and fails as any other handshake does
  18208. auto verify_result = SSL_get_verify_result(ssl);
  18209. if (verify_result == X509_V_OK || verify_result == X509_V_ERR_UNSPECIFIED) {
  18210. return;
  18211. }
  18212. err.code = verify_result == X509_V_ERR_HOSTNAME_MISMATCH
  18213. ? ErrorCode::HostnameMismatch
  18214. : ErrorCode::CertVerifyFailed;
  18215. err.backend_code = static_cast<uint64_t>(verify_result);
  18216. }
  18217. // Helper: Create client CA list from PEM string
  18218. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  18219. // Caller takes ownership of returned list
  18220. inline STACK_OF(X509_NAME) *
  18221. create_client_ca_list_from_pem(const char *ca_pem) {
  18222. if (!ca_pem) { return nullptr; }
  18223. auto ca_list = sk_X509_NAME_new_null();
  18224. if (!ca_list) { return nullptr; }
  18225. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  18226. if (!bio) {
  18227. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  18228. return nullptr;
  18229. }
  18230. X509 *cert = nullptr;
  18231. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  18232. nullptr) {
  18233. const X509_NAME *name = X509_get_subject_name(cert);
  18234. if (name) {
  18235. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  18236. }
  18237. X509_free(cert);
  18238. }
  18239. BIO_free(bio);
  18240. return ca_list;
  18241. }
  18242. inline void free_verify_callback(void * /*parent*/, void *ptr,
  18243. CRYPTO_EX_DATA * /*ad*/, int /*idx*/,
  18244. long /*argl*/, void * /*argp*/) {
  18245. delete static_cast<std::shared_ptr<VerifyCallback> *>(ptr);
  18246. }
  18247. // The SSL_CTX owns its verify callback, so each client or server sees only
  18248. // its own, on whichever thread runs the handshake.
  18249. inline int verify_callback_index() {
  18250. static const auto index = SSL_CTX_get_ex_new_index(
  18251. 0, nullptr, nullptr, nullptr, free_verify_callback);
  18252. return index;
  18253. }
  18254. // OpenSSL verify callback wrapper
  18255. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  18256. // Get SSL object from X509_STORE_CTX
  18257. auto ssl = static_cast<SSL *>(
  18258. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  18259. if (!ssl) { return preverify_ok; }
  18260. std::shared_ptr<VerifyCallback> callback;
  18261. {
  18262. std::lock_guard<std::mutex> guard(verify_callback_mutex());
  18263. auto stored = static_cast<std::shared_ptr<VerifyCallback> *>(
  18264. SSL_CTX_get_ex_data(SSL_get_SSL_CTX(ssl), verify_callback_index()));
  18265. if (stored) { callback = *stored; }
  18266. }
  18267. if (!callback) { return preverify_ok; }
  18268. // Get current certificate and depth
  18269. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  18270. int depth = X509_STORE_CTX_get_error_depth(ctx);
  18271. int error = X509_STORE_CTX_get_error(ctx);
  18272. // Build context
  18273. VerifyContext verify_ctx;
  18274. verify_ctx.session = static_cast<session_t>(ssl);
  18275. verify_ctx.cert = static_cast<cert_t>(cert);
  18276. verify_ctx.depth = depth;
  18277. verify_ctx.preverify_ok = (preverify_ok != 0);
  18278. verify_ctx.error_code = error;
  18279. verify_ctx.error_string =
  18280. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  18281. auto accepted = run_verify_callback(*callback, verify_ctx);
  18282. // A client verifying the server during the handshake, which is what
  18283. // set_verify_client(ctx, true) asks for there, keeps the built-in verdict
  18284. if (!SSL_is_server(ssl) &&
  18285. (SSL_get_verify_mode(ssl) & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  18286. accepted = accepted && preverify_ok;
  18287. }
  18288. return accepted ? 1 : 0;
  18289. }
  18290. // Sets the verify mode from whether the peer's certificate is required and
  18291. // whether a verify callback is set.
  18292. inline void apply_verify_mode(SSL_CTX *ssl_ctx, bool require) {
  18293. auto has_callback =
  18294. SSL_CTX_get_ex_data(ssl_ctx, verify_callback_index()) != nullptr;
  18295. auto mode = require ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  18296. : (has_callback ? SSL_VERIFY_PEER : SSL_VERIFY_NONE);
  18297. SSL_CTX_set_verify(ssl_ctx, mode,
  18298. has_callback ? openssl_verify_callback : nullptr);
  18299. }
  18300. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  18301. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  18302. // that must be released with release_store_objects
  18303. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  18304. OPENSSL_VERSION_NUMBER >= 0x30300000L
  18305. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  18306. #endif
  18307. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  18308. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  18309. return X509_STORE_get1_objects(store);
  18310. #else
  18311. return X509_STORE_get0_objects(store);
  18312. #endif
  18313. }
  18314. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  18315. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  18316. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  18317. #else
  18318. (void)objs; // get0 variant returns an internal pointer; nothing to free
  18319. #endif
  18320. }
  18321. } // namespace impl
  18322. inline ctx_t create_client_context() {
  18323. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  18324. if (ctx) {
  18325. // Disable auto-retry to properly handle non-blocking I/O
  18326. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  18327. // Set minimum TLS version
  18328. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  18329. }
  18330. return static_cast<ctx_t>(ctx);
  18331. }
  18332. inline void free_context(ctx_t ctx) {
  18333. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  18334. }
  18335. inline bool set_min_version(ctx_t ctx, Version version) {
  18336. if (!ctx) return false;
  18337. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  18338. static_cast<uint16_t>(version)) == 1;
  18339. }
  18340. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  18341. if (!ctx || !pem || len == 0) return false;
  18342. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18343. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18344. if (!store) return false;
  18345. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  18346. if (!bio) return false;
  18347. bool ok = true;
  18348. X509 *cert = nullptr;
  18349. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  18350. nullptr) {
  18351. if (X509_STORE_add_cert(store, cert) != 1) {
  18352. // Ignore duplicate errors
  18353. auto err = ERR_peek_last_error();
  18354. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  18355. ok = false;
  18356. }
  18357. }
  18358. X509_free(cert);
  18359. if (!ok) break;
  18360. }
  18361. BIO_free(bio);
  18362. // Clear any "no more certificates" errors
  18363. ERR_clear_error();
  18364. return ok;
  18365. }
  18366. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  18367. if (!ctx || !file_path) return false;
  18368. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  18369. nullptr) == 1;
  18370. }
  18371. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  18372. if (!ctx || !dir_path) return false;
  18373. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  18374. dir_path) == 1;
  18375. }
  18376. inline bool load_system_certs(ctx_t ctx) {
  18377. if (!ctx) return false;
  18378. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18379. #ifdef _WIN32
  18380. // Windows: Load from system certificate store (ROOT and CA)
  18381. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18382. if (!store) return false;
  18383. bool loaded_any = false;
  18384. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  18385. for (auto store_name : store_names) {
  18386. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  18387. if (!hStore) continue;
  18388. PCCERT_CONTEXT pContext = nullptr;
  18389. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  18390. nullptr) {
  18391. const unsigned char *data = pContext->pbCertEncoded;
  18392. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  18393. if (x509) {
  18394. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  18395. X509_free(x509);
  18396. }
  18397. }
  18398. CertCloseStore(hStore, 0);
  18399. }
  18400. return loaded_any;
  18401. #elif defined(__APPLE__)
  18402. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  18403. // macOS: Load from Keychain
  18404. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18405. if (!store) return false;
  18406. auto loaded_any = impl::enumerate_macos_keychain_certs(
  18407. [&](const unsigned char *data, size_t len) {
  18408. auto x509 = d2i_X509(nullptr, &data, static_cast<long>(len));
  18409. if (!x509) { return false; }
  18410. auto added = X509_STORE_add_cert(store, x509) == 1;
  18411. X509_free(x509);
  18412. return added;
  18413. });
  18414. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  18415. #else
  18416. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  18417. #endif
  18418. #else
  18419. // Other Unix: use default verify paths
  18420. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  18421. #endif
  18422. }
  18423. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  18424. const char *password) {
  18425. if (!ctx || !cert || !key) return false;
  18426. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18427. // Load certificate
  18428. auto cert_bio = BIO_new_mem_buf(cert, -1);
  18429. if (!cert_bio) return false;
  18430. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  18431. BIO_free(cert_bio);
  18432. if (!x509) return false;
  18433. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  18434. X509_free(x509);
  18435. if (!cert_ok) return false;
  18436. // Load private key
  18437. auto key_bio = BIO_new_mem_buf(key, -1);
  18438. if (!key_bio) return false;
  18439. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  18440. password ? const_cast<char *>(password)
  18441. : nullptr);
  18442. BIO_free(key_bio);
  18443. if (!pkey) return false;
  18444. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  18445. EVP_PKEY_free(pkey);
  18446. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  18447. }
  18448. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  18449. const char *key_path, const char *password) {
  18450. if (!ctx || !cert_path || !key_path) return false;
  18451. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18452. if (password && password[0] != '\0') {
  18453. SSL_CTX_set_default_passwd_cb_userdata(
  18454. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  18455. }
  18456. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  18457. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  18458. }
  18459. inline ctx_t create_server_context() {
  18460. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18461. if (ctx) {
  18462. // No renegotiation, as on the other backends: it would run a handshake
  18463. // that SSLServer::update_certs_pem() does not wait for
  18464. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  18465. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
  18466. SSL_OP_NO_RENEGOTIATION);
  18467. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  18468. // Without one, a client resuming its session is sent a fatal alert once
  18469. // client certificates are verified.
  18470. static const unsigned char sid_ctx[] = "cpp-httplib";
  18471. SSL_CTX_set_session_id_context(ctx, sid_ctx, sizeof(sid_ctx) - 1);
  18472. }
  18473. return static_cast<ctx_t>(ctx);
  18474. }
  18475. inline void set_verify_client(ctx_t ctx, bool require) {
  18476. if (!ctx) return;
  18477. impl::apply_verify_mode(static_cast<SSL_CTX *>(ctx), require);
  18478. }
  18479. inline session_t create_session(ctx_t ctx, socket_t sock) {
  18480. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  18481. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18482. SSL *ssl = SSL_new(ssl_ctx);
  18483. if (!ssl) return nullptr;
  18484. // Disable auto-retry for proper non-blocking I/O handling
  18485. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  18486. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  18487. if (!bio) {
  18488. SSL_free(ssl);
  18489. return nullptr;
  18490. }
  18491. SSL_set_bio(ssl, bio, bio);
  18492. return static_cast<session_t>(ssl);
  18493. }
  18494. inline void free_session(session_t session) {
  18495. if (session) { SSL_free(static_cast<SSL *>(session)); }
  18496. }
  18497. inline bool set_sni(session_t session, const char *hostname,
  18498. bool verify_hostname) {
  18499. if (!session || !hostname) return false;
  18500. auto ssl = static_cast<SSL *>(session);
  18501. // The handshake's chain verification then checks the name as well
  18502. if (verify_hostname) {
  18503. auto param = SSL_get0_param(ssl);
  18504. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
  18505. if (X509_VERIFY_PARAM_set1_host(param, hostname, strlen(hostname)) != 1) {
  18506. return false;
  18507. }
  18508. }
  18509. #if defined(OPENSSL_IS_BORINGSSL)
  18510. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  18511. #else
  18512. // Direct call instead of macro to suppress -Wold-style-cast warning
  18513. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  18514. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  18515. #endif
  18516. }
  18517. inline TlsError connect(session_t session) {
  18518. if (!session) { return TlsError(); }
  18519. auto ssl = static_cast<SSL *>(session);
  18520. auto ret = SSL_connect(ssl);
  18521. TlsError err;
  18522. if (ret == 1) {
  18523. err.code = ErrorCode::Success;
  18524. } else {
  18525. impl::fill_connect_error(ssl, ret, err);
  18526. }
  18527. return err;
  18528. }
  18529. inline TlsError accept(session_t session) {
  18530. if (!session) { return TlsError(); }
  18531. auto ssl = static_cast<SSL *>(session);
  18532. auto ret = SSL_accept(ssl);
  18533. TlsError err;
  18534. if (ret == 1) {
  18535. err.code = ErrorCode::Success;
  18536. } else {
  18537. auto ssl_err = SSL_get_error(ssl, ret);
  18538. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  18539. err.backend_code = ERR_get_error();
  18540. }
  18541. return err;
  18542. }
  18543. inline bool connect_nonblocking(session_t session, socket_t sock,
  18544. time_t timeout_sec, time_t timeout_usec,
  18545. TlsError *err,
  18546. const std::function<bool()> &interrupted) {
  18547. if (!session) {
  18548. if (err) { err->code = ErrorCode::Fatal; }
  18549. return false;
  18550. }
  18551. auto ssl = static_cast<SSL *>(session);
  18552. auto bio = SSL_get_rbio(ssl);
  18553. // Set non-blocking mode for handshake
  18554. detail::set_nonblocking(sock, true);
  18555. if (bio) { BIO_set_nbio(bio, 1); }
  18556. auto cleanup = detail::scope_exit([&]() {
  18557. // Restore blocking mode after handshake
  18558. if (bio) { BIO_set_nbio(bio, 0); }
  18559. detail::set_nonblocking(sock, false);
  18560. });
  18561. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  18562. auto res = 0;
  18563. while ((res = SSL_connect(ssl)) != 1) {
  18564. auto ssl_err = SSL_get_error(ssl, res);
  18565. switch (ssl_err) {
  18566. case SSL_ERROR_WANT_READ:
  18567. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  18568. continue;
  18569. }
  18570. break;
  18571. case SSL_ERROR_WANT_WRITE:
  18572. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  18573. continue;
  18574. }
  18575. break;
  18576. default: break;
  18577. }
  18578. if (err) { impl::fill_connect_error(ssl, res, *err); }
  18579. return false;
  18580. }
  18581. if (err) { err->code = ErrorCode::Success; }
  18582. return true;
  18583. }
  18584. inline bool accept_nonblocking(session_t session, socket_t sock,
  18585. time_t timeout_sec, time_t timeout_usec,
  18586. TlsError *err) {
  18587. if (!session) {
  18588. if (err) { err->code = ErrorCode::Fatal; }
  18589. return false;
  18590. }
  18591. auto ssl = static_cast<SSL *>(session);
  18592. auto bio = SSL_get_rbio(ssl);
  18593. // Set non-blocking mode for handshake
  18594. detail::set_nonblocking(sock, true);
  18595. if (bio) { BIO_set_nbio(bio, 1); }
  18596. auto cleanup = detail::scope_exit([&]() {
  18597. // Restore blocking mode after handshake
  18598. if (bio) { BIO_set_nbio(bio, 0); }
  18599. detail::set_nonblocking(sock, false);
  18600. });
  18601. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  18602. auto res = 0;
  18603. while ((res = SSL_accept(ssl)) != 1) {
  18604. auto ssl_err = SSL_get_error(ssl, res);
  18605. switch (ssl_err) {
  18606. case SSL_ERROR_WANT_READ:
  18607. if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
  18608. break;
  18609. case SSL_ERROR_WANT_WRITE:
  18610. if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
  18611. break;
  18612. default: break;
  18613. }
  18614. if (err) {
  18615. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  18616. err->backend_code = ERR_get_error();
  18617. }
  18618. return false;
  18619. }
  18620. if (err) { err->code = ErrorCode::Success; }
  18621. return true;
  18622. }
  18623. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  18624. if (!session || !buf) {
  18625. err.code = ErrorCode::Fatal;
  18626. return -1;
  18627. }
  18628. auto ssl = static_cast<SSL *>(session);
  18629. constexpr auto max_len =
  18630. static_cast<size_t>((std::numeric_limits<int>::max)());
  18631. if (len > max_len) { len = max_len; }
  18632. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  18633. if (ret > 0) {
  18634. err.code = ErrorCode::Success;
  18635. return ret;
  18636. }
  18637. auto ssl_err = SSL_get_error(ssl, ret);
  18638. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  18639. if (err.code == ErrorCode::PeerClosed) {
  18640. return 0;
  18641. } // Gracefully handle the peer closed state.
  18642. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  18643. return -1;
  18644. }
  18645. inline ssize_t write(session_t session, const void *buf, size_t len,
  18646. TlsError &err) {
  18647. if (!session || !buf) {
  18648. err.code = ErrorCode::Fatal;
  18649. return -1;
  18650. }
  18651. auto ssl = static_cast<SSL *>(session);
  18652. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  18653. if (ret > 0) {
  18654. err.code = ErrorCode::Success;
  18655. return ret;
  18656. }
  18657. auto ssl_err = SSL_get_error(ssl, ret);
  18658. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  18659. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  18660. return -1;
  18661. }
  18662. inline int pending(const_session_t session) {
  18663. if (!session) return 0;
  18664. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  18665. }
  18666. inline void shutdown(session_t session, bool graceful) {
  18667. if (!session) return;
  18668. auto ssl = static_cast<SSL *>(session);
  18669. if (graceful) {
  18670. // Send close_notify without waiting for the peer's. The connection is
  18671. // closed right after this, so a unidirectional shutdown is enough, and an
  18672. // idle peer that never answers would otherwise hold this thread until the
  18673. // read timeout. The other backends do not wait either.
  18674. SSL_shutdown(ssl);
  18675. }
  18676. }
  18677. inline bool is_peer_closed(session_t session, socket_t sock) {
  18678. if (!session) return true;
  18679. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  18680. detail::set_nonblocking(sock, true);
  18681. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18682. auto ssl = static_cast<SSL *>(session);
  18683. char buf;
  18684. auto ret = SSL_peek(ssl, &buf, 1);
  18685. if (ret > 0) return false;
  18686. auto err = SSL_get_error(ssl, ret);
  18687. return err == SSL_ERROR_ZERO_RETURN;
  18688. }
  18689. inline cert_t get_peer_cert(const_session_t session) {
  18690. if (!session) return nullptr;
  18691. return static_cast<cert_t>(SSL_get1_peer_certificate(
  18692. static_cast<SSL *>(const_cast<void *>(session))));
  18693. }
  18694. inline size_t get_peer_certs(const_session_t session,
  18695. std::vector<cert_t> &certs) {
  18696. certs.clear();
  18697. if (!session) { return 0; }
  18698. auto ssl = static_cast<const SSL *>(session);
  18699. // On the server side, the chain leaves out the peer's own certificate
  18700. if (SSL_is_server(ssl)) {
  18701. if (auto leaf = get_peer_cert(session)) { certs.push_back(leaf); }
  18702. }
  18703. if (auto sk = SSL_get_peer_cert_chain(ssl)) {
  18704. auto count = sk_X509_num(sk);
  18705. for (decltype(count) i = 0; i < count; i++) {
  18706. auto x509 = sk_X509_value(sk, i);
  18707. X509_up_ref(x509);
  18708. certs.push_back(static_cast<cert_t>(x509));
  18709. }
  18710. }
  18711. return certs.size();
  18712. }
  18713. inline void free_cert(cert_t cert) {
  18714. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  18715. }
  18716. inline bool verify_hostname(cert_t cert, const char *hostname) {
  18717. if (!cert || !hostname) return false;
  18718. auto x509 = static_cast<X509 *>(cert);
  18719. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  18720. if (detail::is_ip_address(hostname)) {
  18721. return X509_check_ip_asc(x509, hostname, 0) == 1;
  18722. }
  18723. return X509_check_host(x509, hostname, strlen(hostname),
  18724. X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, nullptr) == 1;
  18725. }
  18726. inline uint64_t hostname_mismatch_code() {
  18727. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  18728. }
  18729. inline long get_verify_result(const_session_t session) {
  18730. if (!session) return X509_V_ERR_UNSPECIFIED;
  18731. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  18732. }
  18733. inline std::string get_cert_subject_cn(cert_t cert) {
  18734. if (!cert) return "";
  18735. auto x509 = static_cast<X509 *>(cert);
  18736. auto subject_name = X509_get_subject_name(x509);
  18737. if (!subject_name) return "";
  18738. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  18739. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  18740. if (idx < 0) return "";
  18741. auto entry = X509_NAME_get_entry(subject_name, idx);
  18742. if (!entry) return "";
  18743. auto data = X509_NAME_ENTRY_get_data(entry);
  18744. if (!data) return "";
  18745. return std::string(
  18746. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  18747. static_cast<size_t>(ASN1_STRING_length(data)));
  18748. }
  18749. inline std::string get_cert_issuer_name(cert_t cert) {
  18750. if (!cert) return "";
  18751. auto x509 = static_cast<X509 *>(cert);
  18752. auto issuer_name = X509_get_issuer_name(x509);
  18753. if (!issuer_name) return "";
  18754. char buf[256];
  18755. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  18756. return std::string(buf);
  18757. }
  18758. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  18759. sans.clear();
  18760. if (!cert) return false;
  18761. auto x509 = static_cast<X509 *>(cert);
  18762. auto names = static_cast<GENERAL_NAMES *>(
  18763. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18764. if (!names) return true; // No SANs is valid
  18765. auto count = sk_GENERAL_NAME_num(names);
  18766. for (decltype(count) i = 0; i < count; i++) {
  18767. auto gen = sk_GENERAL_NAME_value(names, i);
  18768. if (!gen) continue;
  18769. SanEntry entry;
  18770. switch (gen->type) {
  18771. case GEN_DNS:
  18772. entry.type = SanType::DNS;
  18773. if (gen->d.dNSName) {
  18774. entry.value = std::string(
  18775. reinterpret_cast<const char *>(
  18776. ASN1_STRING_get0_data(gen->d.dNSName)),
  18777. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  18778. }
  18779. break;
  18780. case GEN_IPADD:
  18781. entry.type = SanType::IP;
  18782. if (gen->d.iPAddress) {
  18783. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  18784. auto len = ASN1_STRING_length(gen->d.iPAddress);
  18785. if (len == 4) {
  18786. // IPv4
  18787. char buf[INET_ADDRSTRLEN];
  18788. inet_ntop(AF_INET, data, buf, sizeof(buf));
  18789. entry.value = buf;
  18790. } else if (len == 16) {
  18791. // IPv6
  18792. char buf[INET6_ADDRSTRLEN];
  18793. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  18794. entry.value = buf;
  18795. }
  18796. }
  18797. break;
  18798. case GEN_EMAIL:
  18799. entry.type = SanType::EMAIL;
  18800. if (gen->d.rfc822Name) {
  18801. entry.value = std::string(
  18802. reinterpret_cast<const char *>(
  18803. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  18804. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  18805. }
  18806. break;
  18807. case GEN_URI:
  18808. entry.type = SanType::URI;
  18809. if (gen->d.uniformResourceIdentifier) {
  18810. entry.value = std::string(
  18811. reinterpret_cast<const char *>(
  18812. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  18813. static_cast<size_t>(
  18814. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  18815. }
  18816. break;
  18817. default: entry.type = SanType::OTHER; break;
  18818. }
  18819. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  18820. }
  18821. GENERAL_NAMES_free(names);
  18822. return true;
  18823. }
  18824. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  18825. time_t &not_after) {
  18826. if (!cert) return false;
  18827. auto x509 = static_cast<X509 *>(cert);
  18828. auto nb = X509_get0_notBefore(x509);
  18829. auto na = X509_get0_notAfter(x509);
  18830. if (!nb || !na) return false;
  18831. ASN1_TIME *epoch = ASN1_TIME_new();
  18832. if (!epoch) return false;
  18833. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  18834. if (!ASN1_TIME_set(epoch, 0)) return false;
  18835. int pday, psec;
  18836. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  18837. not_before = 86400 * (time_t)pday + psec;
  18838. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  18839. not_after = 86400 * (time_t)pday + psec;
  18840. return true;
  18841. }
  18842. inline std::string get_cert_serial(cert_t cert) {
  18843. if (!cert) return "";
  18844. auto x509 = static_cast<X509 *>(cert);
  18845. auto serial = X509_get_serialNumber(x509);
  18846. if (!serial) return "";
  18847. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  18848. if (!bn) return "";
  18849. auto hex = BN_bn2hex(bn);
  18850. BN_free(bn);
  18851. if (!hex) return "";
  18852. std::string result(hex);
  18853. OPENSSL_free(hex);
  18854. return result;
  18855. }
  18856. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  18857. if (!cert) return false;
  18858. auto x509 = static_cast<X509 *>(cert);
  18859. auto len = i2d_X509(x509, nullptr);
  18860. if (len < 0) return false;
  18861. der.resize(static_cast<size_t>(len));
  18862. auto p = der.data();
  18863. i2d_X509(x509, &p);
  18864. return true;
  18865. }
  18866. inline const char *get_sni(const_session_t session) {
  18867. if (!session) return nullptr;
  18868. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  18869. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  18870. }
  18871. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  18872. inline uint64_t get_error() { return ERR_get_error(); }
  18873. inline std::string error_string(uint64_t code) {
  18874. char buf[256];
  18875. ERR_error_string_n(static_cast<decltype(ERR_get_error())>(code), buf,
  18876. sizeof(buf));
  18877. return std::string(buf);
  18878. }
  18879. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  18880. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  18881. if (!mem) { return nullptr; }
  18882. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  18883. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  18884. if (!inf) { return nullptr; }
  18885. auto store = X509_STORE_new();
  18886. if (store) {
  18887. auto count = sk_X509_INFO_num(inf);
  18888. for (decltype(count) i = 0; i < count; i++) {
  18889. auto itmp = sk_X509_INFO_value(inf, i);
  18890. if (!itmp) { continue; }
  18891. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  18892. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  18893. }
  18894. }
  18895. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  18896. return static_cast<ca_store_t>(store);
  18897. }
  18898. inline void free_ca_store(ca_store_t store) {
  18899. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  18900. }
  18901. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  18902. if (!ctx || !store) { return false; }
  18903. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18904. auto x509_store = static_cast<X509_STORE *>(store);
  18905. // Check if same store is already set
  18906. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  18907. // SSL_CTX_set_cert_store takes ownership and frees the old store
  18908. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  18909. return true;
  18910. }
  18911. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  18912. certs.clear();
  18913. if (!ctx) { return 0; }
  18914. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18915. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18916. if (!store) { return 0; }
  18917. auto objs = impl::get_store_objects(store);
  18918. if (!objs) { return 0; }
  18919. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  18920. auto count = sk_X509_OBJECT_num(objs);
  18921. for (decltype(count) i = 0; i < count; i++) {
  18922. auto obj = sk_X509_OBJECT_value(objs, i);
  18923. if (!obj) { continue; }
  18924. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  18925. auto x509 = X509_OBJECT_get0_X509(obj);
  18926. if (x509) {
  18927. // Increment reference count so caller can free it
  18928. X509_up_ref(x509);
  18929. certs.push_back(static_cast<cert_t>(x509));
  18930. }
  18931. }
  18932. }
  18933. return certs.size();
  18934. }
  18935. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  18936. std::vector<std::string> names;
  18937. if (!ctx) { return names; }
  18938. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18939. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  18940. if (!store) { return names; }
  18941. auto objs = impl::get_store_objects(store);
  18942. if (!objs) { return names; }
  18943. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  18944. auto count = sk_X509_OBJECT_num(objs);
  18945. for (decltype(count) i = 0; i < count; i++) {
  18946. auto obj = sk_X509_OBJECT_value(objs, i);
  18947. if (!obj) { continue; }
  18948. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  18949. auto x509 = X509_OBJECT_get0_X509(obj);
  18950. if (x509) {
  18951. auto subject = X509_get_subject_name(x509);
  18952. if (subject) {
  18953. char buf[512];
  18954. X509_NAME_oneline(subject, buf, sizeof(buf));
  18955. names.push_back(buf);
  18956. }
  18957. }
  18958. }
  18959. }
  18960. return names;
  18961. }
  18962. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  18963. const char *key_pem, const char *password) {
  18964. if (!ctx || !cert_pem || !key_pem) { return false; }
  18965. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18966. // Load certificate from PEM
  18967. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  18968. if (!cert_bio) { return false; }
  18969. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  18970. BIO_free(cert_bio);
  18971. if (!cert) { return false; }
  18972. // Load private key from PEM
  18973. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  18974. if (!key_bio) {
  18975. X509_free(cert);
  18976. return false;
  18977. }
  18978. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  18979. password ? const_cast<char *>(password)
  18980. : nullptr);
  18981. BIO_free(key_bio);
  18982. if (!key) {
  18983. X509_free(cert);
  18984. return false;
  18985. }
  18986. // Update certificate and key
  18987. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  18988. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  18989. X509_free(cert);
  18990. EVP_PKEY_free(key);
  18991. return ret;
  18992. }
  18993. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  18994. if (!ctx || !ca_pem) { return false; }
  18995. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  18996. // Create new X509_STORE from PEM
  18997. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  18998. if (!store) { return false; }
  18999. // A resumed session is not verified again, so the ticket keys from before
  19000. // go, or a client verified under the old CAs could go on resuming.
  19001. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  19002. unsigned char ticket_keys[48];
  19003. #else
  19004. unsigned char ticket_keys[80];
  19005. #endif
  19006. if (RAND_bytes(ticket_keys, sizeof(ticket_keys)) != 1 ||
  19007. SSL_CTX_set_tlsext_ticket_keys(ssl_ctx, ticket_keys,
  19008. sizeof(ticket_keys)) != 1) {
  19009. free_ca_store(store);
  19010. return false;
  19011. }
  19012. // SSL_CTX_set_cert_store takes ownership
  19013. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  19014. // Set client CA list for client certificate request
  19015. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  19016. if (ca_list) {
  19017. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  19018. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  19019. }
  19020. // The cached sessions go for the same reason.
  19021. #if OPENSSL_VERSION_NUMBER >= 0x30400000L
  19022. SSL_CTX_flush_sessions_ex(ssl_ctx, (std::numeric_limits<time_t>::max)());
  19023. #else
  19024. SSL_CTX_flush_sessions(ssl_ctx, (std::numeric_limits<long>::max)());
  19025. #endif
  19026. return true;
  19027. }
  19028. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  19029. if (!ctx) { return false; }
  19030. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  19031. auto index = impl::verify_callback_index();
  19032. if (index < 0) { return false; }
  19033. std::shared_ptr<VerifyCallback> *stored = nullptr;
  19034. if (callback) {
  19035. stored = new std::shared_ptr<VerifyCallback>(
  19036. std::make_shared<VerifyCallback>(std::move(callback)));
  19037. }
  19038. std::shared_ptr<VerifyCallback> *previous = nullptr;
  19039. {
  19040. std::lock_guard<std::mutex> guard(impl::verify_callback_mutex());
  19041. previous = static_cast<std::shared_ptr<VerifyCallback> *>(
  19042. SSL_CTX_get_ex_data(ssl_ctx, index));
  19043. if (SSL_CTX_set_ex_data(ssl_ctx, index, stored) != 1) {
  19044. delete stored;
  19045. return false;
  19046. }
  19047. }
  19048. // A handshake running the previous callback keeps it until it returns.
  19049. delete previous;
  19050. // A resumed handshake shows no certificate to run the callback on.
  19051. if (stored) {
  19052. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
  19053. SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
  19054. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER)
  19055. // TLS 1.3 tickets, which SSL_OP_NO_TICKET leaves on
  19056. SSL_CTX_set_num_tickets(ssl_ctx, 0);
  19057. #endif
  19058. }
  19059. // Keep requiring the peer's certificate if set_verify_client() asked for it
  19060. auto require =
  19061. (SSL_CTX_get_verify_mode(ssl_ctx) & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) != 0;
  19062. impl::apply_verify_mode(ssl_ctx, require);
  19063. return true;
  19064. }
  19065. inline long get_verify_error(const_session_t session) {
  19066. if (!session) { return -1; }
  19067. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  19068. return SSL_get_verify_result(ssl);
  19069. }
  19070. inline std::string verify_error_string(long error_code) {
  19071. if (error_code == X509_V_OK) { return ""; }
  19072. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  19073. return str ? str : "unknown error";
  19074. }
  19075. } // namespace tls
  19076. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  19077. /*
  19078. * Group 9: TLS abstraction layer - Mbed TLS backend
  19079. */
  19080. /*
  19081. * Mbed TLS Backend Implementation
  19082. */
  19083. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19084. namespace tls {
  19085. namespace impl {
  19086. // Mbed TLS session wrapper
  19087. struct MbedTlsSession {
  19088. mbedtls_ssl_context ssl;
  19089. socket_t sock = INVALID_SOCKET;
  19090. std::string hostname; // For client: set via set_sni
  19091. std::string sni_hostname; // For server: received from client via SNI callback
  19092. // Mbed TLS has no SSL_peek() equivalent, so is_peer_closed() must probe with
  19093. // a real 1-byte mbedtls_ssl_read(). If that probe lands on application data
  19094. // (e.g. a response that arrived while this side was still in its post-write
  19095. // check), the byte is pushed back here and served by the next read().
  19096. unsigned char peeked_byte = 0;
  19097. bool has_peeked_byte = false;
  19098. // Set by set_sni() when the caller disabled hostname verification, so the
  19099. // verify callback can clear the CN/SAN mismatch flag while still enforcing
  19100. // the rest of the chain (Mbed TLS ties SNI and identity checking together;
  19101. // OpenSSL and wolfSSL keep them independent).
  19102. bool suppress_hostname_mismatch = false;
  19103. // Copied from the owning MbedTlsContext at creation, so a handshake only
  19104. // ever runs the callback of its own context.
  19105. VerifyCallback verify_callback;
  19106. bool is_server = false;
  19107. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  19108. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  19109. MbedTlsSession(const MbedTlsSession &) = delete;
  19110. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  19111. };
  19112. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  19113. // queue)
  19114. inline int &mbedtls_last_error() {
  19115. static thread_local int err = 0;
  19116. return err;
  19117. }
  19118. // Helper to map Mbed TLS error to ErrorCode
  19119. inline ErrorCode map_mbedtls_error(int ret, int &out_errno,
  19120. uint32_t verify_flags) {
  19121. if (ret == 0) { return ErrorCode::Success; }
  19122. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  19123. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  19124. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  19125. return ErrorCode::PeerClosed;
  19126. }
  19127. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  19128. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  19129. out_errno = errno;
  19130. return ErrorCode::SyscallError;
  19131. }
  19132. if (ret == MBEDTLS_ERR_SSL_CONN_EOF) {
  19133. // EOF without close_notify
  19134. out_errno = 0;
  19135. return ErrorCode::SyscallError;
  19136. }
  19137. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  19138. // Unlike OpenSSL/wolfSSL, Mbed TLS folds the CN/SAN identity check into
  19139. // the handshake's chain verification (see set_sni()); a mismatch there
  19140. // is reported the same way as any other verify_flags bit. Report it as
  19141. // HostnameMismatch, matching the other backends and the post-handshake
  19142. // identity check below, but only when naming is the sole problem -
  19143. // if the chain itself is also untrusted/expired/etc., that takes
  19144. // priority over the naming detail.
  19145. if (verify_flags == static_cast<uint32_t>(hostname_mismatch_code())) {
  19146. return ErrorCode::HostnameMismatch;
  19147. }
  19148. return ErrorCode::CertVerifyFailed;
  19149. }
  19150. return ErrorCode::Fatal;
  19151. }
  19152. // Populates a TlsError from a failed (non-zero) mbedtls_ssl_handshake()
  19153. // return value, including the verify-flags-dependent HostnameMismatch
  19154. // mapping; shared by connect() and connect_nonblocking() so the
  19155. // backend_code policy for that mapping only lives in one place.
  19156. inline void fill_mbedtls_tls_error(TlsError &err, mbedtls_ssl_context &ssl,
  19157. int ret) {
  19158. auto verify_flags = mbedtls_ssl_get_verify_result(&ssl);
  19159. err.code = map_mbedtls_error(ret, err.sys_errno, verify_flags);
  19160. err.backend_code = err.code == ErrorCode::HostnameMismatch
  19161. ? static_cast<uint64_t>(verify_flags)
  19162. : static_cast<uint64_t>(-ret);
  19163. }
  19164. // A TLS 1.3 NewSessionTicket (signaled by default on Mbed TLS 4.x) is a
  19165. // non-fatal notification delivered between records, not an error and not
  19166. // application data, so I/O calls that see it should just be retried. Kept in
  19167. // one helper so the retry loops keep an intact "do { } while (...)" instead of
  19168. // splitting the closing brace across an #if.
  19169. inline bool mbedtls_is_session_ticket(int ret) {
  19170. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  19171. return ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
  19172. #else
  19173. (void)ret;
  19174. return false;
  19175. #endif
  19176. }
  19177. // BIO-like send callback for Mbed TLS
  19178. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  19179. size_t len) {
  19180. auto sock = *static_cast<socket_t *>(ctx);
  19181. #ifdef _WIN32
  19182. auto ret =
  19183. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  19184. if (ret == SOCKET_ERROR) {
  19185. int err = WSAGetLastError();
  19186. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  19187. return MBEDTLS_ERR_NET_SEND_FAILED;
  19188. }
  19189. #else
  19190. auto ret = send(sock, buf, len, 0);
  19191. if (ret < 0) {
  19192. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  19193. return MBEDTLS_ERR_SSL_WANT_WRITE;
  19194. }
  19195. return MBEDTLS_ERR_NET_SEND_FAILED;
  19196. }
  19197. #endif
  19198. return static_cast<int>(ret);
  19199. }
  19200. // BIO-like recv callback for Mbed TLS
  19201. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  19202. auto sock = *static_cast<socket_t *>(ctx);
  19203. #ifdef _WIN32
  19204. auto ret =
  19205. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  19206. if (ret == SOCKET_ERROR) {
  19207. int err = WSAGetLastError();
  19208. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  19209. return MBEDTLS_ERR_NET_RECV_FAILED;
  19210. }
  19211. #else
  19212. auto ret = recv(sock, buf, len, 0);
  19213. if (ret < 0) {
  19214. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  19215. return MBEDTLS_ERR_SSL_WANT_READ;
  19216. }
  19217. return MBEDTLS_ERR_NET_RECV_FAILED;
  19218. }
  19219. #endif
  19220. // EOF is MBEDTLS_ERR_SSL_CONN_EOF; only a close_notify is a clean end
  19221. return static_cast<int>(ret);
  19222. }
  19223. // MbedTlsContext constructor/destructor implementations
  19224. inline MbedTlsContext::MbedTlsContext() {
  19225. mbedtls_ssl_config_init(&conf);
  19226. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19227. mbedtls_entropy_init(&entropy);
  19228. mbedtls_ctr_drbg_init(&ctr_drbg);
  19229. #endif
  19230. mbedtls_x509_crt_init(&ca_chain);
  19231. mbedtls_x509_crt_init(&own_cert);
  19232. mbedtls_pk_init(&own_key);
  19233. }
  19234. inline MbedTlsContext::~MbedTlsContext() {
  19235. mbedtls_pk_free(&own_key);
  19236. mbedtls_x509_crt_free(&own_cert);
  19237. mbedtls_x509_crt_free(&ca_chain);
  19238. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19239. mbedtls_ctr_drbg_free(&ctr_drbg);
  19240. mbedtls_entropy_free(&entropy);
  19241. #endif
  19242. mbedtls_ssl_config_free(&conf);
  19243. }
  19244. // Thread-local storage for SNI captured during handshake
  19245. // This is needed because the SNI callback doesn't have a way to pass
  19246. // session-specific data before the session is fully set up
  19247. inline std::string &mbedpending_sni() {
  19248. static thread_local std::string sni;
  19249. return sni;
  19250. }
  19251. // SNI callback for Mbed TLS server to capture client's SNI hostname
  19252. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  19253. const unsigned char *name, size_t name_len) {
  19254. (void)p_ctx;
  19255. (void)ssl;
  19256. // Store SNI name in thread-local storage
  19257. // It will be retrieved and stored in the session after handshake
  19258. if (name && name_len > 0) {
  19259. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  19260. } else {
  19261. mbedpending_sni().clear();
  19262. }
  19263. return 0; // Accept any SNI
  19264. }
  19265. inline void mbedtls_clear_cn_mismatch(uint32_t *flags) {
  19266. *flags &= ~static_cast<uint32_t>(hostname_mismatch_code());
  19267. }
  19268. // MbedTLS verify callback wrapper
  19269. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  19270. int cert_depth, uint32_t *flags) {
  19271. // data points to the MbedTlsSession
  19272. auto *session = static_cast<MbedTlsSession *>(data);
  19273. // set_sni() disabled hostname verification for this session: ignore the
  19274. // CN/SAN mismatch flag, as the OpenSSL/wolfSSL backends do. The final
  19275. // pass/fail decision still comes from the remaining flags (and, below, from
  19276. // the user's own verify callback).
  19277. if (session->suppress_hostname_mismatch) { mbedtls_clear_cn_mismatch(flags); }
  19278. const auto &callback = session->verify_callback;
  19279. if (!callback) { return 0; } // Continue with default verification
  19280. // Build context
  19281. VerifyContext verify_ctx;
  19282. verify_ctx.session = static_cast<session_t>(session);
  19283. verify_ctx.cert = static_cast<cert_t>(crt);
  19284. verify_ctx.depth = cert_depth;
  19285. verify_ctx.preverify_ok = (*flags == 0);
  19286. verify_ctx.error_code = static_cast<long>(*flags);
  19287. // Convert Mbed TLS flags to error string
  19288. static thread_local char error_buf[256];
  19289. if (*flags != 0) {
  19290. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  19291. verify_ctx.error_string = error_buf;
  19292. } else {
  19293. verify_ctx.error_string = nullptr;
  19294. }
  19295. bool accepted = run_verify_callback(callback, verify_ctx);
  19296. if (accepted) {
  19297. // Overrides the built-in verification only on a server, as on OpenSSL and
  19298. // wolfSSL, whose clients check the verify result after the handshake
  19299. if (session->is_server) { *flags = 0; }
  19300. return 0;
  19301. }
  19302. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  19303. }
  19304. // Sets the authentication mode from whether the peer's certificate is required
  19305. // and whether a verify callback is set. OPTIONAL lets the callback run even if
  19306. // verification is not required (matching OpenSSL's SSL_VERIFY_PEER).
  19307. inline void apply_verify_mode(MbedTlsContext &mctx) {
  19308. auto mode = MBEDTLS_SSL_VERIFY_NONE;
  19309. if (mctx.verify_client) {
  19310. mode = MBEDTLS_SSL_VERIFY_REQUIRED;
  19311. } else if (mctx.verify_callback) {
  19312. mode = MBEDTLS_SSL_VERIFY_OPTIONAL;
  19313. }
  19314. mbedtls_ssl_conf_authmode(&mctx.conf, mode);
  19315. }
  19316. } // namespace impl
  19317. inline ctx_t create_client_context() {
  19318. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  19319. if (!ctx) { return nullptr; }
  19320. ctx->is_server = false;
  19321. #ifdef CPPHTTPLIB_MBEDTLS_V4
  19322. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  19323. if (!detail::ensure_mbedtls_psa_crypto()) {
  19324. delete ctx;
  19325. return nullptr;
  19326. }
  19327. int ret;
  19328. #else
  19329. // Seed the random number generator
  19330. const char *pers = "httplib_client";
  19331. int ret = mbedtls_ctr_drbg_seed(
  19332. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  19333. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  19334. if (ret != 0) {
  19335. impl::mbedtls_last_error() = ret;
  19336. delete ctx;
  19337. return nullptr;
  19338. }
  19339. #endif
  19340. // Set up SSL config for client
  19341. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  19342. MBEDTLS_SSL_TRANSPORT_STREAM,
  19343. MBEDTLS_SSL_PRESET_DEFAULT);
  19344. if (ret != 0) {
  19345. impl::mbedtls_last_error() = ret;
  19346. delete ctx;
  19347. return nullptr;
  19348. }
  19349. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19350. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  19351. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  19352. #endif
  19353. // Default: verify peer certificate
  19354. ctx->verify_client = true;
  19355. impl::apply_verify_mode(*ctx);
  19356. // Set minimum TLS version to 1.2
  19357. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19358. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19359. #else
  19360. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19361. MBEDTLS_SSL_MINOR_VERSION_3);
  19362. #endif
  19363. return static_cast<ctx_t>(ctx);
  19364. }
  19365. inline ctx_t create_server_context() {
  19366. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  19367. if (!ctx) { return nullptr; }
  19368. ctx->is_server = true;
  19369. #ifdef CPPHTTPLIB_MBEDTLS_V4
  19370. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  19371. if (!detail::ensure_mbedtls_psa_crypto()) {
  19372. delete ctx;
  19373. return nullptr;
  19374. }
  19375. int ret;
  19376. #else
  19377. // Seed the random number generator
  19378. const char *pers = "httplib_server";
  19379. int ret = mbedtls_ctr_drbg_seed(
  19380. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  19381. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  19382. if (ret != 0) {
  19383. impl::mbedtls_last_error() = ret;
  19384. delete ctx;
  19385. return nullptr;
  19386. }
  19387. #endif
  19388. // Set up SSL config for server
  19389. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  19390. MBEDTLS_SSL_TRANSPORT_STREAM,
  19391. MBEDTLS_SSL_PRESET_DEFAULT);
  19392. if (ret != 0) {
  19393. impl::mbedtls_last_error() = ret;
  19394. delete ctx;
  19395. return nullptr;
  19396. }
  19397. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19398. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  19399. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  19400. #endif
  19401. // Default: don't verify client
  19402. impl::apply_verify_mode(*ctx);
  19403. // Set minimum TLS version to 1.2
  19404. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19405. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19406. #else
  19407. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19408. MBEDTLS_SSL_MINOR_VERSION_3);
  19409. #endif
  19410. // Set SNI callback to capture client's SNI hostname
  19411. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  19412. return static_cast<ctx_t>(ctx);
  19413. }
  19414. inline void free_context(ctx_t ctx) {
  19415. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  19416. }
  19417. inline bool set_min_version(ctx_t ctx, Version version) {
  19418. if (!ctx) { return false; }
  19419. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19420. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19421. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  19422. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  19423. if (version >= Version::TLS1_3) {
  19424. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  19425. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  19426. #endif
  19427. }
  19428. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  19429. #else
  19430. // Mbed TLS 2.x uses major/minor version numbers
  19431. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  19432. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  19433. if (version >= Version::TLS1_3) {
  19434. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  19435. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  19436. #else
  19437. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  19438. #endif
  19439. }
  19440. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  19441. #endif
  19442. return true;
  19443. }
  19444. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  19445. if (!ctx || !pem) { return false; }
  19446. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19447. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  19448. // Add null terminator if not present
  19449. std::string pem_str(pem, len);
  19450. int ret = mbedtls_x509_crt_parse(
  19451. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  19452. pem_str.size() + 1);
  19453. if (ret != 0) {
  19454. impl::mbedtls_last_error() = ret;
  19455. return false;
  19456. }
  19457. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19458. return true;
  19459. }
  19460. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  19461. if (!ctx || !file_path) { return false; }
  19462. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19463. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  19464. if (ret != 0) {
  19465. impl::mbedtls_last_error() = ret;
  19466. return false;
  19467. }
  19468. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19469. return true;
  19470. }
  19471. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  19472. if (!ctx || !dir_path) { return false; }
  19473. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19474. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  19475. if (ret < 0) { // Returns number of certs on success, negative on error
  19476. impl::mbedtls_last_error() = ret;
  19477. return false;
  19478. }
  19479. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19480. return true;
  19481. }
  19482. inline bool load_system_certs(ctx_t ctx) {
  19483. if (!ctx) { return false; }
  19484. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19485. bool loaded = false;
  19486. #ifdef _WIN32
  19487. loaded = impl::enumerate_windows_system_certs(
  19488. [&](const unsigned char *data, size_t len) {
  19489. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  19490. });
  19491. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  19492. loaded = impl::enumerate_macos_keychain_certs(
  19493. [&](const unsigned char *data, size_t len) {
  19494. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  19495. });
  19496. #else
  19497. for (auto path = impl::system_ca_paths(); *path; ++path) {
  19498. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  19499. loaded = true;
  19500. break;
  19501. }
  19502. }
  19503. if (!loaded) {
  19504. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  19505. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  19506. loaded = true;
  19507. break;
  19508. }
  19509. }
  19510. }
  19511. #endif
  19512. if (loaded) {
  19513. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  19514. }
  19515. return loaded;
  19516. }
  19517. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  19518. const char *password) {
  19519. if (!ctx || !cert || !key) { return false; }
  19520. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19521. // Parse certificate
  19522. std::string cert_str(cert);
  19523. int ret = mbedtls_x509_crt_parse(
  19524. &mctx->own_cert,
  19525. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  19526. cert_str.size() + 1);
  19527. if (ret != 0) {
  19528. impl::mbedtls_last_error() = ret;
  19529. return false;
  19530. }
  19531. // Parse private key
  19532. std::string key_str(key);
  19533. const unsigned char *pwd =
  19534. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  19535. size_t pwd_len = password ? strlen(password) : 0;
  19536. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  19537. ret = mbedtls_pk_parse_key(
  19538. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  19539. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  19540. &mctx->ctr_drbg);
  19541. #else
  19542. ret = mbedtls_pk_parse_key(
  19543. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  19544. key_str.size() + 1, pwd, pwd_len);
  19545. #endif
  19546. if (ret != 0) {
  19547. impl::mbedtls_last_error() = ret;
  19548. return false;
  19549. }
  19550. // Verify that the certificate and private key match.
  19551. // Mbed TLS 4.x: mbedtls_pk_check_pair() reports a spurious mismatch for
  19552. // PSA-backed keys, so skip it and let the handshake surface a real mismatch.
  19553. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19554. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19555. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  19556. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  19557. #else
  19558. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  19559. #endif
  19560. if (ret != 0) {
  19561. impl::mbedtls_last_error() = ret;
  19562. return false;
  19563. }
  19564. #endif
  19565. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  19566. if (ret != 0) {
  19567. impl::mbedtls_last_error() = ret;
  19568. return false;
  19569. }
  19570. return true;
  19571. }
  19572. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  19573. const char *key_path, const char *password) {
  19574. if (!ctx || !cert_path || !key_path) { return false; }
  19575. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19576. // Parse certificate file
  19577. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  19578. if (ret != 0) {
  19579. impl::mbedtls_last_error() = ret;
  19580. return false;
  19581. }
  19582. // Parse private key file
  19583. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  19584. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  19585. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  19586. #else
  19587. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  19588. #endif
  19589. if (ret != 0) {
  19590. impl::mbedtls_last_error() = ret;
  19591. return false;
  19592. }
  19593. // Verify that the certificate and private key match.
  19594. // Mbed TLS 4.x: see set_client_cert() — skip the spurious check_pair.
  19595. #ifndef CPPHTTPLIB_MBEDTLS_V4
  19596. #ifdef CPPHTTPLIB_MBEDTLS_V3
  19597. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  19598. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  19599. #else
  19600. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  19601. #endif
  19602. if (ret != 0) {
  19603. impl::mbedtls_last_error() = ret;
  19604. return false;
  19605. }
  19606. #endif
  19607. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  19608. if (ret != 0) {
  19609. impl::mbedtls_last_error() = ret;
  19610. return false;
  19611. }
  19612. return true;
  19613. }
  19614. inline void set_verify_client(ctx_t ctx, bool require) {
  19615. if (!ctx) { return; }
  19616. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19617. mctx->verify_client = require;
  19618. impl::apply_verify_mode(*mctx);
  19619. }
  19620. inline session_t create_session(ctx_t ctx, socket_t sock) {
  19621. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  19622. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  19623. auto session = new (std::nothrow) impl::MbedTlsSession();
  19624. if (!session) { return nullptr; }
  19625. session->sock = sock;
  19626. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  19627. if (ret != 0) {
  19628. impl::mbedtls_last_error() = ret;
  19629. delete session;
  19630. return nullptr;
  19631. }
  19632. // Explicitly opt out of in-handshake hostname verification by default;
  19633. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  19634. // fails outright when no hostname was set. set_sni() installs the real
  19635. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  19636. // caller verifies the certificate identity post-handshake via
  19637. // verify_hostname().
  19638. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  19639. // Set BIO callbacks
  19640. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  19641. impl::mbedtls_net_recv_cb, nullptr);
  19642. // Installed always, as it also masks the hostname mismatch that set_sni()
  19643. // may ask for. The session runs its own copy of the user's callback, which
  19644. // set_verify_callback() cannot replace under a handshake.
  19645. session->verify_callback = mctx->verify_callback;
  19646. session->is_server = mctx->is_server;
  19647. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback, session);
  19648. return static_cast<session_t>(session);
  19649. }
  19650. inline void free_session(session_t session) {
  19651. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  19652. }
  19653. inline bool set_sni(session_t session, const char *hostname,
  19654. bool verify_hostname) {
  19655. if (!session || !hostname) { return false; }
  19656. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19657. // mbedtls_ssl_set_hostname() both sends the SNI extension and binds the
  19658. // handshake-time CN/SAN check to `hostname`; the two can't be requested
  19659. // independently, so a disabled hostname check is handled below by masking
  19660. // the resulting mismatch flag instead of skipping this call.
  19661. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  19662. if (ret != 0) {
  19663. impl::mbedtls_last_error() = ret;
  19664. return false;
  19665. }
  19666. msession->hostname = hostname;
  19667. if (!verify_hostname) { msession->suppress_hostname_mismatch = true; }
  19668. return true;
  19669. }
  19670. inline TlsError connect(session_t session) {
  19671. TlsError err;
  19672. if (!session) {
  19673. err.code = ErrorCode::Fatal;
  19674. return err;
  19675. }
  19676. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19677. int ret;
  19678. do {
  19679. ret = mbedtls_ssl_handshake(&msession->ssl);
  19680. } while (impl::mbedtls_is_session_ticket(ret));
  19681. if (ret == 0) {
  19682. err.code = ErrorCode::Success;
  19683. } else {
  19684. impl::fill_mbedtls_tls_error(err, msession->ssl, ret);
  19685. impl::mbedtls_last_error() = ret;
  19686. }
  19687. return err;
  19688. }
  19689. inline TlsError accept(session_t session) {
  19690. // A failed handshake leaves its SNI behind, so start without it
  19691. impl::mbedpending_sni().clear();
  19692. // Same as connect for Mbed TLS - handshake works for both client and server
  19693. auto result = connect(session);
  19694. // After successful handshake, capture SNI from thread-local storage
  19695. if (result.code == ErrorCode::Success && session) {
  19696. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19697. msession->sni_hostname = std::move(impl::mbedpending_sni());
  19698. }
  19699. return result;
  19700. }
  19701. inline bool connect_nonblocking(session_t session, socket_t sock,
  19702. time_t timeout_sec, time_t timeout_usec,
  19703. TlsError *err,
  19704. const std::function<bool()> &interrupted) {
  19705. if (!session) {
  19706. if (err) { err->code = ErrorCode::Fatal; }
  19707. return false;
  19708. }
  19709. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19710. // Set socket to non-blocking mode
  19711. detail::set_nonblocking(sock, true);
  19712. auto cleanup =
  19713. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  19714. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  19715. int ret;
  19716. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  19717. // Non-fatal TLS 1.3 ticket; retry immediately.
  19718. if (impl::mbedtls_is_session_ticket(ret)) { continue; }
  19719. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  19720. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  19721. continue;
  19722. }
  19723. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  19724. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  19725. continue;
  19726. }
  19727. }
  19728. // TlsError or timeout
  19729. if (err) { impl::fill_mbedtls_tls_error(*err, msession->ssl, ret); }
  19730. impl::mbedtls_last_error() = ret;
  19731. return false;
  19732. }
  19733. if (err) { err->code = ErrorCode::Success; }
  19734. return true;
  19735. }
  19736. inline bool accept_nonblocking(session_t session, socket_t sock,
  19737. time_t timeout_sec, time_t timeout_usec,
  19738. TlsError *err) {
  19739. // A failed handshake leaves its SNI behind, so start without it
  19740. impl::mbedpending_sni().clear();
  19741. // Same implementation as connect for Mbed TLS
  19742. bool result =
  19743. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  19744. // After successful handshake, capture SNI from thread-local storage
  19745. if (result && session) {
  19746. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19747. msession->sni_hostname = std::move(impl::mbedpending_sni());
  19748. }
  19749. return result;
  19750. }
  19751. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  19752. if (!session || !buf) {
  19753. err.code = ErrorCode::Fatal;
  19754. return -1;
  19755. }
  19756. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19757. // Serve a byte consumed by the is_peer_closed() probe before reading more.
  19758. if (msession->has_peeked_byte) {
  19759. if (len == 0) { return 0; }
  19760. auto p = static_cast<unsigned char *>(buf);
  19761. p[0] = msession->peeked_byte;
  19762. msession->has_peeked_byte = false;
  19763. size_t n = 1;
  19764. // Top up with any already-decrypted bytes without risking a block.
  19765. if (len > 1 && mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  19766. int extra = mbedtls_ssl_read(&msession->ssl, p + 1, len - 1);
  19767. if (extra > 0) { n += static_cast<size_t>(extra); }
  19768. }
  19769. err.code = ErrorCode::Success;
  19770. return static_cast<ssize_t>(n);
  19771. }
  19772. int ret;
  19773. do {
  19774. ret = mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf),
  19775. len);
  19776. } while (impl::mbedtls_is_session_ticket(ret));
  19777. if (ret > 0) {
  19778. err.code = ErrorCode::Success;
  19779. return static_cast<ssize_t>(ret);
  19780. }
  19781. // 0 means EOF without close_notify, which is an error as on OpenSSL
  19782. if (ret == 0) { ret = MBEDTLS_ERR_SSL_CONN_EOF; }
  19783. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  19784. err.backend_code = static_cast<uint64_t>(-ret);
  19785. impl::mbedtls_last_error() = ret;
  19786. // mbedTLS signals a clean close_notify via a negative error code rather
  19787. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  19788. if (err.code == ErrorCode::PeerClosed) { return 0; }
  19789. return -1;
  19790. }
  19791. inline ssize_t write(session_t session, const void *buf, size_t len,
  19792. TlsError &err) {
  19793. if (!session || !buf) {
  19794. err.code = ErrorCode::Fatal;
  19795. return -1;
  19796. }
  19797. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19798. int ret;
  19799. do {
  19800. ret = mbedtls_ssl_write(&msession->ssl,
  19801. static_cast<const unsigned char *>(buf), len);
  19802. } while (impl::mbedtls_is_session_ticket(ret));
  19803. if (ret > 0) {
  19804. err.code = ErrorCode::Success;
  19805. return static_cast<ssize_t>(ret);
  19806. }
  19807. if (ret == 0) {
  19808. err.code = ErrorCode::PeerClosed;
  19809. return 0;
  19810. }
  19811. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  19812. err.backend_code = static_cast<uint64_t>(-ret);
  19813. impl::mbedtls_last_error() = ret;
  19814. return -1;
  19815. }
  19816. inline int pending(const_session_t session) {
  19817. if (!session) { return 0; }
  19818. auto msession =
  19819. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  19820. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl)) +
  19821. (msession->has_peeked_byte ? 1 : 0);
  19822. }
  19823. inline void shutdown(session_t session, bool graceful) {
  19824. if (!session) { return; }
  19825. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19826. if (graceful) {
  19827. // Try to send close_notify, but don't block forever
  19828. int ret;
  19829. int attempts = 0;
  19830. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  19831. attempts < 3) {
  19832. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  19833. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  19834. break;
  19835. }
  19836. attempts++;
  19837. }
  19838. }
  19839. }
  19840. inline bool is_peer_closed(session_t session, socket_t sock) {
  19841. if (!session || sock == INVALID_SOCKET) { return true; }
  19842. auto msession = static_cast<impl::MbedTlsSession *>(session);
  19843. // Check if there's already decrypted or pushed-back data available.
  19844. // If so, the connection is definitely alive.
  19845. if (msession->has_peeked_byte ||
  19846. mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  19847. return false;
  19848. }
  19849. // Set socket to non-blocking to avoid blocking on read
  19850. detail::set_nonblocking(sock, true);
  19851. auto cleanup =
  19852. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  19853. // Probe with a 1-byte read (Mbed TLS has no peek API). If the probe lands
  19854. // on application data — e.g. a response that already arrived — push the
  19855. // byte back so the next read() delivers it instead of losing it.
  19856. unsigned char buf;
  19857. int ret;
  19858. do {
  19859. ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  19860. } while (impl::mbedtls_is_session_ticket(ret));
  19861. // If we got data or WANT_READ (would block), connection is alive
  19862. if (ret > 0) {
  19863. msession->peeked_byte = buf;
  19864. msession->has_peeked_byte = true;
  19865. return false;
  19866. }
  19867. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  19868. // If we get a peer close notify or a connection reset, the peer is closed
  19869. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  19870. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  19871. }
  19872. inline cert_t get_peer_cert(const_session_t session) {
  19873. if (!session) { return nullptr; }
  19874. auto msession =
  19875. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  19876. // Mbed TLS returns a pointer to the internal peer cert chain.
  19877. // WARNING: This pointer is only valid while the session is active.
  19878. // Do not use the certificate after calling free_session().
  19879. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  19880. return const_cast<mbedtls_x509_crt *>(cert);
  19881. }
  19882. inline size_t get_peer_certs(const_session_t session,
  19883. std::vector<cert_t> &certs) {
  19884. certs.clear();
  19885. // Mbed TLS parses the whole received chain into a list headed by the peer
  19886. // certificate, owned by the session like get_peer_cert()'s result
  19887. for (auto crt = static_cast<mbedtls_x509_crt *>(get_peer_cert(session));
  19888. crt && crt->raw.len > 0; crt = crt->next) {
  19889. certs.push_back(static_cast<cert_t>(crt));
  19890. }
  19891. return certs.size();
  19892. }
  19893. inline void free_cert(cert_t cert) {
  19894. // Mbed TLS: every cert_t handed out points into a session's or a context's
  19895. // chain, so there is nothing to free. Callers still call this for the other
  19896. // backends.
  19897. (void)cert;
  19898. }
  19899. inline bool verify_hostname(cert_t cert, const char *hostname) {
  19900. if (!cert || !hostname) { return false; }
  19901. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  19902. std::string host_str(hostname);
  19903. // Check if hostname is an IP address (IPv4 or IPv6)
  19904. unsigned char ip_bytes[16];
  19905. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  19906. auto is_ip = ip_len > 0;
  19907. // Check Subject Alternative Names (SAN). Mbed TLS keeps the GeneralName type
  19908. // in buf.tag and the raw value in buf.p / buf.len.
  19909. for (auto san = &mcert->subject_alt_names; san; san = san->next) {
  19910. if (!san->buf.p || san->buf.len == 0) { continue; }
  19911. const unsigned char *p = san->buf.p;
  19912. size_t len = san->buf.len;
  19913. auto san_type = san->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK;
  19914. if (is_ip) {
  19915. // For an IP host, only a matching iPAddress SAN of the same family
  19916. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  19917. if (san_type == MBEDTLS_X509_SAN_IP_ADDRESS && len == ip_len &&
  19918. memcmp(p, ip_bytes, ip_len) == 0) {
  19919. return true;
  19920. }
  19921. } else if (san_type == MBEDTLS_X509_SAN_DNS_NAME) {
  19922. std::string san_name(reinterpret_cast<const char *>(p), len);
  19923. if (detail::match_hostname(san_name, host_str)) { return true; }
  19924. }
  19925. }
  19926. return false;
  19927. }
  19928. inline uint64_t hostname_mismatch_code() {
  19929. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  19930. }
  19931. inline long get_verify_result(const_session_t session) {
  19932. if (!session) { return -1; }
  19933. auto msession =
  19934. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  19935. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  19936. // Return 0 (X509_V_OK equivalent) if verification passed
  19937. return flags == 0 ? 0 : static_cast<long>(flags);
  19938. }
  19939. inline std::string get_cert_subject_cn(cert_t cert) {
  19940. if (!cert) return "";
  19941. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  19942. // Find the CN in the subject
  19943. const mbedtls_x509_name *name = &x509->subject;
  19944. while (name != nullptr) {
  19945. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  19946. return std::string(reinterpret_cast<const char *>(name->val.p),
  19947. name->val.len);
  19948. }
  19949. name = name->next;
  19950. }
  19951. return "";
  19952. }
  19953. inline std::string get_cert_issuer_name(cert_t cert) {
  19954. if (!cert) return "";
  19955. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  19956. // Build a human-readable issuer name string
  19957. char buf[512];
  19958. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  19959. if (ret < 0) return "";
  19960. return std::string(buf);
  19961. }
  19962. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  19963. sans.clear();
  19964. if (!cert) return false;
  19965. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  19966. // Parse the Subject Alternative Name extension
  19967. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  19968. while (cur != nullptr) {
  19969. if (cur->buf.len > 0) {
  19970. const unsigned char *p = cur->buf.p;
  19971. size_t value_len = cur->buf.len;
  19972. SanEntry entry;
  19973. switch (cur->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK) {
  19974. case MBEDTLS_X509_SAN_DNS_NAME:
  19975. entry.type = SanType::DNS;
  19976. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  19977. break;
  19978. case MBEDTLS_X509_SAN_IP_ADDRESS:
  19979. entry.type = SanType::IP;
  19980. if (value_len == 4) {
  19981. // IPv4
  19982. char buf[16];
  19983. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  19984. entry.value = buf;
  19985. } else if (value_len == 16) {
  19986. // IPv6
  19987. char buf[64];
  19988. snprintf(buf, sizeof(buf),
  19989. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  19990. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  19991. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9],
  19992. p[10], p[11], p[12], p[13], p[14], p[15]);
  19993. entry.value = buf;
  19994. }
  19995. break;
  19996. case MBEDTLS_X509_SAN_RFC822_NAME:
  19997. entry.type = SanType::EMAIL;
  19998. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  19999. break;
  20000. case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER:
  20001. entry.type = SanType::URI;
  20002. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  20003. break;
  20004. default: entry.type = SanType::OTHER; break;
  20005. }
  20006. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  20007. }
  20008. cur = cur->next;
  20009. }
  20010. return true;
  20011. }
  20012. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  20013. time_t &not_after) {
  20014. if (!cert) return false;
  20015. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  20016. // Convert mbedtls_x509_time to time_t
  20017. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  20018. struct tm tm_time = {};
  20019. tm_time.tm_year = t.year - 1900;
  20020. tm_time.tm_mon = t.mon - 1;
  20021. tm_time.tm_mday = t.day;
  20022. tm_time.tm_hour = t.hour;
  20023. tm_time.tm_min = t.min;
  20024. tm_time.tm_sec = t.sec;
  20025. #ifdef _WIN32
  20026. return _mkgmtime(&tm_time);
  20027. #else
  20028. return timegm(&tm_time);
  20029. #endif
  20030. };
  20031. not_before = to_time_t(x509->valid_from);
  20032. not_after = to_time_t(x509->valid_to);
  20033. return true;
  20034. }
  20035. inline std::string get_cert_serial(cert_t cert) {
  20036. if (!cert) return "";
  20037. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  20038. // Convert serial number to hex string
  20039. std::string result;
  20040. result.reserve(x509->serial.len * 2);
  20041. for (size_t i = 0; i < x509->serial.len; i++) {
  20042. char hex[3];
  20043. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  20044. result += hex;
  20045. }
  20046. return result;
  20047. }
  20048. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  20049. if (!cert) return false;
  20050. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  20051. if (!crt->raw.p || crt->raw.len == 0) return false;
  20052. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  20053. return true;
  20054. }
  20055. inline const char *get_sni(const_session_t session) {
  20056. if (!session) return nullptr;
  20057. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  20058. // For server: return SNI received from client during handshake
  20059. if (!msession->sni_hostname.empty()) {
  20060. return msession->sni_hostname.c_str();
  20061. }
  20062. // For client: return the hostname set via set_sni
  20063. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  20064. return nullptr;
  20065. }
  20066. inline uint64_t peek_error() {
  20067. // Mbed TLS doesn't have an error queue, return the last error
  20068. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  20069. }
  20070. inline uint64_t get_error() {
  20071. // Mbed TLS doesn't have an error queue, return and clear the last error
  20072. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  20073. impl::mbedtls_last_error() = 0;
  20074. return err;
  20075. }
  20076. inline std::string error_string(uint64_t code) {
  20077. char buf[256];
  20078. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  20079. return std::string(buf);
  20080. }
  20081. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  20082. #ifdef CPPHTTPLIB_MBEDTLS_V4
  20083. // Parsing certificates needs PSA Crypto, and no context may exist yet
  20084. if (!detail::ensure_mbedtls_psa_crypto()) { return nullptr; }
  20085. #endif
  20086. if (!pem) { return nullptr; }
  20087. // mbedtls_x509_crt_parse expects null-terminated PEM
  20088. std::string pem_str(pem, len);
  20089. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  20090. if (!ca_chain) { return nullptr; }
  20091. mbedtls_x509_crt_init(ca_chain);
  20092. auto ret = mbedtls_x509_crt_parse(
  20093. ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  20094. pem_str.size() + 1);
  20095. if (ret != 0) {
  20096. mbedtls_x509_crt_free(ca_chain);
  20097. delete ca_chain;
  20098. return nullptr;
  20099. }
  20100. return static_cast<ca_store_t>(ca_chain);
  20101. }
  20102. inline void free_ca_store(ca_store_t store) {
  20103. if (store) {
  20104. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  20105. mbedtls_x509_crt_free(ca_chain);
  20106. delete ca_chain;
  20107. }
  20108. }
  20109. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  20110. if (!ctx || !store) { return false; }
  20111. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20112. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  20113. // Free existing CA chain
  20114. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  20115. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  20116. // Copy the CA chain (deep copy)
  20117. // Parse from the raw data of the source cert
  20118. mbedtls_x509_crt *src = ca_chain;
  20119. while (src != nullptr) {
  20120. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  20121. src->raw.len);
  20122. if (ret != 0) {
  20123. free_ca_store(store);
  20124. return false;
  20125. }
  20126. src = src->next;
  20127. }
  20128. // This function takes ownership of the store; the chain was deep-copied
  20129. // above, so release the source
  20130. free_ca_store(store);
  20131. // Update the SSL config to use the new CA chain
  20132. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  20133. return true;
  20134. }
  20135. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  20136. certs.clear();
  20137. if (!ctx) { return 0; }
  20138. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20139. // Owned by the context; see free_cert()
  20140. for (auto cert = &mbed_ctx->ca_chain; cert && cert->raw.len > 0;
  20141. cert = cert->next) {
  20142. certs.push_back(static_cast<cert_t>(cert));
  20143. }
  20144. return certs.size();
  20145. }
  20146. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  20147. std::vector<std::string> names;
  20148. if (!ctx) { return names; }
  20149. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20150. // Iterate through the CA chain
  20151. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  20152. while (cert != nullptr && cert->raw.len > 0) {
  20153. char buf[512];
  20154. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  20155. if (ret > 0) { names.push_back(buf); }
  20156. cert = cert->next;
  20157. }
  20158. return names;
  20159. }
  20160. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  20161. const char *key_pem, const char *password) {
  20162. if (!ctx || !cert_pem || !key_pem) { return false; }
  20163. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20164. // Parse into new objects first, so that a bad pair leaves the old one in
  20165. // place, and swap them in after; the old ones are freed on the way out.
  20166. mbedtls_x509_crt cert;
  20167. mbedtls_pk_context key;
  20168. mbedtls_x509_crt_init(&cert);
  20169. mbedtls_pk_init(&key);
  20170. auto se = detail::scope_exit([&] {
  20171. mbedtls_x509_crt_free(&cert);
  20172. mbedtls_pk_free(&key);
  20173. });
  20174. // Parse certificate PEM
  20175. int ret = mbedtls_x509_crt_parse(
  20176. &cert, reinterpret_cast<const unsigned char *>(cert_pem),
  20177. strlen(cert_pem) + 1);
  20178. if (ret != 0) {
  20179. impl::mbedtls_last_error() = ret;
  20180. return false;
  20181. }
  20182. // Parse private key PEM
  20183. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  20184. ret = mbedtls_pk_parse_key(
  20185. &key, reinterpret_cast<const unsigned char *>(key_pem),
  20186. strlen(key_pem) + 1,
  20187. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  20188. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  20189. &mbed_ctx->ctr_drbg);
  20190. #else
  20191. ret = mbedtls_pk_parse_key(
  20192. &key, reinterpret_cast<const unsigned char *>(key_pem),
  20193. strlen(key_pem) + 1,
  20194. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  20195. password ? strlen(password) : 0);
  20196. #endif
  20197. if (ret != 0) {
  20198. impl::mbedtls_last_error() = ret;
  20199. return false;
  20200. }
  20201. std::swap(mbed_ctx->own_cert, cert);
  20202. std::swap(mbed_ctx->own_key, key);
  20203. // Configure SSL to use the new certificate and key
  20204. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  20205. &mbed_ctx->own_key);
  20206. if (ret != 0) {
  20207. impl::mbedtls_last_error() = ret;
  20208. return false;
  20209. }
  20210. return true;
  20211. }
  20212. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  20213. if (!ctx || !ca_pem) { return false; }
  20214. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20215. // Parse into a new chain first, so that a bad one leaves the old in place
  20216. mbedtls_x509_crt chain;
  20217. mbedtls_x509_crt_init(&chain);
  20218. auto se = detail::scope_exit([&] { mbedtls_x509_crt_free(&chain); });
  20219. // Parse CA PEM
  20220. int ret = mbedtls_x509_crt_parse(
  20221. &chain, reinterpret_cast<const unsigned char *>(ca_pem),
  20222. strlen(ca_pem) + 1);
  20223. if (ret != 0) {
  20224. impl::mbedtls_last_error() = ret;
  20225. return false;
  20226. }
  20227. std::swap(mbed_ctx->ca_chain, chain);
  20228. // Update SSL config to use new CA chain
  20229. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  20230. return true;
  20231. }
  20232. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  20233. if (!ctx) { return false; }
  20234. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  20235. // create_session() hands each session its own copy to run.
  20236. mbed_ctx->verify_callback = std::move(callback);
  20237. impl::apply_verify_mode(*mbed_ctx);
  20238. return true;
  20239. }
  20240. inline long get_verify_error(const_session_t session) {
  20241. if (!session) { return -1; }
  20242. auto *msession =
  20243. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  20244. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  20245. }
  20246. inline std::string verify_error_string(long error_code) {
  20247. if (error_code == 0) { return ""; }
  20248. char buf[256];
  20249. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  20250. static_cast<uint32_t>(error_code));
  20251. // Remove trailing newline if present
  20252. std::string result(buf);
  20253. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  20254. result.pop_back();
  20255. }
  20256. return result;
  20257. }
  20258. } // namespace tls
  20259. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  20260. /*
  20261. * Group 10: TLS abstraction layer - wolfSSL backend
  20262. */
  20263. /*
  20264. * wolfSSL Backend Implementation
  20265. */
  20266. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  20267. namespace tls {
  20268. namespace impl {
  20269. // wolfSSL session wrapper
  20270. struct WolfSSLSession {
  20271. WOLFSSL *ssl = nullptr;
  20272. socket_t sock = INVALID_SOCKET;
  20273. std::string hostname; // For client: set via set_sni
  20274. std::string sni_hostname; // For server: received from client via SNI callback
  20275. WolfSSLSession() = default;
  20276. ~WolfSSLSession() {
  20277. if (ssl) { wolfSSL_free(ssl); }
  20278. }
  20279. WolfSSLSession(const WolfSSLSession &) = delete;
  20280. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  20281. };
  20282. // Thread-local error code accessor for wolfSSL
  20283. inline uint64_t &wolfssl_last_error() {
  20284. static thread_local uint64_t err = 0;
  20285. return err;
  20286. }
  20287. // Helper to map wolfSSL error to ErrorCode.
  20288. // ssl_error is the value from wolfSSL_get_error().
  20289. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  20290. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  20291. int &out_errno) {
  20292. switch (ssl_error) {
  20293. case SSL_ERROR_NONE: return ErrorCode::Success;
  20294. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  20295. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  20296. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  20297. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  20298. // EOF without close_notify
  20299. case SOCKET_PEER_CLOSED_E: out_errno = 0; return ErrorCode::SyscallError;
  20300. default:
  20301. if (ssl) {
  20302. // wolfSSL stores the low-level error code as a negative value.
  20303. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  20304. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  20305. if (low_err == DOMAIN_NAME_MISMATCH) {
  20306. return ErrorCode::HostnameMismatch;
  20307. }
  20308. // Check verify result to distinguish cert verification from generic SSL
  20309. // errors.
  20310. long vr = wolfSSL_get_verify_result(ssl);
  20311. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  20312. }
  20313. return ErrorCode::Fatal;
  20314. }
  20315. }
  20316. // WolfSSLContext constructor/destructor implementations
  20317. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  20318. inline WolfSSLContext::~WolfSSLContext() {
  20319. if (ctx) { wolfSSL_CTX_free(ctx); }
  20320. }
  20321. // Thread-local storage for SNI captured during handshake
  20322. inline std::string &wolfssl_pending_sni() {
  20323. static thread_local std::string sni;
  20324. return sni;
  20325. }
  20326. // SNI callback for wolfSSL server to capture client's SNI hostname
  20327. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  20328. (void)ret;
  20329. (void)exArg;
  20330. void *name_data = nullptr;
  20331. unsigned short name_len =
  20332. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  20333. if (name_data && name_len > 0) {
  20334. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  20335. name_len);
  20336. } else {
  20337. wolfssl_pending_sni().clear();
  20338. }
  20339. return 0; // Continue regardless
  20340. }
  20341. // The WOLFSSL_CTX points back to its WolfSSLContext, so a handshake only ever
  20342. // runs the verify callback of its own context.
  20343. inline int context_ex_data_index() {
  20344. static const auto index =
  20345. wolfSSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
  20346. return index;
  20347. }
  20348. // Each WOLFSSL points back to its WolfSSLSession, the session_t that every
  20349. // other tls:: function takes.
  20350. inline int session_ex_data_index() {
  20351. static const auto index =
  20352. wolfSSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
  20353. return index;
  20354. }
  20355. // A resumed session skips the client's certificate, so a server that checks
  20356. // one would let in a certificate checked against another server's CA, as
  20357. // wolfSSL shares its session cache between contexts, or against a CA since
  20358. // replaced by update_server_client_ca().
  20359. inline void disable_server_resumption(WolfSSLContext *wctx) {
  20360. if (!wctx->is_server) { return; }
  20361. wolfSSL_CTX_set_session_cache_mode(wctx->ctx, WOLFSSL_SESS_CACHE_OFF);
  20362. #ifdef HAVE_SESSION_TICKET
  20363. wolfSSL_CTX_NoTicketTLSv12(wctx->ctx);
  20364. #endif
  20365. }
  20366. // wolfSSL verify callback wrapper
  20367. inline int wolfssl_verify_callback(int preverify_ok,
  20368. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  20369. // Get the WOLFSSL object from the X509_STORE_CTX
  20370. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  20371. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  20372. if (!ssl) { return preverify_ok; }
  20373. auto wctx = static_cast<WolfSSLContext *>(wolfSSL_CTX_get_ex_data(
  20374. wolfSSL_get_SSL_CTX(ssl), context_ex_data_index()));
  20375. if (!wctx) { return preverify_ok; }
  20376. std::shared_ptr<VerifyCallback> callback;
  20377. {
  20378. std::lock_guard<std::mutex> guard(verify_callback_mutex());
  20379. callback = wctx->verify_callback;
  20380. }
  20381. if (!callback) { return preverify_ok; }
  20382. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  20383. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  20384. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  20385. VerifyContext verify_ctx;
  20386. verify_ctx.session = wolfSSL_get_ex_data(ssl, session_ex_data_index());
  20387. verify_ctx.cert = static_cast<cert_t>(cert);
  20388. verify_ctx.depth = depth;
  20389. verify_ctx.preverify_ok = (preverify_ok != 0);
  20390. verify_ctx.error_code = static_cast<long>(err);
  20391. if (err != 0) {
  20392. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  20393. } else {
  20394. verify_ctx.error_string = nullptr;
  20395. }
  20396. auto accepted = run_verify_callback(*callback, verify_ctx);
  20397. // A client verifying the server during the handshake, which is what
  20398. // set_verify_client(ctx, true) asks for there, keeps the built-in verdict
  20399. if (!wolfSSL_is_server(ssl) &&
  20400. (wolfSSL_get_verify_mode(ssl) & WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  20401. accepted = accepted && preverify_ok;
  20402. }
  20403. return accepted ? 1 : 0;
  20404. }
  20405. // Sets the verify mode from whether the peer's certificate is required and
  20406. // whether a verify callback is set.
  20407. inline void apply_verify_mode(WolfSSLContext &wctx) {
  20408. auto has_callback = static_cast<bool>(wctx.verify_callback);
  20409. if (wctx.verify_client || has_callback) { disable_server_resumption(&wctx); }
  20410. auto mode = wctx.verify_client
  20411. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  20412. : (has_callback ? SSL_VERIFY_PEER : SSL_VERIFY_NONE);
  20413. wolfSSL_CTX_set_verify(wctx.ctx, mode,
  20414. has_callback ? wolfssl_verify_callback : nullptr);
  20415. }
  20416. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  20417. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  20418. wolfSSL_CTX_set_default_passwd_cb(
  20419. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  20420. auto *pwd = static_cast<const char *>(userdata);
  20421. if (!pwd) return 0;
  20422. auto len = static_cast<int>(strlen(pwd));
  20423. if (len > size) len = size;
  20424. memcpy(buf, pwd, static_cast<size_t>(len));
  20425. return len;
  20426. });
  20427. }
  20428. } // namespace impl
  20429. inline ctx_t create_client_context() {
  20430. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  20431. if (!ctx) { return nullptr; }
  20432. ctx->is_server = false;
  20433. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  20434. if (!method) {
  20435. delete ctx;
  20436. return nullptr;
  20437. }
  20438. ctx->ctx = wolfSSL_CTX_new(method);
  20439. if (!ctx->ctx ||
  20440. wolfSSL_CTX_set_ex_data(ctx->ctx, impl::context_ex_data_index(), ctx) !=
  20441. WOLFSSL_SUCCESS) {
  20442. delete ctx;
  20443. return nullptr;
  20444. }
  20445. // Default: verify peer certificate
  20446. ctx->verify_client = true;
  20447. impl::apply_verify_mode(*ctx);
  20448. return static_cast<ctx_t>(ctx);
  20449. }
  20450. inline ctx_t create_server_context() {
  20451. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  20452. if (!ctx) { return nullptr; }
  20453. ctx->is_server = true;
  20454. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  20455. if (!method) {
  20456. delete ctx;
  20457. return nullptr;
  20458. }
  20459. ctx->ctx = wolfSSL_CTX_new(method);
  20460. if (!ctx->ctx ||
  20461. wolfSSL_CTX_set_ex_data(ctx->ctx, impl::context_ex_data_index(), ctx) !=
  20462. WOLFSSL_SUCCESS) {
  20463. delete ctx;
  20464. return nullptr;
  20465. }
  20466. // Default: don't verify client
  20467. impl::apply_verify_mode(*ctx);
  20468. // Enable SNI on server
  20469. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  20470. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  20471. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  20472. return static_cast<ctx_t>(ctx);
  20473. }
  20474. inline void free_context(ctx_t ctx) {
  20475. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  20476. }
  20477. inline bool set_min_version(ctx_t ctx, Version version) {
  20478. if (!ctx) { return false; }
  20479. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20480. int min_ver = WOLFSSL_TLSV1_2;
  20481. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  20482. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  20483. }
  20484. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  20485. if (!ctx || !pem) { return false; }
  20486. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20487. int ret = wolfSSL_CTX_load_verify_buffer(
  20488. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  20489. static_cast<long>(len), SSL_FILETYPE_PEM);
  20490. if (ret != SSL_SUCCESS) {
  20491. impl::wolfssl_last_error() =
  20492. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20493. return false;
  20494. }
  20495. wctx->ca_pem_data_.append(pem, len);
  20496. return true;
  20497. }
  20498. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  20499. if (!ctx || !file_path) { return false; }
  20500. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20501. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  20502. if (ret != SSL_SUCCESS) {
  20503. impl::wolfssl_last_error() =
  20504. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20505. return false;
  20506. }
  20507. return true;
  20508. }
  20509. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  20510. if (!ctx || !dir_path) { return false; }
  20511. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20512. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  20513. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  20514. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  20515. // immediately. Return true even on failure since the CA file may have
  20516. // already been loaded, matching OpenSSL's lenient behavior.
  20517. (void)ret;
  20518. return true;
  20519. }
  20520. inline bool load_system_certs(ctx_t ctx) {
  20521. if (!ctx) { return false; }
  20522. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20523. bool loaded = false;
  20524. #ifdef _WIN32
  20525. loaded = impl::enumerate_windows_system_certs(
  20526. [&](const unsigned char *data, size_t len) {
  20527. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  20528. static_cast<long>(len),
  20529. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  20530. });
  20531. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  20532. loaded = impl::enumerate_macos_keychain_certs(
  20533. [&](const unsigned char *data, size_t len) {
  20534. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  20535. static_cast<long>(len),
  20536. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  20537. });
  20538. #else
  20539. for (auto path = impl::system_ca_paths(); *path; ++path) {
  20540. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  20541. SSL_SUCCESS) {
  20542. loaded = true;
  20543. break;
  20544. }
  20545. }
  20546. if (!loaded) {
  20547. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  20548. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  20549. SSL_SUCCESS) {
  20550. loaded = true;
  20551. break;
  20552. }
  20553. }
  20554. }
  20555. #endif
  20556. return loaded;
  20557. }
  20558. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  20559. const char *password) {
  20560. if (!ctx || !cert || !key) { return false; }
  20561. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20562. // Load certificate
  20563. int ret = wolfSSL_CTX_use_certificate_buffer(
  20564. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  20565. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  20566. if (ret != SSL_SUCCESS) {
  20567. impl::wolfssl_last_error() =
  20568. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20569. return false;
  20570. }
  20571. // Set password callback if password is provided
  20572. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  20573. // Load private key
  20574. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  20575. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  20576. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  20577. if (ret != SSL_SUCCESS) {
  20578. impl::wolfssl_last_error() =
  20579. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20580. return false;
  20581. }
  20582. // Verify that the certificate and private key match
  20583. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  20584. }
  20585. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  20586. const char *key_path, const char *password) {
  20587. if (!ctx || !cert_path || !key_path) { return false; }
  20588. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20589. // Load certificate file
  20590. int ret =
  20591. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  20592. if (ret != SSL_SUCCESS) {
  20593. impl::wolfssl_last_error() =
  20594. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20595. return false;
  20596. }
  20597. // Set password callback if password is provided
  20598. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  20599. // Load private key file
  20600. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  20601. if (ret != SSL_SUCCESS) {
  20602. impl::wolfssl_last_error() =
  20603. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20604. return false;
  20605. }
  20606. // Verify that the certificate and private key match
  20607. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  20608. }
  20609. inline void set_verify_client(ctx_t ctx, bool require) {
  20610. if (!ctx) { return; }
  20611. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20612. wctx->verify_client = require;
  20613. impl::apply_verify_mode(*wctx);
  20614. }
  20615. inline session_t create_session(ctx_t ctx, socket_t sock) {
  20616. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  20617. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  20618. auto session = new (std::nothrow) impl::WolfSSLSession();
  20619. if (!session) { return nullptr; }
  20620. session->sock = sock;
  20621. session->ssl = wolfSSL_new(wctx->ctx);
  20622. if (!session->ssl) {
  20623. impl::wolfssl_last_error() =
  20624. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20625. delete session;
  20626. return nullptr;
  20627. }
  20628. if (wolfSSL_set_ex_data(session->ssl, impl::session_ex_data_index(),
  20629. session) != WOLFSSL_SUCCESS) {
  20630. delete session;
  20631. return nullptr;
  20632. }
  20633. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  20634. return static_cast<session_t>(session);
  20635. }
  20636. inline void free_session(session_t session) {
  20637. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  20638. }
  20639. inline bool set_sni(session_t session, const char *hostname,
  20640. bool verify_hostname) {
  20641. if (!session || !hostname) { return false; }
  20642. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20643. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  20644. static_cast<word16>(strlen(hostname)));
  20645. if (ret != WOLFSSL_SUCCESS) {
  20646. impl::wolfssl_last_error() =
  20647. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  20648. return false;
  20649. }
  20650. // wolfSSL_check_domain_name binds identity checking to the handshake,
  20651. // separately from the SNI extension sent above; skip it when hostname
  20652. // verification is disabled so only the chain is checked, matching OpenSSL.
  20653. if (verify_hostname) { wolfSSL_check_domain_name(wsession->ssl, hostname); }
  20654. wsession->hostname = hostname;
  20655. return true;
  20656. }
  20657. inline TlsError connect(session_t session) {
  20658. TlsError err;
  20659. if (!session) {
  20660. err.code = ErrorCode::Fatal;
  20661. return err;
  20662. }
  20663. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20664. int ret = wolfSSL_connect(wsession->ssl);
  20665. if (ret == SSL_SUCCESS) {
  20666. err.code = ErrorCode::Success;
  20667. } else {
  20668. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20669. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20670. err.backend_code = static_cast<uint64_t>(ssl_error);
  20671. impl::wolfssl_last_error() = err.backend_code;
  20672. }
  20673. return err;
  20674. }
  20675. inline TlsError accept(session_t session) {
  20676. TlsError err;
  20677. if (!session) {
  20678. err.code = ErrorCode::Fatal;
  20679. return err;
  20680. }
  20681. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20682. int ret = wolfSSL_accept(wsession->ssl);
  20683. if (ret == SSL_SUCCESS) {
  20684. err.code = ErrorCode::Success;
  20685. // Capture SNI from thread-local storage after successful handshake
  20686. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  20687. impl::wolfssl_pending_sni().clear();
  20688. } else {
  20689. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20690. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20691. err.backend_code = static_cast<uint64_t>(ssl_error);
  20692. impl::wolfssl_last_error() = err.backend_code;
  20693. }
  20694. return err;
  20695. }
  20696. inline bool connect_nonblocking(session_t session, socket_t sock,
  20697. time_t timeout_sec, time_t timeout_usec,
  20698. TlsError *err,
  20699. const std::function<bool()> &interrupted) {
  20700. if (!session) {
  20701. if (err) { err->code = ErrorCode::Fatal; }
  20702. return false;
  20703. }
  20704. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20705. // Set socket to non-blocking mode
  20706. detail::set_nonblocking(sock, true);
  20707. auto cleanup =
  20708. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  20709. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  20710. int ret;
  20711. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  20712. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20713. if (ssl_error == SSL_ERROR_WANT_READ) {
  20714. if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
  20715. continue;
  20716. }
  20717. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  20718. if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
  20719. continue;
  20720. }
  20721. }
  20722. // Error or timeout
  20723. if (err) {
  20724. err->code =
  20725. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  20726. err->backend_code = static_cast<uint64_t>(ssl_error);
  20727. }
  20728. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  20729. return false;
  20730. }
  20731. if (err) { err->code = ErrorCode::Success; }
  20732. return true;
  20733. }
  20734. inline bool accept_nonblocking(session_t session, socket_t sock,
  20735. time_t timeout_sec, time_t timeout_usec,
  20736. TlsError *err) {
  20737. if (!session) {
  20738. if (err) { err->code = ErrorCode::Fatal; }
  20739. return false;
  20740. }
  20741. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20742. // Set socket to non-blocking mode
  20743. detail::set_nonblocking(sock, true);
  20744. auto cleanup =
  20745. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  20746. auto deadline = detail::deadline_after(timeout_sec, timeout_usec);
  20747. int ret;
  20748. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  20749. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20750. if (ssl_error == SSL_ERROR_WANT_READ) {
  20751. if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
  20752. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  20753. if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
  20754. }
  20755. // Error or timeout
  20756. if (err) {
  20757. err->code =
  20758. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  20759. err->backend_code = static_cast<uint64_t>(ssl_error);
  20760. }
  20761. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  20762. return false;
  20763. }
  20764. if (err) { err->code = ErrorCode::Success; }
  20765. // Capture SNI from thread-local storage after successful handshake
  20766. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  20767. impl::wolfssl_pending_sni().clear();
  20768. return true;
  20769. }
  20770. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  20771. if (!session || !buf) {
  20772. err.code = ErrorCode::Fatal;
  20773. return -1;
  20774. }
  20775. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20776. constexpr auto max_len =
  20777. static_cast<size_t>((std::numeric_limits<int>::max)());
  20778. if (len > max_len) { len = max_len; }
  20779. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  20780. if (ret > 0) {
  20781. err.code = ErrorCode::Success;
  20782. return static_cast<ssize_t>(ret);
  20783. }
  20784. // 0 is also returned for EOF without close_notify; get_error tells them apart
  20785. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20786. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20787. if (err.code == ErrorCode::PeerClosed) { return 0; }
  20788. err.backend_code = static_cast<uint64_t>(ssl_error);
  20789. impl::wolfssl_last_error() = err.backend_code;
  20790. return -1;
  20791. }
  20792. inline ssize_t write(session_t session, const void *buf, size_t len,
  20793. TlsError &err) {
  20794. if (!session || !buf) {
  20795. err.code = ErrorCode::Fatal;
  20796. return -1;
  20797. }
  20798. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20799. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  20800. if (ret > 0) {
  20801. err.code = ErrorCode::Success;
  20802. return static_cast<ssize_t>(ret);
  20803. }
  20804. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  20805. // Treat this as an error (return -1) so callers don't spin in a
  20806. // write loop adding zero to the offset.
  20807. if (ret == 0) {
  20808. err.code = ErrorCode::PeerClosed;
  20809. return -1;
  20810. }
  20811. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20812. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  20813. err.backend_code = static_cast<uint64_t>(ssl_error);
  20814. impl::wolfssl_last_error() = err.backend_code;
  20815. return -1;
  20816. }
  20817. inline int pending(const_session_t session) {
  20818. if (!session) { return 0; }
  20819. auto wsession =
  20820. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20821. return wolfSSL_pending(wsession->ssl);
  20822. }
  20823. inline void shutdown(session_t session, bool graceful) {
  20824. if (!session) { return; }
  20825. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20826. if (graceful) {
  20827. int ret;
  20828. int attempts = 0;
  20829. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  20830. attempts < 3) {
  20831. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20832. if (ssl_error != SSL_ERROR_WANT_READ &&
  20833. ssl_error != SSL_ERROR_WANT_WRITE) {
  20834. break;
  20835. }
  20836. attempts++;
  20837. }
  20838. } else {
  20839. wolfSSL_shutdown(wsession->ssl);
  20840. }
  20841. }
  20842. inline bool is_peer_closed(session_t session, socket_t sock) {
  20843. if (!session || sock == INVALID_SOCKET) { return true; }
  20844. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  20845. // Check if there's already decrypted data available
  20846. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  20847. // Set socket to non-blocking to avoid blocking on read
  20848. detail::set_nonblocking(sock, true);
  20849. auto cleanup =
  20850. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  20851. // Peek 1 byte to check connection status without consuming data
  20852. unsigned char buf;
  20853. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  20854. // If we got data or WANT_READ (would block), connection is alive
  20855. if (ret > 0) { return false; }
  20856. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  20857. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  20858. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  20859. ret == 0;
  20860. }
  20861. inline cert_t get_peer_cert(const_session_t session) {
  20862. if (!session) { return nullptr; }
  20863. auto wsession =
  20864. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20865. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  20866. return static_cast<cert_t>(cert);
  20867. }
  20868. inline size_t get_peer_certs(const_session_t session,
  20869. std::vector<cert_t> &certs) {
  20870. certs.clear();
  20871. if (!session) { return 0; }
  20872. // wolfSSL keeps the received chain only when built with SESSION_CERTS
  20873. #ifdef SESSION_CERTS
  20874. auto wsession =
  20875. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20876. auto chain = wolfSSL_get_peer_chain(wsession->ssl);
  20877. auto count = chain ? wolfSSL_get_chain_count(chain) : 0;
  20878. for (int i = 0; i < count; i++) {
  20879. auto x509 = wolfSSL_get_chain_X509(chain, i);
  20880. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  20881. }
  20882. #endif
  20883. return certs.size();
  20884. }
  20885. inline void free_cert(cert_t cert) {
  20886. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  20887. }
  20888. inline bool verify_hostname(cert_t cert, const char *hostname) {
  20889. if (!cert || !hostname) { return false; }
  20890. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  20891. std::string host_str(hostname);
  20892. // Check if hostname is an IP address (IPv4 or IPv6)
  20893. unsigned char ip_bytes[16];
  20894. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  20895. auto is_ip = ip_len > 0;
  20896. // Check Subject Alternative Names
  20897. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  20898. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  20899. if (san_names) {
  20900. int san_count = wolfSSL_sk_num(san_names);
  20901. for (int i = 0; i < san_count; i++) {
  20902. auto *names =
  20903. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  20904. if (!names) continue;
  20905. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  20906. // DNS name
  20907. unsigned char *dns_name = nullptr;
  20908. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  20909. if (dns_name && dns_len > 0) {
  20910. std::string san_name(reinterpret_cast<char *>(dns_name),
  20911. static_cast<size_t>(dns_len));
  20912. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  20913. if (detail::match_hostname(san_name, host_str)) {
  20914. wolfSSL_sk_free(san_names);
  20915. return true;
  20916. }
  20917. }
  20918. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  20919. // IP address: only an iPAddress SAN of the same family (4 bytes for
  20920. // IPv4, 16 bytes for IPv6) may authenticate the host.
  20921. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  20922. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  20923. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  20924. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  20925. wolfSSL_sk_free(san_names);
  20926. return true;
  20927. }
  20928. }
  20929. }
  20930. wolfSSL_sk_free(san_names);
  20931. }
  20932. return false;
  20933. }
  20934. inline uint64_t hostname_mismatch_code() {
  20935. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  20936. }
  20937. inline long get_verify_result(const_session_t session) {
  20938. if (!session) { return -1; }
  20939. auto wsession =
  20940. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  20941. long result = wolfSSL_get_verify_result(wsession->ssl);
  20942. return result;
  20943. }
  20944. inline std::string get_cert_subject_cn(cert_t cert) {
  20945. if (!cert) return "";
  20946. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  20947. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  20948. if (!subject) return "";
  20949. char cn[256] = {};
  20950. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  20951. sizeof(cn));
  20952. if (cn_len <= 0) return "";
  20953. return std::string(cn, static_cast<size_t>(cn_len));
  20954. }
  20955. inline std::string get_cert_issuer_name(cert_t cert) {
  20956. if (!cert) return "";
  20957. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  20958. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  20959. if (!issuer) return "";
  20960. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  20961. if (!name_str) return "";
  20962. std::string result(name_str);
  20963. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  20964. return result;
  20965. }
  20966. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  20967. sans.clear();
  20968. if (!cert) return false;
  20969. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  20970. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  20971. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  20972. if (!san_names) return true; // No SANs is not an error
  20973. int count = wolfSSL_sk_num(san_names);
  20974. for (int i = 0; i < count; i++) {
  20975. auto *name =
  20976. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  20977. if (!name) continue;
  20978. SanEntry entry;
  20979. switch (name->type) {
  20980. case WOLFSSL_GEN_DNS: {
  20981. entry.type = SanType::DNS;
  20982. unsigned char *dns_name = nullptr;
  20983. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  20984. if (dns_name && dns_len > 0) {
  20985. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  20986. static_cast<size_t>(dns_len));
  20987. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  20988. }
  20989. break;
  20990. }
  20991. case WOLFSSL_GEN_IPADD: {
  20992. entry.type = SanType::IP;
  20993. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  20994. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  20995. if (ip_data && ip_len == 4) {
  20996. char buf[16];
  20997. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  20998. ip_data[2], ip_data[3]);
  20999. entry.value = buf;
  21000. } else if (ip_data && ip_len == 16) {
  21001. char buf[64];
  21002. snprintf(buf, sizeof(buf),
  21003. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  21004. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  21005. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  21006. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  21007. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  21008. ip_data[14], ip_data[15]);
  21009. entry.value = buf;
  21010. }
  21011. break;
  21012. }
  21013. case WOLFSSL_GEN_EMAIL:
  21014. entry.type = SanType::EMAIL;
  21015. {
  21016. unsigned char *email = nullptr;
  21017. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  21018. if (email && email_len > 0) {
  21019. entry.value = std::string(reinterpret_cast<char *>(email),
  21020. static_cast<size_t>(email_len));
  21021. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  21022. }
  21023. }
  21024. break;
  21025. case WOLFSSL_GEN_URI:
  21026. entry.type = SanType::URI;
  21027. {
  21028. unsigned char *uri = nullptr;
  21029. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  21030. &uri, name->d.uniformResourceIdentifier);
  21031. if (uri && uri_len > 0) {
  21032. entry.value = std::string(reinterpret_cast<char *>(uri),
  21033. static_cast<size_t>(uri_len));
  21034. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  21035. }
  21036. }
  21037. break;
  21038. default: entry.type = SanType::OTHER; break;
  21039. }
  21040. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  21041. }
  21042. wolfSSL_sk_free(san_names);
  21043. return true;
  21044. }
  21045. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  21046. time_t &not_after) {
  21047. if (!cert) return false;
  21048. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21049. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  21050. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  21051. if (!nb || !na) return false;
  21052. // wolfSSL_ASN1_TIME_to_tm is available
  21053. struct tm tm_nb = {}, tm_na = {};
  21054. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  21055. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  21056. #ifdef _WIN32
  21057. not_before = _mkgmtime(&tm_nb);
  21058. not_after = _mkgmtime(&tm_na);
  21059. #else
  21060. not_before = timegm(&tm_nb);
  21061. not_after = timegm(&tm_na);
  21062. #endif
  21063. return true;
  21064. }
  21065. inline std::string get_cert_serial(cert_t cert) {
  21066. if (!cert) return "";
  21067. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21068. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  21069. if (!serial_asn1) return "";
  21070. // Get the serial number data
  21071. int len = serial_asn1->length;
  21072. unsigned char *data = serial_asn1->data;
  21073. if (!data || len <= 0) return "";
  21074. std::string result;
  21075. result.reserve(static_cast<size_t>(len) * 2);
  21076. for (int i = 0; i < len; i++) {
  21077. char hex[3];
  21078. snprintf(hex, sizeof(hex), "%02X", data[i]);
  21079. result += hex;
  21080. }
  21081. return result;
  21082. }
  21083. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  21084. if (!cert) return false;
  21085. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  21086. int der_len = 0;
  21087. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  21088. if (!der_data || der_len <= 0) return false;
  21089. der.assign(der_data, der_data + der_len);
  21090. return true;
  21091. }
  21092. inline const char *get_sni(const_session_t session) {
  21093. if (!session) return nullptr;
  21094. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  21095. // For server: return SNI received from client during handshake
  21096. if (!wsession->sni_hostname.empty()) {
  21097. return wsession->sni_hostname.c_str();
  21098. }
  21099. // For client: return the hostname set via set_sni
  21100. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  21101. return nullptr;
  21102. }
  21103. inline uint64_t peek_error() {
  21104. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  21105. }
  21106. inline uint64_t get_error() {
  21107. uint64_t err = impl::wolfssl_last_error();
  21108. impl::wolfssl_last_error() = 0;
  21109. return err;
  21110. }
  21111. inline std::string error_string(uint64_t code) {
  21112. char buf[256];
  21113. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  21114. return std::string(buf);
  21115. }
  21116. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  21117. if (!pem || len == 0) { return nullptr; }
  21118. // Validate by attempting to load into a temporary ctx
  21119. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  21120. if (!tmp_ctx) { return nullptr; }
  21121. int ret = wolfSSL_CTX_load_verify_buffer(
  21122. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  21123. static_cast<long>(len), SSL_FILETYPE_PEM);
  21124. wolfSSL_CTX_free(tmp_ctx);
  21125. if (ret != SSL_SUCCESS) { return nullptr; }
  21126. return static_cast<ca_store_t>(
  21127. new impl::WolfSSLCAStore{std::string(pem, len)});
  21128. }
  21129. inline void free_ca_store(ca_store_t store) {
  21130. delete static_cast<impl::WolfSSLCAStore *>(store);
  21131. }
  21132. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  21133. if (!ctx || !store) { return false; }
  21134. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21135. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  21136. int ret = wolfSSL_CTX_load_verify_buffer(
  21137. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  21138. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  21139. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  21140. // This function takes ownership of the store; the PEM data was copied into
  21141. // the context, so release the source
  21142. free_ca_store(store);
  21143. return ret == SSL_SUCCESS;
  21144. }
  21145. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  21146. certs.clear();
  21147. if (!ctx) { return 0; }
  21148. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21149. if (wctx->ca_pem_data_.empty()) { return 0; }
  21150. const std::string &pem = wctx->ca_pem_data_;
  21151. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  21152. const std::string end_marker = "-----END CERTIFICATE-----";
  21153. size_t pos = 0;
  21154. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  21155. size_t end_pos = pem.find(end_marker, pos);
  21156. if (end_pos == std::string::npos) { break; }
  21157. end_pos += end_marker.size();
  21158. std::string cert_pem = pem.substr(pos, end_pos - pos);
  21159. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  21160. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  21161. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  21162. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  21163. pos = end_pos;
  21164. }
  21165. return certs.size();
  21166. }
  21167. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  21168. std::vector<std::string> names;
  21169. if (!ctx) { return names; }
  21170. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21171. if (wctx->ca_pem_data_.empty()) { return names; }
  21172. const std::string &pem = wctx->ca_pem_data_;
  21173. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  21174. const std::string end_marker = "-----END CERTIFICATE-----";
  21175. size_t pos = 0;
  21176. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  21177. size_t end_pos = pem.find(end_marker, pos);
  21178. if (end_pos == std::string::npos) { break; }
  21179. end_pos += end_marker.size();
  21180. std::string cert_pem = pem.substr(pos, end_pos - pos);
  21181. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  21182. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  21183. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  21184. if (x509) {
  21185. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  21186. if (subject) {
  21187. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  21188. if (name_str) {
  21189. names.push_back(name_str);
  21190. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  21191. }
  21192. }
  21193. wolfSSL_X509_free(x509);
  21194. }
  21195. pos = end_pos;
  21196. }
  21197. return names;
  21198. }
  21199. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  21200. const char *key_pem, const char *password) {
  21201. if (!ctx || !cert_pem || !key_pem) { return false; }
  21202. // Try the pair on a scratch context first, so that a bad one leaves the
  21203. // server's certificate and key as they were
  21204. auto tmp = create_server_context();
  21205. if (!tmp) { return false; }
  21206. auto se = detail::scope_exit([&] { free_context(tmp); });
  21207. if (!set_client_cert_pem(tmp, cert_pem, key_pem, password)) { return false; }
  21208. return set_client_cert_pem(ctx, cert_pem, key_pem, password);
  21209. }
  21210. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  21211. if (!ctx || !ca_pem) { return false; }
  21212. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21213. // Replace the CAs rather than add to them, as the other backends do, once
  21214. // the new ones are known to load
  21215. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  21216. if (!store) { return false; }
  21217. free_ca_store(store);
  21218. wolfSSL_CTX_UnloadCAs(wctx->ctx);
  21219. wctx->ca_pem_data_.clear();
  21220. return load_ca_pem(ctx, ca_pem, strlen(ca_pem));
  21221. }
  21222. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  21223. if (!ctx) { return false; }
  21224. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  21225. auto stored = callback ? std::make_shared<VerifyCallback>(std::move(callback))
  21226. : nullptr;
  21227. {
  21228. std::lock_guard<std::mutex> guard(impl::verify_callback_mutex());
  21229. // A handshake running the previous callback keeps it until it returns.
  21230. wctx->verify_callback.swap(stored);
  21231. }
  21232. impl::apply_verify_mode(*wctx);
  21233. return true;
  21234. }
  21235. inline long get_verify_error(const_session_t session) {
  21236. if (!session) { return -1; }
  21237. auto *wsession =
  21238. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  21239. return wolfSSL_get_verify_result(wsession->ssl);
  21240. }
  21241. inline std::string verify_error_string(long error_code) {
  21242. if (error_code == 0) { return ""; }
  21243. const char *str =
  21244. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  21245. return str ? std::string(str) : std::string();
  21246. }
  21247. } // namespace tls
  21248. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  21249. // WebSocket implementation
  21250. namespace ws {
  21251. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  21252. bool fin) {
  21253. std::lock_guard<std::mutex> lock(write_mutex_);
  21254. if (closed_) { return false; }
  21255. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  21256. }
  21257. inline ReadResult WebSocket::read(std::string &msg) {
  21258. // Answers a control frame; any other opcode here is a protocol error.
  21259. // Returns false when the connection is done.
  21260. auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
  21261. switch (op) {
  21262. case Opcode::Ping: {
  21263. std::lock_guard<std::mutex> lock(write_mutex_);
  21264. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  21265. payload.size(), true, !is_server_);
  21266. return true;
  21267. }
  21268. case Opcode::Pong: {
  21269. std::lock_guard<std::mutex> lock(ping_mutex_);
  21270. unacked_pings_ = 0;
  21271. return true;
  21272. }
  21273. case Opcode::Close: {
  21274. // RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
  21275. // malformed, which is answered with a protocol error instead.
  21276. if (closed_.exchange(true)) { return false; }
  21277. auto reply = payload;
  21278. if (!impl::is_valid_close_payload(payload)) {
  21279. auto code = static_cast<uint16_t>(CloseStatus::ProtocolError);
  21280. reply = {static_cast<char>(code >> 8), static_cast<char>(code & 0xff)};
  21281. }
  21282. std::lock_guard<std::mutex> lock(write_mutex_);
  21283. detail::write_websocket_frame(strm_, Opcode::Close, reply.data(),
  21284. reply.size(), true, !is_server_);
  21285. return false;
  21286. }
  21287. default: closed_ = true; return false;
  21288. }
  21289. };
  21290. std::unique_lock<std::mutex> read_lock(read_mutex_);
  21291. // A server going down closes the connection rather than wait on it: its
  21292. // listen() waits for this handler to return.
  21293. auto going_away = [&]() -> ReadResult {
  21294. read_lock.unlock();
  21295. close(CloseStatus::GoingAway, "server stopping");
  21296. return Fail;
  21297. };
  21298. // close() ends the read, even while the peer keeps sending fragments
  21299. while (!closed_) {
  21300. Opcode opcode;
  21301. std::string payload;
  21302. bool fin;
  21303. // While a message is assembled, only what is left of the limit, but room
  21304. // for a control frame, which may come between its fragments.
  21305. auto max_len =
  21306. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH == 0 || message_kind_ == Fail
  21307. ? size_t(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)
  21308. : (std::max)(size_t(125), CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH -
  21309. message_.size());
  21310. auto r = frames_.read(strm_, opcode, payload, fin, is_server_, max_len);
  21311. if (r != impl::FrameRead::Ok && server_stopping()) { return going_away(); }
  21312. // A timeout leaves what was read of the frame and of the message for the
  21313. // next read(), so the connection is still usable wherever it landed: hand
  21314. // control back without closing it. That is only useful to a caller who
  21315. // asked for the timeout; the compile-time default is a backstop against a
  21316. // peer gone quiet, and elapsing it closes the connection so a plain
  21317. // `while (ws.read(msg))` loop ends. A wait that a pong timeout cut short
  21318. // finds the connection closed.
  21319. if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) {
  21320. return Timeout;
  21321. }
  21322. if (r != impl::FrameRead::Ok) {
  21323. closed_ = true;
  21324. return Fail;
  21325. }
  21326. auto continues = opcode == Opcode::Continuation;
  21327. if (opcode != Opcode::Text && opcode != Opcode::Binary && !continues) {
  21328. if (handle_control(opcode, payload)) { continue; }
  21329. return Fail;
  21330. }
  21331. // RFC 6455 5.4: a message is a Text or Binary frame and the continuation
  21332. // frames after it, with only control frames between them.
  21333. if (continues == (message_kind_ == Fail)) {
  21334. closed_ = true;
  21335. return Fail;
  21336. }
  21337. if (continues) {
  21338. message_ += payload;
  21339. } else {
  21340. message_ = std::move(payload);
  21341. message_kind_ = opcode == Opcode::Text ? Text : Binary;
  21342. }
  21343. if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
  21344. message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  21345. closed_ = true;
  21346. return Fail;
  21347. }
  21348. if (!fin) { continue; }
  21349. auto result = message_kind_;
  21350. msg = std::move(message_);
  21351. message_.clear();
  21352. message_kind_ = Fail;
  21353. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  21354. if (result == Text && !impl::is_valid_utf8(msg)) {
  21355. // close() takes the read lock to wait for the peer's Close reply, so
  21356. // it must not run while this thread still holds it.
  21357. read_lock.unlock();
  21358. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  21359. return Fail;
  21360. }
  21361. return result;
  21362. }
  21363. return Fail;
  21364. }
  21365. inline bool WebSocket::send(const std::string &data) {
  21366. return send_frame(Opcode::Text, data.data(), data.size());
  21367. }
  21368. inline bool WebSocket::send(const char *data, size_t len) {
  21369. return send_frame(Opcode::Binary, data, len);
  21370. }
  21371. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  21372. if (closed_.exchange(true)) { return; }
  21373. ping_cv_.notify_all();
  21374. std::string payload;
  21375. auto code = static_cast<uint16_t>(status);
  21376. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  21377. payload.push_back(static_cast<char>(code & 0xFF));
  21378. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  21379. // Close frame has 2-byte status code, so reason is limited to 123 bytes,
  21380. // cut back to a whole UTF-8 character
  21381. auto short_reason = reason.substr(0, 123);
  21382. while (!short_reason.empty() && !impl::is_valid_utf8(short_reason)) {
  21383. short_reason.pop_back();
  21384. }
  21385. payload += short_reason;
  21386. // A code that may not be sent, such as NoStatus, goes without a payload
  21387. if (!impl::is_valid_close_payload(payload)) { payload.clear(); }
  21388. {
  21389. std::lock_guard<std::mutex> lock(write_mutex_);
  21390. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  21391. payload.size(), true, !is_server_);
  21392. }
  21393. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  21394. // Close response before closing the TCP connection.
  21395. //
  21396. // Wait only when no other thread is parsing frames. When one is, it is the
  21397. // thread positioned to see the peer's reply, and reading here would take
  21398. // bytes out of the message it is assembling. Bailing out also leaves the
  21399. // stream, including its read timeout, entirely to that thread.
  21400. std::unique_lock<std::mutex> read_lock(read_mutex_, std::try_to_lock);
  21401. if (!read_lock.owns_lock()) { return; }
  21402. // A max timeout turns a negative (unbounded) read timeout into 0
  21403. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  21404. strm_.set_max_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND * 1000);
  21405. // The max timeout cuts a trickled frame short, the deadline a frame flood
  21406. auto deadline =
  21407. detail::deadline_after(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  21408. // From where the last read() left the stream, inside a frame as it may be
  21409. Opcode op;
  21410. std::string resp;
  21411. bool fin;
  21412. while (std::chrono::steady_clock::now() < deadline &&
  21413. frames_.read(strm_, op, resp, fin, is_server_, 125) ==
  21414. impl::FrameRead::Ok) {
  21415. if (op == Opcode::Close) { break; }
  21416. }
  21417. }
  21418. inline WebSocket::~WebSocket() {
  21419. {
  21420. std::lock_guard<std::mutex> lock(ping_mutex_);
  21421. closed_ = true;
  21422. }
  21423. ping_cv_.notify_all();
  21424. if (ping_thread_.joinable()) { ping_thread_.join(); }
  21425. // A server's stream outlives this object
  21426. strm_.set_read_interrupt(nullptr);
  21427. }
  21428. // A pong timeout ends a read() blocked on the silent peer, and so does the
  21429. // server stopping: its listen() waits for every handler to return.
  21430. inline void WebSocket::interrupt_reads() {
  21431. auto watches_pongs = ping_interval_sec_ > 0 && max_missed_pongs_ > 0;
  21432. if (!watches_pongs && !server_stopping_) { return; }
  21433. strm_.set_read_interrupt(
  21434. [this] { return pong_timed_out_.load() || server_stopping(); });
  21435. }
  21436. inline void WebSocket::start_heartbeat() {
  21437. if (ping_interval_sec_ <= 0) { return; }
  21438. ping_thread_ = std::thread([this]() {
  21439. std::unique_lock<std::mutex> lock(ping_mutex_);
  21440. // The predicate keeps a spurious wakeup from sending a ping early
  21441. while (!ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_),
  21442. [this]() { return closed_.load(); })) {
  21443. // If the peer has failed to respond to the previous pings, give up.
  21444. // RFC 6455 does not define a pong-timeout mechanism; this is an
  21445. // opt-in liveness check controlled by max_missed_pongs_.
  21446. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  21447. lock.unlock();
  21448. close(CloseStatus::GoingAway, "pong timeout");
  21449. pong_timed_out_ = true;
  21450. return;
  21451. }
  21452. lock.unlock();
  21453. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  21454. lock.lock();
  21455. closed_ = true;
  21456. break;
  21457. }
  21458. lock.lock();
  21459. unacked_pings_++;
  21460. }
  21461. });
  21462. }
  21463. inline const Request &WebSocket::request() const { return req_; }
  21464. inline bool WebSocket::is_open() const { return !closed_; }
  21465. inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
  21466. // 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
  21467. // poll(), where 0 would instead mean "return immediately", so hand it the
  21468. // negative poll uses for an unbounded wait.
  21469. if (sec == 0 && usec == 0) { sec = -1; }
  21470. strm_.set_read_timeout(sec, usec);
  21471. read_timeout_set_ = true;
  21472. }
  21473. // WebSocketClient implementation
  21474. inline WebSocketClient::WebSocketClient(
  21475. const std::string &scheme_host_port_path, const Headers &headers)
  21476. : headers_(headers) {
  21477. detail::UrlComponents uc;
  21478. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  21479. !uc.host.empty() && !uc.path.empty()) {
  21480. auto &scheme = uc.scheme;
  21481. #ifdef CPPHTTPLIB_SSL_ENABLED
  21482. if (scheme != "ws" && scheme != "wss") {
  21483. #else
  21484. if (scheme != "ws") {
  21485. #endif
  21486. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  21487. std::string msg = "'" + scheme + "' scheme is not supported.";
  21488. throw std::invalid_argument(msg);
  21489. #endif
  21490. return;
  21491. }
  21492. auto is_ssl = scheme == "wss";
  21493. host_ = std::move(uc.host);
  21494. port_ = is_ssl ? 443 : 80;
  21495. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  21496. path_ = std::move(uc.path);
  21497. if (!uc.query.empty()) { path_ += uc.query; }
  21498. #ifdef CPPHTTPLIB_SSL_ENABLED
  21499. is_ssl_ = is_ssl;
  21500. if (is_ssl_) {
  21501. // The context lives as long as the client so that CA configuration
  21502. // survives reconnects; sessions are created per connection.
  21503. tls_ctx_ = tls::create_client_context();
  21504. if (!tls_ctx_) { return; }
  21505. }
  21506. #else
  21507. if (is_ssl) { return; }
  21508. #endif
  21509. is_valid_ = true;
  21510. }
  21511. }
  21512. #ifdef CPPHTTPLIB_SSL_ENABLED
  21513. inline WebSocketClient::WebSocketClient(
  21514. const std::string &scheme_host_port_path, const PemMemory &pem,
  21515. const Headers &headers)
  21516. : WebSocketClient(scheme_host_port_path, headers) {
  21517. // For ws:// URLs the client certificate is silently ignored, consistent
  21518. // with the TLS-only setters such as set_ca_cert_path().
  21519. if (is_valid_ && is_ssl_ && pem.cert_pem && pem.key_pem) {
  21520. std::string cert_buf, key_buf;
  21521. if (!tls::set_client_cert_pem(
  21522. tls_ctx_,
  21523. detail::pem_c_str(pem.cert_pem, pem.cert_pem_len, cert_buf),
  21524. detail::pem_c_str(pem.key_pem, pem.key_pem_len, key_buf),
  21525. pem.private_key_password)) {
  21526. tls::free_context(tls_ctx_);
  21527. tls_ctx_ = nullptr;
  21528. is_valid_ = false;
  21529. }
  21530. }
  21531. }
  21532. #endif
  21533. inline WebSocketClient::~WebSocketClient() {
  21534. shutdown_and_close();
  21535. #ifdef CPPHTTPLIB_SSL_ENABLED
  21536. if (tls_ctx_) {
  21537. tls::free_context(tls_ctx_);
  21538. tls_ctx_ = nullptr;
  21539. }
  21540. #endif
  21541. }
  21542. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  21543. inline void WebSocketClient::shutdown_and_close() {
  21544. // Send the close frame while the TLS session is still alive: ws_ holds an
  21545. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  21546. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  21547. if (ws_ && ws_->is_open()) { ws_->close(); }
  21548. ws_.reset();
  21549. #ifdef CPPHTTPLIB_SSL_ENABLED
  21550. if (is_ssl_) {
  21551. if (tls_session_) {
  21552. tls::shutdown(tls_session_, true);
  21553. tls::free_session(tls_session_);
  21554. tls_session_ = nullptr;
  21555. }
  21556. }
  21557. #endif
  21558. if (sock_ != INVALID_SOCKET) {
  21559. detail::shutdown_socket(sock_);
  21560. detail::close_socket(sock_);
  21561. sock_ = INVALID_SOCKET;
  21562. }
  21563. }
  21564. // The handshakes belong to establishing the connection, so an unset read
  21565. // timeout leaves them bounded by the connection timeout instead of forever.
  21566. inline std::pair<time_t, time_t> WebSocketClient::handshake_timeout() const {
  21567. if (read_timeout_sec_ == 0 && read_timeout_usec_ == 0) {
  21568. return {connection_timeout_sec_, connection_timeout_usec_};
  21569. }
  21570. return {read_timeout_sec_, read_timeout_usec_};
  21571. }
  21572. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm,
  21573. Error &error, int &ssl_error,
  21574. uint64_t &ssl_backend_error) {
  21575. // A read timeout of 0 means "wait forever", the way SO_RCVTIMEO reads it.
  21576. // The streams wait with poll(), where 0 instead means "return immediately",
  21577. // so they are given the negative poll uses for an unbounded wait.
  21578. auto unbounded = read_timeout_sec_ == 0 && read_timeout_usec_ == 0;
  21579. time_t strm_read_sec = unbounded ? -1 : read_timeout_sec_;
  21580. time_t strm_read_usec = unbounded ? 0 : read_timeout_usec_;
  21581. #ifdef CPPHTTPLIB_SSL_ENABLED
  21582. if (is_ssl_) {
  21583. // A plain flag rather than SSLClient::load_certs()'s call_once: connect()
  21584. // is not safe to call concurrently on one client to begin with, since
  21585. // nothing else here is guarded either.
  21586. if (server_certificate_verification_ && !certs_loaded_) {
  21587. uint64_t backend_error = 0;
  21588. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_,
  21589. ca_cert_dir_path_, custom_ca_loaded_,
  21590. system_ca_mode_, backend_error);
  21591. certs_loaded_ = true;
  21592. }
  21593. detail::ClientTlsSessionOptions options;
  21594. options.server_hostname_verification = server_hostname_verification_;
  21595. options.session_verifier = session_verifier_;
  21596. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  21597. options.windows_cert_verification = detail::use_windows_cert_verification(
  21598. enable_windows_cert_verification_, ca_cert_file_path_,
  21599. ca_cert_dir_path_, custom_ca_loaded_, system_ca_mode_);
  21600. options.server_certificate_verifier_set = server_certificate_verifier_set_;
  21601. #endif
  21602. auto timeout = handshake_timeout();
  21603. detail::ClientTlsSessionError tls_error;
  21604. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  21605. server_certificate_verification_,
  21606. timeout.first, timeout.second,
  21607. &tls_error, options)) {
  21608. error = tls_error.error;
  21609. ssl_error = tls_error.ssl_error;
  21610. ssl_backend_error = tls_error.backend_error;
  21611. return false;
  21612. }
  21613. strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  21614. sock_, tls_session_, strm_read_sec, strm_read_usec, write_timeout_sec_,
  21615. write_timeout_usec_));
  21616. return true;
  21617. }
  21618. #else
  21619. (void)error;
  21620. (void)ssl_error;
  21621. (void)ssl_backend_error;
  21622. #endif
  21623. strm = std::unique_ptr<Stream>(
  21624. new detail::SocketStream(sock_, strm_read_sec, strm_read_usec,
  21625. write_timeout_sec_, write_timeout_usec_));
  21626. return true;
  21627. }
  21628. inline void WebSocketClient::prepare_default_headers(Request &req) {
  21629. #ifdef CPPHTTPLIB_SSL_ENABLED
  21630. auto is_ssl = is_ssl_;
  21631. #else
  21632. auto is_ssl = false;
  21633. #endif
  21634. if (!req.has_header("Host")) {
  21635. req.headers.emplace("Host", detail::make_default_host_header_value(
  21636. host_, port_, is_ssl, address_family_));
  21637. }
  21638. detail::add_default_user_agent_header(req);
  21639. detail::add_authorization_header(req, basic_auth_username_,
  21640. basic_auth_password_,
  21641. bearer_token_auth_token_, false);
  21642. }
  21643. inline Result WebSocketClient::connect() {
  21644. if (!is_valid_) { return Result{Error::Connection, -1, Headers{}}; }
  21645. shutdown_and_close();
  21646. auto error = Error::Success;
  21647. if (!create_and_connect_socket(error)) {
  21648. return Result{error, -1, Headers{}};
  21649. }
  21650. if (is_proxy_enabled()) {
  21651. Response proxy_res;
  21652. if (!connect_with_proxy(proxy_res, error)) {
  21653. shutdown_and_close();
  21654. return Result{error, proxy_res.status, std::move(proxy_res.headers)};
  21655. }
  21656. }
  21657. std::unique_ptr<Stream> strm;
  21658. auto stream_error = Error::SSLConnection;
  21659. int ssl_error = 0;
  21660. uint64_t ssl_backend_error = 0;
  21661. if (!create_stream(strm, stream_error, ssl_error, ssl_backend_error)) {
  21662. shutdown_and_close();
  21663. #ifdef CPPHTTPLIB_SSL_ENABLED
  21664. return Result{stream_error, -1, Headers{}, ssl_error, ssl_backend_error};
  21665. #else
  21666. return Result{stream_error, -1, Headers{}};
  21667. #endif
  21668. }
  21669. Request req;
  21670. req.method = "GET";
  21671. req.path = path_;
  21672. req.headers = headers_;
  21673. prepare_default_headers(req);
  21674. detail::WebSocketUpgradeResponse upgrade;
  21675. if (!detail::perform_websocket_handshake(*strm, req, upgrade)) {
  21676. shutdown_and_close();
  21677. return Result{upgrade.error, upgrade.status, std::move(upgrade.headers)};
  21678. }
  21679. subprotocol_ = std::move(upgrade.selected_subprotocol);
  21680. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  21681. websocket_ping_interval_sec_,
  21682. websocket_max_missed_pongs_));
  21683. // The stream was created with the timeout already; tell the WebSocket
  21684. // whether it came from the caller, so read() knows to report it as Timeout.
  21685. ws_->read_timeout_set_ = read_timeout_set_;
  21686. return Result{Error::Success, upgrade.status, std::move(upgrade.headers)};
  21687. }
  21688. inline ReadResult WebSocketClient::read(std::string &msg) {
  21689. if (!ws_) { return Fail; }
  21690. return ws_->read(msg);
  21691. }
  21692. inline bool WebSocketClient::send(const std::string &data) {
  21693. if (!ws_) { return false; }
  21694. return ws_->send(data);
  21695. }
  21696. inline bool WebSocketClient::send(const char *data, size_t len) {
  21697. if (!ws_) { return false; }
  21698. return ws_->send(data, len);
  21699. }
  21700. inline void WebSocketClient::close(CloseStatus status,
  21701. const std::string &reason) {
  21702. if (ws_) { ws_->close(status, reason); }
  21703. }
  21704. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  21705. inline const std::string &WebSocketClient::subprotocol() const {
  21706. return subprotocol_;
  21707. }
  21708. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  21709. read_timeout_sec_ = sec;
  21710. read_timeout_usec_ = usec;
  21711. read_timeout_set_ = true;
  21712. // The members above only seed the next connect(); read() consults the
  21713. // stream, so an already-open connection has to be told directly.
  21714. if (ws_) { ws_->set_read_timeout(sec, usec); }
  21715. }
  21716. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  21717. write_timeout_sec_ = sec;
  21718. write_timeout_usec_ = usec;
  21719. }
  21720. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  21721. websocket_ping_interval_sec_ = sec;
  21722. }
  21723. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  21724. websocket_max_missed_pongs_ = count;
  21725. }
  21726. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  21727. inline void WebSocketClient::set_address_family(int family) {
  21728. address_family_ = family;
  21729. }
  21730. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  21731. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  21732. socket_options_ = std::move(socket_options);
  21733. }
  21734. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  21735. connection_timeout_sec_ = sec;
  21736. connection_timeout_usec_ = usec;
  21737. }
  21738. inline void WebSocketClient::set_interface(const std::string &intf) {
  21739. interface_ = intf;
  21740. }
  21741. inline void WebSocketClient::set_hostname_addr_map(
  21742. std::map<std::string, std::string> addr_map) {
  21743. set_direct_hostname_addr_map(std::move(addr_map));
  21744. }
  21745. inline void WebSocketClient::set_direct_hostname_addr_map(
  21746. std::map<std::string, std::string> addr_map) {
  21747. addr_map_ = std::move(addr_map);
  21748. }
  21749. inline void WebSocketClient::set_tunnel_hostname_addr_map(
  21750. std::map<std::string, std::string> addr_map) {
  21751. tunnel_addr_map_ = std::move(addr_map);
  21752. }
  21753. inline bool WebSocketClient::is_proxy_enabled() const {
  21754. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  21755. if (no_proxy_entries_.empty()) { return true; }
  21756. return !detail::host_matches_no_proxy(detail::normalize_target(host_),
  21757. no_proxy_entries_);
  21758. }
  21759. inline bool WebSocketClient::create_and_connect_socket(Error &error) {
  21760. std::string connect_host;
  21761. std::string ip;
  21762. auto port = port_;
  21763. if (is_proxy_enabled()) {
  21764. connect_host = proxy_host_;
  21765. port = proxy_port_;
  21766. } else {
  21767. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  21768. }
  21769. sock_ = detail::create_client_socket(
  21770. connect_host, ip, port, address_family_, tcp_nodelay_, ipv6_v6only_,
  21771. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  21772. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  21773. write_timeout_usec_, interface_, error);
  21774. if (sock_ != INVALID_SOCKET) { return true; }
  21775. if (error == Error::Success) { error = Error::Connection; }
  21776. return false;
  21777. }
  21778. inline bool WebSocketClient::send_proxy_connect(Request &req,
  21779. Response &proxy_res,
  21780. Error &error) {
  21781. auto timeout = handshake_timeout();
  21782. detail::SocketStream strm(sock_, timeout.first, timeout.second,
  21783. write_timeout_sec_, write_timeout_usec_);
  21784. if (!detail::write_request_head(strm, req, error)) { return false; }
  21785. if (!detail::read_response_head(strm, proxy_res.status, proxy_res.headers)) {
  21786. error = Error::Read;
  21787. return false;
  21788. }
  21789. return true;
  21790. }
  21791. // RFC 6455 4.1: ws:// is tunnelled with CONNECT as well, since a proxy need not
  21792. // forward an Upgrade request.
  21793. inline bool WebSocketClient::connect_with_proxy(Response &proxy_res,
  21794. Error &error) {
  21795. Request req;
  21796. req.method = "CONNECT";
  21797. req.path =
  21798. detail::make_connect_request_target(tunnel_addr_map_, host_, port_);
  21799. req.headers.emplace("Host", req.path);
  21800. detail::add_default_user_agent_header(req);
  21801. detail::add_authorization_header(req, proxy_basic_auth_username_,
  21802. proxy_basic_auth_password_,
  21803. proxy_bearer_token_auth_token_, true);
  21804. if (!send_proxy_connect(req, proxy_res, error)) { return false; }
  21805. #ifdef CPPHTTPLIB_SSL_ENABLED
  21806. // A Digest challenge gets one retry on a fresh connection, like SSLClient.
  21807. std::map<std::string, std::string> auth;
  21808. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407 &&
  21809. !proxy_digest_auth_username_.empty() &&
  21810. !proxy_digest_auth_password_.empty() &&
  21811. detail::parse_www_authenticate(proxy_res, auth, true)) {
  21812. proxy_res = Response();
  21813. shutdown_and_close();
  21814. if (!create_and_connect_socket(error)) { return false; }
  21815. req.headers.erase("Proxy-Authorization");
  21816. req.headers.insert(detail::make_digest_authentication_header(
  21817. req, req.path, auth, 1, detail::random_string(10),
  21818. proxy_digest_auth_username_, proxy_digest_auth_password_, true));
  21819. if (!send_proxy_connect(req, proxy_res, error)) { return false; }
  21820. }
  21821. #endif
  21822. if (proxy_res.status != StatusCode::OK_200) {
  21823. error = Error::ProxyConnection;
  21824. return false;
  21825. }
  21826. return true;
  21827. }
  21828. inline void WebSocketClient::set_basic_auth(const std::string &username,
  21829. const std::string &password) {
  21830. basic_auth_username_ = username;
  21831. basic_auth_password_ = password;
  21832. }
  21833. inline void WebSocketClient::set_bearer_token_auth(const std::string &token) {
  21834. bearer_token_auth_token_ = token;
  21835. }
  21836. inline void WebSocketClient::set_proxy(const std::string &host, int port) {
  21837. proxy_host_ = host;
  21838. proxy_port_ = port;
  21839. }
  21840. inline void WebSocketClient::set_proxy_basic_auth(const std::string &username,
  21841. const std::string &password) {
  21842. proxy_basic_auth_username_ = username;
  21843. proxy_basic_auth_password_ = password;
  21844. }
  21845. inline void
  21846. WebSocketClient::set_proxy_bearer_token_auth(const std::string &token) {
  21847. proxy_bearer_token_auth_token_ = token;
  21848. }
  21849. inline void
  21850. WebSocketClient::set_no_proxy(const std::vector<std::string> &patterns) {
  21851. no_proxy_entries_ = detail::parse_no_proxy_entries(patterns);
  21852. }
  21853. #ifdef CPPHTTPLIB_SSL_ENABLED
  21854. inline void
  21855. WebSocketClient::set_ca_cert_path(const std::string &ca_cert_file_path,
  21856. const std::string &ca_cert_dir_path) {
  21857. ca_cert_file_path_ = ca_cert_file_path;
  21858. ca_cert_dir_path_ = ca_cert_dir_path;
  21859. }
  21860. inline void
  21861. WebSocketClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  21862. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  21863. server_certificate_verifier_set_ = static_cast<bool>(verifier);
  21864. #endif
  21865. if (tls_ctx_) { tls::set_verify_callback(tls_ctx_, std::move(verifier)); }
  21866. }
  21867. inline void WebSocketClient::set_session_verifier(
  21868. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  21869. session_verifier_ = std::move(verifier);
  21870. }
  21871. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  21872. if (store && tls_ctx_) {
  21873. // set_ca_store takes ownership of store
  21874. tls::set_ca_store(tls_ctx_, store);
  21875. } else if (store) {
  21876. tls::free_ca_store(store);
  21877. }
  21878. custom_ca_loaded_ = true;
  21879. }
  21880. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  21881. std::size_t size) {
  21882. if (tls_ctx_ && ca_cert && size > 0) {
  21883. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  21884. }
  21885. custom_ca_loaded_ = true;
  21886. }
  21887. inline void
  21888. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  21889. server_certificate_verification_ = enabled;
  21890. }
  21891. inline void WebSocketClient::enable_server_hostname_verification(bool enabled) {
  21892. server_hostname_verification_ = enabled;
  21893. }
  21894. inline void WebSocketClient::enable_system_ca(bool enabled) {
  21895. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  21896. }
  21897. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  21898. inline void
  21899. WebSocketClient::enable_windows_certificate_verification(bool enabled) {
  21900. enable_windows_cert_verification_ = enabled;
  21901. }
  21902. #endif
  21903. inline void
  21904. WebSocketClient::set_proxy_digest_auth(const std::string &username,
  21905. const std::string &password) {
  21906. proxy_digest_auth_username_ = username;
  21907. proxy_digest_auth_password_ = password;
  21908. }
  21909. #endif // CPPHTTPLIB_SSL_ENABLED
  21910. } // namespace ws
  21911. // ----------------------------------------------------------------------------
  21912. } // namespace httplib
  21913. #endif // CPPHTTPLIB_HTTPLIB_H