httplib.h 752 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335
  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.53.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003501"
  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. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. // std::regex_match's backtracking implementation (most acutely on libstdc++)
  109. // recurses roughly once per matched character for quantified patterns such
  110. // as "(.*)", so a long enough path can exhaust the calling thread's stack; on
  111. // a default ~8MB thread stack that has been observed to take on the order of
  112. // a couple thousand characters for a simple pattern. 256 leaves a wide safety
  113. // margin below that (well under the 8192-byte request URI limit) while still
  114. // fitting any realistic route segment; raise it if a route legitimately needs
  115. // longer paths. Regex routes are never applied to paths longer than this.
  116. #ifndef CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH
  117. #define CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH 256
  118. #endif
  119. #ifndef CPPHTTPLIB_TCP_NODELAY
  120. #define CPPHTTPLIB_TCP_NODELAY false
  121. #endif
  122. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  123. #define CPPHTTPLIB_IPV6_V6ONLY false
  124. #endif
  125. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  126. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  127. #endif
  128. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  129. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  130. #endif
  131. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  132. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  133. #endif
  134. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  135. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  136. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  137. ? std::thread::hardware_concurrency() - 1 \
  138. : 0))
  139. #endif
  140. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  141. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  142. #endif
  143. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  144. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  145. #endif
  146. #ifndef CPPHTTPLIB_RECV_FLAGS
  147. #define CPPHTTPLIB_RECV_FLAGS 0
  148. #endif
  149. #ifndef CPPHTTPLIB_SEND_FLAGS
  150. #define CPPHTTPLIB_SEND_FLAGS 0
  151. #endif
  152. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  153. #define CPPHTTPLIB_LISTEN_BACKLOG 128
  154. #endif
  155. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  156. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  157. #endif
  158. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  159. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  160. #endif
  161. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  162. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  163. #endif
  164. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  165. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  166. #endif
  167. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  168. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  169. #endif
  170. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  171. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  172. #endif
  173. /*
  174. * Headers
  175. */
  176. #ifdef _WIN32
  177. #ifndef _CRT_SECURE_NO_WARNINGS
  178. #define _CRT_SECURE_NO_WARNINGS
  179. #endif //_CRT_SECURE_NO_WARNINGS
  180. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  181. #define _CRT_NONSTDC_NO_DEPRECATE
  182. #endif //_CRT_NONSTDC_NO_DEPRECATE
  183. #if defined(_MSC_VER)
  184. #if _MSC_VER < 1900
  185. #error Sorry, Visual Studio versions prior to 2015 are not supported
  186. #endif
  187. #pragma comment(lib, "ws2_32.lib")
  188. #ifndef _SSIZE_T_DEFINED
  189. using ssize_t = __int64;
  190. #define _SSIZE_T_DEFINED
  191. #endif
  192. #endif // _MSC_VER
  193. #ifndef S_ISREG
  194. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  195. #endif // S_ISREG
  196. #ifndef S_ISDIR
  197. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  198. #endif // S_ISDIR
  199. #ifndef NOMINMAX
  200. #define NOMINMAX
  201. #endif // NOMINMAX
  202. #include <io.h>
  203. #include <winsock2.h>
  204. #include <ws2tcpip.h>
  205. #if defined(__has_include)
  206. #if __has_include(<afunix.h>)
  207. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  208. #include <afunix.h>
  209. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  210. #endif
  211. #endif
  212. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  213. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  214. #endif
  215. using nfds_t = unsigned long;
  216. using socket_t = SOCKET;
  217. using socklen_t = int;
  218. #else // not _WIN32
  219. #include <arpa/inet.h>
  220. #if !defined(_AIX) && !defined(__MVS__)
  221. #include <ifaddrs.h>
  222. #endif
  223. #ifdef __MVS__
  224. #include <strings.h>
  225. #ifndef NI_MAXHOST
  226. #define NI_MAXHOST 1025
  227. #endif
  228. #endif
  229. #include <net/if.h>
  230. #include <netdb.h>
  231. #include <netinet/in.h>
  232. #ifdef __linux__
  233. #include <resolv.h>
  234. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  235. #endif
  236. #include <csignal>
  237. #include <netinet/tcp.h>
  238. #include <poll.h>
  239. #include <pthread.h>
  240. #include <sys/mman.h>
  241. #include <sys/socket.h>
  242. #include <sys/un.h>
  243. #include <unistd.h>
  244. using socket_t = int;
  245. #ifndef INVALID_SOCKET
  246. #define INVALID_SOCKET (-1)
  247. #endif
  248. #endif //_WIN32
  249. #if defined(__APPLE__)
  250. #include <TargetConditionals.h>
  251. #endif
  252. #include <algorithm>
  253. #include <array>
  254. #include <atomic>
  255. #include <cassert>
  256. #include <chrono>
  257. #include <climits>
  258. #include <condition_variable>
  259. #include <cstdlib>
  260. #include <cstring>
  261. #include <errno.h>
  262. #include <exception>
  263. #include <fcntl.h>
  264. #include <fstream>
  265. #include <functional>
  266. #include <iomanip>
  267. #include <iostream>
  268. #include <iterator>
  269. #include <list>
  270. #include <map>
  271. #include <memory>
  272. #include <mutex>
  273. #include <random>
  274. #include <regex>
  275. #include <set>
  276. #include <sstream>
  277. #include <string>
  278. #include <sys/stat.h>
  279. #include <system_error>
  280. #include <thread>
  281. #include <type_traits>
  282. #include <unordered_map>
  283. #include <unordered_set>
  284. #include <utility>
  285. #include <vector>
  286. // On macOS with a TLS backend, enable Keychain root certificates by default
  287. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  288. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  289. // only; on those platforms the user must provide a CA bundle explicitly.
  290. #if defined(__APPLE__) && defined(__clang__) && \
  291. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  292. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  293. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  294. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  295. #if TARGET_OS_OSX
  296. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  297. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  298. #endif
  299. #endif
  300. #endif
  301. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  302. defined(__APPLE__) && !TARGET_OS_OSX
  303. #error \
  304. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  305. #endif
  306. // On Windows, enable Schannel certificate verification by default
  307. // unless the user explicitly opts out.
  308. #if defined(_WIN32) && \
  309. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  310. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  311. #endif
  312. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  313. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  314. #if TARGET_OS_MAC && defined(__clang__)
  315. #include <CFNetwork/CFHost.h>
  316. #include <CoreFoundation/CoreFoundation.h>
  317. #endif
  318. #endif
  319. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  320. #ifdef _WIN32
  321. #include <wincrypt.h>
  322. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  323. // used
  324. #undef X509_NAME
  325. #undef X509_CERT_PAIR
  326. #undef X509_EXTENSIONS
  327. #undef PKCS7_SIGNER_INFO
  328. #ifdef _MSC_VER
  329. #pragma comment(lib, "crypt32.lib")
  330. #endif
  331. #endif // _WIN32
  332. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  333. #if TARGET_OS_OSX
  334. #include <Security/Security.h>
  335. #endif
  336. #endif
  337. #include <openssl/err.h>
  338. #include <openssl/evp.h>
  339. #include <openssl/ssl.h>
  340. #include <openssl/x509v3.h>
  341. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  342. #include <openssl/applink.c>
  343. #endif
  344. #include <iostream>
  345. #include <sstream>
  346. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  347. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  348. #error Please use OpenSSL or a current version of BoringSSL
  349. #endif
  350. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  351. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  352. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  353. #endif
  354. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  355. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  356. // version.h defines MBEDTLS_VERSION_MAJOR (on 2.x/3.x/4.x alike); it is pulled
  357. // in with this first include group so the version gating below can use it.
  358. #include <mbedtls/error.h>
  359. #include <mbedtls/net_sockets.h>
  360. #include <mbedtls/oid.h>
  361. #include <mbedtls/pk.h>
  362. #include <mbedtls/ssl.h>
  363. #include <mbedtls/version.h>
  364. #include <mbedtls/x509_crt.h>
  365. #if MBEDTLS_VERSION_MAJOR >= 4
  366. // Mbed TLS 4.x moved hashing/RNG to PSA Crypto and removed these headers.
  367. #include <psa/crypto.h>
  368. #else
  369. #include <mbedtls/ctr_drbg.h>
  370. #include <mbedtls/entropy.h>
  371. #include <mbedtls/md5.h>
  372. #include <mbedtls/sha1.h>
  373. #include <mbedtls/sha256.h>
  374. #include <mbedtls/sha512.h>
  375. #endif
  376. #ifdef _WIN32
  377. #include <wincrypt.h>
  378. #ifdef _MSC_VER
  379. #pragma comment(lib, "crypt32.lib")
  380. #endif
  381. #endif // _WIN32
  382. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  383. #if TARGET_OS_OSX
  384. #include <Security/Security.h>
  385. #endif
  386. #endif
  387. // Mbed TLS version API compatibility. Note: V4 implies V3 (both defined on
  388. // 4.x), so version-specific 3.x-only code must check V3 && !V4.
  389. #if MBEDTLS_VERSION_MAJOR >= 4
  390. #define CPPHTTPLIB_MBEDTLS_V4
  391. #endif
  392. #if MBEDTLS_VERSION_MAJOR >= 3
  393. #define CPPHTTPLIB_MBEDTLS_V3
  394. #endif
  395. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  396. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  397. #include <wolfssl/options.h>
  398. #include <wolfssl/openssl/x509v3.h>
  399. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  400. #ifndef WOLFSSL_GEN_EMAIL
  401. #define WOLFSSL_GEN_EMAIL 1
  402. #endif
  403. #ifndef WOLFSSL_GEN_DNS
  404. #define WOLFSSL_GEN_DNS 2
  405. #endif
  406. #ifndef WOLFSSL_GEN_URI
  407. #define WOLFSSL_GEN_URI 6
  408. #endif
  409. #ifndef WOLFSSL_GEN_IPADD
  410. #define WOLFSSL_GEN_IPADD 7
  411. #endif
  412. #include <wolfssl/ssl.h>
  413. #include <wolfssl/wolfcrypt/hash.h>
  414. #include <wolfssl/wolfcrypt/md5.h>
  415. #include <wolfssl/wolfcrypt/sha256.h>
  416. #include <wolfssl/wolfcrypt/sha512.h>
  417. #ifdef _WIN32
  418. #include <wincrypt.h>
  419. #ifdef _MSC_VER
  420. #pragma comment(lib, "crypt32.lib")
  421. #endif
  422. #endif // _WIN32
  423. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  424. #if TARGET_OS_OSX
  425. #include <Security/Security.h>
  426. #endif
  427. #endif
  428. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  429. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  430. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  431. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  432. #define CPPHTTPLIB_SSL_ENABLED
  433. #endif
  434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  435. #include <zlib.h>
  436. #endif
  437. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  438. #include <brotli/decode.h>
  439. #include <brotli/encode.h>
  440. #endif
  441. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  442. #include <zstd.h>
  443. #endif
  444. /*
  445. * Declaration
  446. */
  447. namespace httplib {
  448. namespace ws {
  449. class WebSocket;
  450. } // namespace ws
  451. namespace detail {
  452. /*
  453. * Backport std::make_unique from C++14.
  454. *
  455. * NOTE: This code came up with the following stackoverflow post:
  456. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  457. *
  458. */
  459. template <class T, class... Args>
  460. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  461. make_unique(Args &&...args) {
  462. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  463. }
  464. template <class T>
  465. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  466. make_unique(std::size_t n) {
  467. typedef typename std::remove_extent<T>::type RT;
  468. return std::unique_ptr<T>(new RT[n]);
  469. }
  470. // Locale-independent ASCII character classification. The <cctype>
  471. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  472. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  473. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  474. // classified without regard to the locale.
  475. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  476. inline bool is_ascii_alpha(char c) {
  477. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  478. }
  479. inline bool is_ascii_alnum(char c) {
  480. return is_ascii_digit(c) || is_ascii_alpha(c);
  481. }
  482. namespace case_ignore {
  483. inline unsigned char to_lower(int c) {
  484. const static unsigned char table[256] = {
  485. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  486. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  487. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  488. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  489. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  490. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  491. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  492. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  493. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  494. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  495. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  496. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  497. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  498. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  499. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  500. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  501. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  502. 255,
  503. };
  504. return table[(unsigned char)(char)c];
  505. }
  506. inline std::string to_lower(const std::string &s) {
  507. std::string result = s;
  508. std::transform(
  509. result.begin(), result.end(), result.begin(),
  510. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  511. return result;
  512. }
  513. inline bool equal(const std::string &a, const std::string &b) {
  514. return a.size() == b.size() &&
  515. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  516. return to_lower(ca) == to_lower(cb);
  517. });
  518. }
  519. struct equal_to {
  520. bool operator()(const std::string &a, const std::string &b) const {
  521. return equal(a, b);
  522. }
  523. };
  524. struct hash {
  525. size_t operator()(const std::string &key) const {
  526. return hash_core(key.data(), key.size(), 0);
  527. }
  528. size_t hash_core(const char *s, size_t l, size_t h) const {
  529. return (l == 0) ? h
  530. : hash_core(s + 1, l - 1,
  531. // Unsets the 6 high bits of h, therefore no
  532. // overflow happens
  533. (((std::numeric_limits<size_t>::max)() >> 6) &
  534. h * 33) ^
  535. static_cast<unsigned char>(to_lower(*s)));
  536. }
  537. };
  538. template <typename T>
  539. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  540. detail::case_ignore::equal_to>;
  541. } // namespace case_ignore
  542. // This is based on
  543. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  544. struct scope_exit {
  545. explicit scope_exit(std::function<void(void)> &&f)
  546. : exit_function(std::move(f)), execute_on_destruction{true} {}
  547. scope_exit(scope_exit &&rhs) noexcept
  548. : exit_function(std::move(rhs.exit_function)),
  549. execute_on_destruction{rhs.execute_on_destruction} {
  550. rhs.release();
  551. }
  552. ~scope_exit() {
  553. if (execute_on_destruction) { this->exit_function(); }
  554. }
  555. void release() { this->execute_on_destruction = false; }
  556. private:
  557. scope_exit(const scope_exit &) = delete;
  558. void operator=(const scope_exit &) = delete;
  559. scope_exit &operator=(scope_exit &&) = delete;
  560. std::function<void(void)> exit_function;
  561. bool execute_on_destruction;
  562. };
  563. // Simple from_chars implementation for integer and double types (C++17
  564. // substitute)
  565. template <typename T> struct from_chars_result {
  566. const char *ptr;
  567. std::errc ec;
  568. };
  569. template <typename T>
  570. inline from_chars_result<T> from_chars(const char *first, const char *last,
  571. T &value, int base = 10) {
  572. value = 0;
  573. const char *p = first;
  574. bool negative = false;
  575. if (p != last && *p == '-') {
  576. negative = true;
  577. ++p;
  578. }
  579. if (p == last) { return {first, std::errc::invalid_argument}; }
  580. T result = 0;
  581. for (; p != last; ++p) {
  582. char c = *p;
  583. int digit = -1;
  584. if (is_ascii_digit(c)) {
  585. digit = c - '0';
  586. } else if ('a' <= c && c <= 'z') {
  587. digit = c - 'a' + 10;
  588. } else if ('A' <= c && c <= 'Z') {
  589. digit = c - 'A' + 10;
  590. } else {
  591. break;
  592. }
  593. if (digit < 0 || digit >= base) { break; }
  594. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  595. return {p, std::errc::result_out_of_range};
  596. }
  597. result = result * base + digit;
  598. }
  599. if (p == first || (negative && p == first + 1)) {
  600. return {first, std::errc::invalid_argument};
  601. }
  602. value = negative ? T(0) - result : result;
  603. return {p, std::errc{}};
  604. }
  605. // from_chars for double (hand-written, locale-independent)
  606. //
  607. // The only double consumed by this library is the HTTP quality value, whose
  608. // grammar is (RFC 9110 12.4.2):
  609. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  610. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  611. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  612. // '.' always the decimal separator (std::strtod would instead read it from the
  613. // global C locale, mis-parsing q-values once an embedder calls
  614. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  615. // the result to [0, 1], so inputs outside that range need not be distinguished
  616. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  617. // cases that exponent and wide-range handling would introduce.
  618. inline from_chars_result<double> from_chars(const char *first, const char *last,
  619. double &value) {
  620. value = 0.0;
  621. const char *p = first;
  622. // Each 1eN is exactly representable, so a single final division by the
  623. // matching entry yields a correctly-rounded result.
  624. static const double powers_of_ten[] = {
  625. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  626. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  627. const int max_frac_digits =
  628. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  629. // Accumulate digits into a 64-bit integer and remember how many were
  630. // fractional. Two independent caps keep this bounded and safe:
  631. // * accumulation saturates before mantissa could overflow uint64_t, and
  632. // * frac_digits is capped at max_frac_digits so it is always a valid index
  633. // into powers_of_ten (without this an input like "0.000...0" would never
  634. // grow mantissa, so the saturation cap alone would not bound it).
  635. // Both caps only drop digits far beyond the precision a q-value needs; any
  636. // value they would change is well outside [0, 1] and rejected by the caller.
  637. uint64_t mantissa = 0;
  638. int frac_digits = 0;
  639. bool seen_digit = false;
  640. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  641. auto accumulate = [&](char c) {
  642. if (mantissa <= limit) {
  643. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  644. return true;
  645. }
  646. return false;
  647. };
  648. for (; p != last && is_ascii_digit(*p); ++p) {
  649. seen_digit = true;
  650. accumulate(*p);
  651. }
  652. if (p != last && *p == '.') {
  653. ++p;
  654. for (; p != last && is_ascii_digit(*p); ++p) {
  655. seen_digit = true;
  656. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  657. }
  658. }
  659. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  660. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  661. return {p, std::errc{}};
  662. }
  663. inline bool parse_port(const char *s, size_t len, int &port) {
  664. int val = 0;
  665. auto r = from_chars(s, s + len, val);
  666. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  667. port = val;
  668. return true;
  669. }
  670. inline bool parse_port(const std::string &s, int &port) {
  671. return parse_port(s.data(), s.size(), port);
  672. }
  673. struct UrlComponents {
  674. std::string scheme;
  675. std::string host;
  676. std::string port;
  677. std::string path;
  678. std::string query;
  679. };
  680. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  681. uc = {};
  682. size_t pos = 0;
  683. auto sep = url.find("://");
  684. if (sep != std::string::npos) {
  685. uc.scheme = url.substr(0, sep);
  686. // Scheme must be [a-z]+ only
  687. if (uc.scheme.empty()) { return false; }
  688. for (auto c : uc.scheme) {
  689. if (c < 'a' || c > 'z') { return false; }
  690. }
  691. pos = sep + 3;
  692. } else if (url.compare(0, 2, "//") == 0) {
  693. pos = 2;
  694. }
  695. auto has_authority_prefix = pos > 0;
  696. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  697. url[0] != '?' && url[0] != '#');
  698. if (has_authority) {
  699. if (pos < url.size() && url[pos] == '[') {
  700. auto close = url.find(']', pos);
  701. if (close == std::string::npos) { return false; }
  702. uc.host = url.substr(pos + 1, close - pos - 1);
  703. // IPv6 host must be [a-fA-F0-9:]+ only
  704. if (uc.host.empty()) { return false; }
  705. for (auto c : uc.host) {
  706. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  707. (c >= 'A' && c <= 'F') || c == ':')) {
  708. return false;
  709. }
  710. }
  711. pos = close + 1;
  712. // The IPv6 literal is the whole host, so ']' must be followed by a port,
  713. // path, query or fragment delimiter (or the end of input). Otherwise the
  714. // trailing bytes would be folded into the path while the connection
  715. // still targets the bracketed address.
  716. if (pos < url.size()) {
  717. auto c = url[pos];
  718. if (c != ':' && c != '/' && c != '?' && c != '#') { return false; }
  719. }
  720. } else {
  721. auto end = url.find_first_of(":/?#", pos);
  722. if (end == std::string::npos) { end = url.size(); }
  723. uc.host = url.substr(pos, end - pos);
  724. pos = end;
  725. }
  726. if (pos < url.size() && url[pos] == ':') {
  727. ++pos;
  728. auto end = url.find_first_of("/?#", pos);
  729. if (end == std::string::npos) { end = url.size(); }
  730. uc.port = url.substr(pos, end - pos);
  731. pos = end;
  732. }
  733. // Without :// or //, the entire input must be consumed as host[:port].
  734. // If there is leftover (path, query, etc.), this is not a valid
  735. // host[:port] string — clear and reparse as a plain path.
  736. if (!has_authority_prefix && pos < url.size()) {
  737. uc.host.clear();
  738. uc.port.clear();
  739. pos = 0;
  740. }
  741. }
  742. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  743. auto end = url.find_first_of("?#", pos);
  744. if (end == std::string::npos) { end = url.size(); }
  745. uc.path = url.substr(pos, end - pos);
  746. pos = end;
  747. }
  748. if (pos < url.size() && url[pos] == '?') {
  749. auto end = url.find('#', pos);
  750. if (end == std::string::npos) { end = url.size(); }
  751. uc.query = url.substr(pos, end - pos);
  752. }
  753. return true;
  754. }
  755. } // namespace detail
  756. enum class SSLVerifierResponse {
  757. // no decision has been made, use the built-in certificate verifier
  758. NoDecisionMade,
  759. // connection certificate is verified and accepted
  760. CertificateAccepted,
  761. // connection certificate was processed but is rejected
  762. CertificateRejected
  763. };
  764. // System CA loading policy for SSL clients. Auto (the default) loads system
  765. // CA certs only when no custom CA is configured; enable_system_ca() switches
  766. // to an explicit policy.
  767. enum class SystemCAMode { Auto, Enabled, Disabled };
  768. enum StatusCode {
  769. // Information responses
  770. Continue_100 = 100,
  771. SwitchingProtocol_101 = 101,
  772. Processing_102 = 102,
  773. EarlyHints_103 = 103,
  774. // Successful responses
  775. OK_200 = 200,
  776. Created_201 = 201,
  777. Accepted_202 = 202,
  778. NonAuthoritativeInformation_203 = 203,
  779. NoContent_204 = 204,
  780. ResetContent_205 = 205,
  781. PartialContent_206 = 206,
  782. MultiStatus_207 = 207,
  783. AlreadyReported_208 = 208,
  784. IMUsed_226 = 226,
  785. // Redirection messages
  786. MultipleChoices_300 = 300,
  787. MovedPermanently_301 = 301,
  788. Found_302 = 302,
  789. SeeOther_303 = 303,
  790. NotModified_304 = 304,
  791. UseProxy_305 = 305,
  792. unused_306 = 306,
  793. TemporaryRedirect_307 = 307,
  794. PermanentRedirect_308 = 308,
  795. // Client error responses
  796. BadRequest_400 = 400,
  797. Unauthorized_401 = 401,
  798. PaymentRequired_402 = 402,
  799. Forbidden_403 = 403,
  800. NotFound_404 = 404,
  801. MethodNotAllowed_405 = 405,
  802. NotAcceptable_406 = 406,
  803. ProxyAuthenticationRequired_407 = 407,
  804. RequestTimeout_408 = 408,
  805. Conflict_409 = 409,
  806. Gone_410 = 410,
  807. LengthRequired_411 = 411,
  808. PreconditionFailed_412 = 412,
  809. PayloadTooLarge_413 = 413,
  810. UriTooLong_414 = 414,
  811. UnsupportedMediaType_415 = 415,
  812. RangeNotSatisfiable_416 = 416,
  813. ExpectationFailed_417 = 417,
  814. ImATeapot_418 = 418,
  815. MisdirectedRequest_421 = 421,
  816. UnprocessableContent_422 = 422,
  817. Locked_423 = 423,
  818. FailedDependency_424 = 424,
  819. TooEarly_425 = 425,
  820. UpgradeRequired_426 = 426,
  821. PreconditionRequired_428 = 428,
  822. TooManyRequests_429 = 429,
  823. RequestHeaderFieldsTooLarge_431 = 431,
  824. UnavailableForLegalReasons_451 = 451,
  825. // Server error responses
  826. InternalServerError_500 = 500,
  827. NotImplemented_501 = 501,
  828. BadGateway_502 = 502,
  829. ServiceUnavailable_503 = 503,
  830. GatewayTimeout_504 = 504,
  831. HttpVersionNotSupported_505 = 505,
  832. VariantAlsoNegotiates_506 = 506,
  833. InsufficientStorage_507 = 507,
  834. LoopDetected_508 = 508,
  835. NotExtended_510 = 510,
  836. NetworkAuthenticationRequired_511 = 511,
  837. };
  838. namespace detail {
  839. // A multimap that keeps its entries in the order they were inserted.
  840. //
  841. // HTTP needs that order in two places. RFC 9110 5.3 makes the order of header
  842. // fields sharing a field name significant and forbids a proxy from reordering
  843. // them, and a query string's parameters are meaningful in the order the caller
  844. // wrote them. Neither standard container expresses it: std::unordered_multimap
  845. // gives no ordering guarantee at all for equivalent keys (libstdc++ yields
  846. // reverse insertion order, libc++ insertion order), and std::multimap sorts by
  847. // key, which would drop control data such as Host behind whatever else the
  848. // message carries and alphabetise a query string.
  849. //
  850. // Entries are therefore kept in a flat vector, in order. Lookup is a linear
  851. // scan, which beats hashing for the handful of entries a message carries
  852. // (headers are capped at CPPHTTPLIB_HEADER_MAX_COUNT).
  853. //
  854. // KeyEqual compares keys; it is what makes Headers case-insensitive and
  855. // Params, whose parameter names are case-sensitive, not.
  856. template <typename Mapped, typename KeyEqual> class insertion_ordered_multimap {
  857. public:
  858. using key_type = std::string;
  859. using mapped_type = Mapped;
  860. using value_type = std::pair<std::string, Mapped>;
  861. using size_type = std::size_t;
  862. using difference_type = std::ptrdiff_t;
  863. using reference = value_type &;
  864. using const_reference = const value_type &;
  865. private:
  866. static size_type npos() { return static_cast<size_type>(-1); }
  867. static bool keys_equal(const std::string &a, const std::string &b) {
  868. return KeyEqual()(a, b);
  869. }
  870. // Iterating yields every entry in insertion order, but equal_range() and
  871. // find() have to walk only the entries sharing one key, which are not
  872. // adjacent. Both are the same iterator type: key_idx_ selects between the
  873. // two traversals, and since equality compares only the position, an iterator
  874. // restricted to one key still compares equal to end().
  875. template <typename V> class iterator_t {
  876. public:
  877. using iterator_category = std::bidirectional_iterator_tag;
  878. using value_type = insertion_ordered_multimap::value_type;
  879. using difference_type = insertion_ordered_multimap::difference_type;
  880. using pointer = V *;
  881. using reference = V &;
  882. iterator_t() : data_(nullptr), idx_(0), size_(0), key_idx_(npos()) {}
  883. template <typename U,
  884. typename std::enable_if<std::is_convertible<U *, V *>::value,
  885. int>::type = 0>
  886. iterator_t(const iterator_t<U> &rhs)
  887. : data_(rhs.data_), idx_(rhs.idx_), size_(rhs.size_),
  888. key_idx_(rhs.key_idx_) {}
  889. reference operator*() const { return data_[idx_]; }
  890. pointer operator->() const { return data_ + idx_; }
  891. iterator_t &operator++() {
  892. // Saturating, so that advancing past the last entry of a key (which
  893. // get_multimap_value() does when asked for an out-of-range id) stays at
  894. // end() instead of running off the container.
  895. if (idx_ >= size_) { return *this; }
  896. ++idx_;
  897. if (key_idx_ != npos()) {
  898. while (idx_ < size_ && !matches(idx_)) {
  899. ++idx_;
  900. }
  901. }
  902. return *this;
  903. }
  904. iterator_t operator++(int) {
  905. auto tmp = *this;
  906. ++*this;
  907. return tmp;
  908. }
  909. iterator_t &operator--() {
  910. if (idx_ == 0) { return *this; }
  911. --idx_;
  912. if (key_idx_ != npos()) {
  913. while (idx_ > 0 && !matches(idx_)) {
  914. --idx_;
  915. }
  916. }
  917. return *this;
  918. }
  919. iterator_t operator--(int) {
  920. auto tmp = *this;
  921. --*this;
  922. return tmp;
  923. }
  924. template <typename U> bool operator==(const iterator_t<U> &rhs) const {
  925. return idx_ == rhs.idx_;
  926. }
  927. template <typename U> bool operator!=(const iterator_t<U> &rhs) const {
  928. return idx_ != rhs.idx_;
  929. }
  930. private:
  931. friend class insertion_ordered_multimap;
  932. template <typename> friend class iterator_t;
  933. iterator_t(V *data, size_type idx, size_type size, size_type key_idx)
  934. : data_(data), idx_(idx), size_(size), key_idx_(key_idx) {}
  935. bool matches(size_type i) const {
  936. return keys_equal(data_[i].first, data_[key_idx_].first);
  937. }
  938. V *data_;
  939. size_type idx_;
  940. size_type size_;
  941. size_type key_idx_;
  942. };
  943. public:
  944. using iterator = iterator_t<value_type>;
  945. using const_iterator = iterator_t<const value_type>;
  946. insertion_ordered_multimap() = default;
  947. insertion_ordered_multimap(std::initializer_list<value_type> il)
  948. : entries_(il) {}
  949. template <typename InputIt>
  950. insertion_ordered_multimap(InputIt first, InputIt last)
  951. : entries_(first, last) {}
  952. iterator begin() { return make_iter(0, npos()); }
  953. iterator end() { return make_iter(entries_.size(), npos()); }
  954. const_iterator begin() const { return make_citer(0, npos()); }
  955. const_iterator end() const { return make_citer(entries_.size(), npos()); }
  956. const_iterator cbegin() const { return begin(); }
  957. const_iterator cend() const { return end(); }
  958. bool empty() const { return entries_.empty(); }
  959. size_type size() const { return entries_.size(); }
  960. void clear() { entries_.clear(); }
  961. void swap(insertion_ordered_multimap &rhs) { entries_.swap(rhs.entries_); }
  962. iterator insert(const value_type &val) {
  963. entries_.push_back(val);
  964. return make_iter(entries_.size() - 1, npos());
  965. }
  966. iterator insert(value_type &&val) {
  967. entries_.push_back(std::move(val));
  968. return make_iter(entries_.size() - 1, npos());
  969. }
  970. template <typename... Args> iterator emplace(Args &&...args) {
  971. entries_.emplace_back(std::forward<Args>(args)...);
  972. return make_iter(entries_.size() - 1, npos());
  973. }
  974. // For entries that have to lead the message, such as the Host header field
  975. // (RFC 9110 5.3 recommends sending control data first).
  976. template <typename... Args> iterator emplace_front(Args &&...args) {
  977. entries_.emplace(entries_.begin(), std::forward<Args>(args)...);
  978. return make_iter(0, npos());
  979. }
  980. iterator find(const std::string &key) {
  981. auto i = index_of(key);
  982. return i == npos() ? end() : make_iter(i, i);
  983. }
  984. const_iterator find(const std::string &key) const {
  985. auto i = index_of(key);
  986. return i == npos() ? end() : make_citer(i, i);
  987. }
  988. size_type count(const std::string &key) const {
  989. size_type n = 0;
  990. for (const auto &entry : entries_) {
  991. if (keys_equal(entry.first, key)) { n++; }
  992. }
  993. return n;
  994. }
  995. std::pair<iterator, iterator> equal_range(const std::string &key) {
  996. auto i = index_of(key);
  997. return i == npos() ? std::make_pair(end(), end())
  998. : std::make_pair(make_iter(i, i), end());
  999. }
  1000. std::pair<const_iterator, const_iterator>
  1001. equal_range(const std::string &key) const {
  1002. auto i = index_of(key);
  1003. return i == npos() ? std::make_pair(end(), end())
  1004. : std::make_pair(make_citer(i, i), end());
  1005. }
  1006. size_type erase(const std::string &key) {
  1007. auto before = entries_.size();
  1008. entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
  1009. [&](const value_type &entry) {
  1010. return keys_equal(entry.first, key);
  1011. }),
  1012. entries_.end());
  1013. return before - entries_.size();
  1014. }
  1015. iterator erase(const_iterator pos) {
  1016. entries_.erase(entries_.begin() + static_cast<difference_type>(pos.idx_));
  1017. return make_iter(pos.idx_, npos());
  1018. }
  1019. // Erases what iterating [first, last) would actually visit, so erasing an
  1020. // equal_range() removes only the entries with that key, not everything
  1021. // positioned between them.
  1022. iterator erase(const_iterator first, const_iterator last) {
  1023. auto from = first.idx_;
  1024. auto to = last.idx_;
  1025. if (from >= to) { return make_iter(from, npos()); }
  1026. auto begin_it = entries_.begin();
  1027. auto from_it = begin_it + static_cast<difference_type>(from);
  1028. auto to_it = begin_it + static_cast<difference_type>(to);
  1029. if (first.key_idx_ == npos()) {
  1030. entries_.erase(from_it, to_it);
  1031. } else {
  1032. auto key = entries_[first.key_idx_].first;
  1033. auto keep = from_it;
  1034. for (auto it = from_it; it != to_it; ++it) {
  1035. if (!keys_equal(it->first, key)) {
  1036. if (keep != it) { *keep = std::move(*it); }
  1037. ++keep;
  1038. }
  1039. }
  1040. if (keep != to_it) {
  1041. keep = std::move(to_it, entries_.end(), keep);
  1042. } else {
  1043. keep = entries_.end();
  1044. }
  1045. entries_.erase(keep, entries_.end());
  1046. }
  1047. return make_iter(from, npos());
  1048. }
  1049. friend bool operator==(const insertion_ordered_multimap &lhs,
  1050. const insertion_ordered_multimap &rhs) {
  1051. return lhs.entries_ == rhs.entries_;
  1052. }
  1053. friend bool operator!=(const insertion_ordered_multimap &lhs,
  1054. const insertion_ordered_multimap &rhs) {
  1055. return !(lhs == rhs);
  1056. }
  1057. private:
  1058. size_type index_of(const std::string &key) const {
  1059. for (size_type i = 0; i < entries_.size(); i++) {
  1060. if (keys_equal(entries_[i].first, key)) { return i; }
  1061. }
  1062. return npos();
  1063. }
  1064. iterator make_iter(size_type idx, size_type key_idx) {
  1065. return iterator(entries_.data(), idx, entries_.size(), key_idx);
  1066. }
  1067. const_iterator make_citer(size_type idx, size_type key_idx) const {
  1068. return const_iterator(entries_.data(), idx, entries_.size(), key_idx);
  1069. }
  1070. std::vector<value_type> entries_;
  1071. };
  1072. } // namespace detail
  1073. using Headers =
  1074. detail::insertion_ordered_multimap<std::string,
  1075. detail::case_ignore::equal_to>;
  1076. // Query parameter names are case-sensitive, unlike header field names.
  1077. using Params =
  1078. detail::insertion_ordered_multimap<std::string, std::equal_to<std::string>>;
  1079. using Match = std::smatch;
  1080. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  1081. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  1082. /*
  1083. * detail: type-erased storage used by UserData.
  1084. * ABI-stable regardless of C++ standard — always uses this custom
  1085. * implementation instead of std::any.
  1086. */
  1087. namespace detail {
  1088. using any_type_id = const void *;
  1089. template <typename T> any_type_id any_typeid() noexcept {
  1090. static const char id = 0;
  1091. return &id;
  1092. }
  1093. struct any_storage {
  1094. virtual ~any_storage() = default;
  1095. virtual std::unique_ptr<any_storage> clone() const = 0;
  1096. virtual any_type_id type_id() const noexcept = 0;
  1097. };
  1098. template <typename T> struct any_value final : any_storage {
  1099. T value;
  1100. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  1101. std::unique_ptr<any_storage> clone() const override {
  1102. return std::unique_ptr<any_storage>(new any_value<T>(value));
  1103. }
  1104. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  1105. };
  1106. } // namespace detail
  1107. class UserData {
  1108. public:
  1109. UserData() = default;
  1110. UserData(UserData &&) noexcept = default;
  1111. UserData &operator=(UserData &&) noexcept = default;
  1112. UserData(const UserData &o) {
  1113. for (const auto &e : o.entries_) {
  1114. if (e.second) { entries_[e.first] = e.second->clone(); }
  1115. }
  1116. }
  1117. UserData &operator=(const UserData &o) {
  1118. if (this != &o) {
  1119. entries_.clear();
  1120. for (const auto &e : o.entries_) {
  1121. if (e.second) { entries_[e.first] = e.second->clone(); }
  1122. }
  1123. }
  1124. return *this;
  1125. }
  1126. template <typename T> void set(const std::string &key, T &&value) {
  1127. using D = typename std::decay<T>::type;
  1128. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  1129. }
  1130. template <typename T> T *get(const std::string &key) noexcept {
  1131. auto it = entries_.find(key);
  1132. if (it == entries_.end() || !it->second) { return nullptr; }
  1133. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1134. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  1135. }
  1136. template <typename T> const T *get(const std::string &key) const noexcept {
  1137. auto it = entries_.find(key);
  1138. if (it == entries_.end() || !it->second) { return nullptr; }
  1139. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1140. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  1141. }
  1142. bool has(const std::string &key) const noexcept {
  1143. return entries_.find(key) != entries_.end();
  1144. }
  1145. void erase(const std::string &key) { entries_.erase(key); }
  1146. void clear() noexcept { entries_.clear(); }
  1147. private:
  1148. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  1149. entries_;
  1150. };
  1151. struct Response;
  1152. using ResponseHandler = std::function<bool(const Response &response)>;
  1153. struct FormData {
  1154. std::string name;
  1155. std::string content;
  1156. std::string filename;
  1157. std::string content_type;
  1158. Headers headers;
  1159. };
  1160. struct FormField {
  1161. std::string name;
  1162. std::string content;
  1163. Headers headers;
  1164. };
  1165. // RFC 7578 5.2: a form processor "SHOULD send back results in order" and
  1166. // "Intermediaries MUST NOT reorder the results", so a handler walking these
  1167. // should see the parts as they were sent. A std::multimap sorts by field name
  1168. // and loses that. Field names are case-sensitive, hence std::equal_to rather
  1169. // than the case-insensitive predicate Headers uses.
  1170. using FormFields =
  1171. detail::insertion_ordered_multimap<FormField, std::equal_to<std::string>>;
  1172. using FormFiles =
  1173. detail::insertion_ordered_multimap<FormData, std::equal_to<std::string>>;
  1174. struct MultipartFormData {
  1175. FormFields fields; // Text fields from multipart
  1176. FormFiles files; // Files from multipart
  1177. // Text field access
  1178. std::string get_field(const std::string &key, size_t id = 0) const;
  1179. std::vector<std::string> get_fields(const std::string &key) const;
  1180. bool has_field(const std::string &key) const;
  1181. size_t get_field_count(const std::string &key) const;
  1182. // File access
  1183. FormData get_file(const std::string &key, size_t id = 0) const;
  1184. std::vector<FormData> get_files(const std::string &key) const;
  1185. bool has_file(const std::string &key) const;
  1186. size_t get_file_count(const std::string &key) const;
  1187. };
  1188. struct UploadFormData {
  1189. std::string name;
  1190. std::string content;
  1191. std::string filename;
  1192. std::string content_type;
  1193. };
  1194. using UploadFormDataItems = std::vector<UploadFormData>;
  1195. class DataSink {
  1196. public:
  1197. DataSink() : os(&sb_), sb_(*this) {}
  1198. DataSink(const DataSink &) = delete;
  1199. DataSink &operator=(const DataSink &) = delete;
  1200. DataSink(DataSink &&) = delete;
  1201. DataSink &operator=(DataSink &&) = delete;
  1202. std::function<bool(const char *data, size_t data_len)> write;
  1203. std::function<bool()> is_writable;
  1204. std::function<void()> done;
  1205. std::function<void(const Headers &trailer)> done_with_trailer;
  1206. std::ostream os;
  1207. private:
  1208. class data_sink_streambuf final : public std::streambuf {
  1209. public:
  1210. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  1211. protected:
  1212. std::streamsize xsputn(const char *s, std::streamsize n) override {
  1213. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  1214. return 0;
  1215. }
  1216. private:
  1217. DataSink &sink_;
  1218. };
  1219. data_sink_streambuf sb_;
  1220. };
  1221. using ContentProvider =
  1222. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  1223. using ContentProviderWithoutLength =
  1224. std::function<bool(size_t offset, DataSink &sink)>;
  1225. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  1226. struct FormDataProvider {
  1227. std::string name;
  1228. ContentProviderWithoutLength provider;
  1229. std::string filename;
  1230. std::string content_type;
  1231. };
  1232. using FormDataProviderItems = std::vector<FormDataProvider>;
  1233. inline FormDataProvider
  1234. make_file_provider(const std::string &name, const std::string &filepath,
  1235. const std::string &filename = std::string(),
  1236. const std::string &content_type = std::string()) {
  1237. FormDataProvider fdp;
  1238. fdp.name = name;
  1239. fdp.filename = filename.empty() ? filepath : filename;
  1240. fdp.content_type = content_type;
  1241. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  1242. std::ifstream f(filepath, std::ios::binary);
  1243. if (!f) { return false; }
  1244. if (offset > 0) {
  1245. f.seekg(static_cast<std::streamoff>(offset));
  1246. if (!f.good()) {
  1247. sink.done();
  1248. return true;
  1249. }
  1250. }
  1251. char buf[8192];
  1252. f.read(buf, sizeof(buf));
  1253. auto n = static_cast<size_t>(f.gcount());
  1254. if (n > 0) { return sink.write(buf, n); }
  1255. sink.done(); // EOF
  1256. return true;
  1257. };
  1258. return fdp;
  1259. }
  1260. inline std::pair<size_t, ContentProvider>
  1261. make_file_body(const std::string &filepath) {
  1262. size_t size = 0;
  1263. {
  1264. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  1265. if (!f) { return {0, ContentProvider{}}; }
  1266. size = static_cast<size_t>(f.tellg());
  1267. }
  1268. ContentProvider provider = [filepath](size_t offset, size_t length,
  1269. DataSink &sink) -> bool {
  1270. std::ifstream f(filepath, std::ios::binary);
  1271. if (!f) { return false; }
  1272. f.seekg(static_cast<std::streamoff>(offset));
  1273. if (!f.good()) { return false; }
  1274. char buf[8192];
  1275. while (length > 0) {
  1276. auto to_read = (std::min)(sizeof(buf), length);
  1277. f.read(buf, static_cast<std::streamsize>(to_read));
  1278. auto n = static_cast<size_t>(f.gcount());
  1279. if (n == 0) { break; }
  1280. if (!sink.write(buf, n)) { return false; }
  1281. length -= n;
  1282. }
  1283. return true;
  1284. };
  1285. return {size, std::move(provider)};
  1286. }
  1287. using ContentReceiverWithProgress = std::function<bool(
  1288. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1289. using ContentReceiver =
  1290. std::function<bool(const char *data, size_t data_length)>;
  1291. using FormDataHeader = std::function<bool(const FormData &file)>;
  1292. class ContentReader {
  1293. public:
  1294. using Reader = std::function<bool(ContentReceiver receiver)>;
  1295. using FormDataReader =
  1296. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1297. ContentReader(Reader reader, FormDataReader multipart_reader)
  1298. : reader_(std::move(reader)),
  1299. formdata_reader_(std::move(multipart_reader)) {}
  1300. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1301. return formdata_reader_(std::move(header), std::move(receiver));
  1302. }
  1303. bool operator()(ContentReceiver receiver) const {
  1304. return reader_(std::move(receiver));
  1305. }
  1306. Reader reader_;
  1307. FormDataReader formdata_reader_;
  1308. };
  1309. using Range = std::pair<ssize_t, ssize_t>;
  1310. using Ranges = std::vector<Range>;
  1311. #ifdef CPPHTTPLIB_SSL_ENABLED
  1312. // TLS abstraction layer - public type definitions and API
  1313. namespace tls {
  1314. // Opaque handles (defined as void* for abstraction)
  1315. using ctx_t = void *;
  1316. using session_t = void *;
  1317. using const_session_t = const void *; // For read-only session access
  1318. using cert_t = void *;
  1319. using ca_store_t = void *;
  1320. // TLS versions
  1321. enum class Version {
  1322. TLS1_2 = 0x0303,
  1323. TLS1_3 = 0x0304,
  1324. };
  1325. // Subject Alternative Names (SAN) entry types
  1326. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1327. // SAN entry structure
  1328. struct SanEntry {
  1329. SanType type;
  1330. std::string value;
  1331. };
  1332. // Verification context for certificate verification callback
  1333. struct VerifyContext {
  1334. session_t session; // TLS session handle
  1335. cert_t cert; // Current certificate being verified
  1336. int depth; // Certificate chain depth (0 = leaf)
  1337. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1338. long error_code; // Backend-specific error code (0 = no error)
  1339. const char *error_string; // Human-readable error description
  1340. // Certificate introspection methods
  1341. std::string subject_cn() const;
  1342. std::string issuer_name() const;
  1343. bool check_hostname(const char *hostname) const;
  1344. std::vector<SanEntry> sans() const;
  1345. bool validity(time_t &not_before, time_t &not_after) const;
  1346. std::string serial() const;
  1347. };
  1348. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1349. // TlsError codes for TLS operations (backend-independent)
  1350. enum class ErrorCode : int {
  1351. Success = 0,
  1352. WantRead, // Non-blocking: need to wait for read
  1353. WantWrite, // Non-blocking: need to wait for write
  1354. PeerClosed, // Peer closed the connection
  1355. Fatal, // Unrecoverable error
  1356. SyscallError, // System call error (check sys_errno)
  1357. CertVerifyFailed, // Certificate verification failed
  1358. HostnameMismatch, // Hostname verification failed
  1359. };
  1360. // TLS error information
  1361. struct TlsError {
  1362. ErrorCode code = ErrorCode::Fatal;
  1363. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1364. int sys_errno = 0; // errno when SyscallError
  1365. // Convert verification error code to human-readable string
  1366. static std::string verify_error_to_string(long error_code);
  1367. };
  1368. // RAII wrapper for peer certificate
  1369. class PeerCert {
  1370. public:
  1371. PeerCert();
  1372. PeerCert(PeerCert &&other) noexcept;
  1373. PeerCert &operator=(PeerCert &&other) noexcept;
  1374. ~PeerCert();
  1375. PeerCert(const PeerCert &) = delete;
  1376. PeerCert &operator=(const PeerCert &) = delete;
  1377. explicit operator bool() const;
  1378. std::string subject_cn() const;
  1379. std::string issuer_name() const;
  1380. bool check_hostname(const char *hostname) const;
  1381. std::vector<SanEntry> sans() const;
  1382. bool validity(time_t &not_before, time_t &not_after) const;
  1383. std::string serial() const;
  1384. private:
  1385. explicit PeerCert(cert_t cert);
  1386. cert_t cert_ = nullptr;
  1387. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1388. };
  1389. // Callback for TLS context setup (used by SSLServer constructor)
  1390. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1391. } // namespace tls
  1392. #endif
  1393. struct Request {
  1394. std::string method;
  1395. std::string path;
  1396. std::string matched_route;
  1397. Params params;
  1398. Headers headers;
  1399. Headers trailers;
  1400. std::string body;
  1401. std::string remote_addr;
  1402. int remote_port = -1;
  1403. std::string local_addr;
  1404. int local_port = -1;
  1405. // for server
  1406. std::string version;
  1407. std::string target;
  1408. MultipartFormData form;
  1409. Ranges ranges;
  1410. Match matches;
  1411. std::unordered_map<std::string, std::string> path_params;
  1412. std::function<bool()> is_connection_closed = []() { return true; };
  1413. // for client
  1414. std::vector<std::string> accept_content_types;
  1415. ResponseHandler response_handler;
  1416. ContentReceiverWithProgress content_receiver;
  1417. DownloadProgress download_progress;
  1418. UploadProgress upload_progress;
  1419. bool has_header(const std::string &key) const;
  1420. std::string get_header_value(const std::string &key, const char *def = "",
  1421. size_t id = 0) const;
  1422. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1423. size_t id = 0) const;
  1424. size_t get_header_value_count(const std::string &key) const;
  1425. void set_header(const std::string &key, const std::string &val);
  1426. bool has_trailer(const std::string &key) const;
  1427. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1428. size_t get_trailer_value_count(const std::string &key) const;
  1429. bool has_param(const std::string &key) const;
  1430. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1431. std::vector<std::string> get_param_values(const std::string &key) const;
  1432. size_t get_param_value_count(const std::string &key) const;
  1433. bool is_multipart_form_data() const;
  1434. // private members...
  1435. bool body_consumed_ = false;
  1436. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1437. size_t content_length_ = 0;
  1438. ContentProvider content_provider_;
  1439. bool is_chunked_content_provider_ = false;
  1440. size_t authorization_count_ = 0;
  1441. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1442. (std::chrono::steady_clock::time_point::min)();
  1443. #ifdef CPPHTTPLIB_SSL_ENABLED
  1444. tls::const_session_t ssl = nullptr;
  1445. tls::PeerCert peer_cert() const;
  1446. std::string sni() const;
  1447. #endif
  1448. };
  1449. struct Response {
  1450. std::string version;
  1451. int status = -1;
  1452. std::string reason;
  1453. Headers headers;
  1454. Headers trailers;
  1455. std::string body;
  1456. std::string location; // Redirect location
  1457. // User-defined context — set by pre-routing/pre-request handlers and read
  1458. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1459. UserData user_data;
  1460. bool has_header(const std::string &key) const;
  1461. std::string get_header_value(const std::string &key, const char *def = "",
  1462. size_t id = 0) const;
  1463. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1464. size_t id = 0) const;
  1465. size_t get_header_value_count(const std::string &key) const;
  1466. void set_header(const std::string &key, const std::string &val);
  1467. bool has_trailer(const std::string &key) const;
  1468. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1469. size_t get_trailer_value_count(const std::string &key) const;
  1470. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1471. void set_content(const char *s, size_t n, const std::string &content_type);
  1472. void set_content(const std::string &s, const std::string &content_type);
  1473. void set_content(std::string &&s, const std::string &content_type);
  1474. void set_content_provider(
  1475. size_t length, const std::string &content_type, ContentProvider provider,
  1476. ContentProviderResourceReleaser resource_releaser = nullptr);
  1477. void set_content_provider(
  1478. const std::string &content_type, ContentProviderWithoutLength provider,
  1479. ContentProviderResourceReleaser resource_releaser = nullptr);
  1480. void set_chunked_content_provider(
  1481. const std::string &content_type, ContentProviderWithoutLength provider,
  1482. ContentProviderResourceReleaser resource_releaser = nullptr);
  1483. void set_file_content(const std::string &path,
  1484. const std::string &content_type);
  1485. void set_file_content(const std::string &path);
  1486. Response() = default;
  1487. Response(const Response &) = default;
  1488. Response &operator=(const Response &) = default;
  1489. Response(Response &&) = default;
  1490. Response &operator=(Response &&) = default;
  1491. ~Response() {
  1492. if (content_provider_resource_releaser_) {
  1493. content_provider_resource_releaser_(content_provider_success_);
  1494. }
  1495. }
  1496. // private members...
  1497. size_t content_length_ = 0;
  1498. ContentProvider content_provider_;
  1499. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1500. bool is_chunked_content_provider_ = false;
  1501. bool content_provider_success_ = false;
  1502. std::string file_content_path_;
  1503. std::string file_content_content_type_;
  1504. };
  1505. enum class Error {
  1506. Success = 0,
  1507. Unknown,
  1508. Connection,
  1509. BindIPAddress,
  1510. Read,
  1511. Write,
  1512. ExceedRedirectCount,
  1513. Canceled,
  1514. SSLConnection,
  1515. SSLLoadingCerts,
  1516. SSLServerVerification,
  1517. SSLServerHostnameVerification,
  1518. UnsupportedMultipartBoundaryChars,
  1519. Compression,
  1520. ConnectionTimeout,
  1521. ProxyConnection,
  1522. ConnectionClosed,
  1523. Timeout,
  1524. ResourceExhaustion,
  1525. TooManyFormDataFiles,
  1526. ExceedMaxPayloadSize,
  1527. ExceedUriMaxLength,
  1528. ExceedMaxSocketDescriptorCount,
  1529. InvalidRequestLine,
  1530. InvalidHTTPMethod,
  1531. InvalidHTTPVersion,
  1532. InvalidHeaders,
  1533. MultipartParsing,
  1534. OpenFile,
  1535. Listen,
  1536. GetSockName,
  1537. UnsupportedAddressFamily,
  1538. HTTPParsing,
  1539. InvalidRangeHeader,
  1540. UnsupportedContentEncoding,
  1541. WebSocketHandshake,
  1542. // For internal use only
  1543. SSLPeerCouldBeClosed_,
  1544. };
  1545. std::string to_string(Error error);
  1546. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1547. class Stream {
  1548. public:
  1549. virtual ~Stream() = default;
  1550. virtual bool is_readable() const = 0;
  1551. virtual bool wait_readable() const = 0;
  1552. virtual bool wait_writable() const = 0;
  1553. virtual bool is_peer_alive() const { return wait_writable(); }
  1554. virtual ssize_t read(char *ptr, size_t size) = 0;
  1555. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1556. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1557. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1558. virtual socket_t socket() const = 0;
  1559. virtual time_t duration() const = 0;
  1560. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1561. (void)sec;
  1562. (void)usec;
  1563. }
  1564. // Bytes already pulled off the socket and sitting in this stream's own
  1565. // buffer. Exposing them lets a line reader scan for a terminator in one
  1566. // pass instead of asking for a byte at a time. A stream that does no
  1567. // buffering of its own reports none, and readers fall back to read().
  1568. virtual const char *buffered_data(size_t &size) const {
  1569. size = 0;
  1570. return nullptr;
  1571. }
  1572. // Discards `size` bytes previously returned by buffered_data().
  1573. virtual void consume_buffered(size_t size) { (void)size; }
  1574. ssize_t write(const char *ptr);
  1575. ssize_t write(const std::string &s);
  1576. Error get_error() const { return error_; }
  1577. protected:
  1578. Error error_ = Error::Success;
  1579. };
  1580. class TaskQueue {
  1581. public:
  1582. TaskQueue() = default;
  1583. virtual ~TaskQueue() = default;
  1584. virtual bool enqueue(std::function<void()> fn) = 0;
  1585. virtual void shutdown() = 0;
  1586. virtual void on_idle() {}
  1587. };
  1588. class ThreadPool final : public TaskQueue {
  1589. public:
  1590. explicit ThreadPool(
  1591. size_t n, size_t max_n = 0, size_t mqr = 0,
  1592. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1593. ThreadPool(const ThreadPool &) = delete;
  1594. ~ThreadPool() override = default;
  1595. bool enqueue(std::function<void()> fn) override;
  1596. void shutdown() override;
  1597. private:
  1598. void worker(bool is_dynamic);
  1599. void move_to_finished(std::thread::id id);
  1600. void cleanup_finished_threads();
  1601. size_t base_thread_count_;
  1602. size_t max_thread_count_;
  1603. size_t max_queued_requests_;
  1604. time_t idle_timeout_sec_;
  1605. size_t idle_thread_count_;
  1606. bool shutdown_;
  1607. std::list<std::function<void()>> jobs_;
  1608. std::vector<std::thread> threads_; // base threads
  1609. std::list<std::thread> dynamic_threads_; // dynamic threads
  1610. std::vector<std::thread>
  1611. finished_threads_; // exited dynamic threads awaiting join
  1612. std::condition_variable cond_;
  1613. std::mutex mutex_;
  1614. };
  1615. using Logger = std::function<void(const Request &, const Response &)>;
  1616. // Forward declaration for Error type
  1617. enum class Error;
  1618. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1619. using SocketOptions = std::function<void(socket_t sock)>;
  1620. void default_socket_options(socket_t sock);
  1621. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1622. const char *status_message(int status);
  1623. std::string to_string(Error error);
  1624. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1625. std::string get_bearer_token_auth(const Request &req);
  1626. namespace detail {
  1627. class MatcherBase {
  1628. public:
  1629. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1630. virtual ~MatcherBase() = default;
  1631. const std::string &pattern() const { return pattern_; }
  1632. // Match request path and populate its matches and
  1633. virtual bool match(Request &request) const = 0;
  1634. private:
  1635. std::string pattern_;
  1636. };
  1637. /**
  1638. * Captures parameters in request path and stores them in Request::path_params
  1639. *
  1640. * Capture name is a substring of a pattern from : to /.
  1641. * The rest of the pattern is matched against the request path directly
  1642. * Parameters are captured starting from the next character after
  1643. * the end of the last matched static pattern fragment until the next /.
  1644. *
  1645. * Example pattern:
  1646. * "/path/fragments/:capture/more/fragments/:second_capture"
  1647. * Static fragments:
  1648. * "/path/fragments/", "more/fragments/"
  1649. *
  1650. * Given the following request path:
  1651. * "/path/fragments/:1/more/fragments/:2"
  1652. * the resulting capture will be
  1653. * {{"capture", "1"}, {"second_capture", "2"}}
  1654. */
  1655. class PathParamsMatcher final : public MatcherBase {
  1656. public:
  1657. PathParamsMatcher(const std::string &pattern);
  1658. bool match(Request &request) const override;
  1659. private:
  1660. // Treat segment separators as the end of path parameter capture
  1661. // Does not need to handle query parameters as they are parsed before path
  1662. // matching
  1663. static constexpr char separator = '/';
  1664. // Contains static path fragments to match against, excluding the '/' after
  1665. // path params
  1666. // Fragments are separated by path params
  1667. std::vector<std::string> static_fragments_;
  1668. // Stores the names of the path parameters to be used as keys in the
  1669. // Request::path_params map
  1670. std::vector<std::string> param_names_;
  1671. };
  1672. /**
  1673. * Performs std::regex_match on request path
  1674. * and stores the result in Request::matches
  1675. *
  1676. * Note that regex match is performed directly on the whole request.
  1677. * This means that wildcard patterns may match multiple path segments with /:
  1678. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1679. */
  1680. class RegexMatcher final : public MatcherBase {
  1681. public:
  1682. RegexMatcher(const std::string &pattern)
  1683. : MatcherBase(pattern), regex_(pattern) {}
  1684. bool match(Request &request) const override;
  1685. private:
  1686. std::regex regex_;
  1687. };
  1688. int close_socket(socket_t sock) noexcept;
  1689. bool is_accept_resource_error();
  1690. bool is_accept_transient_error();
  1691. ssize_t write_headers(Stream &strm, const Headers &headers);
  1692. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1693. time_t usec);
  1694. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1695. const std::string &boundary);
  1696. ContentProvider
  1697. make_multipart_content_provider(const UploadFormDataItems &items,
  1698. const std::string &boundary);
  1699. } // namespace detail
  1700. bool is_valid_multipart_boundary(const std::string &boundary);
  1701. // Serializer for multipart/form-data request bodies. The boundary is owned
  1702. // by the writer so that per-part framing and the final terminator always
  1703. // agree. Field names and filenames are escaped following the WHATWG HTML
  1704. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1705. // in content types.
  1706. class MultipartFormDataWriter {
  1707. public:
  1708. MultipartFormDataWriter();
  1709. // precondition: is_valid_multipart_boundary(boundary)
  1710. explicit MultipartFormDataWriter(std::string boundary);
  1711. const std::string &boundary() const;
  1712. std::string content_type() const;
  1713. // In-memory items -> whole body (known length)
  1714. std::string serialize(const UploadFormDataItems &items) const;
  1715. size_t content_length(const UploadFormDataItems &items) const;
  1716. // Per-part framing for streaming via a content provider
  1717. std::string item_begin(const UploadFormData &item) const;
  1718. static std::string item_end();
  1719. std::string finish() const;
  1720. private:
  1721. std::string boundary_;
  1722. };
  1723. class Server {
  1724. public:
  1725. using Handler = std::function<void(const Request &, Response &)>;
  1726. using ExceptionHandler =
  1727. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1728. enum class HandlerResponse {
  1729. Handled,
  1730. Unhandled,
  1731. };
  1732. using HandlerWithResponse =
  1733. std::function<HandlerResponse(const Request &, Response &)>;
  1734. using HandlerWithContentReader = std::function<void(
  1735. const Request &, Response &, const ContentReader &content_reader)>;
  1736. using Expect100ContinueHandler =
  1737. std::function<int(const Request &, Response &)>;
  1738. using StartHandler = std::function<void()>;
  1739. using WebSocketHandler =
  1740. std::function<void(const Request &, ws::WebSocket &)>;
  1741. using SubProtocolSelector =
  1742. std::function<std::string(const std::vector<std::string> &protocols)>;
  1743. Server();
  1744. virtual ~Server();
  1745. virtual bool is_valid() const;
  1746. Server &Get(const std::string &pattern, Handler handler);
  1747. Server &Post(const std::string &pattern, Handler handler);
  1748. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1749. Server &Put(const std::string &pattern, Handler handler);
  1750. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1751. Server &Patch(const std::string &pattern, Handler handler);
  1752. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1753. Server &Delete(const std::string &pattern, Handler handler);
  1754. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1755. Server &Options(const std::string &pattern, Handler handler);
  1756. // Register a handler for an HTTP method outside the built-in set (e.g. the
  1757. // WebDAV methods from RFC 4918). Registering a method here is what makes the
  1758. // server accept it; an unregistered method is still rejected with 400.
  1759. // `method` must be a valid HTTP method token and must not be one of the
  1760. // built-in methods, which have their own registration functions above. A
  1761. // rejected registration makes is_valid() return false, so listen() fails.
  1762. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1763. Handler handler);
  1764. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1765. HandlerWithContentReader handler);
  1766. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1767. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1768. SubProtocolSelector sub_protocol_selector);
  1769. bool set_base_dir(const std::string &dir,
  1770. const std::string &mount_point = std::string());
  1771. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1772. Headers headers = Headers());
  1773. bool remove_mount_point(const std::string &mount_point);
  1774. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1775. const std::string &mime);
  1776. Server &set_default_file_mimetype(const std::string &mime);
  1777. Server &set_file_request_handler(Handler handler);
  1778. template <class ErrorHandlerFunc>
  1779. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1780. return set_error_handler_core(
  1781. std::forward<ErrorHandlerFunc>(handler),
  1782. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1783. }
  1784. Server &set_exception_handler(ExceptionHandler handler);
  1785. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1786. Server &set_post_routing_handler(Handler handler);
  1787. Server &set_pre_request_handler(HandlerWithResponse handler);
  1788. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1789. Server &set_start_handler(StartHandler handler);
  1790. Server &set_logger(Logger logger);
  1791. Server &set_pre_compression_logger(Logger logger);
  1792. Server &set_error_logger(ErrorLogger error_logger);
  1793. Server &set_address_family(int family);
  1794. Server &set_tcp_nodelay(bool on);
  1795. Server &set_ipv6_v6only(bool on);
  1796. Server &set_socket_options(SocketOptions socket_options);
  1797. Server &set_default_headers(Headers headers);
  1798. Server &
  1799. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1800. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1801. Server &set_keep_alive_max_count(size_t count);
  1802. Server &set_keep_alive_timeout(time_t sec);
  1803. template <class Rep, class Period>
  1804. Server &
  1805. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1806. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1807. template <class Rep, class Period>
  1808. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1809. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1810. template <class Rep, class Period>
  1811. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1812. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1813. template <class Rep, class Period>
  1814. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1815. Server &set_payload_max_length(size_t length);
  1816. Server &set_websocket_ping_interval(time_t sec);
  1817. template <class Rep, class Period>
  1818. Server &set_websocket_ping_interval(
  1819. const std::chrono::duration<Rep, Period> &duration);
  1820. Server &set_websocket_max_missed_pongs(int count);
  1821. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1822. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1823. bool listen_after_bind();
  1824. bool listen(const std::string &host, int port, int socket_flags = 0);
  1825. bool is_running() const;
  1826. void wait_until_ready() const;
  1827. void stop() noexcept;
  1828. void decommission();
  1829. std::function<TaskQueue *(void)> new_task_queue;
  1830. protected:
  1831. bool process_request(Stream &strm, const std::string &remote_addr,
  1832. int remote_port, const std::string &local_addr,
  1833. int local_port, bool close_connection,
  1834. bool &connection_closed,
  1835. const std::function<void(Request &)> &setup_request,
  1836. bool *websocket_upgraded = nullptr);
  1837. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1838. std::vector<std::string> trusted_proxies_;
  1839. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1840. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1841. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1842. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1843. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1844. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1845. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1846. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1847. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1848. time_t websocket_ping_interval_sec_ =
  1849. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1850. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1851. private:
  1852. using Handlers =
  1853. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1854. using HandlersForContentReader =
  1855. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1856. HandlerWithContentReader>>;
  1857. // Both handler tables for one custom method live in a single entry, so that
  1858. // routing() needs only one map lookup per request to reach either of them.
  1859. struct CustomHandlerEntry {
  1860. Handlers handlers;
  1861. HandlersForContentReader handlers_for_content_reader;
  1862. };
  1863. using CustomHandlers = std::map<std::string, CustomHandlerEntry>;
  1864. static std::unique_ptr<detail::MatcherBase>
  1865. make_matcher(const std::string &pattern);
  1866. static const std::set<std::string> &builtin_methods();
  1867. CustomHandlerEntry *custom_entry_for_registration(const std::string &method);
  1868. const CustomHandlerEntry *find_custom_entry(const std::string &method) const;
  1869. template <typename H>
  1870. Server &add_handler(
  1871. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1872. const std::string &pattern, H handler) {
  1873. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1874. return *this;
  1875. }
  1876. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1877. Server &set_error_handler_core(Handler handler, std::false_type);
  1878. socket_t create_server_socket(const std::string &host, int port,
  1879. int socket_flags,
  1880. SocketOptions socket_options) const;
  1881. int bind_internal(const std::string &host, int port, int socket_flags);
  1882. bool listen_internal();
  1883. bool routing(Request &req, Response &res, Stream &strm);
  1884. bool handle_file_request(Request &req, Response &res);
  1885. bool check_if_not_modified(const Request &req, Response &res,
  1886. const std::string &etag, time_t mtime) const;
  1887. bool check_if_range(Request &req, const std::string &etag,
  1888. time_t mtime) const;
  1889. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1890. Stream &strm);
  1891. bool dispatch_request_for_content_reader(
  1892. Request &req, Response &res, ContentReader content_reader,
  1893. const HandlersForContentReader &handlers) const;
  1894. bool parse_request_line(const char *s, Request &req) const;
  1895. void apply_ranges(const Request &req, Response &res,
  1896. std::string &content_type, std::string &boundary) const;
  1897. bool write_response(Stream &strm, bool close_connection, Request &req,
  1898. Response &res);
  1899. bool write_response_with_content(Stream &strm, bool close_connection,
  1900. const Request &req, Response &res);
  1901. bool write_response_core(Stream &strm, bool close_connection,
  1902. const Request &req, Response &res,
  1903. bool need_apply_ranges);
  1904. bool write_content_with_provider(Stream &strm, const Request &req,
  1905. Response &res, const std::string &boundary,
  1906. const std::string &content_type);
  1907. bool read_content(Stream &strm, Request &req, Response &res);
  1908. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1909. Response &res,
  1910. ContentReceiver receiver,
  1911. FormDataHeader multipart_header,
  1912. ContentReceiver multipart_receiver);
  1913. bool read_content_core(Stream &strm, Request &req, Response &res,
  1914. ContentReceiver receiver,
  1915. FormDataHeader multipart_header,
  1916. ContentReceiver multipart_receiver) const;
  1917. virtual bool process_and_close_socket(socket_t sock);
  1918. void output_log(const Request &req, const Response &res) const;
  1919. void output_pre_compression_log(const Request &req,
  1920. const Response &res) const;
  1921. void output_error_log(const Error &err, const Request *req) const;
  1922. std::atomic<bool> is_running_{false};
  1923. std::atomic<bool> is_decommissioned{false};
  1924. // Set when CustomRoute() refuses a registration. Written before listen(),
  1925. // read by is_valid() on the same thread, so it needs no synchronization.
  1926. bool has_invalid_registration_ = false;
  1927. struct MountPointEntry {
  1928. std::string mount_point;
  1929. std::string base_dir;
  1930. std::string resolved_base_dir;
  1931. Headers headers;
  1932. };
  1933. std::vector<MountPointEntry> base_dirs_;
  1934. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1935. std::string default_file_mimetype_ = "application/octet-stream";
  1936. Handler file_request_handler_;
  1937. Handlers get_handlers_;
  1938. Handlers post_handlers_;
  1939. HandlersForContentReader post_handlers_for_content_reader_;
  1940. Handlers put_handlers_;
  1941. HandlersForContentReader put_handlers_for_content_reader_;
  1942. Handlers patch_handlers_;
  1943. HandlersForContentReader patch_handlers_for_content_reader_;
  1944. Handlers delete_handlers_;
  1945. HandlersForContentReader delete_handlers_for_content_reader_;
  1946. Handlers options_handlers_;
  1947. CustomHandlers custom_handlers_;
  1948. struct WebSocketHandlerEntry {
  1949. std::unique_ptr<detail::MatcherBase> matcher;
  1950. WebSocketHandler handler;
  1951. SubProtocolSelector sub_protocol_selector;
  1952. };
  1953. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1954. WebSocketHandlers websocket_handlers_;
  1955. HandlerWithResponse error_handler_;
  1956. ExceptionHandler exception_handler_;
  1957. HandlerWithResponse pre_routing_handler_;
  1958. Handler post_routing_handler_;
  1959. HandlerWithResponse pre_request_handler_;
  1960. Expect100ContinueHandler expect_100_continue_handler_;
  1961. StartHandler start_handler_;
  1962. mutable std::mutex logger_mutex_;
  1963. Logger logger_;
  1964. Logger pre_compression_logger_;
  1965. ErrorLogger error_logger_;
  1966. int address_family_ = AF_UNSPEC;
  1967. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1968. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1969. SocketOptions socket_options_ = default_socket_options;
  1970. Headers default_headers_;
  1971. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1972. detail::write_headers;
  1973. };
  1974. class Result {
  1975. public:
  1976. Result() = default;
  1977. Result(std::unique_ptr<Response> &&res, Error err,
  1978. Headers &&request_headers = Headers{})
  1979. : res_(std::move(res)), err_(err),
  1980. request_headers_(std::move(request_headers)) {}
  1981. // Response
  1982. operator bool() const { return res_ != nullptr; }
  1983. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1984. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1985. const Response &value() const { return *res_; }
  1986. Response &value() { return *res_; }
  1987. const Response &operator*() const { return *res_; }
  1988. Response &operator*() { return *res_; }
  1989. const Response *operator->() const { return res_.get(); }
  1990. Response *operator->() { return res_.get(); }
  1991. // Error
  1992. Error error() const { return err_; }
  1993. // Request Headers
  1994. bool has_request_header(const std::string &key) const;
  1995. std::string get_request_header_value(const std::string &key,
  1996. const char *def = "",
  1997. size_t id = 0) const;
  1998. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1999. size_t id = 0) const;
  2000. size_t get_request_header_value_count(const std::string &key) const;
  2001. private:
  2002. std::unique_ptr<Response> res_;
  2003. Error err_ = Error::Unknown;
  2004. Headers request_headers_;
  2005. #ifdef CPPHTTPLIB_SSL_ENABLED
  2006. public:
  2007. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2008. int ssl_error)
  2009. : res_(std::move(res)), err_(err),
  2010. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  2011. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2012. int ssl_error, uint64_t ssl_backend_error)
  2013. : res_(std::move(res)), err_(err),
  2014. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  2015. ssl_backend_error_(ssl_backend_error) {}
  2016. int ssl_error() const { return ssl_error_; }
  2017. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  2018. private:
  2019. int ssl_error_ = 0;
  2020. uint64_t ssl_backend_error_ = 0;
  2021. #endif
  2022. };
  2023. struct ClientConnection {
  2024. socket_t sock = INVALID_SOCKET;
  2025. bool is_open() const { return sock != INVALID_SOCKET; }
  2026. ClientConnection() = default;
  2027. ~ClientConnection();
  2028. ClientConnection(const ClientConnection &) = delete;
  2029. ClientConnection &operator=(const ClientConnection &) = delete;
  2030. ClientConnection(ClientConnection &&other) noexcept
  2031. : sock(other.sock)
  2032. #ifdef CPPHTTPLIB_SSL_ENABLED
  2033. ,
  2034. session(other.session)
  2035. #endif
  2036. {
  2037. other.sock = INVALID_SOCKET;
  2038. #ifdef CPPHTTPLIB_SSL_ENABLED
  2039. other.session = nullptr;
  2040. #endif
  2041. }
  2042. ClientConnection &operator=(ClientConnection &&other) noexcept {
  2043. if (this != &other) {
  2044. sock = other.sock;
  2045. other.sock = INVALID_SOCKET;
  2046. #ifdef CPPHTTPLIB_SSL_ENABLED
  2047. session = other.session;
  2048. other.session = nullptr;
  2049. #endif
  2050. }
  2051. return *this;
  2052. }
  2053. #ifdef CPPHTTPLIB_SSL_ENABLED
  2054. tls::session_t session = nullptr;
  2055. #endif
  2056. };
  2057. namespace detail {
  2058. struct ChunkedDecoder;
  2059. struct BodyReader {
  2060. Stream *stream = nullptr;
  2061. bool has_content_length = false;
  2062. size_t content_length = 0;
  2063. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2064. size_t bytes_read = 0;
  2065. bool chunked = false;
  2066. bool eof = false;
  2067. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  2068. Error last_error = Error::Success;
  2069. ssize_t read(char *buf, size_t len);
  2070. bool has_error() const { return last_error != Error::Success; }
  2071. };
  2072. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  2073. size_t len) {
  2074. (void)stream;
  2075. return br.read(buf, len);
  2076. }
  2077. class decompressor;
  2078. enum class NoProxyKind {
  2079. Wildcard, // "*"
  2080. HostnameSuffix, // "example.com" or ".example.com"
  2081. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  2082. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  2083. };
  2084. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  2085. // Lets one CIDR matcher cover both families.
  2086. using IPBytes = std::array<uint8_t, 16>;
  2087. struct NoProxyEntry {
  2088. NoProxyKind kind = NoProxyKind::Wildcard;
  2089. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  2090. IPBytes net{};
  2091. int prefix_bits = 0;
  2092. };
  2093. struct NormalizedTarget {
  2094. std::string hostname; // lowercase; brackets and trailing dot removed
  2095. bool is_ipv4 = false;
  2096. bool is_ipv6 = false;
  2097. IPBytes ip{};
  2098. };
  2099. } // namespace detail
  2100. class ClientImpl {
  2101. public:
  2102. explicit ClientImpl(const std::string &host);
  2103. explicit ClientImpl(const std::string &host, int port);
  2104. explicit ClientImpl(const std::string &host, int port,
  2105. const std::string &client_cert_path,
  2106. const std::string &client_key_path);
  2107. virtual ~ClientImpl();
  2108. virtual bool is_valid() const;
  2109. struct StreamHandle {
  2110. std::unique_ptr<Response> response;
  2111. Error error = Error::Success;
  2112. StreamHandle() = default;
  2113. StreamHandle(const StreamHandle &) = delete;
  2114. StreamHandle &operator=(const StreamHandle &) = delete;
  2115. StreamHandle(StreamHandle &&) = default;
  2116. StreamHandle &operator=(StreamHandle &&) = default;
  2117. ~StreamHandle() = default;
  2118. bool is_valid() const {
  2119. return response != nullptr && error == Error::Success;
  2120. }
  2121. ssize_t read(char *buf, size_t len);
  2122. void parse_trailers_if_needed();
  2123. Error get_read_error() const { return body_reader_.last_error; }
  2124. bool has_read_error() const { return body_reader_.has_error(); }
  2125. bool trailers_parsed_ = false;
  2126. private:
  2127. friend class ClientImpl;
  2128. ssize_t read_with_decompression(char *buf, size_t len);
  2129. std::unique_ptr<ClientConnection> connection_;
  2130. std::unique_ptr<Stream> socket_stream_;
  2131. Stream *stream_ = nullptr;
  2132. detail::BodyReader body_reader_;
  2133. std::unique_ptr<detail::decompressor> decompressor_;
  2134. std::string decompress_buffer_;
  2135. size_t decompress_offset_ = 0;
  2136. size_t decompressed_bytes_read_ = 0;
  2137. };
  2138. // clang-format off
  2139. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2140. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2141. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2142. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2143. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2144. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2145. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2146. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2147. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2148. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2149. Result Head(const std::string &path);
  2150. Result Head(const std::string &path, const Headers &headers);
  2151. Result Post(const std::string &path);
  2152. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2154. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2155. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2156. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2157. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2158. Result Post(const std::string &path, const Params &params);
  2159. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2160. Result Post(const std::string &path, const Headers &headers);
  2161. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2162. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2163. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2164. 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);
  2165. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2166. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2167. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2168. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2169. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2170. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2171. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2172. Result Put(const std::string &path);
  2173. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2175. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2176. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2177. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2178. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2179. Result Put(const std::string &path, const Params &params);
  2180. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2181. Result Put(const std::string &path, const Headers &headers);
  2182. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2184. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2185. 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);
  2186. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2187. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2188. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2189. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2190. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2191. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2192. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2193. Result Patch(const std::string &path);
  2194. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2196. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2197. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2198. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2199. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2200. Result Patch(const std::string &path, const Params &params);
  2201. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2202. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  2203. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2205. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2206. 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);
  2207. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2208. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2209. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2210. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2211. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2212. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2213. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2214. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2215. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2216. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2217. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2218. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2219. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2220. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2221. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2222. Result Options(const std::string &path);
  2223. Result Options(const std::string &path, const Headers &headers);
  2224. // clang-format on
  2225. // Streaming API: Open a stream for reading response body incrementally
  2226. // Socket ownership is transferred to StreamHandle for true streaming
  2227. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2228. StreamHandle open_stream(const std::string &method, const std::string &path,
  2229. const Params &params = {},
  2230. const Headers &headers = {},
  2231. const std::string &body = {},
  2232. const std::string &content_type = {});
  2233. bool send(Request &req, Response &res, Error &error);
  2234. Result send(const Request &req);
  2235. void stop();
  2236. std::string host() const;
  2237. int port() const;
  2238. size_t is_socket_open() const;
  2239. socket_t socket() const;
  2240. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2241. void set_default_headers(Headers headers);
  2242. void
  2243. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2244. void set_address_family(int family);
  2245. void set_tcp_nodelay(bool on);
  2246. void set_ipv6_v6only(bool on);
  2247. void set_socket_options(SocketOptions socket_options);
  2248. void set_connection_timeout(time_t sec, time_t usec = 0);
  2249. template <class Rep, class Period>
  2250. void
  2251. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2252. void set_read_timeout(time_t sec, time_t usec = 0);
  2253. template <class Rep, class Period>
  2254. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2255. void set_write_timeout(time_t sec, time_t usec = 0);
  2256. template <class Rep, class Period>
  2257. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2258. void set_max_timeout(time_t msec);
  2259. template <class Rep, class Period>
  2260. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2261. void set_basic_auth(const std::string &username, const std::string &password);
  2262. void set_bearer_token_auth(const std::string &token);
  2263. void set_keep_alive(bool on);
  2264. void set_follow_location(bool on);
  2265. void set_path_encode(bool on);
  2266. void set_compress(bool on);
  2267. void set_decompress(bool on);
  2268. void set_payload_max_length(size_t length);
  2269. void set_interface(const std::string &intf);
  2270. void set_proxy(const std::string &host, int port);
  2271. void set_proxy_basic_auth(const std::string &username,
  2272. const std::string &password);
  2273. void set_proxy_bearer_token_auth(const std::string &token);
  2274. void set_no_proxy(const std::vector<std::string> &patterns);
  2275. void set_logger(Logger logger);
  2276. void set_error_logger(ErrorLogger error_logger);
  2277. protected:
  2278. struct Socket {
  2279. socket_t sock = INVALID_SOCKET;
  2280. // For Mbed TLS compatibility: start_time for request timeout tracking
  2281. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2282. bool is_open() const { return sock != INVALID_SOCKET; }
  2283. #ifdef CPPHTTPLIB_SSL_ENABLED
  2284. tls::session_t ssl = nullptr;
  2285. #endif
  2286. };
  2287. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  2288. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  2289. virtual bool setup_proxy_connection(
  2290. Socket &socket,
  2291. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2292. Response &res, bool &success, Error &error);
  2293. bool is_proxy_enabled_for_host(const std::string &host) const;
  2294. // All of:
  2295. // shutdown_ssl
  2296. // shutdown_socket
  2297. // close_socket
  2298. // disconnect
  2299. // should ONLY be called when socket_mutex_ is locked, and only when
  2300. // no other thread is using the socket.
  2301. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  2302. void shutdown_socket(Socket &socket) const;
  2303. void close_socket(Socket &socket);
  2304. void disconnect(bool gracefully);
  2305. bool process_request(Stream &strm, Request &req, Response &res,
  2306. bool close_connection, Error &error);
  2307. bool write_content_with_provider(Stream &strm, const Request &req,
  2308. Error &error) const;
  2309. void copy_settings(const ClientImpl &rhs);
  2310. void output_log(const Request &req, const Response &res) const;
  2311. void output_error_log(const Error &err, const Request *req) const;
  2312. // Socket endpoint information
  2313. const std::string host_;
  2314. const int port_;
  2315. // Current open socket
  2316. Socket socket_;
  2317. mutable std::mutex socket_mutex_;
  2318. std::recursive_mutex request_mutex_;
  2319. // These are all protected under socket_mutex
  2320. size_t socket_requests_in_flight_ = 0;
  2321. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2322. bool socket_should_be_closed_when_request_is_done_ = false;
  2323. // Hostname to connection target map. The value is an IP literal or another
  2324. // hostname; only the connection target changes, never the identity.
  2325. std::map<std::string, std::string> addr_map_;
  2326. // Default headers
  2327. Headers default_headers_;
  2328. // Header writer
  2329. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2330. detail::write_headers;
  2331. // Settings
  2332. std::string client_cert_path_;
  2333. std::string client_key_path_;
  2334. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2335. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2336. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2337. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2338. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2339. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2340. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2341. std::string basic_auth_username_;
  2342. std::string basic_auth_password_;
  2343. std::string bearer_token_auth_token_;
  2344. bool keep_alive_ = false;
  2345. bool follow_location_ = false;
  2346. bool path_encode_ = true;
  2347. int address_family_ = AF_UNSPEC;
  2348. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2349. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2350. SocketOptions socket_options_ = nullptr;
  2351. bool compress_ = false;
  2352. bool decompress_ = true;
  2353. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2354. bool has_payload_max_length_ = false;
  2355. std::string interface_;
  2356. std::string proxy_host_;
  2357. int proxy_port_ = -1;
  2358. std::string proxy_basic_auth_username_;
  2359. std::string proxy_basic_auth_password_;
  2360. std::string proxy_bearer_token_auth_token_;
  2361. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2362. mutable detail::NormalizedTarget host_normalized_;
  2363. mutable bool host_normalized_valid_ = false;
  2364. mutable std::mutex logger_mutex_;
  2365. Logger logger_;
  2366. ErrorLogger error_logger_;
  2367. private:
  2368. bool send_(Request &req, Response &res, Error &error);
  2369. Result send_(Request &&req);
  2370. socket_t create_client_socket(Error &error) const;
  2371. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2372. bool skip_100_continue = true) const;
  2373. bool write_request(Stream &strm, Request &req, bool close_connection,
  2374. Error &error, bool skip_body = false);
  2375. bool write_request_body(Stream &strm, Request &req, Error &error);
  2376. void prepare_default_headers(Request &r, bool for_stream,
  2377. const std::string &ct);
  2378. bool redirect(Request &req, Response &res, Error &error);
  2379. bool create_redirect_client(const std::string &scheme,
  2380. const std::string &host, int port, Request &req,
  2381. Response &res, const std::string &path,
  2382. const std::string &location, Error &error);
  2383. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2384. bool handle_request(Stream &strm, Request &req, Response &res,
  2385. bool close_connection, Error &error);
  2386. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2387. Request &req, const char *body, size_t content_length,
  2388. ContentProvider content_provider,
  2389. ContentProviderWithoutLength content_provider_without_length,
  2390. const std::string &content_type, ContentReceiver content_receiver,
  2391. Error &error);
  2392. Result send_with_content_provider_and_receiver(
  2393. const std::string &method, const std::string &path,
  2394. const Headers &headers, const char *body, size_t content_length,
  2395. ContentProvider content_provider,
  2396. ContentProviderWithoutLength content_provider_without_length,
  2397. const std::string &content_type, ContentReceiver content_receiver,
  2398. UploadProgress progress);
  2399. ContentProviderWithoutLength get_multipart_content_provider(
  2400. const std::string &boundary, const UploadFormDataItems &items,
  2401. const FormDataProviderItems &provider_items) const;
  2402. virtual bool
  2403. process_socket(const Socket &socket,
  2404. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2405. std::function<bool(Stream &strm)> callback);
  2406. virtual bool is_ssl() const;
  2407. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2408. #ifdef CPPHTTPLIB_SSL_ENABLED
  2409. public:
  2410. void set_digest_auth(const std::string &username,
  2411. const std::string &password);
  2412. void set_proxy_digest_auth(const std::string &username,
  2413. const std::string &password);
  2414. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2415. const std::string &ca_cert_dir_path = std::string());
  2416. void enable_server_certificate_verification(bool enabled);
  2417. void enable_server_hostname_verification(bool enabled);
  2418. void enable_system_ca(bool enabled);
  2419. protected:
  2420. std::string digest_auth_username_;
  2421. std::string digest_auth_password_;
  2422. std::string proxy_digest_auth_username_;
  2423. std::string proxy_digest_auth_password_;
  2424. std::string ca_cert_file_path_;
  2425. std::string ca_cert_dir_path_;
  2426. bool server_certificate_verification_ = true;
  2427. bool server_hostname_verification_ = true;
  2428. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2429. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2430. int last_ssl_error_ = 0;
  2431. uint64_t last_backend_error_ = 0;
  2432. #endif
  2433. };
  2434. class Client {
  2435. public:
  2436. // Universal interface
  2437. explicit Client(const std::string &scheme_host_port);
  2438. explicit Client(const std::string &scheme_host_port,
  2439. const std::string &client_cert_path,
  2440. const std::string &client_key_path);
  2441. // HTTP only interface
  2442. explicit Client(const std::string &host, int port);
  2443. explicit Client(const std::string &host, int port,
  2444. const std::string &client_cert_path,
  2445. const std::string &client_key_path);
  2446. Client(Client &&) = default;
  2447. Client &operator=(Client &&) = default;
  2448. ~Client();
  2449. bool is_valid() const;
  2450. // clang-format off
  2451. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2452. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2453. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2454. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2455. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2456. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2457. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2458. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2459. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2460. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2461. Result Head(const std::string &path);
  2462. Result Head(const std::string &path, const Headers &headers);
  2463. Result Post(const std::string &path);
  2464. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2465. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2466. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2467. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2468. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2469. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2470. Result Post(const std::string &path, const Params &params);
  2471. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2472. Result Post(const std::string &path, const Headers &headers);
  2473. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2474. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2475. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2476. 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);
  2477. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2478. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2479. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2480. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2481. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2482. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2483. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2484. Result Put(const std::string &path);
  2485. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2486. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2487. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2488. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2489. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2490. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2491. Result Put(const std::string &path, const Params &params);
  2492. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2493. Result Put(const std::string &path, const Headers &headers);
  2494. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2495. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2496. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2497. 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);
  2498. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2499. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2500. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2501. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2502. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2503. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2504. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2505. Result Patch(const std::string &path);
  2506. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2507. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2508. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2509. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2510. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2511. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2512. Result Patch(const std::string &path, const Params &params);
  2513. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2514. Result Patch(const std::string &path, const Headers &headers);
  2515. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2516. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2517. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2518. 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);
  2519. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2520. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2521. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2522. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2523. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2524. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2525. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2526. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2527. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2528. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2529. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2530. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2531. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2532. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2533. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2534. Result Options(const std::string &path);
  2535. Result Options(const std::string &path, const Headers &headers);
  2536. // clang-format on
  2537. // Streaming API: Open a stream for reading response body incrementally
  2538. // Socket ownership is transferred to StreamHandle for true streaming
  2539. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2540. ClientImpl::StreamHandle open_stream(const std::string &method,
  2541. const std::string &path,
  2542. const Params &params = {},
  2543. const Headers &headers = {},
  2544. const std::string &body = {},
  2545. const std::string &content_type = {});
  2546. bool send(Request &req, Response &res, Error &error);
  2547. Result send(const Request &req);
  2548. void stop();
  2549. std::string host() const;
  2550. int port() const;
  2551. size_t is_socket_open() const;
  2552. socket_t socket() const;
  2553. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2554. void set_default_headers(Headers headers);
  2555. void
  2556. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2557. void set_address_family(int family);
  2558. void set_tcp_nodelay(bool on);
  2559. void set_socket_options(SocketOptions socket_options);
  2560. void set_connection_timeout(time_t sec, time_t usec = 0);
  2561. template <class Rep, class Period>
  2562. void
  2563. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2564. void set_read_timeout(time_t sec, time_t usec = 0);
  2565. template <class Rep, class Period>
  2566. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2567. void set_write_timeout(time_t sec, time_t usec = 0);
  2568. template <class Rep, class Period>
  2569. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2570. void set_max_timeout(time_t msec);
  2571. template <class Rep, class Period>
  2572. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2573. void set_basic_auth(const std::string &username, const std::string &password);
  2574. void set_bearer_token_auth(const std::string &token);
  2575. void set_keep_alive(bool on);
  2576. void set_follow_location(bool on);
  2577. void set_path_encode(bool on);
  2578. void set_compress(bool on);
  2579. void set_decompress(bool on);
  2580. void set_payload_max_length(size_t length);
  2581. void set_interface(const std::string &intf);
  2582. void set_proxy(const std::string &host, int port);
  2583. void set_proxy_basic_auth(const std::string &username,
  2584. const std::string &password);
  2585. void set_proxy_bearer_token_auth(const std::string &token);
  2586. void set_no_proxy(const std::vector<std::string> &patterns);
  2587. void set_logger(Logger logger);
  2588. void set_error_logger(ErrorLogger error_logger);
  2589. private:
  2590. std::unique_ptr<ClientImpl> cli_;
  2591. #ifdef CPPHTTPLIB_SSL_ENABLED
  2592. public:
  2593. void set_digest_auth(const std::string &username,
  2594. const std::string &password);
  2595. void set_proxy_digest_auth(const std::string &username,
  2596. const std::string &password);
  2597. void enable_server_certificate_verification(bool enabled);
  2598. void enable_server_hostname_verification(bool enabled);
  2599. void enable_system_ca(bool enabled);
  2600. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2601. const std::string &ca_cert_dir_path = std::string());
  2602. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2603. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2604. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2605. void set_session_verifier(
  2606. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2607. tls::ctx_t tls_context() const;
  2608. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2609. void enable_windows_certificate_verification(bool enabled);
  2610. #endif
  2611. private:
  2612. bool is_ssl_ = false;
  2613. #endif
  2614. };
  2615. #ifdef CPPHTTPLIB_SSL_ENABLED
  2616. class SSLServer : public Server {
  2617. public:
  2618. SSLServer(const char *cert_path, const char *private_key_path,
  2619. const char *client_ca_cert_file_path = nullptr,
  2620. const char *client_ca_cert_dir_path = nullptr,
  2621. const char *private_key_password = nullptr);
  2622. struct PemMemory {
  2623. const char *cert_pem;
  2624. size_t cert_pem_len;
  2625. const char *key_pem;
  2626. size_t key_pem_len;
  2627. const char *client_ca_pem;
  2628. size_t client_ca_pem_len;
  2629. const char *private_key_password;
  2630. };
  2631. explicit SSLServer(const PemMemory &pem);
  2632. // The callback receives the ctx_t handle which can be cast to the
  2633. // appropriate backend type (SSL_CTX* for OpenSSL,
  2634. // tls::impl::MbedTlsContext* for Mbed TLS)
  2635. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2636. ~SSLServer() override;
  2637. bool is_valid() const override;
  2638. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2639. const char *client_ca_pem = nullptr,
  2640. const char *password = nullptr);
  2641. tls::ctx_t tls_context() const { return ctx_; }
  2642. int ssl_last_error() const { return last_ssl_error_; }
  2643. private:
  2644. bool process_and_close_socket(socket_t sock) override;
  2645. tls::ctx_t ctx_ = nullptr;
  2646. std::mutex ctx_mutex_;
  2647. int last_ssl_error_ = 0;
  2648. };
  2649. class SSLClient final : public ClientImpl {
  2650. public:
  2651. explicit SSLClient(const std::string &host);
  2652. explicit SSLClient(const std::string &host, int port);
  2653. explicit SSLClient(const std::string &host, int port,
  2654. const std::string &client_cert_path,
  2655. const std::string &client_key_path,
  2656. const std::string &private_key_password = std::string());
  2657. struct PemMemory {
  2658. const char *cert_pem;
  2659. size_t cert_pem_len;
  2660. const char *key_pem;
  2661. size_t key_pem_len;
  2662. const char *private_key_password;
  2663. };
  2664. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2665. ~SSLClient() override;
  2666. bool is_valid() const override;
  2667. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2668. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2669. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2670. // Post-handshake session verifier (backend-independent)
  2671. void set_session_verifier(
  2672. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2673. tls::ctx_t tls_context() const { return ctx_; }
  2674. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2675. void enable_windows_certificate_verification(bool enabled);
  2676. #endif
  2677. private:
  2678. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2679. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2680. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2681. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2682. 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) override;
  2686. bool is_ssl() const override;
  2687. bool setup_proxy_connection(
  2688. Socket &socket,
  2689. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2690. Response &res, bool &success, Error &error) override;
  2691. bool connect_with_proxy(
  2692. Socket &sock,
  2693. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2694. Response &res, bool &success, Error &error);
  2695. bool initialize_ssl(Socket &socket, Error &error);
  2696. void init_ctx();
  2697. void reset_ctx_on_error();
  2698. bool load_certs();
  2699. tls::ctx_t ctx_ = nullptr;
  2700. std::mutex ctx_mutex_;
  2701. std::once_flag initialize_cert_;
  2702. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2703. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2704. // Used to keep custom CA configuration exclusive with system CA loading.
  2705. bool ca_cert_store_set_ = false;
  2706. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2707. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2708. bool enable_windows_cert_verification_ = true;
  2709. #endif
  2710. friend class ClientImpl;
  2711. };
  2712. #endif // CPPHTTPLIB_SSL_ENABLED
  2713. namespace detail {
  2714. template <typename T, typename U>
  2715. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2716. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2717. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2718. duration - std::chrono::seconds(sec))
  2719. .count();
  2720. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2721. }
  2722. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2723. return N - 1;
  2724. }
  2725. inline bool is_numeric(const std::string &str) {
  2726. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2727. }
  2728. inline size_t get_header_value_u64(const Headers &headers,
  2729. const std::string &key, size_t def,
  2730. size_t id, bool &is_invalid_value) {
  2731. is_invalid_value = false;
  2732. auto rng = headers.equal_range(key);
  2733. auto it = rng.first;
  2734. std::advance(it, static_cast<ssize_t>(id));
  2735. if (it != rng.second) {
  2736. if (is_numeric(it->second)) {
  2737. // Parse at size_t width so an out-of-range Content-Length is reported
  2738. // rather than silently saturated/truncated (a value above 2^32 would
  2739. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  2740. // and return SIZE_MAX so the existing oversized-value guards reject it.
  2741. size_t val = 0;
  2742. const auto &s = it->second;
  2743. auto r = from_chars(s.data(), s.data() + s.size(), val);
  2744. if (r.ec == std::errc::result_out_of_range) {
  2745. is_invalid_value = true;
  2746. return (std::numeric_limits<size_t>::max)();
  2747. }
  2748. return val;
  2749. } else {
  2750. is_invalid_value = true;
  2751. }
  2752. }
  2753. return def;
  2754. }
  2755. inline size_t get_header_value_u64(const Headers &headers,
  2756. const std::string &key, size_t def,
  2757. size_t id) {
  2758. auto dummy = false;
  2759. return get_header_value_u64(headers, key, def, id, dummy);
  2760. }
  2761. } // namespace detail
  2762. template <class Rep, class Period>
  2763. inline Server &
  2764. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2765. detail::duration_to_sec_and_usec(
  2766. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2767. return *this;
  2768. }
  2769. template <class Rep, class Period>
  2770. inline Server &
  2771. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2772. detail::duration_to_sec_and_usec(
  2773. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2774. return *this;
  2775. }
  2776. template <class Rep, class Period>
  2777. inline Server &
  2778. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2779. detail::duration_to_sec_and_usec(
  2780. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2781. return *this;
  2782. }
  2783. template <class Rep, class Period>
  2784. inline void ClientImpl::set_connection_timeout(
  2785. const std::chrono::duration<Rep, Period> &duration) {
  2786. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2787. set_connection_timeout(sec, usec);
  2788. });
  2789. }
  2790. template <class Rep, class Period>
  2791. inline void ClientImpl::set_read_timeout(
  2792. const std::chrono::duration<Rep, Period> &duration) {
  2793. detail::duration_to_sec_and_usec(
  2794. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2795. }
  2796. template <class Rep, class Period>
  2797. inline void ClientImpl::set_write_timeout(
  2798. const std::chrono::duration<Rep, Period> &duration) {
  2799. detail::duration_to_sec_and_usec(
  2800. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2801. }
  2802. template <class Rep, class Period>
  2803. inline void ClientImpl::set_max_timeout(
  2804. const std::chrono::duration<Rep, Period> &duration) {
  2805. auto msec =
  2806. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2807. set_max_timeout(msec);
  2808. }
  2809. template <class Rep, class Period>
  2810. inline void Client::set_connection_timeout(
  2811. const std::chrono::duration<Rep, Period> &duration) {
  2812. cli_->set_connection_timeout(duration);
  2813. }
  2814. template <class Rep, class Period>
  2815. inline void
  2816. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2817. cli_->set_read_timeout(duration);
  2818. }
  2819. template <class Rep, class Period>
  2820. inline void
  2821. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2822. cli_->set_write_timeout(duration);
  2823. }
  2824. inline void Client::set_max_timeout(time_t msec) {
  2825. cli_->set_max_timeout(msec);
  2826. }
  2827. template <class Rep, class Period>
  2828. inline void
  2829. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2830. cli_->set_max_timeout(duration);
  2831. }
  2832. /*
  2833. * Forward declarations and types that will be part of the .h file if split into
  2834. * .h + .cc.
  2835. */
  2836. std::string hosted_at(const std::string &hostname);
  2837. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2838. // JavaScript-style URL encoding/decoding functions
  2839. std::string encode_uri_component(const std::string &value);
  2840. std::string encode_uri(const std::string &value);
  2841. std::string decode_uri_component(const std::string &value);
  2842. std::string decode_uri(const std::string &value);
  2843. // RFC 3986 compliant URL component encoding/decoding functions
  2844. std::string encode_path_component(const std::string &component);
  2845. std::string decode_path_component(const std::string &component);
  2846. std::string encode_query_component(const std::string &component,
  2847. bool space_as_plus = true);
  2848. std::string decode_query_component(const std::string &component,
  2849. bool plus_as_space = true);
  2850. std::string sanitize_filename(const std::string &filename);
  2851. std::string append_query_params(const std::string &path, const Params &params);
  2852. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2853. std::pair<std::string, std::string>
  2854. make_basic_authentication_header(const std::string &username,
  2855. const std::string &password,
  2856. bool is_proxy = false);
  2857. namespace detail {
  2858. #if defined(_WIN32)
  2859. inline std::wstring u8string_to_wstring(const char *s) {
  2860. if (!s) { return std::wstring(); }
  2861. auto len = static_cast<int>(strlen(s));
  2862. if (!len) { return std::wstring(); }
  2863. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2864. if (!wlen) { return std::wstring(); }
  2865. std::wstring ws;
  2866. ws.resize(wlen);
  2867. wlen = ::MultiByteToWideChar(
  2868. CP_UTF8, 0, s, len,
  2869. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2870. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2871. return ws;
  2872. }
  2873. #endif
  2874. struct FileStat {
  2875. FileStat(const std::string &path);
  2876. bool is_file() const;
  2877. bool is_dir() const;
  2878. time_t mtime() const;
  2879. size_t size() const;
  2880. private:
  2881. #if defined(_WIN32)
  2882. struct _stat st_;
  2883. #else
  2884. struct stat st_;
  2885. #endif
  2886. int ret_ = -1;
  2887. };
  2888. std::string make_host_and_port_string(const std::string &host, int port,
  2889. bool is_ssl);
  2890. template <typename T>
  2891. bool check_and_write_headers(Stream &strm, Headers &headers, T header_writer,
  2892. Error &error);
  2893. std::string trim_copy(const std::string &s);
  2894. void divide(
  2895. const char *data, std::size_t size, char d,
  2896. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2897. fn);
  2898. void divide(
  2899. const std::string &str, char d,
  2900. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2901. fn);
  2902. void split(const char *b, const char *e, char d,
  2903. std::function<void(const char *, const char *)> fn);
  2904. void split(const char *b, const char *e, char d, size_t m,
  2905. std::function<void(const char *, const char *)> fn);
  2906. bool split_find(const char *b, const char *e, char d,
  2907. std::function<bool(const char *, const char *)> fn);
  2908. bool has_header_token(const Headers &headers, const std::string &key,
  2909. const std::string &token);
  2910. std::string websocket_accept_key(const std::string &client_key);
  2911. bool is_websocket_upgrade(const Request &req);
  2912. bool process_client_socket(
  2913. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2914. time_t write_timeout_sec, time_t write_timeout_usec,
  2915. time_t max_timeout_msec,
  2916. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2917. std::function<bool(Stream &)> callback);
  2918. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2919. int port, int address_family, bool tcp_nodelay,
  2920. bool ipv6_v6only, SocketOptions socket_options,
  2921. time_t connection_timeout_sec,
  2922. time_t connection_timeout_usec,
  2923. time_t read_timeout_sec, time_t read_timeout_usec,
  2924. time_t write_timeout_sec,
  2925. time_t write_timeout_usec,
  2926. const std::string &intf, Error &error);
  2927. const char *get_header_value(const Headers &headers, const std::string &key,
  2928. const char *def, size_t id);
  2929. std::string get_combined_header_value(const Headers &headers,
  2930. const std::string &key);
  2931. std::string params_to_query_str(const Params &params);
  2932. void parse_query_text(const char *data, std::size_t size, Params &params);
  2933. void parse_query_text(const std::string &s, Params &params);
  2934. bool parse_multipart_boundary(const std::string &content_type,
  2935. std::string &boundary);
  2936. bool parse_range_header(const std::string &s, Ranges &ranges);
  2937. bool parse_accept_header(const std::string &s,
  2938. std::vector<std::string> &content_types);
  2939. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2940. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2941. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2942. EncodingType encoding_type(const Request &req, const Response &res);
  2943. class BufferStream final : public Stream {
  2944. public:
  2945. BufferStream() = default;
  2946. ~BufferStream() override = default;
  2947. bool is_readable() const override;
  2948. bool wait_readable() const override;
  2949. bool wait_writable() const override;
  2950. ssize_t read(char *ptr, size_t size) override;
  2951. ssize_t write(const char *ptr, size_t size) override;
  2952. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2953. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2954. socket_t socket() const override;
  2955. time_t duration() const override;
  2956. const std::string &get_buffer() const;
  2957. private:
  2958. std::string buffer;
  2959. size_t position = 0;
  2960. };
  2961. class compressor {
  2962. public:
  2963. virtual ~compressor() = default;
  2964. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2965. virtual bool compress(const char *data, size_t data_length, bool last,
  2966. Callback callback) = 0;
  2967. };
  2968. class decompressor {
  2969. public:
  2970. virtual ~decompressor() = default;
  2971. virtual bool is_valid() const = 0;
  2972. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2973. virtual bool decompress(const char *data, size_t data_length,
  2974. Callback callback) = 0;
  2975. };
  2976. class nocompressor final : public compressor {
  2977. public:
  2978. ~nocompressor() override = default;
  2979. bool compress(const char *data, size_t data_length, bool /*last*/,
  2980. Callback callback) override;
  2981. };
  2982. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2983. class gzip_compressor final : public compressor {
  2984. public:
  2985. gzip_compressor();
  2986. ~gzip_compressor() override;
  2987. bool compress(const char *data, size_t data_length, bool last,
  2988. Callback callback) override;
  2989. private:
  2990. bool is_valid_ = false;
  2991. z_stream strm_;
  2992. };
  2993. class gzip_decompressor final : public decompressor {
  2994. public:
  2995. gzip_decompressor();
  2996. ~gzip_decompressor() override;
  2997. bool is_valid() const override;
  2998. bool decompress(const char *data, size_t data_length,
  2999. Callback callback) override;
  3000. private:
  3001. bool is_valid_ = false;
  3002. z_stream strm_;
  3003. };
  3004. #endif
  3005. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3006. class brotli_compressor final : public compressor {
  3007. public:
  3008. brotli_compressor();
  3009. ~brotli_compressor();
  3010. bool compress(const char *data, size_t data_length, bool last,
  3011. Callback callback) override;
  3012. private:
  3013. BrotliEncoderState *state_ = nullptr;
  3014. };
  3015. class brotli_decompressor final : public decompressor {
  3016. public:
  3017. brotli_decompressor();
  3018. ~brotli_decompressor();
  3019. bool is_valid() const override;
  3020. bool decompress(const char *data, size_t data_length,
  3021. Callback callback) override;
  3022. private:
  3023. BrotliDecoderResult decoder_r;
  3024. BrotliDecoderState *decoder_s = nullptr;
  3025. };
  3026. #endif
  3027. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3028. class zstd_compressor : public compressor {
  3029. public:
  3030. zstd_compressor();
  3031. ~zstd_compressor();
  3032. bool compress(const char *data, size_t data_length, bool last,
  3033. Callback callback) override;
  3034. private:
  3035. ZSTD_CCtx *ctx_ = nullptr;
  3036. };
  3037. class zstd_decompressor : public decompressor {
  3038. public:
  3039. zstd_decompressor();
  3040. ~zstd_decompressor();
  3041. bool is_valid() const override;
  3042. bool decompress(const char *data, size_t data_length,
  3043. Callback callback) override;
  3044. private:
  3045. ZSTD_DCtx *ctx_ = nullptr;
  3046. };
  3047. #endif
  3048. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  3049. // to store data. The call can set memory on stack for performance.
  3050. class stream_line_reader {
  3051. public:
  3052. stream_line_reader(Stream &strm, char *fixed_buffer,
  3053. size_t fixed_buffer_size);
  3054. const char *ptr() const;
  3055. size_t size() const;
  3056. bool end_with_crlf() const;
  3057. bool getline();
  3058. private:
  3059. void append(char c);
  3060. void append(const char *data, size_t size);
  3061. Stream &strm_;
  3062. char *fixed_buffer_;
  3063. const size_t fixed_buffer_size_;
  3064. size_t fixed_buffer_used_size_ = 0;
  3065. std::string growable_buffer_;
  3066. };
  3067. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3068. const Headers &src_headers);
  3069. struct ChunkedDecoder {
  3070. Stream &strm;
  3071. size_t chunk_remaining = 0;
  3072. bool finished = false;
  3073. char line_buf[64];
  3074. size_t last_chunk_total = 0;
  3075. size_t last_chunk_offset = 0;
  3076. explicit ChunkedDecoder(Stream &s);
  3077. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  3078. size_t &out_chunk_total);
  3079. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  3080. };
  3081. class mmap {
  3082. public:
  3083. mmap(const char *path);
  3084. ~mmap();
  3085. bool open(const char *path);
  3086. void close();
  3087. bool is_open() const;
  3088. size_t size() const;
  3089. const char *data() const;
  3090. private:
  3091. #if defined(_WIN32)
  3092. HANDLE hFile_ = NULL;
  3093. HANDLE hMapping_ = NULL;
  3094. #else
  3095. int fd_ = -1;
  3096. #endif
  3097. size_t size_ = 0;
  3098. void *addr_ = nullptr;
  3099. bool is_open_empty_file = false;
  3100. };
  3101. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  3102. namespace fields {
  3103. bool is_token_char(char c);
  3104. bool is_token(const std::string &s);
  3105. bool is_field_name(const std::string &s);
  3106. bool is_vchar(char c);
  3107. bool is_obs_text(char c);
  3108. bool is_field_vchar(char c);
  3109. bool is_field_content(const std::string &s);
  3110. bool is_field_value(const std::string &s);
  3111. bool is_field_valid(const std::string &name, const std::string &value);
  3112. } // namespace fields
  3113. } // namespace detail
  3114. /*
  3115. * TLS Abstraction Layer Declarations
  3116. */
  3117. #ifdef CPPHTTPLIB_SSL_ENABLED
  3118. // TLS abstraction layer - backend-specific type declarations
  3119. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  3120. namespace tls {
  3121. namespace impl {
  3122. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  3123. // cert/key). This struct is accessible via tls::impl for use in SSL context
  3124. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  3125. struct MbedTlsContext {
  3126. mbedtls_ssl_config conf;
  3127. #ifndef CPPHTTPLIB_MBEDTLS_V4
  3128. // Mbed TLS 4.x uses PSA Crypto's internal RNG; no explicit entropy/DRBG.
  3129. mbedtls_entropy_context entropy;
  3130. mbedtls_ctr_drbg_context ctr_drbg;
  3131. #endif
  3132. mbedtls_x509_crt ca_chain;
  3133. mbedtls_x509_crt own_cert;
  3134. mbedtls_pk_context own_key;
  3135. bool is_server = false;
  3136. bool verify_client = false;
  3137. bool has_verify_callback = false;
  3138. MbedTlsContext();
  3139. ~MbedTlsContext();
  3140. MbedTlsContext(const MbedTlsContext &) = delete;
  3141. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  3142. };
  3143. } // namespace impl
  3144. } // namespace tls
  3145. #endif
  3146. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  3147. namespace tls {
  3148. namespace impl {
  3149. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  3150. // This struct is accessible via tls::impl for use in SSL context
  3151. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  3152. struct WolfSSLContext {
  3153. WOLFSSL_CTX *ctx = nullptr;
  3154. bool is_server = false;
  3155. bool verify_client = false;
  3156. bool has_verify_callback = false;
  3157. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  3158. WolfSSLContext();
  3159. ~WolfSSLContext();
  3160. WolfSSLContext(const WolfSSLContext &) = delete;
  3161. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  3162. };
  3163. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  3164. struct WolfSSLCAStore {
  3165. std::string pem_data;
  3166. };
  3167. } // namespace impl
  3168. } // namespace tls
  3169. #endif
  3170. #endif // CPPHTTPLIB_SSL_ENABLED
  3171. namespace stream {
  3172. class Result {
  3173. public:
  3174. Result();
  3175. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  3176. Result(Result &&other) noexcept;
  3177. Result &operator=(Result &&other) noexcept;
  3178. Result(const Result &) = delete;
  3179. Result &operator=(const Result &) = delete;
  3180. // Response info
  3181. bool is_valid() const;
  3182. explicit operator bool() const;
  3183. int status() const;
  3184. const Headers &headers() const;
  3185. std::string get_header_value(const std::string &key,
  3186. const char *def = "") const;
  3187. bool has_header(const std::string &key) const;
  3188. Error error() const;
  3189. Error read_error() const;
  3190. bool has_read_error() const;
  3191. // Stream reading
  3192. bool next();
  3193. const char *data() const;
  3194. size_t size() const;
  3195. std::string read_all();
  3196. private:
  3197. ClientImpl::StreamHandle handle_;
  3198. std::string buffer_;
  3199. size_t current_size_ = 0;
  3200. size_t chunk_size_;
  3201. bool finished_ = false;
  3202. };
  3203. // GET
  3204. template <typename ClientType>
  3205. inline Result Get(ClientType &cli, const std::string &path,
  3206. size_t chunk_size = 8192) {
  3207. return Result{cli.open_stream("GET", path), chunk_size};
  3208. }
  3209. template <typename ClientType>
  3210. inline Result Get(ClientType &cli, const std::string &path,
  3211. const Headers &headers, size_t chunk_size = 8192) {
  3212. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  3213. }
  3214. template <typename ClientType>
  3215. inline Result Get(ClientType &cli, const std::string &path,
  3216. const Params &params, size_t chunk_size = 8192) {
  3217. return Result{cli.open_stream("GET", path, params), chunk_size};
  3218. }
  3219. template <typename ClientType>
  3220. inline Result Get(ClientType &cli, const std::string &path,
  3221. const Params &params, const Headers &headers,
  3222. size_t chunk_size = 8192) {
  3223. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  3224. }
  3225. // POST
  3226. template <typename ClientType>
  3227. inline Result Post(ClientType &cli, const std::string &path,
  3228. const std::string &body, const std::string &content_type,
  3229. size_t chunk_size = 8192) {
  3230. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  3231. chunk_size};
  3232. }
  3233. template <typename ClientType>
  3234. inline Result Post(ClientType &cli, const std::string &path,
  3235. const Headers &headers, const std::string &body,
  3236. const std::string &content_type, size_t chunk_size = 8192) {
  3237. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  3238. chunk_size};
  3239. }
  3240. template <typename ClientType>
  3241. inline Result Post(ClientType &cli, const std::string &path,
  3242. const Params &params, const std::string &body,
  3243. const std::string &content_type, size_t chunk_size = 8192) {
  3244. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  3245. chunk_size};
  3246. }
  3247. template <typename ClientType>
  3248. inline Result Post(ClientType &cli, const std::string &path,
  3249. const Params &params, const Headers &headers,
  3250. const std::string &body, const std::string &content_type,
  3251. size_t chunk_size = 8192) {
  3252. return Result{
  3253. cli.open_stream("POST", path, params, headers, body, content_type),
  3254. chunk_size};
  3255. }
  3256. // PUT
  3257. template <typename ClientType>
  3258. inline Result Put(ClientType &cli, const std::string &path,
  3259. const std::string &body, const std::string &content_type,
  3260. size_t chunk_size = 8192) {
  3261. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  3262. chunk_size};
  3263. }
  3264. template <typename ClientType>
  3265. inline Result Put(ClientType &cli, const std::string &path,
  3266. const Headers &headers, const std::string &body,
  3267. const std::string &content_type, size_t chunk_size = 8192) {
  3268. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  3269. chunk_size};
  3270. }
  3271. template <typename ClientType>
  3272. inline Result Put(ClientType &cli, const std::string &path,
  3273. const Params &params, const std::string &body,
  3274. const std::string &content_type, size_t chunk_size = 8192) {
  3275. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  3276. chunk_size};
  3277. }
  3278. template <typename ClientType>
  3279. inline Result Put(ClientType &cli, const std::string &path,
  3280. const Params &params, const Headers &headers,
  3281. const std::string &body, const std::string &content_type,
  3282. size_t chunk_size = 8192) {
  3283. return Result{
  3284. cli.open_stream("PUT", path, params, headers, body, content_type),
  3285. chunk_size};
  3286. }
  3287. // PATCH
  3288. template <typename ClientType>
  3289. inline Result Patch(ClientType &cli, const std::string &path,
  3290. const std::string &body, const std::string &content_type,
  3291. size_t chunk_size = 8192) {
  3292. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  3293. chunk_size};
  3294. }
  3295. template <typename ClientType>
  3296. inline Result Patch(ClientType &cli, const std::string &path,
  3297. const Headers &headers, const std::string &body,
  3298. const std::string &content_type, size_t chunk_size = 8192) {
  3299. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  3300. chunk_size};
  3301. }
  3302. template <typename ClientType>
  3303. inline Result Patch(ClientType &cli, const std::string &path,
  3304. const Params &params, const std::string &body,
  3305. const std::string &content_type, size_t chunk_size = 8192) {
  3306. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  3307. chunk_size};
  3308. }
  3309. template <typename ClientType>
  3310. inline Result Patch(ClientType &cli, const std::string &path,
  3311. const Params &params, const Headers &headers,
  3312. const std::string &body, const std::string &content_type,
  3313. size_t chunk_size = 8192) {
  3314. return Result{
  3315. cli.open_stream("PATCH", path, params, headers, body, content_type),
  3316. chunk_size};
  3317. }
  3318. // DELETE
  3319. template <typename ClientType>
  3320. inline Result Delete(ClientType &cli, const std::string &path,
  3321. size_t chunk_size = 8192) {
  3322. return Result{cli.open_stream("DELETE", path), chunk_size};
  3323. }
  3324. template <typename ClientType>
  3325. inline Result Delete(ClientType &cli, const std::string &path,
  3326. const Headers &headers, size_t chunk_size = 8192) {
  3327. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  3328. }
  3329. template <typename ClientType>
  3330. inline Result Delete(ClientType &cli, const std::string &path,
  3331. const std::string &body, const std::string &content_type,
  3332. size_t chunk_size = 8192) {
  3333. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3334. chunk_size};
  3335. }
  3336. template <typename ClientType>
  3337. inline Result Delete(ClientType &cli, const std::string &path,
  3338. const Headers &headers, const std::string &body,
  3339. const std::string &content_type,
  3340. size_t chunk_size = 8192) {
  3341. return Result{
  3342. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3343. chunk_size};
  3344. }
  3345. template <typename ClientType>
  3346. inline Result Delete(ClientType &cli, const std::string &path,
  3347. const Params &params, size_t chunk_size = 8192) {
  3348. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3349. }
  3350. template <typename ClientType>
  3351. inline Result Delete(ClientType &cli, const std::string &path,
  3352. const Params &params, const Headers &headers,
  3353. size_t chunk_size = 8192) {
  3354. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3355. }
  3356. template <typename ClientType>
  3357. inline Result Delete(ClientType &cli, const std::string &path,
  3358. const Params &params, const std::string &body,
  3359. const std::string &content_type,
  3360. size_t chunk_size = 8192) {
  3361. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3362. chunk_size};
  3363. }
  3364. template <typename ClientType>
  3365. inline Result Delete(ClientType &cli, const std::string &path,
  3366. const Params &params, const Headers &headers,
  3367. const std::string &body, const std::string &content_type,
  3368. size_t chunk_size = 8192) {
  3369. return Result{
  3370. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3371. chunk_size};
  3372. }
  3373. // HEAD
  3374. template <typename ClientType>
  3375. inline Result Head(ClientType &cli, const std::string &path,
  3376. size_t chunk_size = 8192) {
  3377. return Result{cli.open_stream("HEAD", path), chunk_size};
  3378. }
  3379. template <typename ClientType>
  3380. inline Result Head(ClientType &cli, const std::string &path,
  3381. const Headers &headers, size_t chunk_size = 8192) {
  3382. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3383. }
  3384. template <typename ClientType>
  3385. inline Result Head(ClientType &cli, const std::string &path,
  3386. const Params &params, size_t chunk_size = 8192) {
  3387. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3388. }
  3389. template <typename ClientType>
  3390. inline Result Head(ClientType &cli, const std::string &path,
  3391. const Params &params, const Headers &headers,
  3392. size_t chunk_size = 8192) {
  3393. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3394. }
  3395. // OPTIONS
  3396. template <typename ClientType>
  3397. inline Result Options(ClientType &cli, const std::string &path,
  3398. size_t chunk_size = 8192) {
  3399. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3400. }
  3401. template <typename ClientType>
  3402. inline Result Options(ClientType &cli, const std::string &path,
  3403. const Headers &headers, size_t chunk_size = 8192) {
  3404. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3405. }
  3406. template <typename ClientType>
  3407. inline Result Options(ClientType &cli, const std::string &path,
  3408. const Params &params, size_t chunk_size = 8192) {
  3409. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3410. }
  3411. template <typename ClientType>
  3412. inline Result Options(ClientType &cli, const std::string &path,
  3413. const Params &params, const Headers &headers,
  3414. size_t chunk_size = 8192) {
  3415. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3416. }
  3417. } // namespace stream
  3418. namespace sse {
  3419. struct SSEMessage {
  3420. std::string event; // Event type (default: "message")
  3421. std::string data; // Event payload
  3422. std::string id; // Event ID for Last-Event-ID header
  3423. SSEMessage();
  3424. void clear();
  3425. };
  3426. class SSEClient {
  3427. public:
  3428. using MessageHandler = std::function<void(const SSEMessage &)>;
  3429. using ErrorHandler = std::function<void(Error)>;
  3430. using OpenHandler = std::function<void()>;
  3431. SSEClient(Client &client, const std::string &path);
  3432. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3433. ~SSEClient();
  3434. SSEClient(const SSEClient &) = delete;
  3435. SSEClient &operator=(const SSEClient &) = delete;
  3436. // Event handlers
  3437. SSEClient &on_message(MessageHandler handler);
  3438. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3439. SSEClient &on_open(OpenHandler handler);
  3440. SSEClient &on_error(ErrorHandler handler);
  3441. SSEClient &set_reconnect_interval(int ms);
  3442. SSEClient &set_max_reconnect_attempts(int n);
  3443. // Update headers (thread-safe)
  3444. SSEClient &set_headers(const Headers &headers);
  3445. // State accessors
  3446. bool is_connected() const;
  3447. const std::string &last_event_id() const;
  3448. // Blocking start - runs event loop with auto-reconnect
  3449. void start();
  3450. // Non-blocking start - runs in background thread
  3451. void start_async();
  3452. // Stop the client (thread-safe)
  3453. void stop();
  3454. private:
  3455. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3456. void run_event_loop();
  3457. void dispatch_event(const SSEMessage &msg);
  3458. bool should_reconnect(int count) const;
  3459. void wait_for_reconnect();
  3460. // Client and path
  3461. Client &client_;
  3462. std::string path_;
  3463. Headers headers_;
  3464. mutable std::mutex headers_mutex_;
  3465. // Callbacks
  3466. MessageHandler on_message_;
  3467. std::map<std::string, MessageHandler> event_handlers_;
  3468. OpenHandler on_open_;
  3469. ErrorHandler on_error_;
  3470. // Configuration
  3471. int reconnect_interval_ms_ = 3000;
  3472. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3473. // State
  3474. std::atomic<bool> running_{false};
  3475. std::atomic<bool> connected_{false};
  3476. std::string last_event_id_;
  3477. // Async support
  3478. std::thread async_thread_;
  3479. };
  3480. } // namespace sse
  3481. namespace ws {
  3482. enum class Opcode : uint8_t {
  3483. Continuation = 0x0,
  3484. Text = 0x1,
  3485. Binary = 0x2,
  3486. Close = 0x8,
  3487. Ping = 0x9,
  3488. Pong = 0xA,
  3489. };
  3490. enum class CloseStatus : uint16_t {
  3491. Normal = 1000,
  3492. GoingAway = 1001,
  3493. ProtocolError = 1002,
  3494. UnsupportedData = 1003,
  3495. NoStatus = 1005,
  3496. Abnormal = 1006,
  3497. InvalidPayload = 1007,
  3498. PolicyViolation = 1008,
  3499. MessageTooBig = 1009,
  3500. MandatoryExtension = 1010,
  3501. InternalError = 1011,
  3502. };
  3503. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3504. // Result of WebSocketClient::connect(). Truthy only when the WebSocket
  3505. // upgrade handshake fully succeeded. On failure error() identifies the
  3506. // failing layer; status()/headers() expose the server's upgrade response
  3507. // when one was received (status() is -1 otherwise).
  3508. class Result {
  3509. public:
  3510. Result() = default;
  3511. Result(Error err, int status, Headers &&headers)
  3512. : err_(err), status_(status), headers_(std::move(headers)) {}
  3513. explicit operator bool() const { return err_ == Error::Success; }
  3514. Error error() const { return err_; }
  3515. // Upgrade response info
  3516. int status() const { return status_; }
  3517. const Headers &headers() const { return headers_; }
  3518. std::string get_header_value(const std::string &key,
  3519. const char *def = "") const {
  3520. return detail::get_header_value(headers_, key, def, 0);
  3521. }
  3522. bool has_header(const std::string &key) const {
  3523. return headers_.find(key) != headers_.end();
  3524. }
  3525. #ifdef CPPHTTPLIB_SSL_ENABLED
  3526. Result(Error err, int status, Headers &&headers, int ssl_error,
  3527. uint64_t ssl_backend_error)
  3528. : err_(err), status_(status), headers_(std::move(headers)),
  3529. ssl_error_(ssl_error), ssl_backend_error_(ssl_backend_error) {}
  3530. int ssl_error() const { return ssl_error_; }
  3531. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  3532. #endif
  3533. private:
  3534. Error err_ = Error::Unknown; // a default-constructed Result is falsy
  3535. int status_ = -1;
  3536. Headers headers_;
  3537. #ifdef CPPHTTPLIB_SSL_ENABLED
  3538. int ssl_error_ = 0;
  3539. uint64_t ssl_backend_error_ = 0;
  3540. #endif
  3541. };
  3542. class WebSocket {
  3543. public:
  3544. WebSocket(const WebSocket &) = delete;
  3545. WebSocket &operator=(const WebSocket &) = delete;
  3546. ~WebSocket();
  3547. ReadResult read(std::string &msg);
  3548. bool send(const std::string &data);
  3549. bool send(const char *data, size_t len);
  3550. void close(CloseStatus status = CloseStatus::Normal,
  3551. const std::string &reason = "");
  3552. const Request &request() const;
  3553. bool is_open() const;
  3554. private:
  3555. friend class httplib::Server;
  3556. friend class WebSocketClient;
  3557. WebSocket(
  3558. Stream &strm, const Request &req, bool is_server,
  3559. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3560. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3561. : strm_(strm), req_(req), is_server_(is_server),
  3562. ping_interval_sec_(ping_interval_sec),
  3563. max_missed_pongs_(max_missed_pongs) {
  3564. start_heartbeat();
  3565. }
  3566. WebSocket(
  3567. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3568. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3569. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3570. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3571. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3572. max_missed_pongs_(max_missed_pongs) {
  3573. start_heartbeat();
  3574. }
  3575. void start_heartbeat();
  3576. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3577. Stream &strm_;
  3578. std::unique_ptr<Stream> owned_strm_;
  3579. Request req_;
  3580. bool is_server_;
  3581. time_t ping_interval_sec_;
  3582. int max_missed_pongs_;
  3583. int unacked_pings_ = 0;
  3584. std::atomic<bool> closed_{false};
  3585. std::mutex write_mutex_;
  3586. // Owned by whichever thread is parsing frames off strm_. Only one thread
  3587. // may do so: read_websocket_frame() reads a payload until it has the whole
  3588. // declared length, so a second parser stealing bytes silently corrupts the
  3589. // message the first one is assembling.
  3590. std::mutex read_mutex_;
  3591. std::thread ping_thread_;
  3592. std::mutex ping_mutex_;
  3593. std::condition_variable ping_cv_;
  3594. };
  3595. class WebSocketClient {
  3596. public:
  3597. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3598. const Headers &headers = {});
  3599. ~WebSocketClient();
  3600. WebSocketClient(const WebSocketClient &) = delete;
  3601. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3602. bool is_valid() const;
  3603. Result connect();
  3604. ReadResult read(std::string &msg);
  3605. bool send(const std::string &data);
  3606. bool send(const char *data, size_t len);
  3607. void close(CloseStatus status = CloseStatus::Normal,
  3608. const std::string &reason = "");
  3609. bool is_open() const;
  3610. const std::string &subprotocol() const;
  3611. void set_read_timeout(time_t sec, time_t usec = 0);
  3612. template <class Rep, class Period>
  3613. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  3614. void set_write_timeout(time_t sec, time_t usec = 0);
  3615. template <class Rep, class Period>
  3616. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  3617. void set_websocket_ping_interval(time_t sec);
  3618. void set_websocket_max_missed_pongs(int count);
  3619. void set_tcp_nodelay(bool on);
  3620. void set_address_family(int family);
  3621. void set_ipv6_v6only(bool on);
  3622. void set_socket_options(SocketOptions socket_options);
  3623. void set_connection_timeout(time_t sec, time_t usec = 0);
  3624. template <class Rep, class Period>
  3625. void
  3626. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  3627. void set_interface(const std::string &intf);
  3628. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3629. #ifdef CPPHTTPLIB_SSL_ENABLED
  3630. struct PemMemory {
  3631. const char *cert_pem;
  3632. size_t cert_pem_len;
  3633. const char *key_pem;
  3634. size_t key_pem_len;
  3635. const char *private_key_password;
  3636. };
  3637. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3638. const PemMemory &pem, const Headers &headers = {});
  3639. void set_ca_cert_path(const std::string &ca_cert_file_path,
  3640. const std::string &ca_cert_dir_path = std::string());
  3641. void set_ca_cert_store(tls::ca_store_t store);
  3642. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3643. void enable_server_certificate_verification(bool enabled);
  3644. void enable_server_hostname_verification(bool enabled);
  3645. void enable_system_ca(bool enabled);
  3646. #endif
  3647. private:
  3648. void shutdown_and_close();
  3649. bool create_stream(std::unique_ptr<Stream> &strm, Error &error,
  3650. int &ssl_error, uint64_t &ssl_backend_error);
  3651. void prepare_default_headers(Request &req);
  3652. std::string host_;
  3653. int port_;
  3654. std::string path_;
  3655. Headers headers_;
  3656. std::string subprotocol_;
  3657. bool is_valid_ = false;
  3658. socket_t sock_ = INVALID_SOCKET;
  3659. std::unique_ptr<WebSocket> ws_;
  3660. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3661. time_t read_timeout_usec_ = 0;
  3662. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3663. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3664. time_t websocket_ping_interval_sec_ =
  3665. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3666. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3667. int address_family_ = AF_UNSPEC;
  3668. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3669. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3670. SocketOptions socket_options_ = nullptr;
  3671. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3672. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3673. std::string interface_;
  3674. // Hostname to connection target map. The value is an IP literal or another
  3675. // hostname; only the connection target changes, never the identity.
  3676. std::map<std::string, std::string> addr_map_;
  3677. #ifdef CPPHTTPLIB_SSL_ENABLED
  3678. bool is_ssl_ = false;
  3679. tls::ctx_t tls_ctx_ = nullptr;
  3680. tls::session_t tls_session_ = nullptr;
  3681. std::string ca_cert_file_path_;
  3682. std::string ca_cert_dir_path_;
  3683. bool custom_ca_loaded_ = false;
  3684. bool certs_loaded_ = false;
  3685. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3686. bool server_certificate_verification_ = true;
  3687. bool server_hostname_verification_ = true;
  3688. #endif
  3689. };
  3690. template <class Rep, class Period>
  3691. inline void WebSocketClient::set_read_timeout(
  3692. const std::chrono::duration<Rep, Period> &duration) {
  3693. detail::duration_to_sec_and_usec(
  3694. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3695. }
  3696. template <class Rep, class Period>
  3697. inline void WebSocketClient::set_write_timeout(
  3698. const std::chrono::duration<Rep, Period> &duration) {
  3699. detail::duration_to_sec_and_usec(
  3700. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3701. }
  3702. template <class Rep, class Period>
  3703. inline void WebSocketClient::set_connection_timeout(
  3704. const std::chrono::duration<Rep, Period> &duration) {
  3705. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  3706. set_connection_timeout(sec, usec);
  3707. });
  3708. }
  3709. namespace impl {
  3710. bool is_valid_utf8(const std::string &s);
  3711. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3712. bool &fin, bool expect_masked, size_t max_len);
  3713. } // namespace impl
  3714. } // namespace ws
  3715. // ----------------------------------------------------------------------------
  3716. /*
  3717. * Implementation that will be part of the .cc file if split into .h + .cc.
  3718. */
  3719. namespace stream {
  3720. // stream::Result implementations
  3721. inline Result::Result() : chunk_size_(8192) {}
  3722. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3723. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3724. inline Result::Result(Result &&other) noexcept
  3725. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3726. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3727. finished_(other.finished_) {
  3728. other.current_size_ = 0;
  3729. other.finished_ = true;
  3730. }
  3731. inline Result &Result::operator=(Result &&other) noexcept {
  3732. if (this != &other) {
  3733. handle_ = std::move(other.handle_);
  3734. buffer_ = std::move(other.buffer_);
  3735. current_size_ = other.current_size_;
  3736. chunk_size_ = other.chunk_size_;
  3737. finished_ = other.finished_;
  3738. other.current_size_ = 0;
  3739. other.finished_ = true;
  3740. }
  3741. return *this;
  3742. }
  3743. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3744. inline Result::operator bool() const { return is_valid(); }
  3745. inline int Result::status() const {
  3746. return handle_.response ? handle_.response->status : -1;
  3747. }
  3748. inline const Headers &Result::headers() const {
  3749. static const Headers empty_headers;
  3750. return handle_.response ? handle_.response->headers : empty_headers;
  3751. }
  3752. inline std::string Result::get_header_value(const std::string &key,
  3753. const char *def) const {
  3754. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3755. }
  3756. inline bool Result::has_header(const std::string &key) const {
  3757. return handle_.response ? handle_.response->has_header(key) : false;
  3758. }
  3759. inline Error Result::error() const { return handle_.error; }
  3760. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3761. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3762. inline bool Result::next() {
  3763. if (!handle_.is_valid() || finished_) { return false; }
  3764. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3765. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3766. if (n > 0) {
  3767. current_size_ = static_cast<size_t>(n);
  3768. return true;
  3769. }
  3770. current_size_ = 0;
  3771. finished_ = true;
  3772. return false;
  3773. }
  3774. inline const char *Result::data() const { return buffer_.data(); }
  3775. inline size_t Result::size() const { return current_size_; }
  3776. inline std::string Result::read_all() {
  3777. std::string result;
  3778. while (next()) {
  3779. result.append(data(), size());
  3780. }
  3781. return result;
  3782. }
  3783. } // namespace stream
  3784. namespace sse {
  3785. // SSEMessage implementations
  3786. inline SSEMessage::SSEMessage() : event("message") {}
  3787. inline void SSEMessage::clear() {
  3788. event = "message";
  3789. data.clear();
  3790. id.clear();
  3791. }
  3792. // SSEClient implementations
  3793. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3794. : client_(client), path_(path) {}
  3795. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3796. const Headers &headers)
  3797. : client_(client), path_(path), headers_(headers) {}
  3798. inline SSEClient::~SSEClient() { stop(); }
  3799. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3800. on_message_ = std::move(handler);
  3801. return *this;
  3802. }
  3803. inline SSEClient &SSEClient::on_event(const std::string &type,
  3804. MessageHandler handler) {
  3805. event_handlers_[type] = std::move(handler);
  3806. return *this;
  3807. }
  3808. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3809. on_open_ = std::move(handler);
  3810. return *this;
  3811. }
  3812. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3813. on_error_ = std::move(handler);
  3814. return *this;
  3815. }
  3816. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3817. reconnect_interval_ms_ = ms;
  3818. return *this;
  3819. }
  3820. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3821. max_reconnect_attempts_ = n;
  3822. return *this;
  3823. }
  3824. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3825. std::lock_guard<std::mutex> lock(headers_mutex_);
  3826. headers_ = headers;
  3827. return *this;
  3828. }
  3829. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3830. inline const std::string &SSEClient::last_event_id() const {
  3831. return last_event_id_;
  3832. }
  3833. inline void SSEClient::start() {
  3834. running_.store(true);
  3835. run_event_loop();
  3836. }
  3837. inline void SSEClient::start_async() {
  3838. running_.store(true);
  3839. async_thread_ = std::thread([this]() { run_event_loop(); });
  3840. }
  3841. inline void SSEClient::stop() {
  3842. running_.store(false);
  3843. client_.stop(); // Cancel any pending operations
  3844. if (async_thread_.joinable()) { async_thread_.join(); }
  3845. }
  3846. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3847. int &retry_ms) {
  3848. // Blank line signals end of event
  3849. if (line.empty() || line == "\r") { return true; }
  3850. // Lines starting with ':' are comments (ignored)
  3851. if (!line.empty() && line[0] == ':') { return false; }
  3852. // Find the colon separator
  3853. auto colon_pos = line.find(':');
  3854. if (colon_pos == std::string::npos) {
  3855. // Line with no colon is treated as field name with empty value
  3856. return false;
  3857. }
  3858. auto field = line.substr(0, colon_pos);
  3859. std::string value;
  3860. // Value starts after colon, skip optional single space
  3861. if (colon_pos + 1 < line.size()) {
  3862. auto value_start = colon_pos + 1;
  3863. if (line[value_start] == ' ') { value_start++; }
  3864. value = line.substr(value_start);
  3865. // Remove trailing \r if present
  3866. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3867. }
  3868. // Handle known fields
  3869. if (field == "event") {
  3870. msg.event = value;
  3871. } else if (field == "data") {
  3872. // Multiple data lines are concatenated with newlines
  3873. if (!msg.data.empty()) { msg.data += "\n"; }
  3874. msg.data += value;
  3875. } else if (field == "id") {
  3876. // Empty id is valid (clears the last event ID)
  3877. msg.id = value;
  3878. } else if (field == "retry") {
  3879. // Parse retry interval in milliseconds
  3880. {
  3881. int v = 0;
  3882. auto res =
  3883. detail::from_chars(value.data(), value.data() + value.size(), v);
  3884. if (res.ec == std::errc{}) { retry_ms = v; }
  3885. }
  3886. }
  3887. // Unknown fields are ignored per SSE spec
  3888. return false;
  3889. }
  3890. inline void SSEClient::run_event_loop() {
  3891. auto reconnect_count = 0;
  3892. while (running_.load()) {
  3893. // Build headers, including Last-Event-ID if we have one
  3894. Headers request_headers;
  3895. {
  3896. std::lock_guard<std::mutex> lock(headers_mutex_);
  3897. request_headers = headers_;
  3898. }
  3899. if (!last_event_id_.empty()) {
  3900. request_headers.emplace("Last-Event-ID", last_event_id_);
  3901. }
  3902. // Open streaming connection
  3903. auto result = stream::Get(client_, path_, request_headers);
  3904. // Connection error handling
  3905. if (!result) {
  3906. connected_.store(false);
  3907. if (on_error_) { on_error_(result.error()); }
  3908. if (!should_reconnect(reconnect_count)) { break; }
  3909. wait_for_reconnect();
  3910. reconnect_count++;
  3911. continue;
  3912. }
  3913. if (result.status() != StatusCode::OK_200) {
  3914. connected_.store(false);
  3915. if (on_error_) { on_error_(Error::Connection); }
  3916. // For certain errors, don't reconnect.
  3917. // Note: 401 is intentionally absent so that handlers can refresh
  3918. // credentials via set_headers() and let the client reconnect.
  3919. if (result.status() == StatusCode::NoContent_204 ||
  3920. result.status() == StatusCode::NotFound_404 ||
  3921. result.status() == StatusCode::Forbidden_403) {
  3922. break;
  3923. }
  3924. if (!should_reconnect(reconnect_count)) { break; }
  3925. wait_for_reconnect();
  3926. reconnect_count++;
  3927. continue;
  3928. }
  3929. // Connection successful
  3930. connected_.store(true);
  3931. reconnect_count = 0;
  3932. if (on_open_) { on_open_(); }
  3933. // Event receiving loop
  3934. std::string buffer;
  3935. SSEMessage current_msg;
  3936. while (running_.load() && result.next()) {
  3937. buffer.append(result.data(), result.size());
  3938. // Process complete lines in the buffer
  3939. size_t line_start = 0;
  3940. size_t newline_pos;
  3941. while ((newline_pos = buffer.find('\n', line_start)) !=
  3942. std::string::npos) {
  3943. auto line = buffer.substr(line_start, newline_pos - line_start);
  3944. line_start = newline_pos + 1;
  3945. // Parse the line and check if event is complete
  3946. auto event_complete =
  3947. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3948. if (event_complete && !current_msg.data.empty()) {
  3949. // Update last_event_id for reconnection
  3950. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3951. // Dispatch event to appropriate handler
  3952. dispatch_event(current_msg);
  3953. current_msg.clear();
  3954. }
  3955. }
  3956. // Keep unprocessed data in buffer
  3957. buffer.erase(0, line_start);
  3958. }
  3959. // Connection ended
  3960. connected_.store(false);
  3961. if (!running_.load()) { break; }
  3962. // Check for read errors
  3963. if (result.has_read_error()) {
  3964. if (on_error_) { on_error_(result.read_error()); }
  3965. }
  3966. if (!should_reconnect(reconnect_count)) { break; }
  3967. wait_for_reconnect();
  3968. reconnect_count++;
  3969. }
  3970. connected_.store(false);
  3971. }
  3972. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3973. // Check for specific event type handler first
  3974. auto it = event_handlers_.find(msg.event);
  3975. if (it != event_handlers_.end()) {
  3976. it->second(msg);
  3977. return;
  3978. }
  3979. // Fall back to generic message handler
  3980. if (on_message_) { on_message_(msg); }
  3981. }
  3982. inline bool SSEClient::should_reconnect(int count) const {
  3983. if (!running_.load()) { return false; }
  3984. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3985. return count < max_reconnect_attempts_;
  3986. }
  3987. inline void SSEClient::wait_for_reconnect() {
  3988. // Use small increments to check running_ flag frequently
  3989. auto waited = 0;
  3990. while (running_.load() && waited < reconnect_interval_ms_) {
  3991. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3992. waited += 100;
  3993. }
  3994. }
  3995. } // namespace sse
  3996. #ifdef CPPHTTPLIB_SSL_ENABLED
  3997. /*
  3998. * TLS abstraction layer - internal function declarations
  3999. * These are implementation details and not part of the public API.
  4000. */
  4001. namespace tls {
  4002. // Client context
  4003. ctx_t create_client_context();
  4004. void free_context(ctx_t ctx);
  4005. bool set_min_version(ctx_t ctx, Version version);
  4006. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  4007. bool load_ca_file(ctx_t ctx, const char *file_path);
  4008. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  4009. bool load_system_certs(ctx_t ctx);
  4010. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4011. const char *password);
  4012. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  4013. const char *key_path, const char *password);
  4014. // Server context
  4015. ctx_t create_server_context();
  4016. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4017. const char *password);
  4018. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  4019. const char *key_path, const char *password);
  4020. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  4021. void set_verify_client(ctx_t ctx, bool require);
  4022. // Session management
  4023. session_t create_session(ctx_t ctx, socket_t sock);
  4024. void free_session(session_t session);
  4025. bool set_sni(session_t session, const char *hostname, bool verify_hostname);
  4026. // Handshake (non-blocking capable)
  4027. TlsError connect(session_t session);
  4028. TlsError accept(session_t session);
  4029. // Handshake with timeout (blocking until timeout)
  4030. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4031. time_t timeout_usec, TlsError *err);
  4032. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4033. time_t timeout_usec, TlsError *err);
  4034. // I/O (non-blocking capable)
  4035. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  4036. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  4037. int pending(const_session_t session);
  4038. void shutdown(session_t session, bool graceful);
  4039. // Connection state
  4040. bool is_peer_closed(session_t session, socket_t sock);
  4041. // Certificate verification
  4042. cert_t get_peer_cert(const_session_t session);
  4043. void free_cert(cert_t cert);
  4044. bool verify_hostname(cert_t cert, const char *hostname);
  4045. uint64_t hostname_mismatch_code();
  4046. long get_verify_result(const_session_t session);
  4047. // Certificate introspection
  4048. std::string get_cert_subject_cn(cert_t cert);
  4049. std::string get_cert_issuer_name(cert_t cert);
  4050. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  4051. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  4052. std::string get_cert_serial(cert_t cert);
  4053. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  4054. const char *get_sni(const_session_t session);
  4055. // CA store management
  4056. ca_store_t create_ca_store(const char *pem, size_t len);
  4057. void free_ca_store(ca_store_t store);
  4058. bool set_ca_store(ctx_t ctx, ca_store_t store);
  4059. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  4060. std::vector<std::string> get_ca_names(ctx_t ctx);
  4061. // Dynamic certificate update (for servers)
  4062. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  4063. const char *password);
  4064. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  4065. // Certificate verification callback
  4066. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  4067. long get_verify_error(const_session_t session);
  4068. std::string verify_error_string(long error_code);
  4069. // TlsError information
  4070. uint64_t peek_error();
  4071. uint64_t get_error();
  4072. std::string error_string(uint64_t code);
  4073. } // namespace tls
  4074. #endif // CPPHTTPLIB_SSL_ENABLED
  4075. /*
  4076. * Group 1: detail namespace - Non-SSL utilities
  4077. */
  4078. namespace detail {
  4079. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  4080. const void *optval, socklen_t optlen) {
  4081. return setsockopt(sock, level, optname,
  4082. #ifdef _WIN32
  4083. reinterpret_cast<const char *>(optval),
  4084. #else
  4085. optval,
  4086. #endif
  4087. optlen) == 0;
  4088. }
  4089. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  4090. time_t sec, time_t usec) {
  4091. #ifdef _WIN32
  4092. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  4093. #else
  4094. timeval timeout;
  4095. timeout.tv_sec = static_cast<long>(sec);
  4096. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  4097. #endif
  4098. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  4099. }
  4100. inline bool is_hex(char c, int &v) {
  4101. if (is_ascii_digit(c)) {
  4102. v = c - '0';
  4103. return true;
  4104. } else if ('A' <= c && c <= 'F') {
  4105. v = c - 'A' + 10;
  4106. return true;
  4107. } else if ('a' <= c && c <= 'f') {
  4108. v = c - 'a' + 10;
  4109. return true;
  4110. }
  4111. return false;
  4112. }
  4113. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  4114. int &val) {
  4115. if (i >= s.size()) { return false; }
  4116. val = 0;
  4117. for (; cnt; i++, cnt--) {
  4118. if (!s[i]) { return false; }
  4119. auto v = 0;
  4120. if (is_hex(s[i], v)) {
  4121. val = val * 16 + v;
  4122. } else {
  4123. return false;
  4124. }
  4125. }
  4126. return true;
  4127. }
  4128. inline std::string from_i_to_hex(size_t n) {
  4129. static const auto charset = "0123456789abcdef";
  4130. std::string ret;
  4131. do {
  4132. ret = charset[n & 15] + ret;
  4133. n >>= 4;
  4134. } while (n > 0);
  4135. return ret;
  4136. }
  4137. inline std::string compute_etag(const FileStat &fs) {
  4138. if (!fs.is_file()) { return std::string(); }
  4139. // If mtime cannot be determined (negative value indicates an error
  4140. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  4141. // value like 0 could collide with a real file that legitimately has
  4142. // mtime == 0 (epoch) and lead to misleading validators.
  4143. auto mtime_raw = fs.mtime();
  4144. if (mtime_raw < 0) { return std::string(); }
  4145. auto mtime = static_cast<size_t>(mtime_raw);
  4146. auto size = fs.size();
  4147. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  4148. from_i_to_hex(size) + "\"";
  4149. }
  4150. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  4151. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  4152. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  4153. inline std::string file_mtime_to_http_date(time_t mtime) {
  4154. if (mtime < 0) { return std::string(); }
  4155. struct tm tm_buf;
  4156. #ifdef _WIN32
  4157. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  4158. #else
  4159. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  4160. #endif
  4161. char buf[64];
  4162. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  4163. return std::string();
  4164. }
  4165. return std::string(buf);
  4166. }
  4167. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  4168. inline time_t parse_http_date(const std::string &date_str) {
  4169. struct tm tm_buf;
  4170. // Create a classic locale object once for all parsing attempts
  4171. const std::locale classic_locale = std::locale::classic();
  4172. // Try to parse using std::get_time (C++11, cross-platform)
  4173. auto try_parse = [&](const char *fmt) -> bool {
  4174. std::istringstream ss(date_str);
  4175. ss.imbue(classic_locale);
  4176. memset(&tm_buf, 0, sizeof(tm_buf));
  4177. ss >> std::get_time(&tm_buf, fmt);
  4178. return !ss.fail();
  4179. };
  4180. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  4181. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  4182. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  4183. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  4184. // asctime format: "Sun Nov 6 08:49:37 1994"
  4185. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  4186. return static_cast<time_t>(-1);
  4187. }
  4188. }
  4189. }
  4190. #ifdef _WIN32
  4191. return _mkgmtime(&tm_buf);
  4192. #elif defined _AIX
  4193. return mktime(&tm_buf);
  4194. #else
  4195. return timegm(&tm_buf);
  4196. #endif
  4197. }
  4198. inline bool is_weak_etag(const std::string &s) {
  4199. // Check if the string is a weak ETag (starts with 'W/"')
  4200. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  4201. }
  4202. inline bool is_strong_etag(const std::string &s) {
  4203. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  4204. // chars)
  4205. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  4206. }
  4207. inline size_t to_utf8(int code, char *buff) {
  4208. if (code < 0x0080) {
  4209. buff[0] = static_cast<char>(code & 0x7F);
  4210. return 1;
  4211. } else if (code < 0x0800) {
  4212. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  4213. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  4214. return 2;
  4215. } else if (code < 0xD800) {
  4216. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4217. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4218. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4219. return 3;
  4220. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  4221. return 0;
  4222. } else if (code < 0x10000) {
  4223. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4224. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4225. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4226. return 3;
  4227. } else if (code < 0x110000) {
  4228. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  4229. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  4230. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4231. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  4232. return 4;
  4233. }
  4234. // NOTREACHED
  4235. return 0;
  4236. }
  4237. } // namespace detail
  4238. namespace ws {
  4239. namespace impl {
  4240. inline bool is_valid_utf8(const std::string &s) {
  4241. size_t i = 0;
  4242. auto n = s.size();
  4243. while (i < n) {
  4244. auto c = static_cast<unsigned char>(s[i]);
  4245. size_t len;
  4246. uint32_t cp;
  4247. if (c < 0x80) {
  4248. i++;
  4249. continue;
  4250. } else if ((c & 0xE0) == 0xC0) {
  4251. len = 2;
  4252. cp = c & 0x1F;
  4253. } else if ((c & 0xF0) == 0xE0) {
  4254. len = 3;
  4255. cp = c & 0x0F;
  4256. } else if ((c & 0xF8) == 0xF0) {
  4257. len = 4;
  4258. cp = c & 0x07;
  4259. } else {
  4260. return false;
  4261. }
  4262. if (i + len > n) { return false; }
  4263. for (size_t j = 1; j < len; j++) {
  4264. auto b = static_cast<unsigned char>(s[i + j]);
  4265. if ((b & 0xC0) != 0x80) { return false; }
  4266. cp = (cp << 6) | (b & 0x3F);
  4267. }
  4268. // Overlong encoding check
  4269. if (len == 2 && cp < 0x80) { return false; }
  4270. if (len == 3 && cp < 0x800) { return false; }
  4271. if (len == 4 && cp < 0x10000) { return false; }
  4272. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  4273. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  4274. if (cp > 0x10FFFF) { return false; }
  4275. i += len;
  4276. }
  4277. return true;
  4278. }
  4279. } // namespace impl
  4280. } // namespace ws
  4281. namespace detail {
  4282. // NOTE: This code came up with the following stackoverflow post:
  4283. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  4284. inline std::string base64_encode(const std::string &in) {
  4285. static const auto lookup =
  4286. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4287. std::string out;
  4288. out.reserve(in.size());
  4289. // Unsigned: the accumulator is never masked, so with a signed int the
  4290. // `val << 8` below overflows once enough bytes are folded in (undefined
  4291. // behaviour before C++20). Only the low bits are ever emitted, so the
  4292. // wrap-around of an unsigned accumulator does not affect the output.
  4293. uint32_t val = 0;
  4294. auto valb = -6;
  4295. for (auto c : in) {
  4296. val = (val << 8) + static_cast<uint8_t>(c);
  4297. valb += 8;
  4298. while (valb >= 0) {
  4299. out.push_back(lookup[(val >> valb) & 0x3F]);
  4300. valb -= 6;
  4301. }
  4302. }
  4303. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  4304. while (out.size() % 4) {
  4305. out.push_back('=');
  4306. }
  4307. return out;
  4308. }
  4309. inline std::string sha1(const std::string &input) {
  4310. // RFC 3174 SHA-1 implementation
  4311. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  4312. return (x << n) | (x >> (32 - n));
  4313. };
  4314. uint32_t h0 = 0x67452301;
  4315. uint32_t h1 = 0xEFCDAB89;
  4316. uint32_t h2 = 0x98BADCFE;
  4317. uint32_t h3 = 0x10325476;
  4318. uint32_t h4 = 0xC3D2E1F0;
  4319. // Pre-processing: adding padding bits
  4320. std::string msg = input;
  4321. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  4322. msg.push_back(static_cast<char>(0x80u));
  4323. while (msg.size() % 64 != 56) {
  4324. msg.push_back(0);
  4325. }
  4326. // Append original length in bits as 64-bit big-endian
  4327. for (int i = 56; i >= 0; i -= 8) {
  4328. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  4329. }
  4330. // Process each 512-bit chunk
  4331. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  4332. uint32_t w[80];
  4333. for (size_t i = 0; i < 16; i++) {
  4334. w[i] =
  4335. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  4336. << 24) |
  4337. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  4338. << 16) |
  4339. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  4340. << 8) |
  4341. (static_cast<uint32_t>(
  4342. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  4343. }
  4344. for (int i = 16; i < 80; i++) {
  4345. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  4346. }
  4347. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  4348. for (int i = 0; i < 80; i++) {
  4349. uint32_t f, k;
  4350. if (i < 20) {
  4351. f = (b & c) | ((~b) & d);
  4352. k = 0x5A827999;
  4353. } else if (i < 40) {
  4354. f = b ^ c ^ d;
  4355. k = 0x6ED9EBA1;
  4356. } else if (i < 60) {
  4357. f = (b & c) | (b & d) | (c & d);
  4358. k = 0x8F1BBCDC;
  4359. } else {
  4360. f = b ^ c ^ d;
  4361. k = 0xCA62C1D6;
  4362. }
  4363. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  4364. e = d;
  4365. d = c;
  4366. c = left_rotate(b, 30);
  4367. b = a;
  4368. a = temp;
  4369. }
  4370. h0 += a;
  4371. h1 += b;
  4372. h2 += c;
  4373. h3 += d;
  4374. h4 += e;
  4375. }
  4376. // Produce the final hash as a 20-byte binary string
  4377. std::string hash(20, '\0');
  4378. for (size_t i = 0; i < 4; i++) {
  4379. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  4380. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  4381. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  4382. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  4383. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  4384. }
  4385. return hash;
  4386. }
  4387. inline std::string websocket_accept_key(const std::string &client_key) {
  4388. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  4389. return base64_encode(sha1(client_key + magic));
  4390. }
  4391. inline bool is_websocket_upgrade(const Request &req) {
  4392. if (req.method != "GET") { return false; }
  4393. // Check Upgrade: websocket. RFC 9110 7.8 defines Upgrade as a comma-separated
  4394. // list of protocols and asks recipients to match each name
  4395. // case-insensitively, so look for the token rather than compare the whole
  4396. // field value.
  4397. if (!has_header_token(req.headers, "Upgrade", "websocket")) { return false; }
  4398. // Check Connection: Upgrade
  4399. if (!has_header_token(req.headers, "Connection", "upgrade")) { return false; }
  4400. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  4401. // RFC 6455 Section 4.2.1
  4402. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  4403. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  4404. return false;
  4405. }
  4406. static const std::string b64chars =
  4407. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4408. for (size_t i = 0; i < 22; i++) {
  4409. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  4410. }
  4411. // Check Sec-WebSocket-Version: 13
  4412. auto version = req.get_header_value("Sec-WebSocket-Version");
  4413. if (version != "13") { return false; }
  4414. return true;
  4415. }
  4416. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  4417. const char *data, size_t len, bool fin,
  4418. bool mask) {
  4419. // First byte: FIN + opcode
  4420. uint8_t header[2];
  4421. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  4422. (static_cast<uint8_t>(opcode) & 0x0F));
  4423. // Second byte: MASK + payload length
  4424. if (len < 126) {
  4425. header[1] = static_cast<uint8_t>(len);
  4426. if (mask) { header[1] |= 0x80; }
  4427. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4428. } else if (len <= 0xFFFF) {
  4429. header[1] = 126;
  4430. if (mask) { header[1] |= 0x80; }
  4431. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4432. uint8_t ext[2];
  4433. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4434. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4435. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4436. } else {
  4437. header[1] = 127;
  4438. if (mask) { header[1] |= 0x80; }
  4439. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4440. uint8_t ext[8];
  4441. for (int i = 7; i >= 0; i--) {
  4442. ext[7 - i] =
  4443. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4444. }
  4445. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4446. }
  4447. if (mask) {
  4448. // Generate random mask key
  4449. thread_local std::mt19937 rng(std::random_device{}());
  4450. uint8_t mask_key[4];
  4451. auto r = rng();
  4452. std::memcpy(mask_key, &r, 4);
  4453. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4454. // Write masked payload in chunks
  4455. const size_t chunk_size = 4096;
  4456. std::vector<char> buf((std::min)(len, chunk_size));
  4457. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4458. size_t n = (std::min)(chunk_size, len - offset);
  4459. for (size_t i = 0; i < n; i++) {
  4460. buf[i] =
  4461. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4462. }
  4463. if (strm.write(buf.data(), n) < 0) { return false; }
  4464. }
  4465. } else {
  4466. if (len > 0) {
  4467. if (strm.write(data, len) < 0) { return false; }
  4468. }
  4469. }
  4470. return true;
  4471. }
  4472. } // namespace detail
  4473. namespace ws {
  4474. namespace impl {
  4475. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4476. std::string &payload, bool &fin,
  4477. bool expect_masked, size_t max_len) {
  4478. // Read first 2 bytes
  4479. uint8_t header[2];
  4480. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4481. fin = (header[0] & 0x80) != 0;
  4482. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4483. if (header[0] & 0x70) { return false; }
  4484. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4485. bool masked = (header[1] & 0x80) != 0;
  4486. uint64_t payload_len = header[1] & 0x7F;
  4487. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4488. // MUST have a payload length of 125 bytes or less
  4489. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4490. if (is_control) {
  4491. if (!fin) { return false; }
  4492. if (payload_len > 125) { return false; }
  4493. }
  4494. if (masked != expect_masked) { return false; }
  4495. // Extended payload length
  4496. if (payload_len == 126) {
  4497. uint8_t ext[2];
  4498. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4499. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4500. } else if (payload_len == 127) {
  4501. uint8_t ext[8];
  4502. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4503. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4504. if (ext[0] & 0x80) { return false; }
  4505. payload_len = 0;
  4506. for (int i = 0; i < 8; i++) {
  4507. payload_len = (payload_len << 8) | ext[i];
  4508. }
  4509. }
  4510. if (payload_len > max_len) { return false; }
  4511. // Read mask key if present
  4512. uint8_t mask_key[4] = {0};
  4513. if (masked) {
  4514. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4515. }
  4516. // Read payload
  4517. payload.resize(static_cast<size_t>(payload_len));
  4518. if (payload_len > 0) {
  4519. size_t total_read = 0;
  4520. while (total_read < payload_len) {
  4521. auto n = strm.read(&payload[total_read],
  4522. static_cast<size_t>(payload_len - total_read));
  4523. if (n <= 0) { return false; }
  4524. total_read += static_cast<size_t>(n);
  4525. }
  4526. }
  4527. // Unmask if needed
  4528. if (masked) {
  4529. for (size_t i = 0; i < payload.size(); i++) {
  4530. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4531. }
  4532. }
  4533. return true;
  4534. }
  4535. } // namespace impl
  4536. } // namespace ws
  4537. namespace detail {
  4538. inline bool is_valid_path(const std::string &path) {
  4539. size_t level = 0;
  4540. size_t i = 0;
  4541. // Skip slash
  4542. while (i < path.size() && path[i] == '/') {
  4543. i++;
  4544. }
  4545. while (i < path.size()) {
  4546. // Read component
  4547. auto beg = i;
  4548. while (i < path.size() && path[i] != '/') {
  4549. if (path[i] == '\0') {
  4550. return false;
  4551. } else if (path[i] == '\\') {
  4552. return false;
  4553. }
  4554. i++;
  4555. }
  4556. auto len = i - beg;
  4557. assert(len > 0);
  4558. if (!path.compare(beg, len, ".")) {
  4559. ;
  4560. } else if (!path.compare(beg, len, "..")) {
  4561. if (level == 0) { return false; }
  4562. level--;
  4563. } else {
  4564. level++;
  4565. }
  4566. // Skip slash
  4567. while (i < path.size() && path[i] == '/') {
  4568. i++;
  4569. }
  4570. }
  4571. return true;
  4572. }
  4573. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4574. #if defined(_WIN32)
  4575. char buf[_MAX_PATH];
  4576. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4577. resolved = buf;
  4578. #elif defined(PATH_MAX)
  4579. char buf[PATH_MAX];
  4580. if (realpath(path, buf) == nullptr) { return false; }
  4581. resolved = buf;
  4582. #else
  4583. auto buf = realpath(path, nullptr);
  4584. auto guard = scope_exit([&]() { std::free(buf); });
  4585. if (buf == nullptr) { return false; }
  4586. resolved = buf;
  4587. #endif
  4588. return true;
  4589. }
  4590. inline bool is_path_within_base(const std::string &resolved_path,
  4591. const std::string &resolved_base) {
  4592. #if defined(_WIN32)
  4593. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4594. resolved_base.size()) == 0;
  4595. #else
  4596. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4597. resolved_base.size()) == 0;
  4598. #endif
  4599. }
  4600. inline FileStat::FileStat(const std::string &path) {
  4601. #if defined(_WIN32)
  4602. auto wpath = u8string_to_wstring(path.c_str());
  4603. ret_ = _wstat(wpath.c_str(), &st_);
  4604. #else
  4605. ret_ = stat(path.c_str(), &st_);
  4606. #endif
  4607. }
  4608. inline bool FileStat::is_file() const {
  4609. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4610. }
  4611. inline bool FileStat::is_dir() const {
  4612. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4613. }
  4614. inline time_t FileStat::mtime() const {
  4615. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4616. : static_cast<time_t>(-1);
  4617. }
  4618. inline size_t FileStat::size() const {
  4619. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4620. }
  4621. inline std::string encode_path(const std::string &s) {
  4622. std::string result;
  4623. result.reserve(s.size());
  4624. for (size_t i = 0; s[i]; i++) {
  4625. switch (s[i]) {
  4626. case ' ': result += "%20"; break;
  4627. case '+': result += "%2B"; break;
  4628. case '\r': result += "%0D"; break;
  4629. case '\n': result += "%0A"; break;
  4630. case '\'': result += "%27"; break;
  4631. case ',': result += "%2C"; break;
  4632. // case ':': result += "%3A"; break; // ok? probably...
  4633. case ';': result += "%3B"; break;
  4634. default:
  4635. auto c = static_cast<uint8_t>(s[i]);
  4636. if (c >= 0x80) {
  4637. result += '%';
  4638. char hex[4];
  4639. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4640. assert(len == 2);
  4641. result.append(hex, static_cast<size_t>(len));
  4642. } else {
  4643. result += s[i];
  4644. }
  4645. break;
  4646. }
  4647. }
  4648. return result;
  4649. }
  4650. inline std::string file_extension(const std::string &path) {
  4651. std::smatch m;
  4652. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4653. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4654. return std::string();
  4655. }
  4656. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4657. template <typename T>
  4658. inline bool parse_header(const char *beg, const char *end, T fn);
  4659. template <typename T>
  4660. inline bool parse_header(const char *beg, const char *end, T fn) {
  4661. // Skip trailing spaces and tabs.
  4662. while (beg < end && is_space_or_tab(end[-1])) {
  4663. end--;
  4664. }
  4665. auto p = beg;
  4666. while (p < end && *p != ':') {
  4667. p++;
  4668. }
  4669. auto name = std::string(beg, p);
  4670. if (!detail::fields::is_field_name(name)) { return false; }
  4671. if (p == end) { return false; }
  4672. auto key_end = p;
  4673. if (*p++ != ':') { return false; }
  4674. while (p < end && is_space_or_tab(*p)) {
  4675. p++;
  4676. }
  4677. if (p <= end) {
  4678. auto key_len = key_end - beg;
  4679. if (!key_len) { return false; }
  4680. auto key = std::string(beg, key_end);
  4681. auto val = std::string(p, end);
  4682. if (!detail::fields::is_field_value(val)) { return false; }
  4683. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4684. // percent-decoded by the recipient. Applications that need to interpret a
  4685. // value as a URI component should call httplib::decode_uri_component()
  4686. // (or decode_path_component()) explicitly.
  4687. fn(key, val);
  4688. return true;
  4689. }
  4690. return false;
  4691. }
  4692. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4693. const Headers &src_headers) {
  4694. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4695. // transfer coding is complete when a chunk with a chunk-size of zero is
  4696. // received, possibly followed by a trailer section, and finally terminated by
  4697. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4698. //
  4699. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4700. // doesn't care for the existence of the final CRLF. In other words, it seems
  4701. // to be ok whether the final CRLF exists or not in the chunked data.
  4702. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4703. //
  4704. // According to the reference code in RFC 9112, cpp-httplib now allows
  4705. // chunked transfer coding data without the final CRLF.
  4706. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4707. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4708. "transfer-encoding",
  4709. "content-length",
  4710. "host",
  4711. "authorization",
  4712. "www-authenticate",
  4713. "proxy-authenticate",
  4714. "proxy-authorization",
  4715. "cookie",
  4716. "set-cookie",
  4717. "cache-control",
  4718. "expect",
  4719. "max-forwards",
  4720. "pragma",
  4721. "range",
  4722. "te",
  4723. "age",
  4724. "expires",
  4725. "date",
  4726. "location",
  4727. "retry-after",
  4728. "vary",
  4729. "warning",
  4730. "content-encoding",
  4731. "content-type",
  4732. "content-range",
  4733. "trailer"};
  4734. case_ignore::unordered_set<std::string> declared_trailers;
  4735. auto trailer_header = get_combined_header_value(src_headers, "Trailer");
  4736. if (!trailer_header.empty()) {
  4737. // split() trims each token and skips empty ones, so the name arrives ready
  4738. // to look up.
  4739. split(trailer_header.data(), trailer_header.data() + trailer_header.size(),
  4740. ',', [&](const char *b, const char *e) {
  4741. std::string key(b, e);
  4742. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4743. declared_trailers.insert(key);
  4744. }
  4745. });
  4746. }
  4747. size_t trailer_header_count = 0;
  4748. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4749. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4750. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4751. constexpr auto line_terminator_len = 2;
  4752. auto line_beg = line_reader.ptr();
  4753. auto line_end =
  4754. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4755. if (!parse_header(line_beg, line_end,
  4756. [&](const std::string &key, const std::string &val) {
  4757. if (declared_trailers.find(key) !=
  4758. declared_trailers.end()) {
  4759. dest.emplace(key, val);
  4760. trailer_header_count++;
  4761. }
  4762. })) {
  4763. return false;
  4764. }
  4765. if (!line_reader.getline()) { return false; }
  4766. }
  4767. return true;
  4768. }
  4769. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4770. size_t right) {
  4771. while (b + left < e && is_space_or_tab(b[left])) {
  4772. left++;
  4773. }
  4774. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4775. right--;
  4776. }
  4777. return std::make_pair(left, right);
  4778. }
  4779. inline std::string trim_copy(const std::string &s) {
  4780. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4781. return s.substr(r.first, r.second - r.first);
  4782. }
  4783. inline std::string trim_double_quotes_copy(const std::string &s) {
  4784. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4785. return s.substr(1, s.size() - 2);
  4786. }
  4787. return s;
  4788. }
  4789. inline void
  4790. divide(const char *data, std::size_t size, char d,
  4791. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4792. fn) {
  4793. const auto it = std::find(data, data + size, d);
  4794. const auto found = static_cast<std::size_t>(it != data + size);
  4795. const auto lhs_data = data;
  4796. const auto lhs_size = static_cast<std::size_t>(it - data);
  4797. const auto rhs_data = it + found;
  4798. const auto rhs_size = size - lhs_size - found;
  4799. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4800. }
  4801. inline void
  4802. divide(const std::string &str, char d,
  4803. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4804. fn) {
  4805. divide(str.data(), str.size(), d, std::move(fn));
  4806. }
  4807. inline void split(const char *b, const char *e, char d,
  4808. std::function<void(const char *, const char *)> fn) {
  4809. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4810. }
  4811. inline void split(const char *b, const char *e, char d, size_t m,
  4812. std::function<void(const char *, const char *)> fn) {
  4813. size_t i = 0;
  4814. size_t beg = 0;
  4815. size_t count = 1;
  4816. while (e ? (b + i < e) : (b[i] != '\0')) {
  4817. if (b[i] == d && count < m) {
  4818. auto r = trim(b, e, beg, i);
  4819. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4820. beg = i + 1;
  4821. count++;
  4822. }
  4823. i++;
  4824. }
  4825. if (i) {
  4826. auto r = trim(b, e, beg, i);
  4827. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4828. }
  4829. }
  4830. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4831. std::function<bool(const char *, const char *)> fn) {
  4832. size_t i = 0;
  4833. size_t beg = 0;
  4834. size_t count = 1;
  4835. while (e ? (b + i < e) : (b[i] != '\0')) {
  4836. if (b[i] == d && count < m) {
  4837. auto r = trim(b, e, beg, i);
  4838. if (r.first < r.second) {
  4839. auto found = fn(&b[r.first], &b[r.second]);
  4840. if (found) { return true; }
  4841. }
  4842. beg = i + 1;
  4843. count++;
  4844. }
  4845. i++;
  4846. }
  4847. if (i) {
  4848. auto r = trim(b, e, beg, i);
  4849. if (r.first < r.second) {
  4850. auto found = fn(&b[r.first], &b[r.second]);
  4851. if (found) { return true; }
  4852. }
  4853. }
  4854. return false;
  4855. }
  4856. inline bool split_find(const char *b, const char *e, char d,
  4857. std::function<bool(const char *, const char *)> fn) {
  4858. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4859. std::move(fn));
  4860. }
  4861. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4862. size_t fixed_buffer_size)
  4863. : strm_(strm), fixed_buffer_(fixed_buffer),
  4864. fixed_buffer_size_(fixed_buffer_size) {}
  4865. inline const char *stream_line_reader::ptr() const {
  4866. if (growable_buffer_.empty()) {
  4867. return fixed_buffer_;
  4868. } else {
  4869. return growable_buffer_.data();
  4870. }
  4871. }
  4872. inline size_t stream_line_reader::size() const {
  4873. if (growable_buffer_.empty()) {
  4874. return fixed_buffer_used_size_;
  4875. } else {
  4876. return growable_buffer_.size();
  4877. }
  4878. }
  4879. inline bool stream_line_reader::end_with_crlf() const {
  4880. auto end = ptr() + size();
  4881. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4882. }
  4883. inline bool stream_line_reader::getline() {
  4884. fixed_buffer_used_size_ = 0;
  4885. growable_buffer_.clear();
  4886. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4887. char prev_byte = 0;
  4888. #endif
  4889. for (size_t i = 0;; i++) {
  4890. // Fast path: whatever the stream has already buffered can be scanned for
  4891. // the terminator in one pass. Asking for a byte at a time costs a virtual
  4892. // call, a bounds check and a one-byte copy per character of the request.
  4893. size_t buffered_size = 0;
  4894. if (auto buffered = strm_.buffered_data(buffered_size)) {
  4895. auto take = buffered_size;
  4896. auto terminated = false;
  4897. for (size_t at = 0; at < buffered_size;) {
  4898. auto nl = static_cast<const char *>(
  4899. memchr(buffered + at, '\n', buffered_size - at));
  4900. if (!nl) { break; }
  4901. auto pos = static_cast<size_t>(nl - buffered);
  4902. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4903. take = pos + 1;
  4904. terminated = true;
  4905. break;
  4906. #else
  4907. // A bare LF does not end the line; keep looking for CRLF. The CR may
  4908. // be the last byte of an earlier chunk, hence prev_byte.
  4909. if ((pos > 0 ? buffered[pos - 1] : prev_byte) == '\r') {
  4910. take = pos + 1;
  4911. terminated = true;
  4912. break;
  4913. }
  4914. at = pos + 1;
  4915. #endif
  4916. }
  4917. if (size() + take > CPPHTTPLIB_MAX_LINE_LENGTH) { return false; }
  4918. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4919. prev_byte = buffered[take - 1];
  4920. #endif
  4921. append(buffered, take);
  4922. strm_.consume_buffered(take);
  4923. i += take;
  4924. if (terminated) { return true; }
  4925. continue;
  4926. }
  4927. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4928. // Treat exceptionally long lines as an error to
  4929. // prevent infinite loops/memory exhaustion
  4930. return false;
  4931. }
  4932. char byte;
  4933. auto n = strm_.read(&byte, 1);
  4934. if (n < 0) {
  4935. return false;
  4936. } else if (n == 0) {
  4937. if (i == 0) {
  4938. return false;
  4939. } else {
  4940. break;
  4941. }
  4942. }
  4943. append(byte);
  4944. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4945. if (byte == '\n') { break; }
  4946. #else
  4947. if (prev_byte == '\r' && byte == '\n') { break; }
  4948. prev_byte = byte;
  4949. #endif
  4950. }
  4951. return true;
  4952. }
  4953. inline void stream_line_reader::append(char c) { append(&c, 1); }
  4954. inline void stream_line_reader::append(const char *data, size_t size) {
  4955. // Once the line has outgrown the fixed buffer everything must keep going to
  4956. // the growable one, even if a later chunk would have fit. Without the
  4957. // emptiness check a short append after a long one would land in the fixed
  4958. // buffer, which ptr() and size() no longer look at, and be lost.
  4959. if (growable_buffer_.empty() &&
  4960. fixed_buffer_used_size_ + size < fixed_buffer_size_) {
  4961. memcpy(fixed_buffer_ + fixed_buffer_used_size_, data, size);
  4962. fixed_buffer_used_size_ += size;
  4963. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4964. } else {
  4965. // Unlike the per-character overload, this can be the very first append of
  4966. // the line, so the fixed buffer may hold nothing and carry no terminator
  4967. // yet. assign() takes an explicit length and does not need one.
  4968. if (growable_buffer_.empty()) {
  4969. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4970. }
  4971. growable_buffer_.append(data, size);
  4972. }
  4973. }
  4974. inline mmap::mmap(const char *path) { open(path); }
  4975. inline mmap::~mmap() { close(); }
  4976. inline bool mmap::open(const char *path) {
  4977. close();
  4978. #if defined(_WIN32)
  4979. auto wpath = u8string_to_wstring(path);
  4980. if (wpath.empty()) { return false; }
  4981. hFile_ =
  4982. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4983. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4984. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4985. LARGE_INTEGER size{};
  4986. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4987. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4988. // See:
  4989. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4990. if (static_cast<ULONGLONG>(size.QuadPart) >
  4991. (std::numeric_limits<decltype(size_)>::max)()) {
  4992. // `size_t` might be 32-bits, on 32-bits Windows.
  4993. return false;
  4994. }
  4995. size_ = static_cast<size_t>(size.QuadPart);
  4996. hMapping_ =
  4997. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4998. // Special treatment for an empty file...
  4999. if (hMapping_ == NULL && size_ == 0) {
  5000. close();
  5001. is_open_empty_file = true;
  5002. return true;
  5003. }
  5004. if (hMapping_ == NULL) {
  5005. close();
  5006. return false;
  5007. }
  5008. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  5009. if (addr_ == nullptr) {
  5010. close();
  5011. return false;
  5012. }
  5013. #else
  5014. fd_ = ::open(path, O_RDONLY);
  5015. if (fd_ == -1) { return false; }
  5016. struct stat sb;
  5017. if (fstat(fd_, &sb) == -1) {
  5018. close();
  5019. return false;
  5020. }
  5021. size_ = static_cast<size_t>(sb.st_size);
  5022. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  5023. // Special treatment for an empty file...
  5024. if (addr_ == MAP_FAILED && size_ == 0) {
  5025. close();
  5026. is_open_empty_file = true;
  5027. return false;
  5028. }
  5029. if (addr_ == MAP_FAILED) {
  5030. // Clear the sentinel before `close()`, since `is_open()` only checks
  5031. // `addr_` against nullptr and `munmap()` must not be called with it.
  5032. addr_ = nullptr;
  5033. close();
  5034. return false;
  5035. }
  5036. #endif
  5037. return true;
  5038. }
  5039. inline bool mmap::is_open() const {
  5040. return is_open_empty_file ? true : addr_ != nullptr;
  5041. }
  5042. inline size_t mmap::size() const { return size_; }
  5043. inline const char *mmap::data() const {
  5044. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  5045. }
  5046. inline void mmap::close() {
  5047. #if defined(_WIN32)
  5048. if (addr_) {
  5049. ::UnmapViewOfFile(addr_);
  5050. addr_ = nullptr;
  5051. }
  5052. if (hMapping_) {
  5053. ::CloseHandle(hMapping_);
  5054. hMapping_ = NULL;
  5055. }
  5056. if (hFile_ != INVALID_HANDLE_VALUE) {
  5057. ::CloseHandle(hFile_);
  5058. hFile_ = INVALID_HANDLE_VALUE;
  5059. }
  5060. is_open_empty_file = false;
  5061. #else
  5062. if (addr_ != nullptr) {
  5063. munmap(addr_, size_);
  5064. addr_ = nullptr;
  5065. }
  5066. if (fd_ != -1) {
  5067. ::close(fd_);
  5068. fd_ = -1;
  5069. }
  5070. #endif
  5071. size_ = 0;
  5072. }
  5073. inline int close_socket(socket_t sock) noexcept {
  5074. #ifdef _WIN32
  5075. return closesocket(sock);
  5076. #else
  5077. return close(sock);
  5078. #endif
  5079. }
  5080. template <typename T> inline ssize_t handle_EINTR(T fn) {
  5081. ssize_t res = 0;
  5082. while (true) {
  5083. res = fn();
  5084. if (res < 0 && errno == EINTR) {
  5085. std::this_thread::sleep_for(std::chrono::microseconds{1});
  5086. continue;
  5087. }
  5088. break;
  5089. }
  5090. return res;
  5091. }
  5092. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  5093. return handle_EINTR([&]() {
  5094. return recv(sock,
  5095. #ifdef _WIN32
  5096. static_cast<char *>(ptr), static_cast<int>(size),
  5097. #else
  5098. ptr, size,
  5099. #endif
  5100. flags);
  5101. });
  5102. }
  5103. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  5104. int flags) {
  5105. return handle_EINTR([&]() {
  5106. return send(sock,
  5107. #ifdef _WIN32
  5108. static_cast<const char *>(ptr), static_cast<int>(size),
  5109. #else
  5110. ptr, size,
  5111. #endif
  5112. flags);
  5113. });
  5114. }
  5115. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  5116. #ifdef _WIN32
  5117. return ::WSAPoll(fds, nfds, timeout);
  5118. #else
  5119. return ::poll(fds, nfds, timeout);
  5120. #endif
  5121. }
  5122. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  5123. time_t usec) {
  5124. struct pollfd pfd;
  5125. pfd.fd = sock;
  5126. pfd.events = events;
  5127. pfd.revents = 0;
  5128. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  5129. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  5130. }
  5131. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  5132. return select_impl(sock, POLLIN, sec, usec);
  5133. }
  5134. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  5135. return select_impl(sock, POLLOUT, sec, usec);
  5136. }
  5137. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  5138. time_t usec) {
  5139. struct pollfd pfd_read;
  5140. pfd_read.fd = sock;
  5141. pfd_read.events = POLLIN | POLLOUT;
  5142. pfd_read.revents = 0;
  5143. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  5144. auto poll_res =
  5145. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  5146. if (poll_res == 0) { return Error::ConnectionTimeout; }
  5147. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  5148. auto error = 0;
  5149. socklen_t len = sizeof(error);
  5150. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  5151. reinterpret_cast<char *>(&error), &len);
  5152. auto successful = res >= 0 && !error;
  5153. return successful ? Error::Success : Error::Connection;
  5154. }
  5155. return Error::Connection;
  5156. }
  5157. inline bool is_socket_alive(socket_t sock) {
  5158. const auto val = detail::select_read(sock, 0, 0);
  5159. if (val == 0) {
  5160. return true;
  5161. } else if (val < 0 && errno == EBADF) {
  5162. return false;
  5163. }
  5164. char buf[1];
  5165. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  5166. }
  5167. class SocketStream final : public Stream {
  5168. public:
  5169. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5170. time_t write_timeout_sec, time_t write_timeout_usec,
  5171. time_t max_timeout_msec = 0,
  5172. std::chrono::time_point<std::chrono::steady_clock> start_time =
  5173. (std::chrono::steady_clock::time_point::min)());
  5174. ~SocketStream() override;
  5175. bool is_readable() const override;
  5176. bool wait_readable() const override;
  5177. bool wait_writable() const override;
  5178. bool is_peer_alive() const override;
  5179. ssize_t read(char *ptr, size_t size) override;
  5180. ssize_t write(const char *ptr, size_t size) override;
  5181. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  5182. void get_local_ip_and_port(std::string &ip, int &port) const override;
  5183. socket_t socket() const override;
  5184. time_t duration() const override;
  5185. void set_read_timeout(time_t sec, time_t usec = 0) override;
  5186. const char *buffered_data(size_t &size) const override;
  5187. void consume_buffered(size_t size) override;
  5188. // The caller has just seen this socket become readable. Lets the next read
  5189. // skip its own readiness wait, which would otherwise ask the kernel a
  5190. // question that was answered a moment ago. Consumed by that read.
  5191. void set_readable_hint() { readable_hint_ = true; }
  5192. private:
  5193. bool ensure_readable();
  5194. socket_t sock_;
  5195. time_t read_timeout_sec_;
  5196. time_t read_timeout_usec_;
  5197. time_t write_timeout_sec_;
  5198. time_t write_timeout_usec_;
  5199. time_t max_timeout_msec_;
  5200. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  5201. std::vector<char> read_buff_;
  5202. size_t read_buff_off_ = 0;
  5203. size_t read_buff_content_size_ = 0;
  5204. bool readable_hint_ = false;
  5205. static const size_t read_buff_size_ = 1024l * 4;
  5206. };
  5207. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5208. time_t keep_alive_timeout_sec) {
  5209. using namespace std::chrono;
  5210. const auto interval_usec =
  5211. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  5212. // Avoid expensive `steady_clock::now()` call for the first time
  5213. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  5214. const auto start = steady_clock::now() - microseconds{interval_usec};
  5215. const auto timeout = seconds{keep_alive_timeout_sec};
  5216. while (true) {
  5217. if (svr_sock == INVALID_SOCKET) {
  5218. break; // Server socket is closed
  5219. }
  5220. auto val = select_read(sock, 0, interval_usec);
  5221. if (val < 0) {
  5222. break; // Ssocket error
  5223. } else if (val == 0) {
  5224. if (steady_clock::now() - start > timeout) {
  5225. break; // Timeout
  5226. }
  5227. } else {
  5228. return true; // Ready for read
  5229. }
  5230. }
  5231. return false;
  5232. }
  5233. template <typename T>
  5234. inline bool
  5235. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5236. size_t keep_alive_max_count,
  5237. time_t keep_alive_timeout_sec, T callback) {
  5238. assert(keep_alive_max_count > 0);
  5239. auto ret = false;
  5240. auto count = keep_alive_max_count;
  5241. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  5242. auto close_connection = count == 1;
  5243. auto connection_closed = false;
  5244. ret = callback(close_connection, connection_closed);
  5245. if (!ret || connection_closed) { break; }
  5246. count--;
  5247. }
  5248. return ret;
  5249. }
  5250. template <typename T>
  5251. inline bool
  5252. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5253. size_t keep_alive_max_count,
  5254. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  5255. time_t read_timeout_usec, time_t write_timeout_sec,
  5256. time_t write_timeout_usec, T callback) {
  5257. return process_server_socket_core(
  5258. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  5259. [&](bool close_connection, bool &connection_closed) {
  5260. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5261. write_timeout_sec, write_timeout_usec);
  5262. // process_server_socket_core() only gets here once keep_alive() has
  5263. // seen the socket go readable.
  5264. strm.set_readable_hint();
  5265. return callback(strm, close_connection, connection_closed);
  5266. });
  5267. }
  5268. inline bool process_client_socket(
  5269. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5270. time_t write_timeout_sec, time_t write_timeout_usec,
  5271. time_t max_timeout_msec,
  5272. std::chrono::time_point<std::chrono::steady_clock> start_time,
  5273. std::function<bool(Stream &)> callback) {
  5274. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5275. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  5276. start_time);
  5277. return callback(strm);
  5278. }
  5279. inline int shutdown_socket(socket_t sock) noexcept {
  5280. #ifdef _WIN32
  5281. return shutdown(sock, SD_BOTH);
  5282. #else
  5283. return shutdown(sock, SHUT_RDWR);
  5284. #endif
  5285. }
  5286. // Half-closes the write side and drains any in-flight/queued bytes before
  5287. // the final shutdown+close. Closing with unread data in the receive queue
  5288. // (or bytes arriving after the receive side is closed) makes the stack send
  5289. // an abortive RST instead of a graceful FIN, which can make the peer see the
  5290. // response as a failed read even though it was fully written.
  5291. inline void drain_and_close_socket(socket_t sock) noexcept {
  5292. #ifdef _WIN32
  5293. shutdown(sock, SD_SEND);
  5294. #else
  5295. shutdown(sock, SHUT_WR);
  5296. #endif
  5297. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5298. size_t total = 0;
  5299. const auto deadline = std::chrono::steady_clock::now() +
  5300. std::chrono::milliseconds(100); // bound #1
  5301. while (total < size_t(1024u * 1024u)) { // bound #2
  5302. const auto remaining =
  5303. std::chrono::duration_cast<std::chrono::microseconds>(
  5304. deadline - std::chrono::steady_clock::now())
  5305. .count();
  5306. if (remaining <= 0) { break; }
  5307. if (select_read(sock, 0, static_cast<time_t>(remaining)) <= 0) { break; }
  5308. const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  5309. if (n <= 0) { break; }
  5310. total += static_cast<size_t>(n);
  5311. }
  5312. shutdown_socket(sock);
  5313. close_socket(sock);
  5314. }
  5315. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  5316. if (s.size() > 1 && s[0] == '\0') {
  5317. auto ret = s;
  5318. ret[0] = '@';
  5319. return ret;
  5320. }
  5321. return s;
  5322. }
  5323. inline std::string
  5324. unescape_abstract_namespace_unix_domain(const std::string &s) {
  5325. if (s.size() > 1 && s[0] == '@') {
  5326. auto ret = s;
  5327. ret[0] = '\0';
  5328. return ret;
  5329. }
  5330. return s;
  5331. }
  5332. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  5333. const struct addrinfo *hints,
  5334. struct addrinfo **res, time_t timeout_sec) {
  5335. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  5336. if (timeout_sec <= 0) {
  5337. // No timeout specified, use standard getaddrinfo
  5338. return getaddrinfo(node, service, hints, res);
  5339. }
  5340. #ifdef _WIN32
  5341. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  5342. OVERLAPPED overlapped = {};
  5343. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  5344. if (!event) { return EAI_FAIL; }
  5345. overlapped.hEvent = event;
  5346. PADDRINFOEXW result_addrinfo = nullptr;
  5347. HANDLE cancel_handle = nullptr;
  5348. ADDRINFOEXW hints_ex = {};
  5349. if (hints) {
  5350. hints_ex.ai_flags = hints->ai_flags;
  5351. hints_ex.ai_family = hints->ai_family;
  5352. hints_ex.ai_socktype = hints->ai_socktype;
  5353. hints_ex.ai_protocol = hints->ai_protocol;
  5354. }
  5355. auto wnode = u8string_to_wstring(node);
  5356. auto wservice = u8string_to_wstring(service);
  5357. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  5358. hints ? &hints_ex : nullptr, &result_addrinfo,
  5359. nullptr, &overlapped, nullptr, &cancel_handle);
  5360. if (ret == WSA_IO_PENDING) {
  5361. auto wait_result =
  5362. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  5363. if (wait_result == WAIT_TIMEOUT) {
  5364. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  5365. ::CloseHandle(event);
  5366. return EAI_AGAIN;
  5367. }
  5368. DWORD bytes_returned;
  5369. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  5370. &bytes_returned, FALSE)) {
  5371. ::CloseHandle(event);
  5372. return ::WSAGetLastError();
  5373. }
  5374. }
  5375. ::CloseHandle(event);
  5376. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  5377. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  5378. return 0;
  5379. }
  5380. return ret;
  5381. #elif TARGET_OS_MAC && defined(__clang__)
  5382. if (!node) { return EAI_NONAME; }
  5383. // macOS implementation using CFHost API for asynchronous DNS resolution
  5384. CFStringRef hostname_ref = CFStringCreateWithCString(
  5385. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  5386. if (!hostname_ref) { return EAI_MEMORY; }
  5387. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  5388. CFRelease(hostname_ref);
  5389. if (!host_ref) { return EAI_MEMORY; }
  5390. // Set up context for callback
  5391. struct CFHostContext {
  5392. bool completed = false;
  5393. bool success = false;
  5394. CFArrayRef addresses = nullptr;
  5395. std::mutex mutex;
  5396. std::condition_variable cv;
  5397. } context;
  5398. CFHostClientContext client_context;
  5399. memset(&client_context, 0, sizeof(client_context));
  5400. client_context.info = &context;
  5401. // Set callback
  5402. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  5403. const CFStreamError *error, void *info) {
  5404. auto ctx = static_cast<CFHostContext *>(info);
  5405. std::lock_guard<std::mutex> lock(ctx->mutex);
  5406. if (error && error->error != 0) {
  5407. ctx->success = false;
  5408. } else {
  5409. Boolean hasBeenResolved;
  5410. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  5411. if (ctx->addresses && hasBeenResolved) {
  5412. CFRetain(ctx->addresses);
  5413. ctx->success = true;
  5414. } else {
  5415. ctx->success = false;
  5416. }
  5417. }
  5418. ctx->completed = true;
  5419. ctx->cv.notify_one();
  5420. };
  5421. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  5422. CFRelease(host_ref);
  5423. return EAI_SYSTEM;
  5424. }
  5425. // Schedule on run loop
  5426. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  5427. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5428. // Start resolution
  5429. CFStreamError stream_error;
  5430. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  5431. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5432. CFRelease(host_ref);
  5433. return EAI_FAIL;
  5434. }
  5435. // Wait for completion with timeout
  5436. auto timeout_time =
  5437. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  5438. bool timed_out = false;
  5439. {
  5440. std::unique_lock<std::mutex> lock(context.mutex);
  5441. while (!context.completed) {
  5442. auto now = std::chrono::steady_clock::now();
  5443. if (now >= timeout_time) {
  5444. timed_out = true;
  5445. break;
  5446. }
  5447. // Run the runloop for a short time
  5448. lock.unlock();
  5449. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  5450. lock.lock();
  5451. }
  5452. }
  5453. // Clean up
  5454. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5455. CFHostSetClient(host_ref, nullptr, nullptr);
  5456. if (timed_out || !context.completed) {
  5457. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  5458. CFRelease(host_ref);
  5459. return EAI_AGAIN;
  5460. }
  5461. if (!context.success || !context.addresses) {
  5462. CFRelease(host_ref);
  5463. return EAI_NODATA;
  5464. }
  5465. // Convert CFArray to addrinfo
  5466. CFIndex count = CFArrayGetCount(context.addresses);
  5467. if (count == 0) {
  5468. CFRelease(context.addresses);
  5469. CFRelease(host_ref);
  5470. return EAI_NODATA;
  5471. }
  5472. struct addrinfo *result_addrinfo = nullptr;
  5473. struct addrinfo **current = &result_addrinfo;
  5474. for (CFIndex i = 0; i < count; i++) {
  5475. CFDataRef addr_data =
  5476. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  5477. if (!addr_data) continue;
  5478. const struct sockaddr *sockaddr_ptr =
  5479. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  5480. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  5481. // Allocate addrinfo structure
  5482. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  5483. if (!*current) {
  5484. freeaddrinfo(result_addrinfo);
  5485. CFRelease(context.addresses);
  5486. CFRelease(host_ref);
  5487. return EAI_MEMORY;
  5488. }
  5489. memset(*current, 0, sizeof(struct addrinfo));
  5490. // Set up addrinfo fields
  5491. (*current)->ai_family = sockaddr_ptr->sa_family;
  5492. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  5493. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  5494. (*current)->ai_addrlen = sockaddr_len;
  5495. // Copy sockaddr
  5496. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  5497. if (!(*current)->ai_addr) {
  5498. freeaddrinfo(result_addrinfo);
  5499. CFRelease(context.addresses);
  5500. CFRelease(host_ref);
  5501. return EAI_MEMORY;
  5502. }
  5503. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  5504. // Set port if service is specified
  5505. if (service && *service) {
  5506. int port = 0;
  5507. if (parse_port(service, strlen(service), port)) {
  5508. if (sockaddr_ptr->sa_family == AF_INET) {
  5509. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5510. ->sin_port = htons(static_cast<uint16_t>(port));
  5511. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5512. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5513. ->sin6_port = htons(static_cast<uint16_t>(port));
  5514. }
  5515. }
  5516. }
  5517. current = &((*current)->ai_next);
  5518. }
  5519. CFRelease(context.addresses);
  5520. CFRelease(host_ref);
  5521. *res = result_addrinfo;
  5522. return 0;
  5523. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5524. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5525. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5526. // the resolver worker still references the stack-local gaicb. The cancel
  5527. // path therefore waits (gai_suspend with no timeout) for the worker to
  5528. // actually finish before letting the stack frame go. The trade-off is that
  5529. // a wedged DNS server can hold this thread for the system resolver timeout
  5530. // (~30s by default) past the caller's connection timeout.
  5531. struct gaicb request {};
  5532. struct gaicb *requests[1] = {&request};
  5533. struct sigevent sevp {};
  5534. struct timespec timeout {
  5535. timeout_sec, 0
  5536. };
  5537. request.ar_name = node;
  5538. request.ar_service = service;
  5539. request.ar_request = hints;
  5540. sevp.sigev_notify = SIGEV_NONE;
  5541. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5542. if (rc != 0) { return rc; }
  5543. auto cleanup = scope_exit([&] {
  5544. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5545. });
  5546. int wait_result = gai_suspend(requests, 1, &timeout);
  5547. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5548. int gai_result = gai_error(&request);
  5549. if (gai_result == 0) {
  5550. *res = request.ar_result;
  5551. request.ar_result = nullptr;
  5552. return 0;
  5553. }
  5554. return gai_result;
  5555. }
  5556. gai_cancel(&request);
  5557. while (gai_error(&request) == EAI_INPROGRESS) {
  5558. gai_suspend(requests, 1, nullptr);
  5559. }
  5560. return wait_result;
  5561. #else
  5562. // Fallback implementation using thread-based timeout for other Unix systems.
  5563. struct GetAddrInfoState {
  5564. ~GetAddrInfoState() {
  5565. if (info) { freeaddrinfo(info); }
  5566. }
  5567. std::mutex mutex;
  5568. std::condition_variable result_cv;
  5569. bool completed = false;
  5570. int result = EAI_SYSTEM;
  5571. std::string node;
  5572. std::string service;
  5573. struct addrinfo hints;
  5574. struct addrinfo *info = nullptr;
  5575. };
  5576. // Allocate on the heap, so the resolver thread can keep using the data.
  5577. auto state = std::make_shared<GetAddrInfoState>();
  5578. if (node) { state->node = node; }
  5579. state->service = service;
  5580. state->hints = *hints;
  5581. std::thread resolve_thread([state]() {
  5582. auto thread_result =
  5583. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5584. &state->info);
  5585. std::lock_guard<std::mutex> lock(state->mutex);
  5586. state->result = thread_result;
  5587. state->completed = true;
  5588. state->result_cv.notify_one();
  5589. });
  5590. // Wait for completion or timeout
  5591. std::unique_lock<std::mutex> lock(state->mutex);
  5592. auto finished =
  5593. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5594. [&] { return state->completed; });
  5595. if (finished) {
  5596. // Operation completed within timeout
  5597. resolve_thread.join();
  5598. *res = state->info;
  5599. state->info = nullptr; // Pass ownership to caller
  5600. return state->result;
  5601. } else {
  5602. // Timeout occurred
  5603. resolve_thread.detach(); // Let the thread finish in background
  5604. return EAI_AGAIN; // Return timeout error
  5605. }
  5606. #endif
  5607. #else
  5608. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5609. return getaddrinfo(node, service, hints, res);
  5610. #endif
  5611. }
  5612. template <typename BindOrConnect>
  5613. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5614. int address_family, int socket_flags, bool tcp_nodelay,
  5615. bool ipv6_v6only, SocketOptions socket_options,
  5616. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5617. // Get address info
  5618. const char *node = nullptr;
  5619. struct addrinfo hints;
  5620. struct addrinfo *result;
  5621. memset(&hints, 0, sizeof(struct addrinfo));
  5622. hints.ai_socktype = SOCK_STREAM;
  5623. hints.ai_protocol = IPPROTO_IP;
  5624. if (!ip.empty()) {
  5625. node = ip.c_str();
  5626. // Ask getaddrinfo to convert IP in c-string to address
  5627. hints.ai_family = AF_UNSPEC;
  5628. hints.ai_flags = AI_NUMERICHOST;
  5629. } else {
  5630. if (!host.empty()) { node = host.c_str(); }
  5631. hints.ai_family = address_family;
  5632. hints.ai_flags = socket_flags;
  5633. }
  5634. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5635. if (hints.ai_family == AF_UNIX) {
  5636. const auto addrlen = host.length();
  5637. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5638. #ifdef SOCK_CLOEXEC
  5639. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5640. hints.ai_protocol);
  5641. #else
  5642. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5643. #endif
  5644. if (sock != INVALID_SOCKET) {
  5645. sockaddr_un addr{};
  5646. addr.sun_family = AF_UNIX;
  5647. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5648. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5649. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5650. hints.ai_addrlen = static_cast<socklen_t>(
  5651. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5652. #ifndef SOCK_CLOEXEC
  5653. #ifndef _WIN32
  5654. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5655. #endif
  5656. #endif
  5657. if (socket_options) { socket_options(sock); }
  5658. #ifdef _WIN32
  5659. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5660. // remove the option.
  5661. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5662. #endif
  5663. bool dummy;
  5664. if (!bind_or_connect(sock, hints, dummy)) {
  5665. close_socket(sock);
  5666. sock = INVALID_SOCKET;
  5667. }
  5668. }
  5669. return sock;
  5670. }
  5671. #endif
  5672. auto service = std::to_string(port);
  5673. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5674. timeout_sec)) {
  5675. #if defined __linux__ && !defined __ANDROID__
  5676. res_init();
  5677. #endif
  5678. return INVALID_SOCKET;
  5679. }
  5680. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5681. for (auto rp = result; rp; rp = rp->ai_next) {
  5682. // Create a socket
  5683. #ifdef _WIN32
  5684. auto sock =
  5685. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5686. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5687. /**
  5688. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5689. * and above the socket creation fails on older Windows Systems.
  5690. *
  5691. * Let's try to create a socket the old way in this case.
  5692. *
  5693. * Reference:
  5694. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5695. *
  5696. * WSA_FLAG_NO_HANDLE_INHERIT:
  5697. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5698. * SP1, and later
  5699. *
  5700. */
  5701. if (sock == INVALID_SOCKET) {
  5702. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5703. }
  5704. #else
  5705. #ifdef SOCK_CLOEXEC
  5706. auto sock =
  5707. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5708. #else
  5709. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5710. #endif
  5711. #endif
  5712. if (sock == INVALID_SOCKET) { continue; }
  5713. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5714. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5715. close_socket(sock);
  5716. continue;
  5717. }
  5718. #endif
  5719. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5720. if (rp->ai_family == AF_INET6) {
  5721. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5722. }
  5723. if (socket_options) { socket_options(sock); }
  5724. // bind or connect
  5725. auto quit = false;
  5726. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5727. close_socket(sock);
  5728. if (quit) { break; }
  5729. }
  5730. return INVALID_SOCKET;
  5731. }
  5732. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5733. #ifdef _WIN32
  5734. auto flags = nonblocking ? 1UL : 0UL;
  5735. ioctlsocket(sock, FIONBIO, &flags);
  5736. #else
  5737. auto flags = fcntl(sock, F_GETFL, 0);
  5738. fcntl(sock, F_SETFL,
  5739. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5740. #endif
  5741. }
  5742. inline bool is_connection_error() {
  5743. #ifdef _WIN32
  5744. return WSAGetLastError() != WSAEWOULDBLOCK;
  5745. #else
  5746. return errno != EINPROGRESS;
  5747. #endif
  5748. }
  5749. // accept() failed because the process or the network stack is temporarily out
  5750. // of resources. The listening socket is still usable, so back off briefly and
  5751. // try again.
  5752. inline bool is_accept_resource_error() {
  5753. #ifdef _WIN32
  5754. auto err = WSAGetLastError();
  5755. return err == WSAEMFILE || err == WSAENOBUFS;
  5756. #else
  5757. auto err = errno;
  5758. return err == EMFILE || err == ENFILE || err == ENOBUFS || err == ENOMEM;
  5759. #endif
  5760. }
  5761. // accept() failed for a reason that says nothing about the listening socket:
  5762. // the pending connection went away before it could be accepted, or the call
  5763. // was interrupted. Retry immediately. WSAAccept()'s own documentation omits
  5764. // WSAECONNRESET, but the accept() it wraps reports an aborted pending
  5765. // connection that way.
  5766. inline bool is_accept_transient_error() {
  5767. #ifdef _WIN32
  5768. auto err = WSAGetLastError();
  5769. return err == WSAEINTR || err == WSAEWOULDBLOCK || err == WSAECONNRESET ||
  5770. err == WSAECONNABORTED;
  5771. #else
  5772. auto err = errno;
  5773. return err == EINTR || err == EAGAIN || err == EWOULDBLOCK ||
  5774. err == ECONNABORTED;
  5775. #endif
  5776. }
  5777. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5778. struct addrinfo hints;
  5779. struct addrinfo *result;
  5780. memset(&hints, 0, sizeof(struct addrinfo));
  5781. hints.ai_family = AF_UNSPEC;
  5782. hints.ai_socktype = SOCK_STREAM;
  5783. hints.ai_protocol = 0;
  5784. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5785. return false;
  5786. }
  5787. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5788. auto ret = false;
  5789. for (auto rp = result; rp; rp = rp->ai_next) {
  5790. const auto &ai = *rp;
  5791. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5792. ret = true;
  5793. break;
  5794. }
  5795. }
  5796. return ret;
  5797. }
  5798. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5799. #define USE_IF2IP
  5800. #endif
  5801. #ifdef USE_IF2IP
  5802. inline std::string if2ip(int address_family, const std::string &ifn) {
  5803. struct ifaddrs *ifap;
  5804. getifaddrs(&ifap);
  5805. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5806. std::string addr_candidate;
  5807. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5808. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5809. (AF_UNSPEC == address_family ||
  5810. ifa->ifa_addr->sa_family == address_family)) {
  5811. if (ifa->ifa_addr->sa_family == AF_INET) {
  5812. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5813. char buf[INET_ADDRSTRLEN];
  5814. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5815. return std::string(buf, INET_ADDRSTRLEN);
  5816. }
  5817. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5818. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5819. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5820. char buf[INET6_ADDRSTRLEN] = {};
  5821. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5822. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5823. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5824. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5825. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5826. } else {
  5827. return std::string(buf, INET6_ADDRSTRLEN);
  5828. }
  5829. }
  5830. }
  5831. }
  5832. }
  5833. }
  5834. return addr_candidate;
  5835. }
  5836. #endif
  5837. inline socket_t create_client_socket(
  5838. const std::string &host, const std::string &ip, int port,
  5839. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5840. SocketOptions socket_options, time_t connection_timeout_sec,
  5841. time_t connection_timeout_usec, time_t read_timeout_sec,
  5842. time_t read_timeout_usec, time_t write_timeout_sec,
  5843. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5844. auto sock = create_socket(
  5845. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5846. std::move(socket_options),
  5847. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5848. if (!intf.empty()) {
  5849. #ifdef USE_IF2IP
  5850. auto ip_from_if = if2ip(address_family, intf);
  5851. if (ip_from_if.empty()) { ip_from_if = intf; }
  5852. if (!bind_ip_address(sock2, ip_from_if)) {
  5853. error = Error::BindIPAddress;
  5854. return false;
  5855. }
  5856. #endif
  5857. }
  5858. set_nonblocking(sock2, true);
  5859. auto ret =
  5860. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5861. if (ret < 0) {
  5862. if (is_connection_error()) {
  5863. error = Error::Connection;
  5864. return false;
  5865. }
  5866. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5867. connection_timeout_usec);
  5868. if (error != Error::Success) {
  5869. if (error == Error::ConnectionTimeout) { quit = true; }
  5870. return false;
  5871. }
  5872. }
  5873. set_nonblocking(sock2, false);
  5874. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5875. read_timeout_usec);
  5876. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5877. write_timeout_usec);
  5878. error = Error::Success;
  5879. return true;
  5880. },
  5881. connection_timeout_sec); // Pass DNS timeout
  5882. if (sock != INVALID_SOCKET) {
  5883. error = Error::Success;
  5884. } else {
  5885. if (error == Error::Success) { error = Error::Connection; }
  5886. }
  5887. return sock;
  5888. }
  5889. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5890. socklen_t addr_len, std::string &ip, int &port) {
  5891. if (addr.ss_family == AF_INET) {
  5892. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5893. } else if (addr.ss_family == AF_INET6) {
  5894. port =
  5895. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5896. } else {
  5897. return false;
  5898. }
  5899. std::array<char, NI_MAXHOST> ipstr{};
  5900. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5901. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5902. 0, NI_NUMERICHOST)) {
  5903. return false;
  5904. }
  5905. ip = ipstr.data();
  5906. return true;
  5907. }
  5908. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5909. struct sockaddr_storage addr;
  5910. socklen_t addr_len = sizeof(addr);
  5911. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5912. &addr_len)) {
  5913. get_ip_and_port(addr, addr_len, ip, port);
  5914. }
  5915. }
  5916. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5917. struct sockaddr_storage addr;
  5918. socklen_t addr_len = sizeof(addr);
  5919. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5920. &addr_len)) {
  5921. #ifndef _WIN32
  5922. if (addr.ss_family == AF_UNIX) {
  5923. #if defined(__linux__)
  5924. struct ucred ucred;
  5925. socklen_t len = sizeof(ucred);
  5926. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5927. port = ucred.pid;
  5928. }
  5929. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5930. pid_t pid;
  5931. socklen_t len = sizeof(pid);
  5932. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5933. port = pid;
  5934. }
  5935. #endif
  5936. return;
  5937. }
  5938. #endif
  5939. get_ip_and_port(addr, addr_len, ip, port);
  5940. }
  5941. }
  5942. // Recursive form retained so operator""_t below can compute hashes for
  5943. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5944. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5945. // instead, which is iterative and stack-safe.
  5946. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5947. unsigned int h) {
  5948. return (l == 0)
  5949. ? h
  5950. : str2tag_core(
  5951. s + 1, l - 1,
  5952. // Unsets the 6 high bits of h, therefore no overflow happens
  5953. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5954. h * 33) ^
  5955. static_cast<unsigned char>(*s));
  5956. }
  5957. inline unsigned int str2tag(const std::string &s) {
  5958. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5959. // for compile-time UDL evaluation of short string literals, but at runtime
  5960. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5961. // would blow the stack with one frame per character.
  5962. unsigned int h = 0;
  5963. for (auto c : s) {
  5964. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5965. static_cast<unsigned char>(c);
  5966. }
  5967. return h;
  5968. }
  5969. namespace udl {
  5970. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5971. return str2tag_core(s, l, 0);
  5972. }
  5973. } // namespace udl
  5974. inline std::string
  5975. find_content_type(const std::string &path,
  5976. const std::map<std::string, std::string> &user_data,
  5977. const std::string &default_content_type) {
  5978. auto ext = file_extension(path);
  5979. auto it = user_data.find(ext);
  5980. if (it != user_data.end()) { return it->second; }
  5981. using udl::operator""_t;
  5982. switch (str2tag(ext)) {
  5983. default: return default_content_type;
  5984. case "css"_t: return "text/css";
  5985. case "csv"_t: return "text/csv";
  5986. case "htm"_t:
  5987. case "html"_t: return "text/html";
  5988. case "js"_t:
  5989. case "mjs"_t: return "text/javascript";
  5990. case "txt"_t: return "text/plain";
  5991. case "vtt"_t: return "text/vtt";
  5992. case "apng"_t: return "image/apng";
  5993. case "avif"_t: return "image/avif";
  5994. case "bmp"_t: return "image/bmp";
  5995. case "gif"_t: return "image/gif";
  5996. case "png"_t: return "image/png";
  5997. case "svg"_t: return "image/svg+xml";
  5998. case "webp"_t: return "image/webp";
  5999. case "ico"_t: return "image/x-icon";
  6000. case "tif"_t: return "image/tiff";
  6001. case "tiff"_t: return "image/tiff";
  6002. case "jpg"_t:
  6003. case "jpeg"_t: return "image/jpeg";
  6004. case "mp4"_t: return "video/mp4";
  6005. case "mpeg"_t: return "video/mpeg";
  6006. case "webm"_t: return "video/webm";
  6007. case "mp3"_t: return "audio/mp3";
  6008. case "mpga"_t: return "audio/mpeg";
  6009. case "weba"_t: return "audio/webm";
  6010. case "wav"_t: return "audio/wave";
  6011. case "otf"_t: return "font/otf";
  6012. case "ttf"_t: return "font/ttf";
  6013. case "woff"_t: return "font/woff";
  6014. case "woff2"_t: return "font/woff2";
  6015. case "7z"_t: return "application/x-7z-compressed";
  6016. case "atom"_t: return "application/atom+xml";
  6017. case "pdf"_t: return "application/pdf";
  6018. case "json"_t: return "application/json";
  6019. case "rss"_t: return "application/rss+xml";
  6020. case "tar"_t: return "application/x-tar";
  6021. case "xht"_t:
  6022. case "xhtml"_t: return "application/xhtml+xml";
  6023. case "xslt"_t: return "application/xslt+xml";
  6024. case "xml"_t: return "application/xml";
  6025. case "gz"_t: return "application/gzip";
  6026. case "zip"_t: return "application/zip";
  6027. case "wasm"_t: return "application/wasm";
  6028. }
  6029. }
  6030. inline std::string
  6031. extract_media_type(const std::string &content_type,
  6032. std::map<std::string, std::string> *params = nullptr) {
  6033. // Extract type/subtype from Content-Type value (RFC 2045)
  6034. // e.g. "application/json; charset=utf-8" -> "application/json"
  6035. auto media_type = content_type;
  6036. auto semicolon_pos = media_type.find(';');
  6037. if (semicolon_pos != std::string::npos) {
  6038. auto param_str = media_type.substr(semicolon_pos + 1);
  6039. media_type = media_type.substr(0, semicolon_pos);
  6040. if (params) {
  6041. // Parse parameters: key=value pairs separated by ';'
  6042. split(param_str.data(), param_str.data() + param_str.size(), ';',
  6043. [&](const char *b, const char *e) {
  6044. std::string key;
  6045. std::string val;
  6046. split(b, e, '=', [&](const char *b2, const char *e2) {
  6047. if (key.empty()) {
  6048. key.assign(b2, e2);
  6049. } else {
  6050. val.assign(b2, e2);
  6051. }
  6052. });
  6053. if (!key.empty()) {
  6054. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  6055. }
  6056. });
  6057. }
  6058. }
  6059. // Trim whitespace from media type
  6060. return trim_copy(media_type);
  6061. }
  6062. inline bool can_compress_content_type(const std::string &content_type) {
  6063. using udl::operator""_t;
  6064. auto mime_type = extract_media_type(content_type);
  6065. auto tag = str2tag(mime_type);
  6066. switch (tag) {
  6067. case "image/svg+xml"_t:
  6068. case "application/javascript"_t:
  6069. case "application/x-javascript"_t:
  6070. case "application/json"_t:
  6071. case "application/ld+json"_t:
  6072. case "application/xml"_t:
  6073. case "application/xhtml+xml"_t:
  6074. case "application/rss+xml"_t:
  6075. case "application/atom+xml"_t:
  6076. case "application/xslt+xml"_t:
  6077. case "application/protobuf"_t: return true;
  6078. case "text/event-stream"_t: return false;
  6079. default: return !mime_type.rfind("text/", 0);
  6080. }
  6081. }
  6082. inline bool parse_quality(const char *b, const char *e, std::string &token,
  6083. double &quality) {
  6084. quality = 1.0;
  6085. token.clear();
  6086. // Split on first ';': left = token name, right = parameters
  6087. const char *params_b = nullptr;
  6088. std::size_t params_len = 0;
  6089. divide(
  6090. b, static_cast<std::size_t>(e - b), ';',
  6091. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  6092. auto r = trim(lb, lb + llen, 0, llen);
  6093. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  6094. params_b = rb;
  6095. params_len = rlen;
  6096. });
  6097. if (token.empty()) { return false; }
  6098. if (params_len == 0) { return true; }
  6099. // Scan parameters for q= (stops on first match)
  6100. bool invalid = false;
  6101. split_find(params_b, params_b + params_len, ';',
  6102. (std::numeric_limits<size_t>::max)(),
  6103. [&](const char *pb, const char *pe) -> bool {
  6104. // Match exactly "q=" or "Q=" (not "query=" etc.)
  6105. auto len = static_cast<size_t>(pe - pb);
  6106. if (len < 2) { return false; }
  6107. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  6108. return false;
  6109. }
  6110. // Trim the value portion
  6111. auto r = trim(pb, pe, 2, len);
  6112. if (r.first >= r.second) {
  6113. invalid = true;
  6114. return true;
  6115. }
  6116. double v = 0.0;
  6117. auto res = from_chars(pb + r.first, pb + r.second, v);
  6118. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  6119. invalid = true;
  6120. return true;
  6121. }
  6122. quality = v;
  6123. return true;
  6124. });
  6125. return !invalid;
  6126. }
  6127. inline EncodingType encoding_type(const Request &req, const Response &res) {
  6128. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  6129. return EncodingType::None;
  6130. }
  6131. auto s = get_combined_header_value(req.headers, "Accept-Encoding");
  6132. if (s.empty()) { return EncodingType::None; }
  6133. // Single-pass: iterate tokens and track the best supported encoding.
  6134. // Server preference breaks ties (br > gzip > zstd).
  6135. EncodingType best = EncodingType::None;
  6136. double best_q = 0.0; // q=0 means "not acceptable"
  6137. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  6138. auto priority = [](EncodingType t) -> int {
  6139. switch (t) {
  6140. case EncodingType::Brotli: return 0;
  6141. case EncodingType::Gzip: return 1;
  6142. case EncodingType::Zstd: return 2;
  6143. default: return 3;
  6144. }
  6145. };
  6146. std::string name;
  6147. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6148. double quality = 1.0;
  6149. if (!parse_quality(b, e, name, quality)) { return; }
  6150. if (quality <= 0.0) { return; }
  6151. EncodingType type = EncodingType::None;
  6152. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6153. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  6154. #endif
  6155. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6156. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  6157. type = EncodingType::Gzip;
  6158. }
  6159. #endif
  6160. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6161. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  6162. type = EncodingType::Zstd;
  6163. }
  6164. #endif
  6165. if (type == EncodingType::None) { return; }
  6166. // Higher q-value wins; for equal q, server preference breaks ties
  6167. if (quality > best_q ||
  6168. (quality == best_q && priority(type) < priority(best))) {
  6169. best_q = quality;
  6170. best = type;
  6171. }
  6172. });
  6173. return best;
  6174. }
  6175. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  6176. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6177. if (type == EncodingType::Gzip) {
  6178. return detail::make_unique<gzip_compressor>();
  6179. }
  6180. #endif
  6181. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6182. if (type == EncodingType::Brotli) {
  6183. return detail::make_unique<brotli_compressor>();
  6184. }
  6185. #endif
  6186. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6187. if (type == EncodingType::Zstd) {
  6188. return detail::make_unique<zstd_compressor>();
  6189. }
  6190. #endif
  6191. (void)type;
  6192. return nullptr;
  6193. }
  6194. inline const char *encoding_name(EncodingType type) {
  6195. switch (type) {
  6196. case EncodingType::Gzip: return "gzip";
  6197. case EncodingType::Brotli: return "br";
  6198. case EncodingType::Zstd: return "zstd";
  6199. default: return "";
  6200. }
  6201. }
  6202. inline bool nocompressor::compress(const char *data, size_t data_length,
  6203. bool /*last*/, Callback callback) {
  6204. if (!data_length) { return true; }
  6205. return callback(data, data_length);
  6206. }
  6207. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6208. inline gzip_compressor::gzip_compressor() {
  6209. std::memset(&strm_, 0, sizeof(strm_));
  6210. strm_.zalloc = Z_NULL;
  6211. strm_.zfree = Z_NULL;
  6212. strm_.opaque = Z_NULL;
  6213. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  6214. Z_DEFAULT_STRATEGY) == Z_OK;
  6215. }
  6216. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  6217. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  6218. bool last, Callback callback) {
  6219. assert(is_valid_);
  6220. do {
  6221. constexpr size_t max_avail_in =
  6222. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6223. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6224. (std::min)(data_length, max_avail_in));
  6225. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6226. data_length -= strm_.avail_in;
  6227. data += strm_.avail_in;
  6228. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  6229. auto ret = Z_OK;
  6230. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6231. do {
  6232. strm_.avail_out = static_cast<uInt>(buff.size());
  6233. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6234. ret = deflate(&strm_, flush);
  6235. if (ret == Z_STREAM_ERROR) { return false; }
  6236. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6237. return false;
  6238. }
  6239. } while (strm_.avail_out == 0);
  6240. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  6241. (flush == Z_NO_FLUSH && ret == Z_OK));
  6242. assert(strm_.avail_in == 0);
  6243. } while (data_length > 0);
  6244. return true;
  6245. }
  6246. inline gzip_decompressor::gzip_decompressor() {
  6247. std::memset(&strm_, 0, sizeof(strm_));
  6248. strm_.zalloc = Z_NULL;
  6249. strm_.zfree = Z_NULL;
  6250. strm_.opaque = Z_NULL;
  6251. // 15 is the value of wbits, which should be at the maximum possible value
  6252. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  6253. // that the stream type should be automatically detected either gzip or
  6254. // deflate.
  6255. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  6256. }
  6257. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  6258. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  6259. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  6260. Callback callback) {
  6261. assert(is_valid_);
  6262. auto ret = Z_OK;
  6263. do {
  6264. constexpr size_t max_avail_in =
  6265. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6266. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6267. (std::min)(data_length, max_avail_in));
  6268. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6269. data_length -= strm_.avail_in;
  6270. data += strm_.avail_in;
  6271. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6272. while (strm_.avail_in > 0 && ret == Z_OK) {
  6273. strm_.avail_out = static_cast<uInt>(buff.size());
  6274. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6275. ret = inflate(&strm_, Z_NO_FLUSH);
  6276. assert(ret != Z_STREAM_ERROR);
  6277. switch (ret) {
  6278. case Z_NEED_DICT:
  6279. case Z_DATA_ERROR:
  6280. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  6281. }
  6282. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6283. return false;
  6284. }
  6285. }
  6286. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  6287. } while (data_length > 0);
  6288. return true;
  6289. }
  6290. #endif
  6291. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6292. inline brotli_compressor::brotli_compressor() {
  6293. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  6294. }
  6295. inline brotli_compressor::~brotli_compressor() {
  6296. BrotliEncoderDestroyInstance(state_);
  6297. }
  6298. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  6299. bool last, Callback callback) {
  6300. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6301. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  6302. auto available_in = data_length;
  6303. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6304. for (;;) {
  6305. if (last) {
  6306. if (BrotliEncoderIsFinished(state_)) { break; }
  6307. } else {
  6308. if (!available_in) { break; }
  6309. }
  6310. auto available_out = buff.size();
  6311. auto next_out = buff.data();
  6312. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  6313. &available_out, &next_out, nullptr)) {
  6314. return false;
  6315. }
  6316. auto output_bytes = buff.size() - available_out;
  6317. if (output_bytes) {
  6318. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  6319. }
  6320. }
  6321. return true;
  6322. }
  6323. inline brotli_decompressor::brotli_decompressor() {
  6324. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  6325. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  6326. : BROTLI_DECODER_RESULT_ERROR;
  6327. }
  6328. inline brotli_decompressor::~brotli_decompressor() {
  6329. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  6330. }
  6331. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  6332. inline bool brotli_decompressor::decompress(const char *data,
  6333. size_t data_length,
  6334. Callback callback) {
  6335. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6336. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  6337. return 0;
  6338. }
  6339. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6340. size_t avail_in = data_length;
  6341. size_t total_out;
  6342. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  6343. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6344. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  6345. char *next_out = buff.data();
  6346. size_t avail_out = buff.size();
  6347. decoder_r = BrotliDecoderDecompressStream(
  6348. decoder_s, &avail_in, &next_in, &avail_out,
  6349. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  6350. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  6351. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  6352. }
  6353. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6354. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  6355. }
  6356. #endif
  6357. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6358. inline zstd_compressor::zstd_compressor() {
  6359. ctx_ = ZSTD_createCCtx();
  6360. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  6361. }
  6362. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  6363. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  6364. bool last, Callback callback) {
  6365. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6366. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  6367. ZSTD_inBuffer input = {data, data_length, 0};
  6368. bool finished;
  6369. do {
  6370. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6371. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  6372. if (ZSTD_isError(remaining)) { return false; }
  6373. if (!callback(buff.data(), output.pos)) { return false; }
  6374. finished = last ? (remaining == 0) : (input.pos == input.size);
  6375. } while (!finished);
  6376. return true;
  6377. }
  6378. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  6379. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  6380. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  6381. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  6382. Callback callback) {
  6383. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6384. ZSTD_inBuffer input = {data, data_length, 0};
  6385. while (input.pos < input.size) {
  6386. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6387. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  6388. if (ZSTD_isError(remaining)) { return false; }
  6389. if (!callback(buff.data(), output.pos)) { return false; }
  6390. }
  6391. return true;
  6392. }
  6393. #endif
  6394. // Content codings are case-insensitive (RFC 9110 8.4.1). Matching them
  6395. // case-sensitively would make a response labeled e.g. "GZIP" look like an
  6396. // unknown coding, and its payload would be handed back still compressed.
  6397. inline bool is_zlib_encoding(const std::string &encoding) {
  6398. return case_ignore::equal(encoding, "gzip") ||
  6399. case_ignore::equal(encoding, "deflate");
  6400. }
  6401. inline bool is_brotli_encoding(const std::string &encoding) {
  6402. return case_ignore::equal(encoding, "br");
  6403. }
  6404. inline bool is_zstd_encoding(const std::string &encoding) {
  6405. return case_ignore::equal(encoding, "zstd");
  6406. }
  6407. // Returns true if the content coding is one cpp-httplib is able to decompress
  6408. // when the corresponding support is compiled in.
  6409. inline bool is_known_content_encoding(const std::string &encoding) {
  6410. return is_zlib_encoding(encoding) || is_brotli_encoding(encoding) ||
  6411. is_zstd_encoding(encoding);
  6412. }
  6413. inline std::unique_ptr<decompressor>
  6414. create_decompressor(const std::string &encoding) {
  6415. std::unique_ptr<decompressor> decompressor;
  6416. if (is_zlib_encoding(encoding)) {
  6417. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6418. decompressor = detail::make_unique<gzip_decompressor>();
  6419. #endif
  6420. } else if (is_brotli_encoding(encoding)) {
  6421. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6422. decompressor = detail::make_unique<brotli_decompressor>();
  6423. #endif
  6424. } else if (is_zstd_encoding(encoding)) {
  6425. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6426. decompressor = detail::make_unique<zstd_decompressor>();
  6427. #endif
  6428. }
  6429. return decompressor;
  6430. }
  6431. // Returns the best available compressor and its Content-Encoding name.
  6432. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  6433. inline std::pair<std::unique_ptr<compressor>, const char *>
  6434. create_compressor() {
  6435. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6436. return {detail::make_unique<brotli_compressor>(), "br"};
  6437. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6438. return {detail::make_unique<gzip_compressor>(), "gzip"};
  6439. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6440. return {detail::make_unique<zstd_compressor>(), "zstd"};
  6441. #else
  6442. return {nullptr, nullptr};
  6443. #endif
  6444. }
  6445. inline bool is_prohibited_header_name(const std::string &name) {
  6446. using udl::operator""_t;
  6447. switch (str2tag(name)) {
  6448. case "REMOTE_ADDR"_t:
  6449. case "REMOTE_PORT"_t:
  6450. case "LOCAL_ADDR"_t:
  6451. case "LOCAL_PORT"_t: return true;
  6452. default: return false;
  6453. }
  6454. }
  6455. inline bool has_header(const Headers &headers, const std::string &key) {
  6456. if (is_prohibited_header_name(key)) { return false; }
  6457. return headers.find(key) != headers.end();
  6458. }
  6459. inline const char *get_header_value(const Headers &headers,
  6460. const std::string &key, const char *def,
  6461. size_t id) {
  6462. if (is_prohibited_header_name(key)) {
  6463. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6464. std::string msg = "Prohibited header name '" + key + "' is specified.";
  6465. throw std::invalid_argument(msg);
  6466. #else
  6467. return "";
  6468. #endif
  6469. }
  6470. auto rng = headers.equal_range(key);
  6471. auto it = rng.first;
  6472. std::advance(it, static_cast<ssize_t>(id));
  6473. if (it != rng.second) { return it->second.c_str(); }
  6474. return def;
  6475. }
  6476. inline size_t get_header_value_count(const Headers &headers,
  6477. const std::string &key) {
  6478. return headers.count(key);
  6479. }
  6480. // RFC 9110 Section 5.2 and 5.3: a field that is defined as a comma-separated
  6481. // list may be sent as several field lines, and the combined field value is
  6482. // those values joined by commas in the order they were received. Callers that
  6483. // parse such a list must work on the combined value; reading only the first
  6484. // occurrence silently drops whatever the later field lines carry.
  6485. inline std::string get_combined_header_value(const Headers &headers,
  6486. const std::string &key) {
  6487. std::string combined;
  6488. auto rng = headers.equal_range(key);
  6489. for (auto it = rng.first; it != rng.second; ++it) {
  6490. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  6491. // elements, so an empty field line must not contribute a bare comma to the
  6492. // combined value. parse_accept_header() rejects a leading comma outright,
  6493. // which would turn a legal request into 400 Bad Request.
  6494. if (it->second.empty()) { continue; }
  6495. if (!combined.empty()) { combined += ", "; }
  6496. combined += it->second;
  6497. }
  6498. return combined;
  6499. }
  6500. inline bool has_header_token(const Headers &headers, const std::string &key,
  6501. const std::string &token) {
  6502. // RFC 9110 7.6.1: a comma-separated token list field such as Connection may
  6503. // carry several tokens, and RFC 9110 5.3 lets that list be split across
  6504. // several lines. Match complete tokens rather than searching the raw value,
  6505. // so that a value such as "notupgrade" is not read as the token "upgrade".
  6506. auto rng = headers.equal_range(key);
  6507. for (auto it = rng.first; it != rng.second; ++it) {
  6508. const auto &value = it->second;
  6509. if (split_find(value.data(), value.data() + value.size(), ',',
  6510. [&](const char *b, const char *e) {
  6511. return case_ignore::equal(std::string(b, e), token);
  6512. })) {
  6513. return true;
  6514. }
  6515. }
  6516. return false;
  6517. }
  6518. template <typename Map>
  6519. inline typename Map::mapped_type
  6520. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  6521. auto rng = m.equal_range(key);
  6522. auto it = rng.first;
  6523. std::advance(it, static_cast<ssize_t>(id));
  6524. if (it != rng.second) { return it->second; }
  6525. return typename Map::mapped_type();
  6526. }
  6527. inline void set_header(Headers &headers, const std::string &key,
  6528. const std::string &val) {
  6529. if (fields::is_field_valid(key, val)) { headers.emplace(key, val); }
  6530. }
  6531. inline bool read_headers(Stream &strm, Headers &headers) {
  6532. const auto bufsiz = 2048;
  6533. char buf[bufsiz];
  6534. stream_line_reader line_reader(strm, buf, bufsiz);
  6535. size_t header_count = 0;
  6536. for (;;) {
  6537. if (!line_reader.getline()) { return false; }
  6538. // Check if the line ends with CRLF.
  6539. auto line_terminator_len = 2;
  6540. if (line_reader.end_with_crlf()) {
  6541. // Blank line indicates end of headers.
  6542. if (line_reader.size() == 2) { break; }
  6543. } else {
  6544. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6545. // Blank line indicates end of headers.
  6546. if (line_reader.size() == 1) { break; }
  6547. line_terminator_len = 1;
  6548. #else
  6549. continue; // Skip invalid line.
  6550. #endif
  6551. }
  6552. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6553. // Check header count limit
  6554. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  6555. // Exclude line terminator
  6556. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  6557. if (!parse_header(line_reader.ptr(), end,
  6558. [&](const std::string &key, const std::string &val) {
  6559. headers.emplace(key, val);
  6560. })) {
  6561. return false;
  6562. }
  6563. header_count++;
  6564. }
  6565. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  6566. // headers that have different values to prevent request smuggling.
  6567. auto cl_range = headers.equal_range("Content-Length");
  6568. if (cl_range.first != cl_range.second) {
  6569. const auto &first_val = cl_range.first->second;
  6570. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  6571. if (it->second != first_val) { return false; }
  6572. }
  6573. }
  6574. return true;
  6575. }
  6576. inline bool parse_status_line(const char *line, std::string &version,
  6577. int &status, std::string &reason) {
  6578. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6579. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  6580. #else
  6581. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  6582. #endif
  6583. std::cmatch m;
  6584. if (!std::regex_match(line, m, re)) { return false; }
  6585. version = std::string(m[1]);
  6586. status = std::stoi(std::string(m[2]));
  6587. reason = std::string(m[3]);
  6588. return true;
  6589. }
  6590. // Everything WebSocketClient::connect() reports about the upgrade exchange.
  6591. // status stays -1 until a status line is parsed, mirroring stream::Result.
  6592. struct WebSocketUpgradeResponse {
  6593. Error error = Error::Success;
  6594. int status = -1;
  6595. Headers headers;
  6596. std::string selected_subprotocol;
  6597. };
  6598. inline bool read_websocket_upgrade_response(Stream &strm,
  6599. const std::string &expected_accept,
  6600. WebSocketUpgradeResponse &upgrade) {
  6601. // Read status line
  6602. const auto bufsiz = 2048;
  6603. char buf[bufsiz];
  6604. stream_line_reader line_reader(strm, buf, bufsiz);
  6605. if (!line_reader.getline()) {
  6606. upgrade.error = Error::Read;
  6607. return false;
  6608. }
  6609. std::string version;
  6610. std::string reason;
  6611. if (!parse_status_line(line_reader.ptr(), version, upgrade.status, reason)) {
  6612. upgrade.error = Error::WebSocketHandshake;
  6613. return false;
  6614. }
  6615. // Read the headers even for a rejection so the caller can see why the
  6616. // server refused the upgrade. A non-101 response may carry a body; it is
  6617. // deliberately left unread since the caller closes the socket right away.
  6618. if (!read_headers(strm, upgrade.headers)) {
  6619. upgrade.error = Error::Read;
  6620. return false;
  6621. }
  6622. const auto &headers = upgrade.headers;
  6623. if (upgrade.status != StatusCode::SwitchingProtocol_101) {
  6624. upgrade.error = Error::WebSocketHandshake;
  6625. return false;
  6626. }
  6627. // Verify Upgrade: websocket (a comma-separated list, matched per token)
  6628. if (!has_header_token(headers, "Upgrade", "websocket")) {
  6629. upgrade.error = Error::WebSocketHandshake;
  6630. return false;
  6631. }
  6632. // Verify Connection: Upgrade
  6633. if (!has_header_token(headers, "Connection", "upgrade")) {
  6634. upgrade.error = Error::WebSocketHandshake;
  6635. return false;
  6636. }
  6637. // Verify Sec-WebSocket-Accept header value
  6638. auto it = headers.find("Sec-WebSocket-Accept");
  6639. if (it == headers.end() || it->second != expected_accept) {
  6640. upgrade.error = Error::WebSocketHandshake;
  6641. return false;
  6642. }
  6643. // Extract negotiated subprotocol
  6644. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6645. if (proto_it != headers.end()) {
  6646. upgrade.selected_subprotocol = proto_it->second;
  6647. }
  6648. return true;
  6649. }
  6650. enum class ReadContentResult {
  6651. Success, // Successfully read the content
  6652. PayloadTooLarge, // The content exceeds the specified payload limit
  6653. Error // An error occurred while reading the content
  6654. };
  6655. inline ReadContentResult read_content_with_length(
  6656. Stream &strm, size_t len, DownloadProgress progress,
  6657. ContentReceiverWithProgress out,
  6658. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6659. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6660. detail::BodyReader br;
  6661. br.stream = &strm;
  6662. br.has_content_length = true;
  6663. br.content_length = len;
  6664. br.payload_max_length = payload_max_length;
  6665. br.chunked = false;
  6666. br.bytes_read = 0;
  6667. br.last_error = Error::Success;
  6668. size_t r = 0;
  6669. while (r < len) {
  6670. auto read_len = static_cast<size_t>(len - r);
  6671. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6672. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6673. if (n <= 0) {
  6674. // Check if it was a payload size error
  6675. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6676. return ReadContentResult::PayloadTooLarge;
  6677. }
  6678. return ReadContentResult::Error;
  6679. }
  6680. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6681. return ReadContentResult::Error;
  6682. }
  6683. r += static_cast<size_t>(n);
  6684. if (progress) {
  6685. if (!progress(r, len)) { return ReadContentResult::Error; }
  6686. }
  6687. }
  6688. return ReadContentResult::Success;
  6689. }
  6690. inline ReadContentResult
  6691. read_content_without_length(Stream &strm, size_t payload_max_length,
  6692. ContentReceiverWithProgress out) {
  6693. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6694. size_t r = 0;
  6695. for (;;) {
  6696. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6697. if (n == 0) { return ReadContentResult::Success; }
  6698. if (n < 0) { return ReadContentResult::Error; }
  6699. // Check if adding this data would exceed the payload limit
  6700. if (r > payload_max_length ||
  6701. payload_max_length - r < static_cast<size_t>(n)) {
  6702. return ReadContentResult::PayloadTooLarge;
  6703. }
  6704. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6705. return ReadContentResult::Error;
  6706. }
  6707. r += static_cast<size_t>(n);
  6708. }
  6709. return ReadContentResult::Success;
  6710. }
  6711. template <typename T>
  6712. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6713. size_t payload_max_length,
  6714. ContentReceiverWithProgress out) {
  6715. detail::ChunkedDecoder dec(strm);
  6716. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6717. size_t total_len = 0;
  6718. for (;;) {
  6719. size_t chunk_offset = 0;
  6720. size_t chunk_total = 0;
  6721. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6722. if (n < 0) { return ReadContentResult::Error; }
  6723. if (n == 0) {
  6724. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6725. return ReadContentResult::Error;
  6726. }
  6727. return ReadContentResult::Success;
  6728. }
  6729. if (total_len > payload_max_length ||
  6730. payload_max_length - total_len < static_cast<size_t>(n)) {
  6731. return ReadContentResult::PayloadTooLarge;
  6732. }
  6733. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6734. return ReadContentResult::Error;
  6735. }
  6736. total_len += static_cast<size_t>(n);
  6737. }
  6738. }
  6739. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6740. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  6741. // is the final transfer coding. A single field value may list several
  6742. // codings ("gzip, chunked"), and RFC 9110 5.3 lets that list be split across
  6743. // several Transfer-Encoding lines, which combine into one comma-separated
  6744. // list in the order the lines were received. Headers preserves that order,
  6745. // so the final coding is the last token of the last line. Match it
  6746. // case-insensitively rather than comparing the whole value against
  6747. // "chunked".
  6748. //
  6749. // Security: reading a chunked message as unframed leaves its body in the
  6750. // socket, where a keep-alive connection parses it as a smuggled request.
  6751. // Server::process_request() answers 400 and closes when the final coding is
  6752. // not chunked, so a request whose framing cannot be determined never
  6753. // reaches the "no body" path.
  6754. auto rng = headers.equal_range("Transfer-Encoding");
  6755. if (rng.first == rng.second) { return false; }
  6756. // Cleared per line, so a trailing line carrying no coding at all leaves the
  6757. // combined list ending in nothing rather than inheriting the line before it.
  6758. std::string last_coding;
  6759. for (auto it = rng.first; it != rng.second; ++it) {
  6760. const auto &value = it->second;
  6761. last_coding.clear();
  6762. split(value.data(), value.data() + value.size(), ',',
  6763. [&](const char *b, const char *e) { last_coding.assign(b, e); });
  6764. }
  6765. return case_ignore::equal(last_coding, "chunked");
  6766. }
  6767. template <typename T, typename U>
  6768. bool prepare_content_receiver(T &x, int &status,
  6769. ContentReceiverWithProgress receiver,
  6770. bool decompress, size_t payload_max_length,
  6771. bool &exceed_payload_max_length, U callback) {
  6772. if (decompress) {
  6773. auto encoding = get_combined_header_value(x.headers, "Content-Encoding");
  6774. std::unique_ptr<decompressor> decompressor;
  6775. if (!encoding.empty()) {
  6776. // A coding we know about but were not built with is an error. An
  6777. // unrecognized coding (including "identity") is left alone and the
  6778. // payload is passed through as-is, since some servers misuse the header,
  6779. // e.g. by sending a character set such as "Content-Encoding: UTF-8".
  6780. decompressor = detail::create_decompressor(encoding);
  6781. if (!decompressor && detail::is_known_content_encoding(encoding)) {
  6782. status = StatusCode::UnsupportedMediaType_415;
  6783. return false;
  6784. }
  6785. }
  6786. if (decompressor) {
  6787. if (decompressor->is_valid()) {
  6788. size_t decompressed_size = 0;
  6789. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6790. size_t off, size_t len) {
  6791. return decompressor->decompress(
  6792. buf, n, [&](const char *buf2, size_t n2) {
  6793. // Guard against zip-bomb: check
  6794. // decompressed size against limit.
  6795. if (payload_max_length > 0 &&
  6796. (decompressed_size >= payload_max_length ||
  6797. n2 > payload_max_length - decompressed_size)) {
  6798. exceed_payload_max_length = true;
  6799. return false;
  6800. }
  6801. decompressed_size += n2;
  6802. return receiver(buf2, n2, off, len);
  6803. });
  6804. };
  6805. return callback(std::move(out));
  6806. } else {
  6807. status = StatusCode::InternalServerError_500;
  6808. return false;
  6809. }
  6810. }
  6811. }
  6812. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6813. size_t len) {
  6814. return receiver(buf, n, off, len);
  6815. };
  6816. return callback(std::move(out));
  6817. }
  6818. template <typename T>
  6819. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6820. DownloadProgress progress,
  6821. ContentReceiverWithProgress receiver, bool decompress) {
  6822. bool exceed_payload_max_length = false;
  6823. return prepare_content_receiver(
  6824. x, status, std::move(receiver), decompress, payload_max_length,
  6825. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6826. auto ret = true;
  6827. // Note: exceed_payload_max_length may also be set by the decompressor
  6828. // wrapper in prepare_content_receiver when the decompressed payload
  6829. // size exceeds the limit.
  6830. if (is_chunked_transfer_encoding(x.headers)) {
  6831. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6832. if (result == ReadContentResult::Success) {
  6833. ret = true;
  6834. } else if (result == ReadContentResult::PayloadTooLarge) {
  6835. exceed_payload_max_length = true;
  6836. ret = false;
  6837. } else {
  6838. ret = false;
  6839. }
  6840. } else if (!has_header(x.headers, "Content-Length")) {
  6841. auto result =
  6842. read_content_without_length(strm, payload_max_length, out);
  6843. if (result == ReadContentResult::Success) {
  6844. ret = true;
  6845. } else if (result == ReadContentResult::PayloadTooLarge) {
  6846. exceed_payload_max_length = true;
  6847. ret = false;
  6848. } else {
  6849. ret = false;
  6850. }
  6851. } else {
  6852. auto is_invalid_value = false;
  6853. auto len = get_header_value_u64(x.headers, "Content-Length",
  6854. (std::numeric_limits<size_t>::max)(),
  6855. 0, is_invalid_value);
  6856. if (is_invalid_value) {
  6857. ret = false;
  6858. } else if (len > 0) {
  6859. auto result = read_content_with_length(
  6860. strm, len, std::move(progress), out, payload_max_length);
  6861. ret = (result == ReadContentResult::Success);
  6862. if (result == ReadContentResult::PayloadTooLarge) {
  6863. exceed_payload_max_length = true;
  6864. }
  6865. }
  6866. }
  6867. if (!ret) {
  6868. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6869. : StatusCode::BadRequest_400;
  6870. }
  6871. return ret;
  6872. });
  6873. }
  6874. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6875. const std::string &path) {
  6876. // A request target must not carry CR/LF (or other control octets); otherwise
  6877. // a value smuggled into it splits the request line and injects headers or a
  6878. // whole request. The same field-value check already guards header values in
  6879. // check_and_write_headers and the request target in
  6880. // perform_websocket_handshake; apply it here too.
  6881. if (!fields::is_field_value(path)) { return -1; }
  6882. std::string s = method;
  6883. s += ' ';
  6884. s += path;
  6885. s += " HTTP/1.1\r\n";
  6886. return strm.write(s.data(), s.size());
  6887. }
  6888. inline ssize_t write_response_line(Stream &strm, int status) {
  6889. std::string s = "HTTP/1.1 ";
  6890. s += std::to_string(status);
  6891. s += ' ';
  6892. s += httplib::status_message(status);
  6893. s += "\r\n";
  6894. return strm.write(s.data(), s.size());
  6895. }
  6896. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6897. ssize_t write_len = 0;
  6898. for (const auto &x : headers) {
  6899. // Skip fields with invalid names or values to prevent response splitting
  6900. // via CR/LF injection, matching set_header(). The client validates request
  6901. // headers up front in check_and_write_headers, but the server passes
  6902. // res.headers straight to this writer, and res.headers is a public field
  6903. // an application can populate directly with request-derived values.
  6904. if (!fields::is_field_valid(x.first, x.second)) { continue; }
  6905. std::string s;
  6906. s = x.first;
  6907. s += ": ";
  6908. s += x.second;
  6909. s += "\r\n";
  6910. auto len = strm.write(s.data(), s.size());
  6911. if (len < 0) { return len; }
  6912. write_len += len;
  6913. }
  6914. auto len = strm.write("\r\n");
  6915. if (len < 0) { return len; }
  6916. write_len += len;
  6917. return write_len;
  6918. }
  6919. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6920. size_t offset = 0;
  6921. while (offset < l) {
  6922. auto length = strm.write(d + offset, l - offset);
  6923. if (length < 0) { return false; }
  6924. offset += static_cast<size_t>(length);
  6925. }
  6926. return true;
  6927. }
  6928. template <typename T>
  6929. inline bool write_content_with_progress(Stream &strm,
  6930. const ContentProvider &content_provider,
  6931. size_t offset, size_t length,
  6932. T is_shutting_down,
  6933. const UploadProgress &upload_progress,
  6934. Error &error) {
  6935. size_t end_offset = offset + length;
  6936. size_t start_offset = offset;
  6937. auto ok = true;
  6938. DataSink data_sink;
  6939. data_sink.write = [&](const char *d, size_t l) -> bool {
  6940. if (ok) {
  6941. if (write_data(strm, d, l)) {
  6942. offset += l;
  6943. if (upload_progress && length > 0) {
  6944. size_t current_written = offset - start_offset;
  6945. if (!upload_progress(current_written, length)) {
  6946. ok = false;
  6947. return false;
  6948. }
  6949. }
  6950. } else {
  6951. ok = false;
  6952. }
  6953. }
  6954. return ok;
  6955. };
  6956. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6957. while (offset < end_offset && !is_shutting_down()) {
  6958. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6959. error = Error::Write;
  6960. return false;
  6961. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6962. error = Error::Canceled;
  6963. return false;
  6964. } else if (!ok) {
  6965. error = Error::Write;
  6966. return false;
  6967. }
  6968. }
  6969. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6970. error = Error::Write;
  6971. return false;
  6972. }
  6973. error = Error::Success;
  6974. return true;
  6975. }
  6976. template <typename T>
  6977. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6978. size_t offset, size_t length, T is_shutting_down,
  6979. Error &error) {
  6980. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6981. is_shutting_down, nullptr, error);
  6982. }
  6983. template <typename T>
  6984. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6985. size_t offset, size_t length,
  6986. const T &is_shutting_down) {
  6987. auto error = Error::Success;
  6988. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6989. error);
  6990. }
  6991. template <typename T>
  6992. inline bool
  6993. write_content_without_length(Stream &strm,
  6994. const ContentProvider &content_provider,
  6995. const T &is_shutting_down) {
  6996. size_t offset = 0;
  6997. auto data_available = true;
  6998. auto ok = true;
  6999. DataSink data_sink;
  7000. data_sink.write = [&](const char *d, size_t l) -> bool {
  7001. if (ok) {
  7002. offset += l;
  7003. if (!write_data(strm, d, l)) { ok = false; }
  7004. }
  7005. return ok;
  7006. };
  7007. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7008. data_sink.done = [&](void) { data_available = false; };
  7009. while (data_available && !is_shutting_down()) {
  7010. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7011. return false;
  7012. } else if (!content_provider(offset, 0, data_sink)) {
  7013. return false;
  7014. } else if (!ok) {
  7015. return false;
  7016. }
  7017. }
  7018. return !data_available; // true only if done() was called, false if shutting
  7019. // down
  7020. }
  7021. template <typename T, typename U>
  7022. inline bool
  7023. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  7024. const T &is_shutting_down, U &compressor, Error &error) {
  7025. size_t offset = 0;
  7026. auto data_available = true;
  7027. auto ok = true;
  7028. DataSink data_sink;
  7029. data_sink.write = [&](const char *d, size_t l) -> bool {
  7030. if (ok) {
  7031. data_available = l > 0;
  7032. offset += l;
  7033. std::string payload;
  7034. if (compressor.compress(d, l, false,
  7035. [&](const char *data, size_t data_len) {
  7036. payload.append(data, data_len);
  7037. return true;
  7038. })) {
  7039. if (!payload.empty()) {
  7040. // Emit chunked response header and footer for each chunk
  7041. auto chunk =
  7042. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7043. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  7044. }
  7045. } else {
  7046. ok = false;
  7047. }
  7048. }
  7049. return ok;
  7050. };
  7051. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7052. auto done_with_trailer = [&](const Headers *trailer) {
  7053. if (!ok) { return; }
  7054. data_available = false;
  7055. std::string payload;
  7056. if (!compressor.compress(nullptr, 0, true,
  7057. [&](const char *data, size_t data_len) {
  7058. payload.append(data, data_len);
  7059. return true;
  7060. })) {
  7061. ok = false;
  7062. return;
  7063. }
  7064. if (!payload.empty()) {
  7065. // Emit chunked response header and footer for each chunk
  7066. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7067. if (!write_data(strm, chunk.data(), chunk.size())) {
  7068. ok = false;
  7069. return;
  7070. }
  7071. }
  7072. constexpr const char done_marker[] = "0\r\n";
  7073. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  7074. // Trailer
  7075. if (trailer) {
  7076. for (const auto &kv : *trailer) {
  7077. // Skip fields with invalid names or values to prevent response
  7078. // splitting via CR/LF injection, matching set_header().
  7079. if (!fields::is_field_valid(kv.first, kv.second)) { continue; }
  7080. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  7081. if (!write_data(strm, field_line.data(), field_line.size())) {
  7082. ok = false;
  7083. }
  7084. }
  7085. }
  7086. constexpr const char crlf[] = "\r\n";
  7087. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  7088. };
  7089. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  7090. data_sink.done_with_trailer = [&](const Headers &trailer) {
  7091. done_with_trailer(&trailer);
  7092. };
  7093. while (data_available && !is_shutting_down()) {
  7094. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7095. error = Error::Write;
  7096. return false;
  7097. } else if (!content_provider(offset, 0, data_sink)) {
  7098. error = Error::Canceled;
  7099. return false;
  7100. } else if (!ok) {
  7101. error = Error::Write;
  7102. return false;
  7103. }
  7104. }
  7105. if (data_available) { // exited due to is_shutting_down(), not done()
  7106. error = Error::Write;
  7107. return false;
  7108. }
  7109. error = Error::Success;
  7110. return true;
  7111. }
  7112. template <typename T, typename U>
  7113. inline bool write_content_chunked(Stream &strm,
  7114. const ContentProvider &content_provider,
  7115. const T &is_shutting_down, U &compressor) {
  7116. auto error = Error::Success;
  7117. return write_content_chunked(strm, content_provider, is_shutting_down,
  7118. compressor, error);
  7119. }
  7120. template <typename T>
  7121. inline bool redirect(T &cli, Request &req, Response &res,
  7122. const std::string &path, const std::string &location,
  7123. Error &error) {
  7124. Request new_req = req;
  7125. new_req.path = path;
  7126. new_req.redirect_count_ -= 1;
  7127. if (res.status == StatusCode::SeeOther_303 &&
  7128. (req.method != "GET" && req.method != "HEAD")) {
  7129. new_req.method = "GET";
  7130. new_req.body.clear();
  7131. new_req.headers.clear();
  7132. }
  7133. Response new_res;
  7134. auto ret = cli.send(new_req, new_res, error);
  7135. if (ret) {
  7136. req = std::move(new_req);
  7137. res = std::move(new_res);
  7138. if (res.location.empty()) { res.location = location; }
  7139. }
  7140. return ret;
  7141. }
  7142. inline std::string params_to_query_str(const Params &params) {
  7143. std::string query;
  7144. for (auto it = params.begin(); it != params.end(); ++it) {
  7145. if (it != params.begin()) { query += '&'; }
  7146. query += encode_query_component(it->first);
  7147. query += '=';
  7148. query += encode_query_component(it->second);
  7149. }
  7150. return query;
  7151. }
  7152. // Splits one "key=value" span of a query string at its first '='. A span with
  7153. // no '=' at all lands entirely in key, leaving val empty, which is how a bare
  7154. // "?flag" keeps its name.
  7155. inline void divide_query_pair(const char *b, const char *e, std::string &key,
  7156. std::string &val) {
  7157. divide(b, static_cast<std::size_t>(e - b), '=',
  7158. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  7159. std::size_t rhs_size) {
  7160. key.assign(lhs_data, lhs_size);
  7161. val.assign(rhs_data, rhs_size);
  7162. });
  7163. }
  7164. inline void parse_query_text(const char *data, std::size_t size,
  7165. Params &params) {
  7166. std::set<std::string> cache;
  7167. split(data, data + size, '&', [&](const char *b, const char *e) {
  7168. std::string kv(b, e);
  7169. if (cache.find(kv) != cache.end()) { return; }
  7170. cache.insert(std::move(kv));
  7171. std::string key;
  7172. std::string val;
  7173. divide_query_pair(b, e, key, val);
  7174. if (!key.empty()) {
  7175. params.emplace(decode_query_component(key), decode_query_component(val));
  7176. }
  7177. });
  7178. }
  7179. inline void parse_query_text(const std::string &s, Params &params) {
  7180. parse_query_text(s.data(), s.size(), params);
  7181. }
  7182. // Normalize a query string by decoding and re-encoding each key/value pair
  7183. // while preserving the original parameter order. This avoids double-encoding
  7184. // and ensures consistent encoding. It works on the raw string rather than
  7185. // parsing into Params and re-serializing, because that round trip cannot
  7186. // reproduce the input: params_to_query_str() always emits '=', so a bare
  7187. // "flag" would come back as "flag=", and parse_query_text() drops exactly
  7188. // duplicated pairs.
  7189. inline std::string normalize_query_string(const std::string &query) {
  7190. std::string result;
  7191. split(query.data(), query.data() + query.size(), '&',
  7192. [&](const char *b, const char *e) {
  7193. std::string key;
  7194. std::string val;
  7195. divide_query_pair(b, e, key, val);
  7196. if (!key.empty()) {
  7197. auto dec_key = decode_query_component(key);
  7198. auto dec_val = decode_query_component(val);
  7199. if (!result.empty()) { result += '&'; }
  7200. result += encode_query_component(dec_key);
  7201. if (!val.empty() || std::find(b, e, '=') != e) {
  7202. result += '=';
  7203. result += encode_query_component(dec_val);
  7204. }
  7205. }
  7206. });
  7207. return result;
  7208. }
  7209. // Build the request target that goes on the wire from a caller-supplied path.
  7210. // Shared by the buffered send path and the streaming API so that both put the
  7211. // same bytes in the request line for the same input.
  7212. inline std::string encode_request_target(const std::string &target,
  7213. bool path_encode) {
  7214. // `substr(0, npos)` yields the whole string, which is what the no-query
  7215. // case needs.
  7216. auto query_pos = target.find('?');
  7217. auto path_part = target.substr(0, query_pos);
  7218. std::string query_part;
  7219. if (query_pos != std::string::npos) {
  7220. query_part = target.substr(query_pos + 1);
  7221. }
  7222. auto result = path_encode ? encode_path(path_part) : std::move(path_part);
  7223. if (!query_part.empty()) {
  7224. // When path encoding is disabled the caller has supplied an already-encoded
  7225. // target and expects the exact bytes to be sent on the wire, so skip
  7226. // normalization for the query too. Normalizing would decode-then-re-encode
  7227. // it and corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  7228. // which a strict RFC 3986 server decodes back as `+`, not a space).
  7229. if (path_encode) {
  7230. auto normalized = normalize_query_string(query_part);
  7231. if (!normalized.empty()) {
  7232. result += '?';
  7233. result += normalized;
  7234. }
  7235. } else {
  7236. result += '?';
  7237. result += query_part;
  7238. }
  7239. }
  7240. return result;
  7241. }
  7242. inline bool parse_multipart_boundary(const std::string &content_type,
  7243. std::string &boundary) {
  7244. std::map<std::string, std::string> params;
  7245. extract_media_type(content_type, &params);
  7246. auto it = params.find("boundary");
  7247. if (it == params.end()) { return false; }
  7248. boundary = it->second;
  7249. // RFC 2046 5.1.1 caps a boundary at 70 characters. The parser scans the body
  7250. // for "--" + boundary, so a body crafted to repeat that delimiter's leading
  7251. // bytes costs a nearly full comparison at nearly every position: the
  7252. // boundary's length multiplies the worst-case cost of scanning a body.
  7253. return !boundary.empty() && boundary.size() <= 70;
  7254. }
  7255. inline void parse_disposition_params(const std::string &s, Params &params) {
  7256. std::set<std::string> cache;
  7257. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  7258. std::string kv(b, e);
  7259. if (cache.find(kv) != cache.end()) { return; }
  7260. cache.insert(kv);
  7261. std::string key;
  7262. std::string val;
  7263. split(b, e, '=', [&](const char *b2, const char *e2) {
  7264. if (key.empty()) {
  7265. key.assign(b2, e2);
  7266. } else {
  7267. val.assign(b2, e2);
  7268. }
  7269. });
  7270. if (!key.empty()) {
  7271. params.emplace(trim_double_quotes_copy((key)),
  7272. trim_double_quotes_copy((val)));
  7273. }
  7274. });
  7275. }
  7276. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7277. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  7278. #else
  7279. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  7280. #endif
  7281. auto is_valid = [](const std::string &str) {
  7282. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  7283. };
  7284. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  7285. const auto pos = static_cast<size_t>(6);
  7286. const auto len = static_cast<size_t>(s.size() - 6);
  7287. auto all_valid_ranges = true;
  7288. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  7289. if (!all_valid_ranges) { return; }
  7290. const auto it = std::find(b, e, '-');
  7291. if (it == e) {
  7292. all_valid_ranges = false;
  7293. return;
  7294. }
  7295. const auto lhs = std::string(b, it);
  7296. const auto rhs = std::string(it + 1, e);
  7297. if (!is_valid(lhs) || !is_valid(rhs)) {
  7298. all_valid_ranges = false;
  7299. return;
  7300. }
  7301. ssize_t first = -1;
  7302. if (!lhs.empty()) {
  7303. ssize_t v;
  7304. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  7305. if (res.ec == std::errc{}) { first = v; }
  7306. }
  7307. ssize_t last = -1;
  7308. if (!rhs.empty()) {
  7309. ssize_t v;
  7310. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  7311. if (res.ec == std::errc{}) { last = v; }
  7312. }
  7313. if ((first == -1 && last == -1) ||
  7314. (first != -1 && last != -1 && first > last)) {
  7315. all_valid_ranges = false;
  7316. return;
  7317. }
  7318. ranges.emplace_back(first, last);
  7319. });
  7320. return all_valid_ranges && !ranges.empty();
  7321. }
  7322. return false;
  7323. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7324. }
  7325. #else
  7326. } catch (...) { return false; }
  7327. #endif
  7328. inline bool parse_accept_header(const std::string &s,
  7329. std::vector<std::string> &content_types) {
  7330. content_types.clear();
  7331. // Empty string is considered valid (no preference)
  7332. if (s.empty()) { return true; }
  7333. // Check for invalid patterns: leading/trailing commas or consecutive commas
  7334. if (s.front() == ',' || s.back() == ',' ||
  7335. s.find(",,") != std::string::npos) {
  7336. return false;
  7337. }
  7338. struct AcceptEntry {
  7339. std::string media_type;
  7340. double quality;
  7341. int order;
  7342. };
  7343. std::vector<AcceptEntry> entries;
  7344. int order = 0;
  7345. bool has_invalid_entry = false;
  7346. // Split by comma and parse each entry
  7347. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  7348. std::string entry(b, e);
  7349. entry = trim_copy(entry);
  7350. if (entry.empty()) {
  7351. has_invalid_entry = true;
  7352. return;
  7353. }
  7354. AcceptEntry accept_entry;
  7355. accept_entry.order = order++;
  7356. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  7357. accept_entry.media_type, accept_entry.quality)) {
  7358. has_invalid_entry = true;
  7359. return;
  7360. }
  7361. // Remove additional parameters from media type
  7362. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  7363. // Basic validation of media type format
  7364. if (accept_entry.media_type.empty()) {
  7365. has_invalid_entry = true;
  7366. return;
  7367. }
  7368. // Check for basic media type format (should contain '/' or be '*')
  7369. if (accept_entry.media_type != "*" &&
  7370. accept_entry.media_type.find('/') == std::string::npos) {
  7371. has_invalid_entry = true;
  7372. return;
  7373. }
  7374. entries.push_back(std::move(accept_entry));
  7375. });
  7376. // Return false if any invalid entry was found
  7377. if (has_invalid_entry) { return false; }
  7378. // Sort by quality (descending), then by original order (ascending)
  7379. std::sort(entries.begin(), entries.end(),
  7380. [](const AcceptEntry &a, const AcceptEntry &b) {
  7381. if (a.quality != b.quality) {
  7382. return a.quality > b.quality; // Higher quality first
  7383. }
  7384. return a.order < b.order; // Earlier order first for same quality
  7385. });
  7386. // Extract sorted media types
  7387. content_types.reserve(entries.size());
  7388. for (auto &entry : entries) {
  7389. content_types.push_back(std::move(entry.media_type));
  7390. }
  7391. return true;
  7392. }
  7393. class FormDataParser {
  7394. public:
  7395. FormDataParser() = default;
  7396. void set_boundary(std::string &&boundary) {
  7397. boundary_ = std::move(boundary);
  7398. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  7399. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  7400. }
  7401. bool is_valid() const { return is_valid_; }
  7402. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  7403. const ContentReceiver &content_callback) {
  7404. // Once the close delimiter has been seen the rest of the body is epilogue
  7405. // to be discarded (RFC 2046). Drop it without buffering so a large epilogue
  7406. // spread across reads is not copied in only to be erased right away.
  7407. if (state_ == 5) { return true; }
  7408. buf_append(buf, n);
  7409. while (buf_size() > 0) {
  7410. switch (state_) {
  7411. case 0: { // Initial boundary
  7412. auto pos = buf_find(dash_boundary_crlf_);
  7413. if (pos == buf_size()) {
  7414. // Not found yet: keep only a possible partial boundary at the tail so
  7415. // that a body which never contains the boundary cannot grow the
  7416. // buffer (and get rescanned from the start) without bound.
  7417. auto keep = dash_boundary_crlf_.size() - 1;
  7418. if (buf_size() > keep) { buf_erase(buf_size() - keep); }
  7419. return true;
  7420. }
  7421. buf_erase(pos + dash_boundary_crlf_.size());
  7422. state_ = 1;
  7423. break;
  7424. }
  7425. case 1: { // New entry
  7426. clear_file_info();
  7427. state_ = 2;
  7428. break;
  7429. }
  7430. case 2: { // Headers
  7431. auto pos = buf_find(crlf_);
  7432. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  7433. while (pos < buf_size()) {
  7434. // Empty line
  7435. if (pos == 0) {
  7436. if (!header_callback(file_)) {
  7437. is_valid_ = false;
  7438. return false;
  7439. }
  7440. buf_erase(crlf_.size());
  7441. state_ = 3;
  7442. break;
  7443. }
  7444. // Check header count limit
  7445. if (header_count_ >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  7446. is_valid_ = false;
  7447. return false;
  7448. }
  7449. header_count_++;
  7450. const auto header = buf_head(pos);
  7451. if (!parse_header(header.data(), header.data() + header.size(),
  7452. [&](const std::string &, const std::string &) {})) {
  7453. is_valid_ = false;
  7454. return false;
  7455. }
  7456. // Parse and emplace space trimmed headers into a map
  7457. if (!parse_header(
  7458. header.data(), header.data() + header.size(),
  7459. [&](const std::string &key, const std::string &val) {
  7460. file_.headers.emplace(key, val);
  7461. })) {
  7462. is_valid_ = false;
  7463. return false;
  7464. }
  7465. constexpr const char header_content_type[] = "Content-Type:";
  7466. if (start_with_case_ignore(header, header_content_type)) {
  7467. file_.content_type =
  7468. trim_copy(header.substr(str_len(header_content_type)));
  7469. } else {
  7470. std::string disposition_params;
  7471. if (parse_content_disposition(header, disposition_params)) {
  7472. Params params;
  7473. parse_disposition_params(disposition_params, params);
  7474. auto it = params.find("name");
  7475. if (it != params.end()) {
  7476. file_.name = it->second;
  7477. } else {
  7478. is_valid_ = false;
  7479. return false;
  7480. }
  7481. it = params.find("filename");
  7482. if (it != params.end()) { file_.filename = it->second; }
  7483. it = params.find("filename*");
  7484. if (it != params.end()) {
  7485. // RFC 5987: only UTF-8 encoding is allowed
  7486. const auto &val = it->second;
  7487. constexpr const char utf8_prefix[] = "UTF-8''";
  7488. constexpr size_t prefix_len = str_len(utf8_prefix);
  7489. if (val.size() > prefix_len &&
  7490. start_with_case_ignore(val, utf8_prefix)) {
  7491. file_.filename = decode_path_component(
  7492. val.substr(prefix_len)); // override...
  7493. } else {
  7494. is_valid_ = false;
  7495. return false;
  7496. }
  7497. }
  7498. }
  7499. }
  7500. buf_erase(pos + crlf_.size());
  7501. pos = buf_find(crlf_);
  7502. }
  7503. if (state_ != 3) { return true; }
  7504. break;
  7505. }
  7506. case 3: { // Body
  7507. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  7508. auto pos = buf_find(crlf_dash_boundary_);
  7509. if (pos < buf_size()) {
  7510. if (!content_callback(buf_data(), pos)) {
  7511. is_valid_ = false;
  7512. return false;
  7513. }
  7514. buf_erase(pos + crlf_dash_boundary_.size());
  7515. state_ = 4;
  7516. } else {
  7517. auto len = buf_size() - crlf_dash_boundary_.size();
  7518. if (len > 0) {
  7519. if (!content_callback(buf_data(), len)) {
  7520. is_valid_ = false;
  7521. return false;
  7522. }
  7523. buf_erase(len);
  7524. }
  7525. return true;
  7526. }
  7527. break;
  7528. }
  7529. case 4: { // Boundary
  7530. if (crlf_.size() > buf_size()) { return true; }
  7531. if (buf_start_with(crlf_)) {
  7532. buf_erase(crlf_.size());
  7533. state_ = 1;
  7534. } else if (buf_start_with(dash_)) {
  7535. buf_erase(dash_.size());
  7536. is_valid_ = true;
  7537. state_ = 5;
  7538. } else {
  7539. // Only CRLF (another part follows) and "--" (close-delimiter) are
  7540. // accepted after a boundary; RFC 2046 allows transport-padding in
  7541. // between, but this parser has never supported it. Either way the
  7542. // body is already destined to be rejected, so fail now instead of
  7543. // buffering the rest of it. Both are two bytes, so the check above
  7544. // already guarantees enough buffered data to decide.
  7545. is_valid_ = false;
  7546. return false;
  7547. }
  7548. break;
  7549. }
  7550. case 5: { // Epilogue
  7551. buf_erase(buf_size());
  7552. break;
  7553. }
  7554. }
  7555. }
  7556. return true;
  7557. }
  7558. private:
  7559. void clear_file_info() {
  7560. file_.name.clear();
  7561. file_.filename.clear();
  7562. file_.content_type.clear();
  7563. file_.headers.clear();
  7564. header_count_ = 0;
  7565. }
  7566. bool start_with_case_ignore(const std::string &a, const char *b,
  7567. size_t offset = 0) const {
  7568. const auto b_len = strlen(b);
  7569. if (a.size() < offset + b_len) { return false; }
  7570. for (size_t i = 0; i < b_len; i++) {
  7571. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  7572. return false;
  7573. }
  7574. }
  7575. return true;
  7576. }
  7577. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  7578. // Returns true if header matches, with the params portion in `params_out`.
  7579. bool parse_content_disposition(const std::string &header,
  7580. std::string &params_out) const {
  7581. constexpr const char prefix[] = "Content-Disposition:";
  7582. constexpr size_t prefix_len = str_len(prefix);
  7583. if (!start_with_case_ignore(header, prefix)) { return false; }
  7584. // Skip whitespace after "Content-Disposition:"
  7585. auto pos = prefix_len;
  7586. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  7587. pos++;
  7588. }
  7589. // Match "form-data;" (case-insensitive)
  7590. constexpr const char form_data[] = "form-data;";
  7591. constexpr size_t form_data_len = str_len(form_data);
  7592. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  7593. pos += form_data_len;
  7594. // Skip whitespace after "form-data;"
  7595. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  7596. pos++;
  7597. }
  7598. params_out = header.substr(pos);
  7599. return true;
  7600. }
  7601. const std::string dash_ = "--";
  7602. const std::string crlf_ = "\r\n";
  7603. std::string boundary_;
  7604. std::string dash_boundary_crlf_;
  7605. std::string crlf_dash_boundary_;
  7606. size_t state_ = 0;
  7607. bool is_valid_ = false;
  7608. FormData file_;
  7609. size_t header_count_ = 0;
  7610. // Buffer
  7611. bool start_with(const std::string &a, size_t spos, size_t epos,
  7612. const std::string &b) const {
  7613. if (epos - spos < b.size()) { return false; }
  7614. for (size_t i = 0; i < b.size(); i++) {
  7615. if (a[i + spos] != b[i]) { return false; }
  7616. }
  7617. return true;
  7618. }
  7619. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  7620. const char *buf_data() const { return &buf_[buf_spos_]; }
  7621. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  7622. bool buf_start_with(const std::string &s) const {
  7623. return start_with(buf_, buf_spos_, buf_epos_, s);
  7624. }
  7625. size_t buf_find(const std::string &s) const {
  7626. auto c = s.front();
  7627. size_t off = buf_spos_;
  7628. while (off < buf_epos_) {
  7629. auto pos = off;
  7630. while (true) {
  7631. if (pos == buf_epos_) { return buf_size(); }
  7632. if (buf_[pos] == c) { break; }
  7633. pos++;
  7634. }
  7635. auto remaining_size = buf_epos_ - pos;
  7636. if (s.size() > remaining_size) { return buf_size(); }
  7637. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  7638. off = pos + 1;
  7639. }
  7640. return buf_size();
  7641. }
  7642. void buf_append(const char *data, size_t n) {
  7643. auto remaining_size = buf_size();
  7644. if (remaining_size > 0 && buf_spos_ > 0) {
  7645. for (size_t i = 0; i < remaining_size; i++) {
  7646. buf_[i] = buf_[buf_spos_ + i];
  7647. }
  7648. }
  7649. buf_spos_ = 0;
  7650. buf_epos_ = remaining_size;
  7651. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  7652. for (size_t i = 0; i < n; i++) {
  7653. buf_[buf_epos_ + i] = data[i];
  7654. }
  7655. buf_epos_ += n;
  7656. }
  7657. void buf_erase(size_t size) { buf_spos_ += size; }
  7658. std::string buf_;
  7659. size_t buf_spos_ = 0;
  7660. size_t buf_epos_ = 0;
  7661. };
  7662. inline std::string random_string(size_t length) {
  7663. constexpr const char data[] =
  7664. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  7665. thread_local auto engine([]() {
  7666. // std::random_device might actually be deterministic on some
  7667. // platforms, but due to lack of support in the c++ standard library,
  7668. // doing better requires either some ugly hacks or breaking portability.
  7669. std::random_device seed_gen;
  7670. // Request 128 bits of entropy for initialization
  7671. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  7672. return std::mt19937(seed_sequence);
  7673. }());
  7674. std::string result;
  7675. for (size_t i = 0; i < length; i++) {
  7676. result += data[engine() % (sizeof(data) - 1)];
  7677. }
  7678. return result;
  7679. }
  7680. inline std::string make_multipart_data_boundary() {
  7681. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  7682. }
  7683. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  7684. auto valid = true;
  7685. for (size_t i = 0; i < boundary.size(); i++) {
  7686. auto c = boundary[i];
  7687. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  7688. valid = false;
  7689. break;
  7690. }
  7691. }
  7692. return valid;
  7693. }
  7694. // Escape a multipart field name/filename following the WHATWG HTML standard
  7695. // ("escape a multipart form-data name"), which is what browsers send:
  7696. // '"' -> %22, CR -> %0D, LF -> %0A
  7697. // With escape_quote = false, only CR and LF are escaped; this is for header
  7698. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  7699. inline std::string escape_multipart_field(const std::string &s,
  7700. bool escape_quote = true) {
  7701. std::string result;
  7702. result.reserve(s.size());
  7703. for (auto c : s) {
  7704. switch (c) {
  7705. case '"':
  7706. if (escape_quote) {
  7707. result += "%22";
  7708. } else {
  7709. result += c;
  7710. }
  7711. break;
  7712. case '\r': result += "%0D"; break;
  7713. case '\n': result += "%0A"; break;
  7714. default: result += c; break;
  7715. }
  7716. }
  7717. return result;
  7718. }
  7719. template <typename T>
  7720. inline std::string
  7721. serialize_multipart_formdata_item_begin(const T &item,
  7722. const std::string &boundary) {
  7723. std::string body = "--" + boundary + "\r\n";
  7724. body += "Content-Disposition: form-data; name=\"" +
  7725. escape_multipart_field(item.name) + "\"";
  7726. if (!item.filename.empty()) {
  7727. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  7728. }
  7729. body += "\r\n";
  7730. if (!item.content_type.empty()) {
  7731. body +=
  7732. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  7733. "\r\n";
  7734. }
  7735. body += "\r\n";
  7736. return body;
  7737. }
  7738. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  7739. inline std::string
  7740. serialize_multipart_formdata_finish(const std::string &boundary) {
  7741. return "--" + boundary + "--\r\n";
  7742. }
  7743. inline std::string
  7744. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7745. return "multipart/form-data; boundary=" + boundary;
  7746. }
  7747. inline std::string
  7748. serialize_multipart_formdata(const UploadFormDataItems &items,
  7749. const std::string &boundary, bool finish = true) {
  7750. std::string body;
  7751. for (const auto &item : items) {
  7752. body += serialize_multipart_formdata_item_begin(item, boundary);
  7753. body += item.content + serialize_multipart_formdata_item_end();
  7754. }
  7755. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7756. return body;
  7757. }
  7758. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7759. const std::string &boundary) {
  7760. size_t total = 0;
  7761. for (const auto &item : items) {
  7762. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7763. total += item.content.size();
  7764. total += serialize_multipart_formdata_item_end().size();
  7765. }
  7766. total += serialize_multipart_formdata_finish(boundary).size();
  7767. return total;
  7768. }
  7769. struct MultipartSegment {
  7770. const char *data;
  7771. size_t size;
  7772. };
  7773. // NOTE: items must outlive the returned ContentProvider
  7774. // (safe for synchronous use inside Post/Put/Patch)
  7775. inline ContentProvider
  7776. make_multipart_content_provider(const UploadFormDataItems &items,
  7777. const std::string &boundary) {
  7778. // Own the per-item header strings and the finish string
  7779. std::vector<std::string> owned;
  7780. owned.reserve(items.size() + 1);
  7781. for (const auto &item : items)
  7782. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7783. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7784. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7785. std::vector<MultipartSegment> segs;
  7786. segs.reserve(items.size() * 3 + 1);
  7787. static const char crlf[] = "\r\n";
  7788. for (size_t i = 0; i < items.size(); i++) {
  7789. segs.push_back({owned[i].data(), owned[i].size()});
  7790. segs.push_back({items[i].content.data(), items[i].content.size()});
  7791. segs.push_back({crlf, 2});
  7792. }
  7793. segs.push_back({owned.back().data(), owned.back().size()});
  7794. struct MultipartState {
  7795. std::vector<std::string> owned;
  7796. std::vector<MultipartSegment> segs;
  7797. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7798. };
  7799. auto state = std::make_shared<MultipartState>();
  7800. state->owned = std::move(owned);
  7801. // `segs` holds raw pointers into owned strings; std::string move preserves
  7802. // the data pointer, so these pointers remain valid after the move above.
  7803. state->segs = std::move(segs);
  7804. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7805. // Buffer multiple small segments into fewer, larger writes to avoid
  7806. // excessive TCP packets when there are many form data items (#2410)
  7807. auto &buf = state->buf;
  7808. auto buf_size = buf.size();
  7809. size_t buf_len = 0;
  7810. size_t remaining = length;
  7811. // Find the first segment containing 'offset'
  7812. size_t pos = 0;
  7813. size_t seg_idx = 0;
  7814. for (; seg_idx < state->segs.size(); seg_idx++) {
  7815. const auto &seg = state->segs[seg_idx];
  7816. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7817. pos += seg.size;
  7818. }
  7819. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7820. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7821. const auto &seg = state->segs[seg_idx];
  7822. size_t available = seg.size - seg_offset;
  7823. size_t to_copy = (std::min)(available, remaining);
  7824. const char *src = seg.data + seg_offset;
  7825. seg_offset = 0; // only the first segment has a non-zero offset
  7826. while (to_copy > 0) {
  7827. size_t space = buf_size - buf_len;
  7828. size_t chunk = (std::min)(to_copy, space);
  7829. std::memcpy(buf.data() + buf_len, src, chunk);
  7830. buf_len += chunk;
  7831. src += chunk;
  7832. to_copy -= chunk;
  7833. remaining -= chunk;
  7834. if (buf_len == buf_size) {
  7835. if (!sink.write(buf.data(), buf_len)) { return false; }
  7836. buf_len = 0;
  7837. }
  7838. }
  7839. }
  7840. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7841. return true;
  7842. };
  7843. }
  7844. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7845. if (ranges.size() <= 1) return;
  7846. // Sort ranges by start position
  7847. std::sort(ranges.begin(), ranges.end(),
  7848. [](const Range &a, const Range &b) { return a.first < b.first; });
  7849. Ranges coalesced;
  7850. coalesced.reserve(ranges.size());
  7851. for (auto &r : ranges) {
  7852. auto first_pos = r.first;
  7853. auto last_pos = r.second;
  7854. // Handle special cases like in range_error
  7855. if (first_pos == -1 && last_pos == -1) {
  7856. first_pos = 0;
  7857. last_pos = static_cast<ssize_t>(content_length);
  7858. }
  7859. if (first_pos == -1) {
  7860. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7861. last_pos = static_cast<ssize_t>(content_length) - 1;
  7862. }
  7863. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7864. last_pos = static_cast<ssize_t>(content_length) - 1;
  7865. }
  7866. // Skip invalid ranges
  7867. if (!(0 <= first_pos && first_pos <= last_pos &&
  7868. last_pos < static_cast<ssize_t>(content_length))) {
  7869. continue;
  7870. }
  7871. // Coalesce with previous range if overlapping or adjacent (but not
  7872. // identical)
  7873. if (!coalesced.empty()) {
  7874. auto &prev = coalesced.back();
  7875. // Check if current range overlaps or is adjacent to previous range
  7876. // but don't coalesce identical ranges (allow duplicates)
  7877. if (first_pos <= prev.second + 1 &&
  7878. !(first_pos == prev.first && last_pos == prev.second)) {
  7879. // Extend the previous range
  7880. prev.second = (std::max)(prev.second, last_pos);
  7881. continue;
  7882. }
  7883. }
  7884. // Add new range
  7885. coalesced.emplace_back(first_pos, last_pos);
  7886. }
  7887. ranges = std::move(coalesced);
  7888. }
  7889. inline bool range_error(Request &req, Response &res) {
  7890. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7891. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7892. req.ranges.clear();
  7893. if (res.status == StatusCode::PartialContent_206) {
  7894. res.status = StatusCode::OK_200;
  7895. }
  7896. return false;
  7897. }
  7898. ssize_t content_len = static_cast<ssize_t>(
  7899. res.content_length_ ? res.content_length_ : res.body.size());
  7900. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7901. size_t overwrapping_count = 0;
  7902. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7903. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7904. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7905. // Too many ranges
  7906. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7907. for (auto &r : req.ranges) {
  7908. auto &first_pos = r.first;
  7909. auto &last_pos = r.second;
  7910. if (first_pos == -1 && last_pos == -1) {
  7911. first_pos = 0;
  7912. last_pos = content_len;
  7913. }
  7914. if (first_pos == -1) {
  7915. first_pos = content_len - last_pos;
  7916. last_pos = content_len - 1;
  7917. }
  7918. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7919. // A client can limit the number of bytes requested without knowing the
  7920. // size of the selected representation. If the last-pos value is absent,
  7921. // or if the value is greater than or equal to the current length of the
  7922. // representation data, the byte range is interpreted as the remainder of
  7923. // the representation (i.e., the server replaces the value of last-pos
  7924. // with a value that is one less than the current length of the selected
  7925. // representation).
  7926. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7927. if (last_pos == -1 || last_pos >= content_len) {
  7928. last_pos = content_len - 1;
  7929. }
  7930. // Range must be within content length
  7931. if (!(0 <= first_pos && first_pos <= last_pos &&
  7932. last_pos <= content_len - 1)) {
  7933. return true;
  7934. }
  7935. // Request must not have more than two overlapping ranges
  7936. for (const auto &processed_range : processed_ranges) {
  7937. if (!(last_pos < processed_range.first ||
  7938. first_pos > processed_range.second)) {
  7939. overwrapping_count++;
  7940. if (overwrapping_count > 2) { return true; }
  7941. break; // Only count once per range
  7942. }
  7943. }
  7944. processed_ranges.emplace_back(first_pos, last_pos);
  7945. }
  7946. // After validation, coalesce overlapping ranges as per RFC 9110
  7947. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7948. }
  7949. return false;
  7950. }
  7951. inline std::pair<size_t, size_t>
  7952. get_range_offset_and_length(Range r, size_t content_length) {
  7953. assert(r.first != -1 && r.second != -1);
  7954. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7955. assert(r.first <= r.second &&
  7956. r.second < static_cast<ssize_t>(content_length));
  7957. (void)(content_length);
  7958. return std::make_pair(static_cast<size_t>(r.first),
  7959. static_cast<size_t>(r.second - r.first) + 1);
  7960. }
  7961. inline std::string make_content_range_header_field(
  7962. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7963. auto st = offset_and_length.first;
  7964. auto ed = st + offset_and_length.second - 1;
  7965. std::string field = "bytes ";
  7966. field += std::to_string(st);
  7967. field += '-';
  7968. field += std::to_string(ed);
  7969. field += '/';
  7970. field += std::to_string(content_length);
  7971. return field;
  7972. }
  7973. template <typename SToken, typename CToken, typename Content>
  7974. bool process_multipart_ranges_data(const Request &req,
  7975. const std::string &boundary,
  7976. const std::string &content_type,
  7977. size_t content_length, SToken stoken,
  7978. CToken ctoken, Content content) {
  7979. for (size_t i = 0; i < req.ranges.size(); i++) {
  7980. ctoken("--");
  7981. stoken(boundary);
  7982. ctoken("\r\n");
  7983. if (!content_type.empty()) {
  7984. ctoken("Content-Type: ");
  7985. stoken(content_type);
  7986. ctoken("\r\n");
  7987. }
  7988. auto offset_and_length =
  7989. get_range_offset_and_length(req.ranges[i], content_length);
  7990. ctoken("Content-Range: ");
  7991. stoken(make_content_range_header_field(offset_and_length, content_length));
  7992. ctoken("\r\n");
  7993. ctoken("\r\n");
  7994. if (!content(offset_and_length.first, offset_and_length.second)) {
  7995. return false;
  7996. }
  7997. ctoken("\r\n");
  7998. }
  7999. ctoken("--");
  8000. stoken(boundary);
  8001. ctoken("--");
  8002. return true;
  8003. }
  8004. inline void make_multipart_ranges_data(const Request &req, Response &res,
  8005. const std::string &boundary,
  8006. const std::string &content_type,
  8007. size_t content_length,
  8008. std::string &data) {
  8009. process_multipart_ranges_data(
  8010. req, boundary, content_type, content_length,
  8011. [&](const std::string &token) { data += token; },
  8012. [&](const std::string &token) { data += token; },
  8013. [&](size_t offset, size_t length) {
  8014. assert(offset + length <= content_length);
  8015. data += res.body.substr(offset, length);
  8016. return true;
  8017. });
  8018. }
  8019. inline size_t get_multipart_ranges_data_length(const Request &req,
  8020. const std::string &boundary,
  8021. const std::string &content_type,
  8022. size_t content_length) {
  8023. size_t data_length = 0;
  8024. process_multipart_ranges_data(
  8025. req, boundary, content_type, content_length,
  8026. [&](const std::string &token) { data_length += token.size(); },
  8027. [&](const std::string &token) { data_length += token.size(); },
  8028. [&](size_t /*offset*/, size_t length) {
  8029. data_length += length;
  8030. return true;
  8031. });
  8032. return data_length;
  8033. }
  8034. template <typename T>
  8035. inline bool
  8036. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  8037. const std::string &boundary,
  8038. const std::string &content_type,
  8039. size_t content_length, const T &is_shutting_down) {
  8040. return process_multipart_ranges_data(
  8041. req, boundary, content_type, content_length,
  8042. [&](const std::string &token) { strm.write(token); },
  8043. [&](const std::string &token) { strm.write(token); },
  8044. [&](size_t offset, size_t length) {
  8045. return write_content(strm, res.content_provider_, offset, length,
  8046. is_shutting_down);
  8047. });
  8048. }
  8049. inline bool has_framed_body(const Request &req) {
  8050. return is_chunked_transfer_encoding(req.headers) ||
  8051. req.get_header_value_u64("Content-Length") > 0;
  8052. }
  8053. inline bool is_connection_persistent(const Request &req) {
  8054. if (has_header_token(req.headers, "Connection", "close")) { return false; }
  8055. if (req.version == "HTTP/1.0" &&
  8056. !has_header_token(req.headers, "Connection", "keep-alive")) {
  8057. return false;
  8058. }
  8059. return true;
  8060. }
  8061. inline bool expect_content(const Request &req) {
  8062. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  8063. req.method == "DELETE") {
  8064. return true;
  8065. }
  8066. return has_framed_body(req);
  8067. }
  8068. #ifdef _WIN32
  8069. class WSInit {
  8070. public:
  8071. WSInit() {
  8072. WSADATA wsaData;
  8073. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  8074. }
  8075. ~WSInit() {
  8076. if (is_valid_) WSACleanup();
  8077. }
  8078. bool is_valid_ = false;
  8079. };
  8080. static WSInit wsinit_;
  8081. #endif
  8082. // RFC 9110 Section 11.6.1 defines a challenge list as
  8083. // WWW-Authenticate = #challenge
  8084. // challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
  8085. // auth-param = token BWS "=" BWS ( token / quoted-string )
  8086. // so a server may offer several schemes, each with its own comma-separated
  8087. // auth-param list, in either order and either as separate field lines or
  8088. // packed into one. Splitting on every comma would break apart a challenge's
  8089. // own param list; splitting only on the first space would miss a Digest
  8090. // challenge that isn't first. Split on commas that aren't inside a
  8091. // quoted-string instead, then track which scheme each resulting segment
  8092. // belongs to: a segment whose text before "=" contains whitespace (or that
  8093. // has no "=" at all) starts a new challenge named by its leading token.
  8094. inline std::vector<std::string> split_challenge_segments(const std::string &s) {
  8095. std::vector<std::string> segments;
  8096. size_t start = 0;
  8097. auto in_quotes = false;
  8098. for (size_t i = 0; i < s.size(); i++) {
  8099. auto c = s[i];
  8100. if (in_quotes) {
  8101. if (c == '\\' && i + 1 < s.size()) {
  8102. i++;
  8103. } else if (c == '"') {
  8104. in_quotes = false;
  8105. }
  8106. } else if (c == '"') {
  8107. in_quotes = true;
  8108. } else if (c == ',') {
  8109. segments.push_back(s.substr(start, i - start));
  8110. start = i + 1;
  8111. }
  8112. }
  8113. segments.push_back(s.substr(start));
  8114. return segments;
  8115. }
  8116. inline std::string unescape_quoted_pairs(const std::string &s) {
  8117. std::string out;
  8118. out.reserve(s.size());
  8119. for (size_t i = 0; i < s.size(); i++) {
  8120. if (s[i] == '\\' && i + 1 < s.size()) {
  8121. out += s[++i];
  8122. } else {
  8123. out += s[i];
  8124. }
  8125. }
  8126. return out;
  8127. }
  8128. inline bool parse_www_authenticate(const Response &res,
  8129. std::map<std::string, std::string> &auth,
  8130. bool is_proxy) {
  8131. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  8132. auto combined = get_combined_header_value(res.headers, auth_key);
  8133. if (combined.empty()) { return false; }
  8134. auto found_digest = false;
  8135. auto in_digest_challenge = false;
  8136. for (const auto &raw_segment : split_challenge_segments(combined)) {
  8137. auto segment = trim_copy(raw_segment);
  8138. if (segment.empty()) { continue; }
  8139. auto eq_pos = segment.find('=');
  8140. // BWS is allowed on both sides of "=", so the text naming the key (or,
  8141. // for the first segment of a challenge, "<scheme> <key>") must be
  8142. // trimmed before its boundaries are inspected.
  8143. auto key_part = trim_copy(
  8144. eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
  8145. auto space_pos = key_part.find_last_of(" \t");
  8146. if (space_pos != std::string::npos || eq_pos == std::string::npos) {
  8147. // "<scheme>[ <key>]" starts a new challenge.
  8148. auto scheme_end =
  8149. space_pos == std::string::npos ? key_part.size() : space_pos;
  8150. // RFC 7616 Section 3.7: a server may offer more than one Digest
  8151. // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
  8152. // from one challenge is never paired with another's algorithm.
  8153. in_digest_challenge =
  8154. !found_digest &&
  8155. case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
  8156. if (in_digest_challenge) { found_digest = true; }
  8157. if (space_pos == std::string::npos) {
  8158. // Bare scheme (or a token68), no auth-param on this segment.
  8159. continue;
  8160. }
  8161. key_part = key_part.substr(space_pos + 1);
  8162. }
  8163. if (!in_digest_challenge) { continue; }
  8164. auto val = trim_copy(segment.substr(eq_pos + 1));
  8165. auto unquoted = trim_double_quotes_copy(val);
  8166. if (unquoted.size() != val.size()) {
  8167. unquoted = unescape_quoted_pairs(unquoted);
  8168. }
  8169. auth[std::move(key_part)] = std::move(unquoted);
  8170. }
  8171. // A challenge with no auth-param can't produce a usable Authorization
  8172. // header, so treat it the same as no Digest challenge at all.
  8173. return found_digest && !auth.empty();
  8174. }
  8175. class ContentProviderAdapter {
  8176. public:
  8177. explicit ContentProviderAdapter(
  8178. ContentProviderWithoutLength &&content_provider)
  8179. : content_provider_(std::move(content_provider)) {}
  8180. bool operator()(size_t offset, size_t, DataSink &sink) {
  8181. return content_provider_(offset, sink);
  8182. }
  8183. private:
  8184. ContentProviderWithoutLength content_provider_;
  8185. };
  8186. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  8187. namespace fields {
  8188. inline bool is_token_char(char c) {
  8189. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  8190. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  8191. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  8192. }
  8193. inline bool is_token(const std::string &s) {
  8194. if (s.empty()) { return false; }
  8195. for (auto c : s) {
  8196. if (!is_token_char(c)) { return false; }
  8197. }
  8198. return true;
  8199. }
  8200. inline bool is_field_name(const std::string &s) { return is_token(s); }
  8201. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  8202. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  8203. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  8204. inline bool is_field_content(const std::string &s) {
  8205. if (s.empty()) { return true; }
  8206. if (s.size() == 1) {
  8207. return is_field_vchar(s[0]);
  8208. } else if (s.size() == 2) {
  8209. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  8210. } else {
  8211. size_t i = 0;
  8212. if (!is_field_vchar(s[i])) { return false; }
  8213. i++;
  8214. while (i < s.size() - 1) {
  8215. auto c = s[i++];
  8216. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  8217. } else {
  8218. return false;
  8219. }
  8220. }
  8221. return is_field_vchar(s[i]);
  8222. }
  8223. }
  8224. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  8225. inline bool is_field_valid(const std::string &name, const std::string &value) {
  8226. return is_field_name(name) && is_field_value(value);
  8227. }
  8228. } // namespace fields
  8229. inline bool perform_websocket_handshake(Stream &strm, Request &req,
  8230. WebSocketUpgradeResponse &upgrade) {
  8231. // Generate random Sec-WebSocket-Key
  8232. thread_local std::mt19937 rng(std::random_device{}());
  8233. std::string key_bytes(16, '\0');
  8234. for (size_t i = 0; i < 16; i += 4) {
  8235. auto r = rng();
  8236. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  8237. }
  8238. auto client_key = base64_encode(key_bytes);
  8239. req.headers.erase("Upgrade");
  8240. req.headers.erase("Connection");
  8241. req.headers.erase("Sec-WebSocket-Key");
  8242. req.headers.erase("Sec-WebSocket-Version");
  8243. req.headers.emplace("Upgrade", "websocket");
  8244. req.headers.emplace("Connection", "Upgrade");
  8245. req.headers.emplace("Sec-WebSocket-Key", client_key);
  8246. req.headers.emplace("Sec-WebSocket-Version", "13");
  8247. // Build the request in memory first, like ClientImpl::write_request does.
  8248. // Writing straight to the socket would leak a request line onto the wire
  8249. // before check_and_write_headers gets a chance to reject an invalid header,
  8250. // and would emit one small write per header.
  8251. BufferStream bstrm;
  8252. if (write_request_line(bstrm, req.method, req.path) < 0) {
  8253. upgrade.error = Error::Write;
  8254. return false;
  8255. }
  8256. auto error = Error::Success;
  8257. if (!check_and_write_headers(bstrm, req.headers, write_headers, error)) {
  8258. upgrade.error = error;
  8259. return false;
  8260. }
  8261. const auto &data = bstrm.get_buffer();
  8262. if (!write_data(strm, data.data(), data.size())) {
  8263. upgrade.error = Error::Write;
  8264. return false;
  8265. }
  8266. // Verify 101 response and Sec-WebSocket-Accept header
  8267. auto expected_accept = websocket_accept_key(client_key);
  8268. return read_websocket_upgrade_response(strm, expected_accept, upgrade);
  8269. }
  8270. inline bool is_ip_address(const std::string &host) {
  8271. struct in_addr addr4;
  8272. struct in6_addr addr6;
  8273. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  8274. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  8275. }
  8276. // Resolve where a client should connect for `host`, honoring a user-supplied
  8277. // hostname-to-address map. `host` itself is never rewritten, so it keeps
  8278. // supplying the Host header and SNI; only the connection target changes.
  8279. //
  8280. // A mapped IP literal goes to `ip`, which keeps create_socket's AI_NUMERICHOST
  8281. // path. Anything else goes to `connect_host`, which create_socket resolves as
  8282. // a name, or uses as the socket path when the address family is AF_UNIX. An
  8283. // absent or empty mapping leaves `host` as the connection target; without the
  8284. // empty check the value would reach getaddrinfo as a null node and silently
  8285. // resolve to loopback.
  8286. inline void apply_addr_map(const std::map<std::string, std::string> &addr_map,
  8287. const std::string &host, std::string &connect_host,
  8288. std::string &ip) {
  8289. connect_host = host;
  8290. ip.clear();
  8291. auto it = addr_map.find(host);
  8292. if (it == addr_map.end() || it->second.empty()) { return; }
  8293. if (is_ip_address(it->second)) {
  8294. ip = it->second;
  8295. } else {
  8296. connect_host = it->second;
  8297. }
  8298. }
  8299. } // namespace detail
  8300. /*
  8301. * Group 2: detail namespace - SSL common utilities
  8302. */
  8303. #ifdef CPPHTTPLIB_SSL_ENABLED
  8304. namespace detail {
  8305. class SSLSocketStream final : public Stream {
  8306. public:
  8307. SSLSocketStream(
  8308. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8309. time_t read_timeout_usec, time_t write_timeout_sec,
  8310. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  8311. std::chrono::time_point<std::chrono::steady_clock> start_time =
  8312. (std::chrono::steady_clock::time_point::min)());
  8313. ~SSLSocketStream() override;
  8314. bool is_readable() const override;
  8315. bool wait_readable() const override;
  8316. bool wait_writable() const override;
  8317. bool is_peer_alive() const override;
  8318. ssize_t read(char *ptr, size_t size) override;
  8319. ssize_t write(const char *ptr, size_t size) override;
  8320. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8321. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8322. socket_t socket() const override;
  8323. time_t duration() const override;
  8324. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8325. // See SocketStream::set_readable_hint().
  8326. void set_readable_hint() { readable_hint_ = true; }
  8327. private:
  8328. bool ensure_readable();
  8329. socket_t sock_;
  8330. tls::session_t session_;
  8331. time_t read_timeout_sec_;
  8332. time_t read_timeout_usec_;
  8333. time_t write_timeout_sec_;
  8334. time_t write_timeout_usec_;
  8335. time_t max_timeout_msec_;
  8336. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8337. bool readable_hint_ = false;
  8338. };
  8339. // A TLS stream for WebSocket connections, where the receive path and the
  8340. // send path (application send() plus the heartbeat ping thread) run on
  8341. // different threads. A single TLS session must never be entered
  8342. // concurrently, so every call into the session is serialized by one mutex.
  8343. //
  8344. // Unlike SSLSocketStream, the socket is kept non-blocking for the stream's
  8345. // whole lifetime and each read()/write() performs a single non-blocking TLS
  8346. // call under the lock, then waits for readiness with select() outside the
  8347. // lock. The lock is therefore held only for CPU-bound work, so a reader
  8348. // blocked waiting for data never stalls a concurrent sender.
  8349. //
  8350. // This stream is used only for wss:// connections. Plain ws:// and ordinary
  8351. // HTTP/HTTPS keep using SocketStream/SSLSocketStream unchanged.
  8352. class WebSocketSSLStream final : public Stream {
  8353. public:
  8354. WebSocketSSLStream(socket_t sock, tls::session_t session,
  8355. time_t read_timeout_sec, time_t read_timeout_usec,
  8356. time_t write_timeout_sec, time_t write_timeout_usec);
  8357. ~WebSocketSSLStream() override;
  8358. bool is_readable() const override;
  8359. bool wait_readable() const override;
  8360. bool wait_writable() const override;
  8361. ssize_t read(char *ptr, size_t size) override;
  8362. ssize_t write(const char *ptr, size_t size) override;
  8363. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8364. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8365. socket_t socket() const override;
  8366. time_t duration() const override;
  8367. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8368. private:
  8369. mutable std::mutex session_mutex_;
  8370. socket_t sock_;
  8371. tls::session_t session_;
  8372. // WebSocket::close() shortens the read timeout from the closing thread
  8373. // while the receive thread is inside wait_readable(), so these two are read
  8374. // and written concurrently. The write timeouts are never mutated.
  8375. std::atomic<time_t> read_timeout_sec_;
  8376. std::atomic<time_t> read_timeout_usec_;
  8377. time_t write_timeout_sec_;
  8378. time_t write_timeout_usec_;
  8379. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8380. };
  8381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8382. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  8383. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  8384. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  8385. unsigned int hash_length = 0;
  8386. unsigned char hash[EVP_MAX_MD_SIZE];
  8387. EVP_DigestInit_ex(context.get(), algo, nullptr);
  8388. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  8389. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  8390. std::stringstream ss;
  8391. for (auto i = 0u; i < hash_length; ++i) {
  8392. ss << std::hex << std::setw(2) << std::setfill('0')
  8393. << static_cast<unsigned int>(hash[i]);
  8394. }
  8395. return ss.str();
  8396. }
  8397. inline std::string MD5(const std::string &s) {
  8398. return message_digest(s, EVP_md5());
  8399. }
  8400. inline std::string SHA_256(const std::string &s) {
  8401. return message_digest(s, EVP_sha256());
  8402. }
  8403. inline std::string SHA_512(const std::string &s) {
  8404. return message_digest(s, EVP_sha512());
  8405. }
  8406. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  8407. namespace {
  8408. template <size_t N>
  8409. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8410. std::stringstream ss;
  8411. for (size_t i = 0; i < N; ++i) {
  8412. ss << std::hex << std::setw(2) << std::setfill('0')
  8413. << static_cast<unsigned int>(hash[i]);
  8414. }
  8415. return ss.str();
  8416. }
  8417. } // namespace
  8418. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8419. // Mbed TLS 4.x provides hashing (and TLS RNG) via PSA Crypto, which must be
  8420. // initialized once. PSA state is process-global; do not free it.
  8421. inline bool ensure_mbedtls_psa_crypto() {
  8422. static std::once_flag once;
  8423. static bool ok = false;
  8424. std::call_once(once, []() { ok = (psa_crypto_init() == PSA_SUCCESS); });
  8425. return ok;
  8426. }
  8427. inline bool psa_hash(psa_algorithm_t alg, const std::string &s,
  8428. unsigned char *out, size_t out_size) {
  8429. if (!ensure_mbedtls_psa_crypto()) { return false; }
  8430. size_t olen = 0;
  8431. return psa_hash_compute(alg, reinterpret_cast<const uint8_t *>(s.data()),
  8432. s.size(), out, out_size, &olen) == PSA_SUCCESS &&
  8433. olen == out_size;
  8434. }
  8435. #endif
  8436. inline std::string MD5(const std::string &s) {
  8437. unsigned char hash[16];
  8438. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8439. if (!psa_hash(PSA_ALG_MD5, s, hash, sizeof(hash))) { return {}; }
  8440. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8441. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8442. hash);
  8443. #else
  8444. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8445. hash);
  8446. #endif
  8447. return hash_to_hex(hash);
  8448. }
  8449. inline std::string SHA_256(const std::string &s) {
  8450. unsigned char hash[32];
  8451. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8452. if (!psa_hash(PSA_ALG_SHA_256, s, hash, sizeof(hash))) { return {}; }
  8453. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8454. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8455. hash, 0);
  8456. #else
  8457. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8458. s.size(), hash, 0);
  8459. #endif
  8460. return hash_to_hex(hash);
  8461. }
  8462. inline std::string SHA_512(const std::string &s) {
  8463. unsigned char hash[64];
  8464. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8465. if (!psa_hash(PSA_ALG_SHA_512, s, hash, sizeof(hash))) { return {}; }
  8466. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8467. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8468. hash, 0);
  8469. #else
  8470. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8471. s.size(), hash, 0);
  8472. #endif
  8473. return hash_to_hex(hash);
  8474. }
  8475. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  8476. namespace {
  8477. template <size_t N>
  8478. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8479. std::stringstream ss;
  8480. for (size_t i = 0; i < N; ++i) {
  8481. ss << std::hex << std::setw(2) << std::setfill('0')
  8482. << static_cast<unsigned int>(hash[i]);
  8483. }
  8484. return ss.str();
  8485. }
  8486. } // namespace
  8487. inline std::string MD5(const std::string &s) {
  8488. unsigned char hash[WC_MD5_DIGEST_SIZE];
  8489. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8490. static_cast<word32>(s.size()), hash);
  8491. return hash_to_hex(hash);
  8492. }
  8493. inline std::string SHA_256(const std::string &s) {
  8494. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  8495. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8496. static_cast<word32>(s.size()), hash);
  8497. return hash_to_hex(hash);
  8498. }
  8499. inline std::string SHA_512(const std::string &s) {
  8500. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  8501. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8502. static_cast<word32>(s.size()), hash);
  8503. return hash_to_hex(hash);
  8504. }
  8505. #endif
  8506. template <typename T>
  8507. inline bool process_server_socket_ssl(
  8508. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  8509. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8510. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8511. time_t write_timeout_usec, T callback) {
  8512. return process_server_socket_core(
  8513. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8514. [&](bool close_connection, bool &connection_closed) {
  8515. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  8516. write_timeout_sec, write_timeout_usec);
  8517. // See the non-TLS path in process_server_socket().
  8518. strm.set_readable_hint();
  8519. return callback(strm, close_connection, connection_closed);
  8520. });
  8521. }
  8522. template <typename T>
  8523. inline bool process_client_socket_ssl(
  8524. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  8525. time_t read_timeout_usec, time_t write_timeout_sec,
  8526. time_t write_timeout_usec, time_t max_timeout_msec,
  8527. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  8528. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  8529. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  8530. start_time);
  8531. return callback(strm);
  8532. }
  8533. inline std::pair<std::string, std::string> make_digest_authentication_header(
  8534. const Request &req, const std::map<std::string, std::string> &auth,
  8535. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  8536. const std::string &password, bool is_proxy = false) {
  8537. std::string nc;
  8538. {
  8539. std::stringstream ss;
  8540. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  8541. nc = ss.str();
  8542. }
  8543. std::string qop;
  8544. if (auth.find("qop") != auth.end()) {
  8545. qop = auth.at("qop");
  8546. if (qop.find("auth-int") != std::string::npos) {
  8547. qop = "auth-int";
  8548. } else if (qop.find("auth") != std::string::npos) {
  8549. qop = "auth";
  8550. } else {
  8551. qop.clear();
  8552. }
  8553. }
  8554. std::string algo = "MD5";
  8555. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  8556. std::string response;
  8557. {
  8558. auto H = algo == "SHA-256" ? detail::SHA_256
  8559. : algo == "SHA-512" ? detail::SHA_512
  8560. : detail::MD5;
  8561. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  8562. auto A2 = req.method + ":" + req.path;
  8563. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  8564. if (qop.empty()) {
  8565. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  8566. } else {
  8567. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  8568. ":" + qop + ":" + H(A2));
  8569. }
  8570. }
  8571. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  8572. auto field = "Digest username=\"" + username + "\", realm=\"" +
  8573. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  8574. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  8575. (qop.empty() ? ", response=\""
  8576. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  8577. cnonce + "\", response=\"") +
  8578. response + "\"" +
  8579. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  8580. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8581. return std::make_pair(key, field);
  8582. }
  8583. inline bool match_hostname(const std::string &pattern,
  8584. const std::string &hostname) {
  8585. // Exact match (case-insensitive)
  8586. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  8587. // Split both pattern and hostname into components by '.'
  8588. std::vector<std::string> pattern_components;
  8589. if (!pattern.empty()) {
  8590. split(pattern.data(), pattern.data() + pattern.size(), '.',
  8591. [&](const char *b, const char *e) {
  8592. pattern_components.emplace_back(b, e);
  8593. });
  8594. }
  8595. std::vector<std::string> host_components;
  8596. if (!hostname.empty()) {
  8597. split(hostname.data(), hostname.data() + hostname.size(), '.',
  8598. [&](const char *b, const char *e) {
  8599. host_components.emplace_back(b, e);
  8600. });
  8601. }
  8602. // Component count must match
  8603. if (host_components.size() != pattern_components.size()) { return false; }
  8604. // Compare each component with wildcard support
  8605. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  8606. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  8607. auto itr = pattern_components.begin();
  8608. for (const auto &h : host_components) {
  8609. auto &p = *itr;
  8610. if (!detail::case_ignore::equal(p, h) && p != "*") {
  8611. bool partial_match = false;
  8612. if (!p.empty() && p[p.size() - 1] == '*') {
  8613. const auto prefix_length = p.size() - 1;
  8614. if (prefix_length == 0) {
  8615. partial_match = true;
  8616. } else if (h.size() >= prefix_length) {
  8617. partial_match =
  8618. std::equal(p.begin(),
  8619. p.begin() + static_cast<std::string::difference_type>(
  8620. prefix_length),
  8621. h.begin(), [](const char ca, const char cb) {
  8622. return detail::case_ignore::to_lower(ca) ==
  8623. detail::case_ignore::to_lower(cb);
  8624. });
  8625. }
  8626. }
  8627. if (!partial_match) { return false; }
  8628. }
  8629. ++itr;
  8630. }
  8631. return true;
  8632. }
  8633. #ifdef _WIN32
  8634. // Verify certificate using Windows CertGetCertificateChain API.
  8635. // This provides real-time certificate validation with Windows Update
  8636. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  8637. inline bool
  8638. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  8639. const std::string &hostname,
  8640. bool verify_hostname, uint64_t &out_error) {
  8641. if (der_cert.empty()) { return false; }
  8642. out_error = 0;
  8643. // Create Windows certificate context from DER data
  8644. auto cert_context = CertCreateCertificateContext(
  8645. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  8646. static_cast<DWORD>(der_cert.size()));
  8647. if (!cert_context) {
  8648. out_error = GetLastError();
  8649. return false;
  8650. }
  8651. auto cert_guard =
  8652. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  8653. // Setup chain parameters
  8654. CERT_CHAIN_PARA chain_para = {};
  8655. chain_para.cbSize = sizeof(chain_para);
  8656. // Build certificate chain with revocation checking
  8657. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  8658. auto chain_result = CertGetCertificateChain(
  8659. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  8660. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  8661. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  8662. nullptr, &chain_context);
  8663. if (!chain_result || !chain_context) {
  8664. out_error = GetLastError();
  8665. return false;
  8666. }
  8667. auto chain_guard =
  8668. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  8669. // Check if chain has errors
  8670. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  8671. out_error = chain_context->TrustStatus.dwErrorStatus;
  8672. return false;
  8673. }
  8674. // Verify SSL policy
  8675. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  8676. extra_policy_para.cbSize = sizeof(extra_policy_para);
  8677. #ifdef AUTHTYPE_SERVER
  8678. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  8679. #endif
  8680. std::wstring whost;
  8681. if (verify_hostname) {
  8682. whost = u8string_to_wstring(hostname.c_str());
  8683. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  8684. }
  8685. CERT_CHAIN_POLICY_PARA policy_para = {};
  8686. policy_para.cbSize = sizeof(policy_para);
  8687. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  8688. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  8689. #else
  8690. policy_para.dwFlags = 0;
  8691. #endif
  8692. policy_para.pvExtraPolicyPara = &extra_policy_para;
  8693. CERT_CHAIN_POLICY_STATUS policy_status = {};
  8694. policy_status.cbSize = sizeof(policy_status);
  8695. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  8696. &policy_para, &policy_status)) {
  8697. out_error = GetLastError();
  8698. return false;
  8699. }
  8700. if (policy_status.dwError != 0) {
  8701. out_error = policy_status.dwError;
  8702. return false;
  8703. }
  8704. return true;
  8705. }
  8706. #endif // _WIN32
  8707. // Loads CA file/dir configuration and applies the system CA policy to a
  8708. // client TLS context. PEM data and native stores are applied to the context
  8709. // directly at set time; has_custom_store reflects them for the Auto policy
  8710. // decision.
  8711. inline bool load_client_ca_config(tls::ctx_t ctx,
  8712. const std::string &ca_cert_file_path,
  8713. const std::string &ca_cert_dir_path,
  8714. bool has_custom_store, SystemCAMode mode,
  8715. uint64_t &backend_error) {
  8716. auto ret = true;
  8717. if (!ca_cert_file_path.empty()) {
  8718. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  8719. backend_error = tls::get_error();
  8720. ret = false;
  8721. }
  8722. } else if (!ca_cert_dir_path.empty()) {
  8723. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  8724. backend_error = tls::get_error();
  8725. ret = false;
  8726. }
  8727. }
  8728. auto has_custom_ca = !ca_cert_file_path.empty() ||
  8729. !ca_cert_dir_path.empty() || has_custom_store;
  8730. if (mode == SystemCAMode::Enabled ||
  8731. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  8732. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  8733. }
  8734. return ret;
  8735. }
  8736. // The parts of session setup that only SSLClient needs, plus the handful
  8737. // WebSocketClient also exposes; everything else takes the defaults, which is
  8738. // what keeps the two clients on one implementation.
  8739. struct ClientTlsSessionOptions {
  8740. // Both SSLClient and WebSocketClient expose this independently of
  8741. // certificate verification.
  8742. bool server_hostname_verification = true;
  8743. std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
  8744. // When non-null, guards session creation against concurrent use of the
  8745. // context. A WebSocketClient is not safe to use from several threads to
  8746. // begin with, so it passes nothing.
  8747. std::mutex *ctx_mutex = nullptr;
  8748. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  8749. // The caller decides whether Schannel has anything to say about this
  8750. // connection; see SSLClient::initialize_ssl().
  8751. bool windows_cert_verification = false;
  8752. #endif
  8753. };
  8754. // Filled in on failure for callers that report error details.
  8755. struct ClientTlsSessionError {
  8756. Error error = Error::Success;
  8757. int ssl_error = 0;
  8758. uint64_t backend_error = 0;
  8759. };
  8760. // Establishes a client TLS session on an already connected socket. On failure
  8761. // the session is left for the caller to free: SSLClient frees it right away,
  8762. // WebSocketClient keeps it in a member that shutdown_and_close() cleans up.
  8763. inline bool setup_client_tls_session(
  8764. const std::string &host, tls::ctx_t ctx, tls::session_t &session,
  8765. socket_t sock, bool server_certificate_verification, time_t timeout_sec,
  8766. time_t timeout_usec, ClientTlsSessionError *out_error = nullptr,
  8767. const ClientTlsSessionOptions &options = ClientTlsSessionOptions()) {
  8768. using namespace tls;
  8769. auto fail = [&](Error error, int ssl_error, uint64_t backend_error) {
  8770. if (out_error) {
  8771. out_error->error = error;
  8772. out_error->ssl_error = ssl_error;
  8773. out_error->backend_error = backend_error;
  8774. }
  8775. return false;
  8776. };
  8777. if (!ctx) {
  8778. session = nullptr;
  8779. return fail(Error::SSLConnection, 0, 0);
  8780. }
  8781. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  8782. // Mbed TLS and wolfSSL need the verification mode set explicitly; OpenSSL
  8783. // uses SSL_VERIFY_NONE and does all verification post-handshake. Chain
  8784. // verification happens during the handshake even for IP hosts; the
  8785. // certificate identity is verified post-handshake via verify_hostname().
  8786. set_verify_client(ctx, server_certificate_verification);
  8787. #endif
  8788. {
  8789. std::unique_lock<std::mutex> guard;
  8790. if (options.ctx_mutex) {
  8791. guard = std::unique_lock<std::mutex>(*options.ctx_mutex);
  8792. }
  8793. session = create_session(ctx, sock);
  8794. }
  8795. if (!session) { return fail(Error::SSLConnection, 0, get_error()); }
  8796. // RFC 6066: SNI must not be set for IP addresses; skip it for IP hosts, so
  8797. // their identity is checked post-handshake below instead. On Mbed TLS and
  8798. // wolfSSL, set_sni also drives handshake-time hostname verification, so
  8799. // options.server_hostname_verification is threaded through here.
  8800. if (!is_ip_address(host)) {
  8801. if (!set_sni(session, host.c_str(), options.server_hostname_verification)) {
  8802. return fail(Error::SSLConnection, 0, get_error());
  8803. }
  8804. }
  8805. TlsError tls_err;
  8806. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec,
  8807. &tls_err)) {
  8808. auto error = Error::SSLConnection;
  8809. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  8810. error = Error::SSLServerVerification;
  8811. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  8812. error = Error::SSLServerHostnameVerification;
  8813. }
  8814. return fail(error, static_cast<int>(tls_err.code), tls_err.backend_code);
  8815. }
  8816. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  8817. if (options.session_verifier) {
  8818. verification_status = options.session_verifier(session);
  8819. }
  8820. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  8821. return fail(Error::SSLServerVerification, 0, get_error());
  8822. }
  8823. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  8824. server_certificate_verification) {
  8825. auto verify_result = get_verify_result(session);
  8826. if (verify_result != 0) {
  8827. return fail(Error::SSLServerVerification, 0,
  8828. static_cast<uint64_t>(verify_result));
  8829. }
  8830. auto server_cert = get_peer_cert(session);
  8831. if (!server_cert) {
  8832. return fail(Error::SSLServerVerification, 0, get_error());
  8833. }
  8834. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  8835. // Identity check against the peer certificate, post-handshake for all
  8836. // backends. For IP hosts this is the only identity verification, since no
  8837. // hostname is bound during the handshake.
  8838. if (options.server_hostname_verification) {
  8839. if (!verify_hostname(server_cert, host.c_str())) {
  8840. return fail(Error::SSLServerHostnameVerification, 0,
  8841. hostname_mismatch_code());
  8842. }
  8843. }
  8844. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  8845. // Additional Windows Schannel verification.
  8846. // This provides real-time certificate validation with Windows Update
  8847. // integration, working with both OpenSSL and MbedTLS backends.
  8848. if (options.windows_cert_verification) {
  8849. std::vector<unsigned char> der;
  8850. if (get_cert_der(server_cert, der)) {
  8851. uint64_t wincrypt_error = 0;
  8852. if (!verify_cert_with_windows_schannel(
  8853. der, host, options.server_hostname_verification,
  8854. wincrypt_error)) {
  8855. return fail(Error::SSLServerVerification, 0, wincrypt_error);
  8856. }
  8857. }
  8858. }
  8859. #endif
  8860. }
  8861. return true;
  8862. }
  8863. } // namespace detail
  8864. #endif // CPPHTTPLIB_SSL_ENABLED
  8865. /*
  8866. * Group 3: httplib namespace - Non-SSL public API implementations
  8867. */
  8868. inline void default_socket_options(socket_t sock) {
  8869. set_socket_opt(sock, SOL_SOCKET,
  8870. #ifdef SO_REUSEPORT
  8871. SO_REUSEPORT,
  8872. #else
  8873. SO_REUSEADDR,
  8874. #endif
  8875. 1);
  8876. }
  8877. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  8878. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  8879. sizeof(optval));
  8880. }
  8881. inline std::string get_bearer_token_auth(const Request &req) {
  8882. // The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
  8883. // than the prefix carries no token.
  8884. constexpr const char bearer_prefix[] = "Bearer ";
  8885. constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
  8886. auto value = req.get_header_value("Authorization");
  8887. if (value.size() >= bearer_prefix_len &&
  8888. detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
  8889. bearer_prefix)) {
  8890. return value.substr(bearer_prefix_len);
  8891. }
  8892. return "";
  8893. }
  8894. inline const char *status_message(int status) {
  8895. switch (status) {
  8896. case StatusCode::Continue_100: return "Continue";
  8897. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  8898. case StatusCode::Processing_102: return "Processing";
  8899. case StatusCode::EarlyHints_103: return "Early Hints";
  8900. case StatusCode::OK_200: return "OK";
  8901. case StatusCode::Created_201: return "Created";
  8902. case StatusCode::Accepted_202: return "Accepted";
  8903. case StatusCode::NonAuthoritativeInformation_203:
  8904. return "Non-Authoritative Information";
  8905. case StatusCode::NoContent_204: return "No Content";
  8906. case StatusCode::ResetContent_205: return "Reset Content";
  8907. case StatusCode::PartialContent_206: return "Partial Content";
  8908. case StatusCode::MultiStatus_207: return "Multi-Status";
  8909. case StatusCode::AlreadyReported_208: return "Already Reported";
  8910. case StatusCode::IMUsed_226: return "IM Used";
  8911. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  8912. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  8913. case StatusCode::Found_302: return "Found";
  8914. case StatusCode::SeeOther_303: return "See Other";
  8915. case StatusCode::NotModified_304: return "Not Modified";
  8916. case StatusCode::UseProxy_305: return "Use Proxy";
  8917. case StatusCode::unused_306: return "unused";
  8918. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  8919. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  8920. case StatusCode::BadRequest_400: return "Bad Request";
  8921. case StatusCode::Unauthorized_401: return "Unauthorized";
  8922. case StatusCode::PaymentRequired_402: return "Payment Required";
  8923. case StatusCode::Forbidden_403: return "Forbidden";
  8924. case StatusCode::NotFound_404: return "Not Found";
  8925. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  8926. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  8927. case StatusCode::ProxyAuthenticationRequired_407:
  8928. return "Proxy Authentication Required";
  8929. case StatusCode::RequestTimeout_408: return "Request Timeout";
  8930. case StatusCode::Conflict_409: return "Conflict";
  8931. case StatusCode::Gone_410: return "Gone";
  8932. case StatusCode::LengthRequired_411: return "Length Required";
  8933. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  8934. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  8935. case StatusCode::UriTooLong_414: return "URI Too Long";
  8936. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  8937. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  8938. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  8939. case StatusCode::ImATeapot_418: return "I'm a teapot";
  8940. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  8941. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  8942. case StatusCode::Locked_423: return "Locked";
  8943. case StatusCode::FailedDependency_424: return "Failed Dependency";
  8944. case StatusCode::TooEarly_425: return "Too Early";
  8945. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  8946. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  8947. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  8948. case StatusCode::RequestHeaderFieldsTooLarge_431:
  8949. return "Request Header Fields Too Large";
  8950. case StatusCode::UnavailableForLegalReasons_451:
  8951. return "Unavailable For Legal Reasons";
  8952. case StatusCode::NotImplemented_501: return "Not Implemented";
  8953. case StatusCode::BadGateway_502: return "Bad Gateway";
  8954. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  8955. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  8956. case StatusCode::HttpVersionNotSupported_505:
  8957. return "HTTP Version Not Supported";
  8958. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  8959. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  8960. case StatusCode::LoopDetected_508: return "Loop Detected";
  8961. case StatusCode::NotExtended_510: return "Not Extended";
  8962. case StatusCode::NetworkAuthenticationRequired_511:
  8963. return "Network Authentication Required";
  8964. default:
  8965. case StatusCode::InternalServerError_500: return "Internal Server Error";
  8966. }
  8967. }
  8968. inline std::string to_string(const Error error) {
  8969. switch (error) {
  8970. case Error::Success: return "Success (no error)";
  8971. case Error::Unknown: return "Unknown";
  8972. case Error::Connection: return "Could not establish connection";
  8973. case Error::BindIPAddress: return "Failed to bind IP address";
  8974. case Error::Read: return "Failed to read connection";
  8975. case Error::Write: return "Failed to write connection";
  8976. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  8977. case Error::Canceled: return "Connection handling canceled";
  8978. case Error::SSLConnection: return "SSL connection failed";
  8979. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  8980. case Error::SSLServerVerification: return "SSL server verification failed";
  8981. case Error::SSLServerHostnameVerification:
  8982. return "SSL server hostname verification failed";
  8983. case Error::UnsupportedMultipartBoundaryChars:
  8984. return "Unsupported HTTP multipart boundary characters";
  8985. case Error::Compression: return "Compression failed";
  8986. case Error::ConnectionTimeout: return "Connection timed out";
  8987. case Error::ProxyConnection: return "Proxy connection failed";
  8988. case Error::ConnectionClosed: return "Connection closed by server";
  8989. case Error::Timeout: return "Read timeout";
  8990. case Error::ResourceExhaustion: return "Resource exhaustion";
  8991. case Error::TooManyFormDataFiles: return "Too many form data files";
  8992. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  8993. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  8994. case Error::ExceedMaxSocketDescriptorCount:
  8995. return "Exceeded maximum socket descriptor count";
  8996. case Error::InvalidRequestLine: return "Invalid request line";
  8997. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8998. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8999. case Error::InvalidHeaders: return "Invalid headers";
  9000. case Error::MultipartParsing: return "Multipart parsing failed";
  9001. case Error::OpenFile: return "Failed to open file";
  9002. case Error::Listen: return "Failed to listen on socket";
  9003. case Error::GetSockName: return "Failed to get socket name";
  9004. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  9005. case Error::HTTPParsing: return "HTTP parsing failed";
  9006. case Error::InvalidRangeHeader: return "Invalid Range header";
  9007. case Error::UnsupportedContentEncoding: return "Unsupported Content-Encoding";
  9008. case Error::WebSocketHandshake: return "WebSocket handshake failed";
  9009. default: break;
  9010. }
  9011. return "Invalid";
  9012. }
  9013. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  9014. os << to_string(obj);
  9015. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  9016. return os;
  9017. }
  9018. inline std::string hosted_at(const std::string &hostname) {
  9019. std::vector<std::string> addrs;
  9020. hosted_at(hostname, addrs);
  9021. if (addrs.empty()) { return std::string(); }
  9022. return addrs[0];
  9023. }
  9024. inline void hosted_at(const std::string &hostname,
  9025. std::vector<std::string> &addrs) {
  9026. struct addrinfo hints;
  9027. struct addrinfo *result;
  9028. memset(&hints, 0, sizeof(struct addrinfo));
  9029. hints.ai_family = AF_UNSPEC;
  9030. hints.ai_socktype = SOCK_STREAM;
  9031. hints.ai_protocol = 0;
  9032. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  9033. &result, 0)) {
  9034. #if defined __linux__ && !defined __ANDROID__
  9035. res_init();
  9036. #endif
  9037. return;
  9038. }
  9039. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  9040. for (auto rp = result; rp; rp = rp->ai_next) {
  9041. const auto &addr =
  9042. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  9043. std::string ip;
  9044. auto dummy = -1;
  9045. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  9046. dummy)) {
  9047. addrs.emplace_back(std::move(ip));
  9048. }
  9049. }
  9050. }
  9051. inline std::string encode_uri_component(const std::string &value) {
  9052. std::ostringstream escaped;
  9053. escaped.fill('0');
  9054. escaped << std::hex;
  9055. for (auto c : value) {
  9056. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9057. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  9058. escaped << c;
  9059. } else {
  9060. escaped << std::uppercase;
  9061. escaped << '%' << std::setw(2)
  9062. << static_cast<int>(static_cast<unsigned char>(c));
  9063. escaped << std::nouppercase;
  9064. }
  9065. }
  9066. return escaped.str();
  9067. }
  9068. inline std::string encode_uri(const std::string &value) {
  9069. std::ostringstream escaped;
  9070. escaped.fill('0');
  9071. escaped << std::hex;
  9072. for (auto c : value) {
  9073. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9074. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  9075. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  9076. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  9077. escaped << c;
  9078. } else {
  9079. escaped << std::uppercase;
  9080. escaped << '%' << std::setw(2)
  9081. << static_cast<int>(static_cast<unsigned char>(c));
  9082. escaped << std::nouppercase;
  9083. }
  9084. }
  9085. return escaped.str();
  9086. }
  9087. inline std::string decode_uri_component(const std::string &value) {
  9088. std::string result;
  9089. for (size_t i = 0; i < value.size(); i++) {
  9090. if (value[i] == '%' && i + 2 < value.size()) {
  9091. auto val = 0;
  9092. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9093. result += static_cast<char>(val);
  9094. i += 2;
  9095. } else {
  9096. result += value[i];
  9097. }
  9098. } else {
  9099. result += value[i];
  9100. }
  9101. }
  9102. return result;
  9103. }
  9104. inline std::string decode_uri(const std::string &value) {
  9105. std::string result;
  9106. for (size_t i = 0; i < value.size(); i++) {
  9107. if (value[i] == '%' && i + 2 < value.size()) {
  9108. auto val = 0;
  9109. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9110. auto c = static_cast<char>(val);
  9111. // Keep escapes of the reserved characters that encode_uri leaves
  9112. // literal, so decode_uri is the inverse of encode_uri and an escaped
  9113. // delimiter is not promoted into a real one (as with JS decodeURI).
  9114. if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  9115. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' ||
  9116. c == '#') {
  9117. result += value[i];
  9118. result += value[i + 1];
  9119. result += value[i + 2];
  9120. } else {
  9121. result += c;
  9122. }
  9123. i += 2;
  9124. } else {
  9125. result += value[i];
  9126. }
  9127. } else {
  9128. result += value[i];
  9129. }
  9130. }
  9131. return result;
  9132. }
  9133. inline std::string encode_path_component(const std::string &component) {
  9134. std::string result;
  9135. result.reserve(component.size() * 3);
  9136. for (size_t i = 0; i < component.size(); i++) {
  9137. auto c = static_cast<unsigned char>(component[i]);
  9138. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  9139. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9140. c == '_' || c == '~') {
  9141. result += static_cast<char>(c);
  9142. }
  9143. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  9144. // "," / ";" / "="
  9145. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  9146. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  9147. c == '=') {
  9148. result += static_cast<char>(c);
  9149. }
  9150. // Colon is allowed in path segments except first segment
  9151. else if (c == ':') {
  9152. result += static_cast<char>(c);
  9153. }
  9154. // @ is allowed in path
  9155. else if (c == '@') {
  9156. result += static_cast<char>(c);
  9157. } else {
  9158. result += '%';
  9159. char hex[3];
  9160. snprintf(hex, sizeof(hex), "%02X", c);
  9161. result.append(hex, 2);
  9162. }
  9163. }
  9164. return result;
  9165. }
  9166. inline std::string decode_path_component(const std::string &component) {
  9167. std::string result;
  9168. result.reserve(component.size());
  9169. for (size_t i = 0; i < component.size(); i++) {
  9170. if (component[i] == '%' && i + 1 < component.size()) {
  9171. if (component[i + 1] == 'u') {
  9172. // Unicode %uXXXX encoding
  9173. auto val = 0;
  9174. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  9175. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  9176. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  9177. char buff[4];
  9178. size_t len = detail::to_utf8(val, buff);
  9179. if (len > 0) { result.append(buff, len); }
  9180. i += 5; // 'u0000'
  9181. } else {
  9182. result += component[i];
  9183. }
  9184. } else {
  9185. // Standard %XX encoding
  9186. auto val = 0;
  9187. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9188. // 2 digits hex codes
  9189. result += static_cast<char>(val);
  9190. i += 2; // 'XX'
  9191. } else {
  9192. result += component[i];
  9193. }
  9194. }
  9195. } else {
  9196. result += component[i];
  9197. }
  9198. }
  9199. return result;
  9200. }
  9201. inline std::string encode_query_component(const std::string &component,
  9202. bool space_as_plus) {
  9203. std::string result;
  9204. result.reserve(component.size() * 3);
  9205. for (size_t i = 0; i < component.size(); i++) {
  9206. auto c = static_cast<unsigned char>(component[i]);
  9207. // Unreserved characters per RFC 3986
  9208. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9209. c == '_' || c == '~') {
  9210. result += static_cast<char>(c);
  9211. }
  9212. // Space handling
  9213. else if (c == ' ') {
  9214. if (space_as_plus) {
  9215. result += '+';
  9216. } else {
  9217. result += "%20";
  9218. }
  9219. }
  9220. // Plus sign handling
  9221. else if (c == '+') {
  9222. if (space_as_plus) {
  9223. result += "%2B";
  9224. } else {
  9225. result += static_cast<char>(c);
  9226. }
  9227. }
  9228. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  9229. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  9230. c == '*' || c == ',' || c == ';') {
  9231. result += static_cast<char>(c);
  9232. }
  9233. // Colon and @ are allowed in query
  9234. else if (c == ':' || c == '@') {
  9235. result += static_cast<char>(c);
  9236. }
  9237. // Forward slash is allowed in query values
  9238. else if (c == '/') {
  9239. result += static_cast<char>(c);
  9240. }
  9241. // Question mark is allowed in query values (after first ?)
  9242. else if (c == '?') {
  9243. result += static_cast<char>(c);
  9244. } else {
  9245. result += '%';
  9246. char hex[3];
  9247. snprintf(hex, sizeof(hex), "%02X", c);
  9248. result.append(hex, 2);
  9249. }
  9250. }
  9251. return result;
  9252. }
  9253. inline std::string decode_query_component(const std::string &component,
  9254. bool plus_as_space) {
  9255. std::string result;
  9256. result.reserve(component.size());
  9257. for (size_t i = 0; i < component.size(); i++) {
  9258. if (component[i] == '%' && i + 2 < component.size()) {
  9259. auto val = 0;
  9260. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9261. result += static_cast<char>(val);
  9262. i += 2;
  9263. } else {
  9264. result += component[i];
  9265. }
  9266. } else if (component[i] == '+' && plus_as_space) {
  9267. result += ' '; // + becomes space in form-urlencoded
  9268. } else {
  9269. result += component[i];
  9270. }
  9271. }
  9272. return result;
  9273. }
  9274. inline std::string sanitize_filename(const std::string &filename) {
  9275. // Extract basename: find the last path separator (/ or \)
  9276. auto pos = filename.find_last_of("/\\");
  9277. auto result =
  9278. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  9279. // Strip null bytes
  9280. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  9281. // Trim whitespace
  9282. {
  9283. auto start = result.find_first_not_of(" \t");
  9284. auto end = result.find_last_not_of(" \t");
  9285. result = (start == std::string::npos)
  9286. ? ""
  9287. : result.substr(start, end - start + 1);
  9288. }
  9289. // Reject . and ..
  9290. if (result == "." || result == "..") { return ""; }
  9291. return result;
  9292. }
  9293. inline std::string append_query_params(const std::string &path,
  9294. const Params &params) {
  9295. std::string path_with_query = path;
  9296. thread_local const std::regex re("[^?]+\\?.*");
  9297. auto delm = std::regex_match(path, re) ? '&' : '?';
  9298. path_with_query += delm + detail::params_to_query_str(params);
  9299. return path_with_query;
  9300. }
  9301. // Header utilities
  9302. inline std::pair<std::string, std::string>
  9303. make_range_header(const Ranges &ranges) {
  9304. std::string field = "bytes=";
  9305. auto i = 0;
  9306. for (const auto &r : ranges) {
  9307. if (i != 0) { field += ", "; }
  9308. if (r.first != -1) { field += std::to_string(r.first); }
  9309. field += '-';
  9310. if (r.second != -1) { field += std::to_string(r.second); }
  9311. i++;
  9312. }
  9313. return std::make_pair("Range", std::move(field));
  9314. }
  9315. inline std::pair<std::string, std::string>
  9316. make_basic_authentication_header(const std::string &username,
  9317. const std::string &password, bool is_proxy) {
  9318. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  9319. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9320. return std::make_pair(key, std::move(field));
  9321. }
  9322. inline std::pair<std::string, std::string>
  9323. make_bearer_token_authentication_header(const std::string &token,
  9324. bool is_proxy = false) {
  9325. auto field = "Bearer " + token;
  9326. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9327. return std::make_pair(key, std::move(field));
  9328. }
  9329. // Request implementation
  9330. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  9331. size_t id) const {
  9332. return detail::get_header_value_u64(headers, key, def, id);
  9333. }
  9334. inline bool Request::has_header(const std::string &key) const {
  9335. return detail::has_header(headers, key);
  9336. }
  9337. inline std::string Request::get_header_value(const std::string &key,
  9338. const char *def, size_t id) const {
  9339. return detail::get_header_value(headers, key, def, id);
  9340. }
  9341. inline size_t Request::get_header_value_count(const std::string &key) const {
  9342. return detail::get_header_value_count(headers, key);
  9343. }
  9344. inline void Request::set_header(const std::string &key,
  9345. const std::string &val) {
  9346. detail::set_header(headers, key, val);
  9347. }
  9348. inline bool Request::has_trailer(const std::string &key) const {
  9349. return trailers.find(key) != trailers.end();
  9350. }
  9351. inline std::string Request::get_trailer_value(const std::string &key,
  9352. size_t id) const {
  9353. return detail::get_multimap_value(trailers, key, id);
  9354. }
  9355. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  9356. return trailers.count(key);
  9357. }
  9358. inline bool Request::has_param(const std::string &key) const {
  9359. return params.find(key) != params.end();
  9360. }
  9361. inline std::string Request::get_param_value(const std::string &key,
  9362. size_t id) const {
  9363. return detail::get_multimap_value(params, key, id);
  9364. }
  9365. inline std::vector<std::string>
  9366. Request::get_param_values(const std::string &key) const {
  9367. auto rng = params.equal_range(key);
  9368. std::vector<std::string> values;
  9369. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  9370. for (auto it = rng.first; it != rng.second; ++it) {
  9371. values.push_back(it->second);
  9372. }
  9373. return values;
  9374. }
  9375. inline size_t Request::get_param_value_count(const std::string &key) const {
  9376. return params.count(key);
  9377. }
  9378. inline bool Request::is_multipart_form_data() const {
  9379. const auto &content_type = get_header_value("Content-Type");
  9380. return detail::extract_media_type(content_type) == "multipart/form-data";
  9381. }
  9382. // Multipart FormData implementation
  9383. inline std::string MultipartFormData::get_field(const std::string &key,
  9384. size_t id) const {
  9385. auto rng = fields.equal_range(key);
  9386. auto it = rng.first;
  9387. std::advance(it, static_cast<ssize_t>(id));
  9388. if (it != rng.second) { return it->second.content; }
  9389. return std::string();
  9390. }
  9391. inline std::vector<std::string>
  9392. MultipartFormData::get_fields(const std::string &key) const {
  9393. std::vector<std::string> values;
  9394. auto rng = fields.equal_range(key);
  9395. for (auto it = rng.first; it != rng.second; it++) {
  9396. values.push_back(it->second.content);
  9397. }
  9398. return values;
  9399. }
  9400. inline bool MultipartFormData::has_field(const std::string &key) const {
  9401. return fields.find(key) != fields.end();
  9402. }
  9403. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  9404. return fields.count(key);
  9405. }
  9406. inline FormData MultipartFormData::get_file(const std::string &key,
  9407. size_t id) const {
  9408. return detail::get_multimap_value(files, key, id);
  9409. }
  9410. inline std::vector<FormData>
  9411. MultipartFormData::get_files(const std::string &key) const {
  9412. std::vector<FormData> values;
  9413. auto rng = files.equal_range(key);
  9414. for (auto it = rng.first; it != rng.second; it++) {
  9415. values.push_back(it->second);
  9416. }
  9417. return values;
  9418. }
  9419. inline bool MultipartFormData::has_file(const std::string &key) const {
  9420. return files.find(key) != files.end();
  9421. }
  9422. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  9423. return files.count(key);
  9424. }
  9425. // Multipart FormData writer implementation
  9426. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  9427. return detail::is_multipart_boundary_chars_valid(boundary);
  9428. }
  9429. inline MultipartFormDataWriter::MultipartFormDataWriter()
  9430. : boundary_(detail::make_multipart_data_boundary()) {}
  9431. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  9432. : boundary_(std::move(boundary)) {}
  9433. inline const std::string &MultipartFormDataWriter::boundary() const {
  9434. return boundary_;
  9435. }
  9436. inline std::string MultipartFormDataWriter::content_type() const {
  9437. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  9438. }
  9439. inline std::string
  9440. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  9441. return detail::serialize_multipart_formdata(items, boundary_);
  9442. }
  9443. inline size_t MultipartFormDataWriter::content_length(
  9444. const UploadFormDataItems &items) const {
  9445. return detail::get_multipart_content_length(items, boundary_);
  9446. }
  9447. inline std::string
  9448. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  9449. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  9450. }
  9451. inline std::string MultipartFormDataWriter::item_end() {
  9452. return detail::serialize_multipart_formdata_item_end();
  9453. }
  9454. inline std::string MultipartFormDataWriter::finish() const {
  9455. return detail::serialize_multipart_formdata_finish(boundary_);
  9456. }
  9457. // Response implementation
  9458. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  9459. size_t id) const {
  9460. return detail::get_header_value_u64(headers, key, def, id);
  9461. }
  9462. inline bool Response::has_header(const std::string &key) const {
  9463. return headers.find(key) != headers.end();
  9464. }
  9465. inline std::string Response::get_header_value(const std::string &key,
  9466. const char *def,
  9467. size_t id) const {
  9468. return detail::get_header_value(headers, key, def, id);
  9469. }
  9470. inline size_t Response::get_header_value_count(const std::string &key) const {
  9471. return detail::get_header_value_count(headers, key);
  9472. }
  9473. inline void Response::set_header(const std::string &key,
  9474. const std::string &val) {
  9475. detail::set_header(headers, key, val);
  9476. }
  9477. inline bool Response::has_trailer(const std::string &key) const {
  9478. return trailers.find(key) != trailers.end();
  9479. }
  9480. inline std::string Response::get_trailer_value(const std::string &key,
  9481. size_t id) const {
  9482. return detail::get_multimap_value(trailers, key, id);
  9483. }
  9484. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  9485. return trailers.count(key);
  9486. }
  9487. inline void Response::set_redirect(const std::string &url, int stat) {
  9488. if (detail::fields::is_field_value(url)) {
  9489. set_header("Location", url);
  9490. if (300 <= stat && stat < 400) {
  9491. this->status = stat;
  9492. } else {
  9493. this->status = StatusCode::Found_302;
  9494. }
  9495. }
  9496. }
  9497. inline void Response::set_content(const char *s, size_t n,
  9498. const std::string &content_type) {
  9499. body.assign(s, n);
  9500. auto rng = headers.equal_range("Content-Type");
  9501. headers.erase(rng.first, rng.second);
  9502. set_header("Content-Type", content_type);
  9503. }
  9504. inline void Response::set_content(const std::string &s,
  9505. const std::string &content_type) {
  9506. set_content(s.data(), s.size(), content_type);
  9507. }
  9508. inline void Response::set_content(std::string &&s,
  9509. const std::string &content_type) {
  9510. body = std::move(s);
  9511. auto rng = headers.equal_range("Content-Type");
  9512. headers.erase(rng.first, rng.second);
  9513. set_header("Content-Type", content_type);
  9514. }
  9515. inline void Response::set_content_provider(
  9516. size_t in_length, const std::string &content_type, ContentProvider provider,
  9517. ContentProviderResourceReleaser resource_releaser) {
  9518. set_header("Content-Type", content_type);
  9519. content_length_ = in_length;
  9520. if (in_length > 0) { content_provider_ = std::move(provider); }
  9521. content_provider_resource_releaser_ = std::move(resource_releaser);
  9522. is_chunked_content_provider_ = false;
  9523. }
  9524. inline void Response::set_content_provider(
  9525. const std::string &content_type, ContentProviderWithoutLength provider,
  9526. ContentProviderResourceReleaser resource_releaser) {
  9527. set_header("Content-Type", content_type);
  9528. content_length_ = 0;
  9529. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  9530. content_provider_resource_releaser_ = std::move(resource_releaser);
  9531. is_chunked_content_provider_ = false;
  9532. }
  9533. inline void Response::set_chunked_content_provider(
  9534. const std::string &content_type, ContentProviderWithoutLength provider,
  9535. ContentProviderResourceReleaser resource_releaser) {
  9536. set_header("Content-Type", content_type);
  9537. content_length_ = 0;
  9538. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  9539. content_provider_resource_releaser_ = std::move(resource_releaser);
  9540. is_chunked_content_provider_ = true;
  9541. }
  9542. inline void Response::set_file_content(const std::string &path,
  9543. const std::string &content_type) {
  9544. file_content_path_ = path;
  9545. file_content_content_type_ = content_type;
  9546. }
  9547. inline void Response::set_file_content(const std::string &path) {
  9548. file_content_path_ = path;
  9549. }
  9550. // Result implementation
  9551. inline size_t Result::get_request_header_value_u64(const std::string &key,
  9552. size_t def,
  9553. size_t id) const {
  9554. return detail::get_header_value_u64(request_headers_, key, def, id);
  9555. }
  9556. inline bool Result::has_request_header(const std::string &key) const {
  9557. return request_headers_.find(key) != request_headers_.end();
  9558. }
  9559. inline std::string Result::get_request_header_value(const std::string &key,
  9560. const char *def,
  9561. size_t id) const {
  9562. return detail::get_header_value(request_headers_, key, def, id);
  9563. }
  9564. inline size_t
  9565. Result::get_request_header_value_count(const std::string &key) const {
  9566. return request_headers_.count(key);
  9567. }
  9568. // Stream implementation
  9569. inline ssize_t Stream::write(const char *ptr) {
  9570. return write(ptr, strlen(ptr));
  9571. }
  9572. inline ssize_t Stream::write(const std::string &s) {
  9573. return write(s.data(), s.size());
  9574. }
  9575. // BodyReader implementation
  9576. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  9577. if (!stream) {
  9578. last_error = Error::Connection;
  9579. return -1;
  9580. }
  9581. if (eof) { return 0; }
  9582. if (!chunked) {
  9583. // Content-Length based reading
  9584. if (has_content_length && bytes_read >= content_length) {
  9585. eof = true;
  9586. return 0;
  9587. }
  9588. auto to_read = len;
  9589. if (has_content_length) {
  9590. auto remaining = content_length - bytes_read;
  9591. to_read = (std::min)(len, remaining);
  9592. }
  9593. auto n = stream->read(buf, to_read);
  9594. if (n < 0) {
  9595. last_error = stream->get_error();
  9596. if (last_error == Error::Success) { last_error = Error::Read; }
  9597. eof = true;
  9598. return n;
  9599. }
  9600. if (n == 0) {
  9601. // Unexpected EOF before content_length
  9602. last_error = stream->get_error();
  9603. if (last_error == Error::Success) { last_error = Error::Read; }
  9604. eof = true;
  9605. return 0;
  9606. }
  9607. bytes_read += static_cast<size_t>(n);
  9608. if (has_content_length && bytes_read >= content_length) { eof = true; }
  9609. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  9610. last_error = Error::ExceedMaxPayloadSize;
  9611. eof = true;
  9612. return -1;
  9613. }
  9614. return n;
  9615. }
  9616. // Chunked transfer encoding: delegate to shared decoder instance.
  9617. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  9618. size_t chunk_offset = 0;
  9619. size_t chunk_total = 0;
  9620. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  9621. if (n < 0) {
  9622. last_error = stream->get_error();
  9623. if (last_error == Error::Success) { last_error = Error::Read; }
  9624. eof = true;
  9625. return n;
  9626. }
  9627. if (n == 0) {
  9628. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  9629. eof = true;
  9630. return 0;
  9631. }
  9632. bytes_read += static_cast<size_t>(n);
  9633. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  9634. last_error = Error::ExceedMaxPayloadSize;
  9635. eof = true;
  9636. return -1;
  9637. }
  9638. return n;
  9639. }
  9640. // ThreadPool implementation
  9641. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  9642. time_t idle_timeout_sec)
  9643. : base_thread_count_(n), max_queued_requests_(mqr),
  9644. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  9645. shutdown_(false) {
  9646. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9647. if (max_n != 0 && max_n < n) {
  9648. std::string msg = "max_threads must be >= base_threads";
  9649. throw std::invalid_argument(msg);
  9650. }
  9651. #endif
  9652. max_thread_count_ = max_n == 0 ? n : max_n;
  9653. threads_.reserve(base_thread_count_);
  9654. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9655. try {
  9656. #endif
  9657. for (size_t i = 0; i < base_thread_count_; i++) {
  9658. threads_.emplace_back(std::thread([this]() { worker(false); }));
  9659. }
  9660. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9661. } catch (...) {
  9662. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  9663. // signal the workers we already spawned to exit and join them so the
  9664. // vector destructor does not see joinable threads (which would call
  9665. // std::terminate). Then rethrow so the caller learns of the failure.
  9666. {
  9667. std::unique_lock<std::mutex> lock(mutex_);
  9668. shutdown_ = true;
  9669. }
  9670. cond_.notify_all();
  9671. for (auto &t : threads_) {
  9672. if (t.joinable()) { t.join(); }
  9673. }
  9674. throw;
  9675. }
  9676. #endif
  9677. }
  9678. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  9679. {
  9680. std::unique_lock<std::mutex> lock(mutex_);
  9681. if (shutdown_) { return false; }
  9682. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  9683. return false;
  9684. }
  9685. jobs_.push_back(std::move(fn));
  9686. // Spawn a dynamic thread if no idle threads and under max
  9687. if (idle_thread_count_ == 0 &&
  9688. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  9689. cleanup_finished_threads();
  9690. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  9691. }
  9692. }
  9693. cond_.notify_one();
  9694. return true;
  9695. }
  9696. inline void ThreadPool::shutdown() {
  9697. {
  9698. std::unique_lock<std::mutex> lock(mutex_);
  9699. shutdown_ = true;
  9700. }
  9701. cond_.notify_all();
  9702. for (auto &t : threads_) {
  9703. if (t.joinable()) { t.join(); }
  9704. }
  9705. // Move dynamic_threads_ to a local list under the lock to avoid racing
  9706. // with worker threads that call move_to_finished() concurrently.
  9707. std::list<std::thread> remaining_dynamic;
  9708. {
  9709. std::unique_lock<std::mutex> lock(mutex_);
  9710. remaining_dynamic = std::move(dynamic_threads_);
  9711. }
  9712. for (auto &t : remaining_dynamic) {
  9713. if (t.joinable()) { t.join(); }
  9714. }
  9715. std::unique_lock<std::mutex> lock(mutex_);
  9716. cleanup_finished_threads();
  9717. }
  9718. inline void ThreadPool::move_to_finished(std::thread::id id) {
  9719. // Must be called with mutex_ held
  9720. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  9721. if (it->get_id() == id) {
  9722. finished_threads_.push_back(std::move(*it));
  9723. dynamic_threads_.erase(it);
  9724. return;
  9725. }
  9726. }
  9727. }
  9728. inline void ThreadPool::cleanup_finished_threads() {
  9729. // Must be called with mutex_ held
  9730. for (auto &t : finished_threads_) {
  9731. if (t.joinable()) { t.join(); }
  9732. }
  9733. finished_threads_.clear();
  9734. }
  9735. inline void ThreadPool::worker(bool is_dynamic) {
  9736. for (;;) {
  9737. std::function<void()> fn;
  9738. {
  9739. std::unique_lock<std::mutex> lock(mutex_);
  9740. idle_thread_count_++;
  9741. if (is_dynamic) {
  9742. auto has_work =
  9743. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  9744. [&] { return !jobs_.empty() || shutdown_; });
  9745. if (!has_work) {
  9746. // Timed out with no work - exit this dynamic thread
  9747. idle_thread_count_--;
  9748. move_to_finished(std::this_thread::get_id());
  9749. break;
  9750. }
  9751. } else {
  9752. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  9753. }
  9754. idle_thread_count_--;
  9755. if (shutdown_ && jobs_.empty()) { break; }
  9756. fn = std::move(jobs_.front());
  9757. jobs_.pop_front();
  9758. }
  9759. assert(true == static_cast<bool>(fn));
  9760. fn();
  9761. }
  9762. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  9763. !defined(LIBRESSL_VERSION_NUMBER)
  9764. OPENSSL_thread_stop();
  9765. #endif
  9766. }
  9767. /*
  9768. * Group 1 (continued): detail namespace - Stream implementations
  9769. */
  9770. namespace detail {
  9771. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  9772. time_t timeout_sec, time_t timeout_usec,
  9773. time_t &actual_timeout_sec,
  9774. time_t &actual_timeout_usec) {
  9775. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  9776. auto actual_timeout_msec =
  9777. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  9778. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  9779. actual_timeout_sec = actual_timeout_msec / 1000;
  9780. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  9781. }
  9782. // Socket stream implementation
  9783. inline SocketStream::SocketStream(
  9784. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  9785. time_t write_timeout_sec, time_t write_timeout_usec,
  9786. time_t max_timeout_msec,
  9787. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9788. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  9789. read_timeout_usec_(read_timeout_usec),
  9790. write_timeout_sec_(write_timeout_sec),
  9791. write_timeout_usec_(write_timeout_usec),
  9792. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  9793. read_buff_(read_buff_size_, 0) {}
  9794. inline SocketStream::~SocketStream() = default;
  9795. inline bool SocketStream::is_readable() const {
  9796. return read_buff_off_ < read_buff_content_size_;
  9797. }
  9798. inline bool SocketStream::wait_readable() const {
  9799. if (max_timeout_msec_ <= 0) {
  9800. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9801. }
  9802. time_t read_timeout_sec;
  9803. time_t read_timeout_usec;
  9804. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9805. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9806. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9807. }
  9808. inline bool SocketStream::wait_writable() const {
  9809. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  9810. }
  9811. inline bool SocketStream::ensure_readable() {
  9812. if (readable_hint_) {
  9813. readable_hint_ = false;
  9814. return true;
  9815. }
  9816. return wait_readable();
  9817. }
  9818. inline const char *SocketStream::buffered_data(size_t &size) const {
  9819. size = read_buff_content_size_ - read_buff_off_;
  9820. return size ? read_buff_.data() + read_buff_off_ : nullptr;
  9821. }
  9822. inline void SocketStream::consume_buffered(size_t size) {
  9823. assert(size <= read_buff_content_size_ - read_buff_off_);
  9824. read_buff_off_ += size;
  9825. }
  9826. inline bool SocketStream::is_peer_alive() const {
  9827. return detail::is_socket_alive(sock_);
  9828. }
  9829. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  9830. #ifdef _WIN32
  9831. size =
  9832. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  9833. #else
  9834. size = (std::min)(size,
  9835. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  9836. #endif
  9837. if (read_buff_off_ < read_buff_content_size_) {
  9838. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  9839. if (size <= remaining_size) {
  9840. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  9841. read_buff_off_ += size;
  9842. return static_cast<ssize_t>(size);
  9843. } else {
  9844. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  9845. read_buff_off_ += remaining_size;
  9846. return static_cast<ssize_t>(remaining_size);
  9847. }
  9848. }
  9849. if (!ensure_readable()) {
  9850. error_ = Error::Timeout;
  9851. return -1;
  9852. }
  9853. read_buff_off_ = 0;
  9854. read_buff_content_size_ = 0;
  9855. if (size < read_buff_size_) {
  9856. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  9857. CPPHTTPLIB_RECV_FLAGS);
  9858. if (n <= 0) {
  9859. if (n == 0) {
  9860. error_ = Error::ConnectionClosed;
  9861. } else {
  9862. error_ = Error::Read;
  9863. }
  9864. return n;
  9865. } else if (n <= static_cast<ssize_t>(size)) {
  9866. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  9867. return n;
  9868. } else {
  9869. memcpy(ptr, read_buff_.data(), size);
  9870. read_buff_off_ = size;
  9871. read_buff_content_size_ = static_cast<size_t>(n);
  9872. return static_cast<ssize_t>(size);
  9873. }
  9874. } else {
  9875. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  9876. if (n <= 0) {
  9877. if (n == 0) {
  9878. error_ = Error::ConnectionClosed;
  9879. } else {
  9880. error_ = Error::Read;
  9881. }
  9882. }
  9883. return n;
  9884. }
  9885. }
  9886. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  9887. if (!wait_writable()) { return -1; }
  9888. #if defined(_WIN32) && !defined(_WIN64)
  9889. size =
  9890. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  9891. #endif
  9892. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  9893. }
  9894. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  9895. int &port) const {
  9896. return detail::get_remote_ip_and_port(sock_, ip, port);
  9897. }
  9898. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  9899. int &port) const {
  9900. return detail::get_local_ip_and_port(sock_, ip, port);
  9901. }
  9902. inline socket_t SocketStream::socket() const { return sock_; }
  9903. inline time_t SocketStream::duration() const {
  9904. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9905. std::chrono::steady_clock::now() - start_time_)
  9906. .count();
  9907. }
  9908. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  9909. read_timeout_sec_ = sec;
  9910. read_timeout_usec_ = usec;
  9911. }
  9912. // Buffer stream implementation
  9913. inline bool BufferStream::is_readable() const { return true; }
  9914. inline bool BufferStream::wait_readable() const { return true; }
  9915. inline bool BufferStream::wait_writable() const { return true; }
  9916. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  9917. #if defined(_MSC_VER) && _MSC_VER < 1910
  9918. auto len_read = buffer._Copy_s(ptr, size, size, position);
  9919. #else
  9920. auto len_read = buffer.copy(ptr, size, position);
  9921. #endif
  9922. position += static_cast<size_t>(len_read);
  9923. return static_cast<ssize_t>(len_read);
  9924. }
  9925. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  9926. buffer.append(ptr, size);
  9927. return static_cast<ssize_t>(size);
  9928. }
  9929. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  9930. int & /*port*/) const {}
  9931. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  9932. int & /*port*/) const {}
  9933. inline socket_t BufferStream::socket() const { return 0; }
  9934. inline time_t BufferStream::duration() const { return 0; }
  9935. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  9936. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  9937. : MatcherBase(pattern) {
  9938. constexpr const char marker[] = "/:";
  9939. // One past the last ending position of a path param substring
  9940. std::size_t last_param_end = 0;
  9941. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9942. // Needed to ensure that parameter names are unique during matcher
  9943. // construction
  9944. // If exceptions are disabled, only last duplicate path
  9945. // parameter will be set
  9946. std::unordered_set<std::string> param_name_set;
  9947. #endif
  9948. while (true) {
  9949. const auto marker_pos = pattern.find(
  9950. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  9951. if (marker_pos == std::string::npos) { break; }
  9952. static_fragments_.push_back(
  9953. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  9954. const auto param_name_start = marker_pos + str_len(marker);
  9955. auto sep_pos = pattern.find(separator, param_name_start);
  9956. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  9957. auto param_name =
  9958. pattern.substr(param_name_start, sep_pos - param_name_start);
  9959. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9960. if (param_name_set.find(param_name) != param_name_set.cend()) {
  9961. std::string msg = "Encountered path parameter '" + param_name +
  9962. "' multiple times in route pattern '" + pattern + "'.";
  9963. throw std::invalid_argument(msg);
  9964. }
  9965. #endif
  9966. param_names_.push_back(std::move(param_name));
  9967. last_param_end = sep_pos + 1;
  9968. }
  9969. if (last_param_end < pattern.length()) {
  9970. static_fragments_.push_back(pattern.substr(last_param_end));
  9971. }
  9972. }
  9973. inline bool PathParamsMatcher::match(Request &request) const {
  9974. request.matches = std::smatch();
  9975. request.path_params.clear();
  9976. // A pattern without parameters is just a literal path to compare against
  9977. if (param_names_.empty()) { return request.path == pattern(); }
  9978. request.path_params.reserve(param_names_.size());
  9979. // One past the position at which the path matched the pattern last time
  9980. std::size_t starting_pos = 0;
  9981. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  9982. const auto &fragment = static_fragments_[i];
  9983. if (starting_pos + fragment.length() > request.path.length()) {
  9984. return false;
  9985. }
  9986. // Avoid unnecessary allocation by using strncmp instead of substr +
  9987. // comparison
  9988. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  9989. fragment.length()) != 0) {
  9990. return false;
  9991. }
  9992. starting_pos += fragment.length();
  9993. // Should only happen when we have a static fragment after a param
  9994. // Example: '/users/:id/subscriptions'
  9995. // The 'subscriptions' fragment here does not have a corresponding param
  9996. if (i >= param_names_.size()) { continue; }
  9997. auto sep_pos = request.path.find(separator, starting_pos);
  9998. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  9999. const auto &param_name = param_names_[i];
  10000. request.path_params.emplace(
  10001. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  10002. // Mark everything up to '/' as matched
  10003. starting_pos = sep_pos + 1;
  10004. }
  10005. // Returns false if the path is longer than the pattern
  10006. return starting_pos >= request.path.length();
  10007. }
  10008. inline bool RegexMatcher::match(Request &request) const {
  10009. request.path_params.clear();
  10010. // See CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH: an overlong path is treated as
  10011. // a non-match rather than risking a stack overflow in std::regex_match.
  10012. if (request.path.length() > CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH) {
  10013. return false;
  10014. }
  10015. return std::regex_match(request.path, request.matches, regex_);
  10016. }
  10017. // Enclose IPv6 address in brackets if needed
  10018. inline std::string prepare_host_string(const std::string &host) {
  10019. // Enclose IPv6 address in brackets (but not if already enclosed)
  10020. if (host.find(':') == std::string::npos ||
  10021. (!host.empty() && host[0] == '[')) {
  10022. // IPv4, hostname, or already bracketed IPv6
  10023. return host;
  10024. } else {
  10025. // IPv6 address without brackets
  10026. return "[" + host + "]";
  10027. }
  10028. }
  10029. inline std::string make_host_and_port_string(const std::string &host, int port,
  10030. bool is_ssl) {
  10031. auto result = prepare_host_string(host);
  10032. // Append port if not default
  10033. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  10034. ; // do nothing
  10035. } else {
  10036. result += ":" + std::to_string(port);
  10037. }
  10038. return result;
  10039. }
  10040. // Create "host:port" string always including port number (for CONNECT method)
  10041. inline std::string
  10042. make_host_and_port_string_always_port(const std::string &host, int port) {
  10043. return prepare_host_string(host) + ":" + std::to_string(port);
  10044. }
  10045. // Value for the Host header a client sends when the caller supplied none.
  10046. // Only the value: callers decide where in their header list it goes.
  10047. inline std::string make_default_host_header_value(const std::string &host,
  10048. int port, bool is_ssl,
  10049. int address_family) {
  10050. if (address_family == AF_UNIX) { return "localhost"; }
  10051. return make_host_and_port_string(host, port, is_ssl);
  10052. }
  10053. inline void add_default_user_agent_header(Request &req) {
  10054. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10055. if (!req.has_header("User-Agent")) {
  10056. req.set_header("User-Agent",
  10057. std::string("cpp-httplib/") + CPPHTTPLIB_VERSION);
  10058. }
  10059. #else
  10060. (void)req;
  10061. #endif
  10062. }
  10063. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  10064. NormalizedTarget normalize_target(const std::string &host);
  10065. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  10066. bool host_matches_no_proxy(const NormalizedTarget &target,
  10067. const std::vector<NoProxyEntry> &entries);
  10068. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  10069. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  10070. if (prefix_bits == 0) { return true; }
  10071. int full_bytes = prefix_bits / 8;
  10072. int rem_bits = prefix_bits % 8;
  10073. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  10074. static_cast<size_t>(full_bytes)) != 0) {
  10075. return false;
  10076. }
  10077. if (rem_bits == 0) { return true; }
  10078. auto i = static_cast<size_t>(full_bytes);
  10079. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  10080. return (ip[i] & mask) == (net[i] & mask);
  10081. }
  10082. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  10083. if (token.empty()) { return false; }
  10084. if (token == "*") {
  10085. out.kind = NoProxyKind::Wildcard;
  10086. return true;
  10087. }
  10088. auto slash = token.find('/');
  10089. std::string addr_part =
  10090. (slash == std::string::npos) ? token : token.substr(0, slash);
  10091. std::string prefix_part =
  10092. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  10093. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  10094. // don't silently treat it as a /32 (or /128).
  10095. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  10096. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  10097. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  10098. // when brackets are present.
  10099. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  10100. addr_part.back() == ']';
  10101. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  10102. if (!bracketed) {
  10103. struct in_addr v4;
  10104. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  10105. int prefix = 32;
  10106. if (!prefix_part.empty()) {
  10107. auto r = from_chars(prefix_part.data(),
  10108. prefix_part.data() + prefix_part.size(), prefix);
  10109. if (r.ec != std::errc{} ||
  10110. r.ptr != prefix_part.data() + prefix_part.size()) {
  10111. return false;
  10112. }
  10113. if (prefix < 0 || prefix > 32) { return false; }
  10114. }
  10115. out.kind = NoProxyKind::IPv4Cidr;
  10116. std::memcpy(out.net.data(), &v4, sizeof(v4));
  10117. out.prefix_bits = prefix;
  10118. return true;
  10119. }
  10120. }
  10121. struct in6_addr v6;
  10122. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  10123. int prefix = 128;
  10124. if (!prefix_part.empty()) {
  10125. auto r = from_chars(prefix_part.data(),
  10126. prefix_part.data() + prefix_part.size(), prefix);
  10127. if (r.ec != std::errc{} ||
  10128. r.ptr != prefix_part.data() + prefix_part.size()) {
  10129. return false;
  10130. }
  10131. if (prefix < 0 || prefix > 128) { return false; }
  10132. }
  10133. out.kind = NoProxyKind::IPv6Cidr;
  10134. std::memcpy(out.net.data(), &v6, sizeof(v6));
  10135. out.prefix_bits = prefix;
  10136. return true;
  10137. }
  10138. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  10139. // the entry is malformed — don't fall through to the hostname branch.
  10140. if (bracketed) { return false; }
  10141. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  10142. if (slash != std::string::npos) { return false; }
  10143. // Port-specific entries (host:port) are not supported.
  10144. if (token.find(':') != std::string::npos) { return false; }
  10145. std::string hostname = case_ignore::to_lower(token);
  10146. while (!hostname.empty() && hostname.front() == '.') {
  10147. hostname.erase(hostname.begin());
  10148. }
  10149. while (!hostname.empty() && hostname.back() == '.') {
  10150. hostname.pop_back();
  10151. }
  10152. if (hostname.empty()) { return false; }
  10153. out.kind = NoProxyKind::HostnameSuffix;
  10154. out.hostname_pattern = std::move(hostname);
  10155. return true;
  10156. }
  10157. inline NormalizedTarget normalize_target(const std::string &host) {
  10158. NormalizedTarget t;
  10159. std::string h = host;
  10160. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  10161. h = h.substr(1, h.size() - 2);
  10162. }
  10163. // Strip a single trailing dot so "example.com." canonicalizes to
  10164. // "example.com".
  10165. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  10166. t.hostname = case_ignore::to_lower(h);
  10167. if (!t.hostname.empty()) {
  10168. struct in_addr v4;
  10169. struct in6_addr v6;
  10170. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  10171. t.is_ipv4 = true;
  10172. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  10173. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  10174. t.is_ipv6 = true;
  10175. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  10176. }
  10177. }
  10178. return t;
  10179. }
  10180. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  10181. const std::vector<NoProxyEntry> &entries) {
  10182. if (target.hostname.empty()) { return false; }
  10183. for (const auto &e : entries) {
  10184. switch (e.kind) {
  10185. case NoProxyKind::Wildcard: return true;
  10186. case NoProxyKind::IPv4Cidr:
  10187. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10188. return true;
  10189. }
  10190. break;
  10191. case NoProxyKind::IPv6Cidr:
  10192. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10193. return true;
  10194. }
  10195. break;
  10196. case NoProxyKind::HostnameSuffix:
  10197. if (target.is_ipv4 || target.is_ipv6) { break; }
  10198. if (target.hostname == e.hostname_pattern) { return true; }
  10199. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  10200. // an entry of "example.com".
  10201. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  10202. auto offset = target.hostname.size() - e.hostname_pattern.size();
  10203. if (target.hostname[offset - 1] == '.' &&
  10204. target.hostname.compare(offset, e.hostname_pattern.size(),
  10205. e.hostname_pattern) == 0) {
  10206. return true;
  10207. }
  10208. }
  10209. break;
  10210. }
  10211. }
  10212. return false;
  10213. }
  10214. template <typename T>
  10215. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  10216. T header_writer, Error &error) {
  10217. for (const auto &h : headers) {
  10218. if (!detail::fields::is_field_valid(h.first, h.second)) {
  10219. error = Error::InvalidHeaders;
  10220. return false;
  10221. }
  10222. }
  10223. if (header_writer(strm, headers) <= 0) {
  10224. error = Error::Write;
  10225. return false;
  10226. }
  10227. return true;
  10228. }
  10229. } // namespace detail
  10230. /*
  10231. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  10232. */
  10233. #ifdef CPPHTTPLIB_SSL_ENABLED
  10234. namespace detail {
  10235. // SSL socket stream implementation
  10236. inline SSLSocketStream::SSLSocketStream(
  10237. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  10238. time_t read_timeout_usec, time_t write_timeout_sec,
  10239. time_t write_timeout_usec, time_t max_timeout_msec,
  10240. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10241. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10242. read_timeout_usec_(read_timeout_usec),
  10243. write_timeout_sec_(write_timeout_sec),
  10244. write_timeout_usec_(write_timeout_usec),
  10245. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  10246. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10247. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  10248. // Note: create_session() also clears this, but SSLClient currently
  10249. // uses ssl_new() which does not. Until full TLS API migration is complete,
  10250. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  10251. // SSL session was created.
  10252. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  10253. #endif
  10254. }
  10255. inline SSLSocketStream::~SSLSocketStream() = default;
  10256. inline bool SSLSocketStream::is_readable() const {
  10257. return tls::pending(session_) > 0;
  10258. }
  10259. inline bool SSLSocketStream::wait_readable() const {
  10260. if (max_timeout_msec_ <= 0) {
  10261. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10262. }
  10263. time_t read_timeout_sec;
  10264. time_t read_timeout_usec;
  10265. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10266. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10267. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10268. }
  10269. inline bool SSLSocketStream::wait_writable() const {
  10270. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  10271. !tls::is_peer_closed(session_, sock_);
  10272. }
  10273. inline bool SSLSocketStream::ensure_readable() {
  10274. if (readable_hint_) {
  10275. readable_hint_ = false;
  10276. return true;
  10277. }
  10278. return wait_readable();
  10279. }
  10280. inline bool SSLSocketStream::is_peer_alive() const {
  10281. return !tls::is_peer_closed(session_, sock_);
  10282. }
  10283. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  10284. if (tls::pending(session_) > 0) {
  10285. tls::TlsError err;
  10286. auto ret = tls::read(session_, ptr, size, err);
  10287. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10288. error_ = Error::ConnectionClosed;
  10289. }
  10290. return ret;
  10291. } else if (ensure_readable()) {
  10292. tls::TlsError err;
  10293. auto ret = tls::read(session_, ptr, size, err);
  10294. if (ret < 0) {
  10295. auto n = 1000;
  10296. #ifdef _WIN32
  10297. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  10298. (err.code == tls::ErrorCode::SyscallError &&
  10299. WSAGetLastError() == WSAETIMEDOUT))) {
  10300. #else
  10301. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  10302. #endif
  10303. if (tls::pending(session_) > 0) {
  10304. return tls::read(session_, ptr, size, err);
  10305. } else if (wait_readable()) {
  10306. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10307. ret = tls::read(session_, ptr, size, err);
  10308. if (ret >= 0) { return ret; }
  10309. } else {
  10310. break;
  10311. }
  10312. }
  10313. assert(ret < 0);
  10314. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10315. error_ = Error::ConnectionClosed;
  10316. }
  10317. return ret;
  10318. } else {
  10319. error_ = Error::Timeout;
  10320. return -1;
  10321. }
  10322. }
  10323. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  10324. if (wait_writable()) {
  10325. auto handle_size =
  10326. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10327. tls::TlsError err;
  10328. auto ret = tls::write(session_, ptr, handle_size, err);
  10329. if (ret < 0) {
  10330. auto n = 1000;
  10331. #ifdef _WIN32
  10332. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  10333. (err.code == tls::ErrorCode::SyscallError &&
  10334. WSAGetLastError() == WSAETIMEDOUT))) {
  10335. #else
  10336. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  10337. #endif
  10338. if (wait_writable()) {
  10339. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10340. ret = tls::write(session_, ptr, handle_size, err);
  10341. if (ret >= 0) { return ret; }
  10342. } else {
  10343. break;
  10344. }
  10345. }
  10346. assert(ret < 0);
  10347. }
  10348. return ret;
  10349. }
  10350. return -1;
  10351. }
  10352. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  10353. int &port) const {
  10354. detail::get_remote_ip_and_port(sock_, ip, port);
  10355. }
  10356. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  10357. int &port) const {
  10358. detail::get_local_ip_and_port(sock_, ip, port);
  10359. }
  10360. inline socket_t SSLSocketStream::socket() const { return sock_; }
  10361. inline time_t SSLSocketStream::duration() const {
  10362. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10363. std::chrono::steady_clock::now() - start_time_)
  10364. .count();
  10365. }
  10366. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  10367. read_timeout_sec_ = sec;
  10368. read_timeout_usec_ = usec;
  10369. }
  10370. inline WebSocketSSLStream::WebSocketSSLStream(socket_t sock,
  10371. tls::session_t session,
  10372. time_t read_timeout_sec,
  10373. time_t read_timeout_usec,
  10374. time_t write_timeout_sec,
  10375. time_t write_timeout_usec)
  10376. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10377. read_timeout_usec_(read_timeout_usec),
  10378. write_timeout_sec_(write_timeout_sec),
  10379. write_timeout_usec_(write_timeout_usec),
  10380. start_time_(std::chrono::steady_clock::now()) {
  10381. // The receive and send paths run on different threads, so each TLS call is
  10382. // driven in non-blocking mode and readiness is awaited with select()
  10383. // outside the session lock. Set the socket non-blocking once here; it is
  10384. // never flipped back, so no thread races on the flag.
  10385. detail::set_nonblocking(sock_, true);
  10386. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10387. SSL_clear_mode(static_cast<SSL *>(session_), SSL_MODE_AUTO_RETRY);
  10388. #endif
  10389. }
  10390. inline WebSocketSSLStream::~WebSocketSSLStream() = default;
  10391. inline bool WebSocketSSLStream::is_readable() const {
  10392. std::lock_guard<std::mutex> guard(session_mutex_);
  10393. return tls::pending(session_) > 0;
  10394. }
  10395. inline bool WebSocketSSLStream::wait_readable() const {
  10396. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10397. }
  10398. inline bool WebSocketSSLStream::wait_writable() const {
  10399. // Unlike SSLSocketStream, this deliberately does not call is_peer_closed():
  10400. // that probe toggles the socket's blocking flag, which would race with the
  10401. // concurrent reader on a permanently non-blocking socket.
  10402. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  10403. }
  10404. inline ssize_t WebSocketSSLStream::read(char *ptr, size_t size) {
  10405. tls::TlsError err;
  10406. auto n = 1000;
  10407. while (--n >= 0) {
  10408. {
  10409. std::lock_guard<std::mutex> guard(session_mutex_);
  10410. auto ret = tls::read(session_, ptr, size, err);
  10411. if (ret > 0) { return ret; }
  10412. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10413. error_ = Error::ConnectionClosed;
  10414. return ret;
  10415. }
  10416. }
  10417. // ret < 0. On a non-blocking socket a TLS read can stop needing either
  10418. // direction: the send path shares this session, so output it left pending
  10419. // has to be flushed before more input can be decrypted. Anything else is
  10420. // a hard error.
  10421. auto needs_readable = err.code == tls::ErrorCode::WantRead;
  10422. #ifdef _WIN32
  10423. // On Windows a socket timeout surfaces as a syscall error, not WantRead.
  10424. needs_readable =
  10425. needs_readable || (err.code == tls::ErrorCode::SyscallError &&
  10426. WSAGetLastError() == WSAETIMEDOUT);
  10427. #endif
  10428. if (!needs_readable && err.code != tls::ErrorCode::WantWrite) { return -1; }
  10429. if (!(needs_readable ? wait_readable() : wait_writable())) {
  10430. error_ = Error::Timeout;
  10431. return -1;
  10432. }
  10433. }
  10434. return -1;
  10435. }
  10436. inline ssize_t WebSocketSSLStream::write(const char *ptr, size_t size) {
  10437. auto handle_size = std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10438. tls::TlsError err;
  10439. auto n = 1000;
  10440. while (--n >= 0) {
  10441. {
  10442. std::lock_guard<std::mutex> guard(session_mutex_);
  10443. auto ret = tls::write(session_, ptr, handle_size, err);
  10444. if (ret >= 0) { return ret; }
  10445. }
  10446. // ret < 0. As in read(), either direction can be needed: a renegotiation
  10447. // or a post-handshake message must be consumed before the record goes
  10448. // out. Anything else is a hard error.
  10449. auto needs_writable = err.code == tls::ErrorCode::WantWrite;
  10450. #ifdef _WIN32
  10451. // On Windows a socket timeout surfaces as a syscall error, not WantWrite.
  10452. needs_writable =
  10453. needs_writable || (err.code == tls::ErrorCode::SyscallError &&
  10454. WSAGetLastError() == WSAETIMEDOUT);
  10455. #endif
  10456. if (!needs_writable && err.code != tls::ErrorCode::WantRead) { return -1; }
  10457. if (!(needs_writable ? wait_writable() : wait_readable())) { return -1; }
  10458. }
  10459. return -1;
  10460. }
  10461. inline void WebSocketSSLStream::get_remote_ip_and_port(std::string &ip,
  10462. int &port) const {
  10463. detail::get_remote_ip_and_port(sock_, ip, port);
  10464. }
  10465. inline void WebSocketSSLStream::get_local_ip_and_port(std::string &ip,
  10466. int &port) const {
  10467. detail::get_local_ip_and_port(sock_, ip, port);
  10468. }
  10469. inline socket_t WebSocketSSLStream::socket() const { return sock_; }
  10470. inline time_t WebSocketSSLStream::duration() const {
  10471. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10472. std::chrono::steady_clock::now() - start_time_)
  10473. .count();
  10474. }
  10475. inline void WebSocketSSLStream::set_read_timeout(time_t sec, time_t usec) {
  10476. read_timeout_sec_ = sec;
  10477. read_timeout_usec_ = usec;
  10478. }
  10479. } // namespace detail
  10480. #endif // CPPHTTPLIB_SSL_ENABLED
  10481. /*
  10482. * Group 4: Server implementation
  10483. */
  10484. // HTTP server implementation
  10485. inline Server::Server()
  10486. : new_task_queue([] {
  10487. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  10488. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  10489. }) {
  10490. #ifndef _WIN32
  10491. signal(SIGPIPE, SIG_IGN);
  10492. #endif
  10493. }
  10494. inline Server::~Server() = default;
  10495. inline std::unique_ptr<detail::MatcherBase>
  10496. Server::make_matcher(const std::string &pattern) {
  10497. // Path params take precedence, so "/users/:id/(.*)" keeps being matched as
  10498. // a path params pattern
  10499. if (pattern.find("/:") != std::string::npos) {
  10500. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  10501. }
  10502. // A pattern with no regex metacharacter only has to be compared literally,
  10503. // which is what PathParamsMatcher already does when it captures no
  10504. // parameter, so std::regex is only worth building for the patterns that
  10505. // actually need it
  10506. if (pattern.find_first_of(".^$|()[]{}*+?\\") == std::string::npos) {
  10507. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  10508. }
  10509. return detail::make_unique<detail::RegexMatcher>(pattern);
  10510. }
  10511. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  10512. return add_handler(get_handlers_, pattern, std::move(handler));
  10513. }
  10514. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  10515. return add_handler(post_handlers_, pattern, std::move(handler));
  10516. }
  10517. inline Server &Server::Post(const std::string &pattern,
  10518. HandlerWithContentReader handler) {
  10519. return add_handler(post_handlers_for_content_reader_, pattern,
  10520. std::move(handler));
  10521. }
  10522. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  10523. return add_handler(put_handlers_, pattern, std::move(handler));
  10524. }
  10525. inline Server &Server::Put(const std::string &pattern,
  10526. HandlerWithContentReader handler) {
  10527. return add_handler(put_handlers_for_content_reader_, pattern,
  10528. std::move(handler));
  10529. }
  10530. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  10531. return add_handler(patch_handlers_, pattern, std::move(handler));
  10532. }
  10533. inline Server &Server::Patch(const std::string &pattern,
  10534. HandlerWithContentReader handler) {
  10535. return add_handler(patch_handlers_for_content_reader_, pattern,
  10536. std::move(handler));
  10537. }
  10538. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  10539. return add_handler(delete_handlers_, pattern, std::move(handler));
  10540. }
  10541. inline Server &Server::Delete(const std::string &pattern,
  10542. HandlerWithContentReader handler) {
  10543. return add_handler(delete_handlers_for_content_reader_, pattern,
  10544. std::move(handler));
  10545. }
  10546. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  10547. return add_handler(options_handlers_, pattern, std::move(handler));
  10548. }
  10549. inline const std::set<std::string> &Server::builtin_methods() {
  10550. thread_local const std::set<std::string> methods{
  10551. "GET", "HEAD", "POST", "PUT", "DELETE",
  10552. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10553. return methods;
  10554. }
  10555. inline Server::CustomHandlerEntry *
  10556. Server::custom_entry_for_registration(const std::string &method) {
  10557. // Built-in methods are refused for two different reasons. GET, HEAD, POST,
  10558. // PUT, DELETE, OPTIONS and PATCH are dispatched by the if/else chain in
  10559. // routing() before the custom tables are consulted, so a route registered
  10560. // for one of them could never fire. CONNECT, TRACE and PRI have no branch
  10561. // there and would be reachable, but they carry protocol-level meaning
  10562. // (tunnel setup, request echo, the HTTP/2 connection preface) that this
  10563. // library does not route.
  10564. if (!detail::fields::is_token(method) || builtin_methods().count(method)) {
  10565. output_error_log(Error::InvalidHTTPMethod, nullptr);
  10566. has_invalid_registration_ = true;
  10567. return nullptr;
  10568. }
  10569. return &custom_handlers_[method];
  10570. }
  10571. inline Server &Server::CustomRoute(const std::string &method,
  10572. const std::string &pattern,
  10573. Handler handler) {
  10574. auto *entry = custom_entry_for_registration(method);
  10575. if (!entry) { return *this; }
  10576. return add_handler(entry->handlers, pattern, std::move(handler));
  10577. }
  10578. inline Server &Server::CustomRoute(const std::string &method,
  10579. const std::string &pattern,
  10580. HandlerWithContentReader handler) {
  10581. auto *entry = custom_entry_for_registration(method);
  10582. if (!entry) { return *this; }
  10583. return add_handler(entry->handlers_for_content_reader, pattern,
  10584. std::move(handler));
  10585. }
  10586. inline const Server::CustomHandlerEntry *
  10587. Server::find_custom_entry(const std::string &method) const {
  10588. // find() alone would be correct here. The empty() check is what keeps the
  10589. // per-request cost off servers that never call CustomRoute(), which is the
  10590. // overwhelmingly common case; keep it rather than walking into the tree.
  10591. if (custom_handlers_.empty()) { return nullptr; }
  10592. auto it = custom_handlers_.find(method);
  10593. return it == custom_handlers_.end() ? nullptr : &it->second;
  10594. }
  10595. inline Server &Server::WebSocket(const std::string &pattern,
  10596. WebSocketHandler handler) {
  10597. websocket_handlers_.push_back(
  10598. {make_matcher(pattern), std::move(handler), nullptr});
  10599. return *this;
  10600. }
  10601. inline Server &Server::WebSocket(const std::string &pattern,
  10602. WebSocketHandler handler,
  10603. SubProtocolSelector sub_protocol_selector) {
  10604. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  10605. std::move(sub_protocol_selector)});
  10606. return *this;
  10607. }
  10608. inline bool Server::set_base_dir(const std::string &dir,
  10609. const std::string &mount_point) {
  10610. return set_mount_point(mount_point, dir);
  10611. }
  10612. inline bool Server::set_mount_point(const std::string &mount_point,
  10613. const std::string &dir, Headers headers) {
  10614. detail::FileStat stat(dir);
  10615. if (stat.is_dir()) {
  10616. std::string mnt = !mount_point.empty() ? mount_point : "/";
  10617. if (!mnt.empty() && mnt[0] == '/') {
  10618. std::string resolved_base;
  10619. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  10620. #if defined(_WIN32)
  10621. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  10622. resolved_base += '\\';
  10623. }
  10624. #else
  10625. if (resolved_base.back() != '/') { resolved_base += '/'; }
  10626. #endif
  10627. }
  10628. base_dirs_.push_back(
  10629. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  10630. return true;
  10631. }
  10632. }
  10633. return false;
  10634. }
  10635. inline bool Server::remove_mount_point(const std::string &mount_point) {
  10636. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  10637. if (it->mount_point == mount_point) {
  10638. base_dirs_.erase(it);
  10639. return true;
  10640. }
  10641. }
  10642. return false;
  10643. }
  10644. inline Server &
  10645. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  10646. const std::string &mime) {
  10647. file_extension_and_mimetype_map_[ext] = mime;
  10648. return *this;
  10649. }
  10650. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  10651. default_file_mimetype_ = mime;
  10652. return *this;
  10653. }
  10654. inline Server &Server::set_file_request_handler(Handler handler) {
  10655. file_request_handler_ = std::move(handler);
  10656. return *this;
  10657. }
  10658. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  10659. std::true_type) {
  10660. error_handler_ = std::move(handler);
  10661. return *this;
  10662. }
  10663. inline Server &Server::set_error_handler_core(Handler handler,
  10664. std::false_type) {
  10665. error_handler_ = [handler](const Request &req, Response &res) {
  10666. handler(req, res);
  10667. return HandlerResponse::Handled;
  10668. };
  10669. return *this;
  10670. }
  10671. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  10672. exception_handler_ = std::move(handler);
  10673. return *this;
  10674. }
  10675. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  10676. pre_routing_handler_ = std::move(handler);
  10677. return *this;
  10678. }
  10679. inline Server &Server::set_post_routing_handler(Handler handler) {
  10680. post_routing_handler_ = std::move(handler);
  10681. return *this;
  10682. }
  10683. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  10684. pre_request_handler_ = std::move(handler);
  10685. return *this;
  10686. }
  10687. inline Server &Server::set_logger(Logger logger) {
  10688. logger_ = std::move(logger);
  10689. return *this;
  10690. }
  10691. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  10692. error_logger_ = std::move(error_logger);
  10693. return *this;
  10694. }
  10695. inline Server &Server::set_pre_compression_logger(Logger logger) {
  10696. pre_compression_logger_ = std::move(logger);
  10697. return *this;
  10698. }
  10699. inline Server &
  10700. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  10701. expect_100_continue_handler_ = std::move(handler);
  10702. return *this;
  10703. }
  10704. inline Server &Server::set_start_handler(StartHandler handler) {
  10705. start_handler_ = std::move(handler);
  10706. return *this;
  10707. }
  10708. inline Server &Server::set_address_family(int family) {
  10709. address_family_ = family;
  10710. return *this;
  10711. }
  10712. inline Server &Server::set_tcp_nodelay(bool on) {
  10713. tcp_nodelay_ = on;
  10714. return *this;
  10715. }
  10716. inline Server &Server::set_ipv6_v6only(bool on) {
  10717. ipv6_v6only_ = on;
  10718. return *this;
  10719. }
  10720. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  10721. socket_options_ = std::move(socket_options);
  10722. return *this;
  10723. }
  10724. inline Server &Server::set_default_headers(Headers headers) {
  10725. default_headers_ = std::move(headers);
  10726. return *this;
  10727. }
  10728. inline Server &Server::set_header_writer(
  10729. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10730. header_writer_ = writer;
  10731. return *this;
  10732. }
  10733. inline Server &
  10734. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  10735. trusted_proxies_ = proxies;
  10736. return *this;
  10737. }
  10738. inline Server &Server::set_keep_alive_max_count(size_t count) {
  10739. keep_alive_max_count_ = count;
  10740. return *this;
  10741. }
  10742. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  10743. keep_alive_timeout_sec_ = sec;
  10744. return *this;
  10745. }
  10746. template <class Rep, class Period>
  10747. inline Server &Server::set_keep_alive_timeout(
  10748. const std::chrono::duration<Rep, Period> &duration) {
  10749. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  10750. set_keep_alive_timeout(sec);
  10751. });
  10752. return *this;
  10753. }
  10754. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  10755. read_timeout_sec_ = sec;
  10756. read_timeout_usec_ = usec;
  10757. return *this;
  10758. }
  10759. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  10760. write_timeout_sec_ = sec;
  10761. write_timeout_usec_ = usec;
  10762. return *this;
  10763. }
  10764. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  10765. idle_interval_sec_ = sec;
  10766. idle_interval_usec_ = usec;
  10767. return *this;
  10768. }
  10769. inline Server &Server::set_payload_max_length(size_t length) {
  10770. payload_max_length_ = length;
  10771. return *this;
  10772. }
  10773. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  10774. websocket_max_missed_pongs_ = count;
  10775. return *this;
  10776. }
  10777. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  10778. websocket_ping_interval_sec_ = sec;
  10779. return *this;
  10780. }
  10781. template <class Rep, class Period>
  10782. inline Server &Server::set_websocket_ping_interval(
  10783. const std::chrono::duration<Rep, Period> &duration) {
  10784. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  10785. set_websocket_ping_interval(sec);
  10786. });
  10787. return *this;
  10788. }
  10789. inline bool Server::bind_to_port(const std::string &host, int port,
  10790. int socket_flags) {
  10791. auto ret = bind_internal(host, port, socket_flags);
  10792. if (ret == -1) { is_decommissioned = true; }
  10793. return ret >= 0;
  10794. }
  10795. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  10796. auto ret = bind_internal(host, 0, socket_flags);
  10797. if (ret == -1) { is_decommissioned = true; }
  10798. return ret;
  10799. }
  10800. inline bool Server::listen_after_bind() { return listen_internal(); }
  10801. inline bool Server::listen(const std::string &host, int port,
  10802. int socket_flags) {
  10803. return bind_to_port(host, port, socket_flags) && listen_internal();
  10804. }
  10805. inline bool Server::is_running() const { return is_running_; }
  10806. inline void Server::wait_until_ready() const {
  10807. while (!is_running_ && !is_decommissioned) {
  10808. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10809. }
  10810. }
  10811. inline void Server::stop() noexcept {
  10812. // Release the listening socket whether or not the accept loop is running:
  10813. // bind_to_port() without listen_after_bind() still owns the descriptor. The
  10814. // exchange is what makes this safe to call concurrently with the accept loop.
  10815. socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
  10816. if (sock != INVALID_SOCKET) {
  10817. detail::shutdown_socket(sock);
  10818. detail::close_socket(sock);
  10819. }
  10820. is_decommissioned = false;
  10821. }
  10822. inline void Server::decommission() { is_decommissioned = true; }
  10823. inline bool Server::parse_request_line(const char *s, Request &req) const {
  10824. auto len = strlen(s);
  10825. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  10826. len -= 2;
  10827. {
  10828. size_t count = 0;
  10829. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  10830. switch (count) {
  10831. case 0: req.method = std::string(b, e); break;
  10832. case 1: req.target = std::string(b, e); break;
  10833. case 2: req.version = std::string(b, e); break;
  10834. default: break;
  10835. }
  10836. count++;
  10837. });
  10838. if (count != 3) { return false; }
  10839. }
  10840. // A method outside the built-in set is accepted only when a handler has been
  10841. // registered for it with CustomRoute().
  10842. const auto &methods = builtin_methods();
  10843. if (methods.find(req.method) == methods.end() &&
  10844. !find_custom_entry(req.method)) {
  10845. output_error_log(Error::InvalidHTTPMethod, &req);
  10846. return false;
  10847. }
  10848. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  10849. output_error_log(Error::InvalidHTTPVersion, &req);
  10850. return false;
  10851. }
  10852. {
  10853. // Skip URL fragment
  10854. for (size_t i = 0; i < req.target.size(); i++) {
  10855. if (req.target[i] == '#') {
  10856. req.target.erase(i);
  10857. break;
  10858. }
  10859. }
  10860. detail::divide(req.target, '?',
  10861. [&](const char *lhs_data, std::size_t lhs_size,
  10862. const char *rhs_data, std::size_t rhs_size) {
  10863. req.path =
  10864. decode_path_component(std::string(lhs_data, lhs_size));
  10865. detail::parse_query_text(rhs_data, rhs_size, req.params);
  10866. });
  10867. }
  10868. return true;
  10869. }
  10870. inline bool Server::write_response(Stream &strm, bool close_connection,
  10871. Request &req, Response &res) {
  10872. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  10873. // incorrectly to the error content.
  10874. req.ranges.clear();
  10875. return write_response_core(strm, close_connection, req, res, false);
  10876. }
  10877. inline bool Server::write_response_with_content(Stream &strm,
  10878. bool close_connection,
  10879. const Request &req,
  10880. Response &res) {
  10881. return write_response_core(strm, close_connection, req, res, true);
  10882. }
  10883. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  10884. const Request &req, Response &res,
  10885. bool need_apply_ranges) {
  10886. assert(res.status != -1);
  10887. if (400 <= res.status && error_handler_ &&
  10888. error_handler_(req, res) == HandlerResponse::Handled) {
  10889. need_apply_ranges = true;
  10890. }
  10891. std::string content_type;
  10892. std::string boundary;
  10893. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  10894. // Prepare additional headers
  10895. if (close_connection ||
  10896. detail::has_header_token(req.headers, "Connection", "close") ||
  10897. 400 <= res.status) { // Don't leave connections open after errors
  10898. res.set_header("Connection", "close");
  10899. } else {
  10900. std::string s = "timeout=";
  10901. s += std::to_string(keep_alive_timeout_sec_);
  10902. s += ", max=";
  10903. s += std::to_string(keep_alive_max_count_);
  10904. res.set_header("Keep-Alive", s);
  10905. }
  10906. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  10907. !res.has_header("Content-Type")) {
  10908. res.set_header("Content-Type", "text/plain");
  10909. }
  10910. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  10911. !res.has_header("Content-Length")) {
  10912. res.set_header("Content-Length", "0");
  10913. }
  10914. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  10915. res.set_header("Accept-Ranges", "bytes");
  10916. }
  10917. if (post_routing_handler_) { post_routing_handler_(req, res); }
  10918. // Response line and headers
  10919. detail::BufferStream bstrm;
  10920. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  10921. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  10922. // Combine small body with headers to reduce write syscalls
  10923. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  10924. bstrm.write(res.body.data(), res.body.size());
  10925. }
  10926. // Log before writing to avoid race condition with client-side code that
  10927. // accesses logger-captured data immediately after receiving the response.
  10928. output_log(req, res);
  10929. // Flush buffer
  10930. auto &data = bstrm.get_buffer();
  10931. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  10932. // Streaming body
  10933. auto ret = true;
  10934. if (req.method != "HEAD" && res.content_provider_) {
  10935. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  10936. res.content_provider_success_ = true;
  10937. } else {
  10938. ret = false;
  10939. }
  10940. }
  10941. return ret;
  10942. }
  10943. inline bool
  10944. Server::write_content_with_provider(Stream &strm, const Request &req,
  10945. Response &res, const std::string &boundary,
  10946. const std::string &content_type) {
  10947. auto is_shutting_down = [this]() {
  10948. return this->svr_sock_ == INVALID_SOCKET;
  10949. };
  10950. if (res.content_length_ > 0) {
  10951. // Only a 206 response is served as a partial representation, matching the
  10952. // condition `apply_ranges()` used to decide the Content-Length and the
  10953. // multipart boundary. Since `detail::range_error()` validates `req.ranges`
  10954. // only for a 2xx status, slicing under any other status would write a body
  10955. // that disagrees with the header already sent, from an unchecked offset.
  10956. auto is_partial =
  10957. !req.ranges.empty() && res.status == StatusCode::PartialContent_206;
  10958. if (!is_partial) {
  10959. return detail::write_content(strm, res.content_provider_, 0,
  10960. res.content_length_, is_shutting_down);
  10961. } else if (req.ranges.size() == 1) {
  10962. auto offset_and_length = detail::get_range_offset_and_length(
  10963. req.ranges[0], res.content_length_);
  10964. return detail::write_content(strm, res.content_provider_,
  10965. offset_and_length.first,
  10966. offset_and_length.second, is_shutting_down);
  10967. } else {
  10968. return detail::write_multipart_ranges_data(
  10969. strm, req, res, boundary, content_type, res.content_length_,
  10970. is_shutting_down);
  10971. }
  10972. } else {
  10973. if (res.is_chunked_content_provider_) {
  10974. auto type = detail::encoding_type(req, res);
  10975. auto compressor = detail::make_compressor(type);
  10976. if (!compressor) {
  10977. compressor = detail::make_unique<detail::nocompressor>();
  10978. }
  10979. return detail::write_content_chunked(strm, res.content_provider_,
  10980. is_shutting_down, *compressor);
  10981. } else {
  10982. return detail::write_content_without_length(strm, res.content_provider_,
  10983. is_shutting_down);
  10984. }
  10985. }
  10986. }
  10987. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  10988. FormFields::iterator cur_field;
  10989. FormFiles::iterator cur_file;
  10990. auto is_text_field = false;
  10991. size_t count = 0;
  10992. if (read_content_core(
  10993. strm, req, res,
  10994. // Regular
  10995. [&](const char *buf, size_t n) {
  10996. // Prevent arithmetic overflow when checking sizes.
  10997. // Avoid computing (req.body.size() + n) directly because
  10998. // adding two unsigned `size_t` values can wrap around and
  10999. // produce a small result instead of indicating overflow.
  11000. // Instead, check using subtraction: ensure `n` does not
  11001. // exceed the remaining capacity `max_size() - size()`.
  11002. if (req.body.size() >= req.body.max_size() ||
  11003. n > req.body.max_size() - req.body.size()) {
  11004. return false;
  11005. }
  11006. // Limit decompressed body size to payload_max_length_ to protect
  11007. // against "zip bomb" attacks where a small compressed payload
  11008. // decompresses to a massive size.
  11009. if (payload_max_length_ > 0 &&
  11010. (req.body.size() >= payload_max_length_ ||
  11011. n > payload_max_length_ - req.body.size())) {
  11012. return false;
  11013. }
  11014. req.body.append(buf, n);
  11015. return true;
  11016. },
  11017. // Multipart FormData
  11018. [&](const FormData &file) {
  11019. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  11020. output_error_log(Error::TooManyFormDataFiles, &req);
  11021. return false;
  11022. }
  11023. if (file.filename.empty()) {
  11024. cur_field = req.form.fields.emplace(
  11025. file.name, FormField{file.name, file.content, file.headers});
  11026. is_text_field = true;
  11027. } else {
  11028. cur_file = req.form.files.emplace(file.name, file);
  11029. is_text_field = false;
  11030. }
  11031. return true;
  11032. },
  11033. [&](const char *buf, size_t n) {
  11034. if (is_text_field) {
  11035. auto &content = cur_field->second.content;
  11036. if (content.size() + n > content.max_size()) { return false; }
  11037. content.append(buf, n);
  11038. } else {
  11039. auto &content = cur_file->second.content;
  11040. if (content.size() + n > content.max_size()) { return false; }
  11041. content.append(buf, n);
  11042. }
  11043. return true;
  11044. })) {
  11045. const auto &content_type = req.get_header_value("Content-Type");
  11046. if (detail::extract_media_type(content_type) ==
  11047. "application/x-www-form-urlencoded") {
  11048. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  11049. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  11050. output_error_log(Error::ExceedMaxPayloadSize, &req);
  11051. return false;
  11052. }
  11053. detail::parse_query_text(req.body, req.params);
  11054. }
  11055. return true;
  11056. }
  11057. return false;
  11058. }
  11059. inline bool Server::read_content_with_content_receiver(
  11060. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11061. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  11062. return read_content_core(strm, req, res, std::move(receiver),
  11063. std::move(multipart_header),
  11064. std::move(multipart_receiver));
  11065. }
  11066. inline bool Server::read_content_core(
  11067. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11068. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  11069. detail::FormDataParser multipart_form_data_parser;
  11070. ContentReceiverWithProgress out;
  11071. if (req.is_multipart_form_data()) {
  11072. const auto &content_type = req.get_header_value("Content-Type");
  11073. std::string boundary;
  11074. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  11075. res.status = StatusCode::BadRequest_400;
  11076. output_error_log(Error::MultipartParsing, &req);
  11077. return false;
  11078. }
  11079. multipart_form_data_parser.set_boundary(std::move(boundary));
  11080. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  11081. return multipart_form_data_parser.parse(buf, n, multipart_header,
  11082. multipart_receiver);
  11083. };
  11084. } else {
  11085. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  11086. size_t /*len*/) { return receiver(buf, n); };
  11087. }
  11088. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  11089. // For non-SSL builds we still scan non-persistent connections for stray
  11090. // body bytes so the payload limit is enforced (413). On keep-alive,
  11091. // pending bytes may be the next request (issue #2450), so skip.
  11092. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  11093. if (!req.has_header("Content-Length") &&
  11094. !detail::is_chunked_transfer_encoding(req.headers)) {
  11095. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  11096. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  11097. auto has_data = strm.is_readable();
  11098. if (!has_data) {
  11099. auto s = strm.socket();
  11100. if (s != INVALID_SOCKET) {
  11101. has_data = detail::select_read(s, 0, 0) > 0;
  11102. }
  11103. }
  11104. if (has_data) {
  11105. // Route through the same decompressing reader used by the
  11106. // length-framed and chunked paths below, so payload_max_length_ is
  11107. // enforced on the decompressed size here too instead of only on the
  11108. // compressed wire bytes.
  11109. return detail::read_content(strm, req, payload_max_length_, res.status,
  11110. nullptr, out, true);
  11111. }
  11112. }
  11113. return true;
  11114. }
  11115. #else
  11116. if (!req.has_header("Content-Length") &&
  11117. !detail::is_chunked_transfer_encoding(req.headers)) {
  11118. return true;
  11119. }
  11120. #endif
  11121. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  11122. out, true)) {
  11123. return false;
  11124. }
  11125. req.body_consumed_ = true;
  11126. if (req.is_multipart_form_data()) {
  11127. if (!multipart_form_data_parser.is_valid()) {
  11128. res.status = StatusCode::BadRequest_400;
  11129. output_error_log(Error::MultipartParsing, &req);
  11130. return false;
  11131. }
  11132. }
  11133. return true;
  11134. }
  11135. inline bool Server::handle_file_request(Request &req, Response &res) {
  11136. for (const auto &entry : base_dirs_) {
  11137. // Prefix match, on a path segment boundary. A mount point of "/mount"
  11138. // covers "/mount" and "/mount/...", but must not swallow "/mountdir/...".
  11139. // One that already ends in '/' (the root mount among them) carries its own
  11140. // boundary; set_mount_point() guarantees the mount point is not empty.
  11141. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point) &&
  11142. (entry.mount_point.back() == '/' ||
  11143. req.path.size() == entry.mount_point.size() ||
  11144. req.path[entry.mount_point.size()] == '/')) {
  11145. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  11146. if (detail::is_valid_path(sub_path)) {
  11147. auto path = entry.base_dir + sub_path;
  11148. if (path.back() == '/') { path += "index.html"; }
  11149. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  11150. // but symlinks/junctions can still escape the base directory.
  11151. if (!entry.resolved_base_dir.empty()) {
  11152. std::string resolved_path;
  11153. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  11154. !detail::is_path_within_base(resolved_path,
  11155. entry.resolved_base_dir)) {
  11156. res.status = StatusCode::Forbidden_403;
  11157. return true;
  11158. }
  11159. }
  11160. detail::FileStat stat(path);
  11161. if (stat.is_dir()) {
  11162. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  11163. return true;
  11164. }
  11165. if (stat.is_file()) {
  11166. for (const auto &kv : entry.headers) {
  11167. res.set_header(kv.first, kv.second);
  11168. }
  11169. auto etag = detail::compute_etag(stat);
  11170. if (!etag.empty()) { res.set_header("ETag", etag); }
  11171. auto mtime = stat.mtime();
  11172. auto last_modified = detail::file_mtime_to_http_date(mtime);
  11173. if (!last_modified.empty()) {
  11174. res.set_header("Last-Modified", last_modified);
  11175. }
  11176. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  11177. check_if_range(req, etag, mtime);
  11178. auto mm = std::make_shared<detail::mmap>(path.c_str());
  11179. if (!mm->is_open()) {
  11180. output_error_log(Error::OpenFile, &req);
  11181. return false;
  11182. }
  11183. res.set_content_provider(
  11184. mm->size(),
  11185. detail::find_content_type(path, file_extension_and_mimetype_map_,
  11186. default_file_mimetype_),
  11187. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  11188. sink.write(mm->data() + offset, length);
  11189. return true;
  11190. });
  11191. if (req.method != "HEAD" && file_request_handler_) {
  11192. file_request_handler_(req, res);
  11193. }
  11194. return true;
  11195. } else {
  11196. output_error_log(Error::OpenFile, &req);
  11197. }
  11198. }
  11199. }
  11200. }
  11201. return false;
  11202. }
  11203. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  11204. const std::string &etag,
  11205. time_t mtime) const {
  11206. // Handle conditional GET:
  11207. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  11208. // 2. If-Modified-Since is checked only when If-None-Match is absent
  11209. if (req.has_header("If-None-Match")) {
  11210. if (!etag.empty()) {
  11211. auto val =
  11212. detail::get_combined_header_value(req.headers, "If-None-Match");
  11213. // NOTE: We use exact string matching here. This works correctly
  11214. // because our server always generates weak ETags (W/"..."), and
  11215. // clients typically send back the same ETag they received.
  11216. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  11217. // If-None-Match, where W/"x" and "x" would match, but this
  11218. // simplified implementation requires exact matches.
  11219. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  11220. [&](const char *b, const char *e) {
  11221. auto seg_len = static_cast<size_t>(e - b);
  11222. return (seg_len == 1 && *b == '*') ||
  11223. (seg_len == etag.size() &&
  11224. std::equal(b, e, etag.begin()));
  11225. });
  11226. if (ret) {
  11227. res.status = StatusCode::NotModified_304;
  11228. return true;
  11229. }
  11230. }
  11231. } else if (req.has_header("If-Modified-Since")) {
  11232. auto val = req.get_header_value("If-Modified-Since");
  11233. auto t = detail::parse_http_date(val);
  11234. if (t != static_cast<time_t>(-1) && mtime <= t) {
  11235. res.status = StatusCode::NotModified_304;
  11236. return true;
  11237. }
  11238. }
  11239. return false;
  11240. }
  11241. inline bool Server::check_if_range(Request &req, const std::string &etag,
  11242. time_t mtime) const {
  11243. // Handle If-Range for partial content requests (RFC 9110
  11244. // Section 13.1.5). If-Range is only evaluated when Range header is
  11245. // present. If the validator matches, serve partial content; otherwise
  11246. // serve full content.
  11247. if (!req.ranges.empty() && req.has_header("If-Range")) {
  11248. auto val = req.get_header_value("If-Range");
  11249. auto is_valid_range = [&]() {
  11250. if (detail::is_strong_etag(val)) {
  11251. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  11252. // comparison.
  11253. return (!etag.empty() && val == etag);
  11254. } else if (detail::is_weak_etag(val)) {
  11255. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  11256. return false;
  11257. } else {
  11258. // HTTP-date comparison
  11259. auto t = detail::parse_http_date(val);
  11260. return (t != static_cast<time_t>(-1) && mtime <= t);
  11261. }
  11262. };
  11263. if (!is_valid_range()) {
  11264. // Validator doesn't match: ignore Range and serve full content
  11265. req.ranges.clear();
  11266. return false;
  11267. }
  11268. }
  11269. return true;
  11270. }
  11271. inline socket_t
  11272. Server::create_server_socket(const std::string &host, int port,
  11273. int socket_flags,
  11274. SocketOptions socket_options) const {
  11275. return detail::create_socket(
  11276. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  11277. ipv6_v6only_, std::move(socket_options),
  11278. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  11279. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  11280. output_error_log(Error::BindIPAddress, nullptr);
  11281. return false;
  11282. }
  11283. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  11284. output_error_log(Error::Listen, nullptr);
  11285. return false;
  11286. }
  11287. return true;
  11288. });
  11289. }
  11290. inline int Server::bind_internal(const std::string &host, int port,
  11291. int socket_flags) {
  11292. if (is_decommissioned) { return -1; }
  11293. if (!is_valid()) { return -1; }
  11294. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  11295. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  11296. if (port == 0) {
  11297. struct sockaddr_storage addr;
  11298. socklen_t addr_len = sizeof(addr);
  11299. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  11300. &addr_len) == -1) {
  11301. output_error_log(Error::GetSockName, nullptr);
  11302. return -1;
  11303. }
  11304. if (addr.ss_family == AF_INET) {
  11305. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  11306. } else if (addr.ss_family == AF_INET6) {
  11307. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  11308. } else {
  11309. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  11310. return -1;
  11311. }
  11312. } else {
  11313. return port;
  11314. }
  11315. }
  11316. inline bool Server::listen_internal() {
  11317. // A stop() between bind and listen leaves nothing to accept on. Report
  11318. // failure instead of returning success without ever serving, and mark the
  11319. // server decommissioned the way any failed listen does so that a concurrent
  11320. // wait_until_ready() wakes up instead of spinning forever.
  11321. if (is_decommissioned || svr_sock_ == INVALID_SOCKET) {
  11322. is_decommissioned = true;
  11323. return false;
  11324. }
  11325. auto ret = true;
  11326. is_running_ = true;
  11327. auto se = detail::scope_exit([&]() { is_running_ = false; });
  11328. if (start_handler_) { start_handler_(); }
  11329. {
  11330. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  11331. while (svr_sock_ != INVALID_SOCKET) {
  11332. #ifndef _WIN32
  11333. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  11334. #endif
  11335. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  11336. idle_interval_usec_);
  11337. if (val == 0) { // Timeout
  11338. task_queue->on_idle();
  11339. continue;
  11340. }
  11341. #ifndef _WIN32
  11342. }
  11343. #endif
  11344. #if defined _WIN32
  11345. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  11346. // OVERLAPPED
  11347. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  11348. #elif defined SOCK_CLOEXEC
  11349. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  11350. #else
  11351. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  11352. #endif
  11353. if (sock == INVALID_SOCKET) {
  11354. // NOTE: Winsock reports failures through WSAGetLastError() and never
  11355. // touches the CRT errno, so the two have to be asked platform by
  11356. // platform rather than by testing errno here.
  11357. if (detail::is_accept_resource_error()) {
  11358. // The per-process descriptor limit or the network stack's buffer
  11359. // space has been reached. Try to accept new connections after a
  11360. // short sleep.
  11361. std::this_thread::sleep_for(std::chrono::microseconds{1});
  11362. continue;
  11363. } else if (detail::is_accept_transient_error()) {
  11364. continue;
  11365. }
  11366. // Take the descriptor out of svr_sock_ before closing it: a later
  11367. // stop() would otherwise shutdown()/close() a value the OS may have
  11368. // reused, and keep_alive() watches svr_sock_ to notice the server is
  11369. // gone. The exchange also settles the race with a concurrent stop(),
  11370. // since whichever side takes the descriptor closes it exactly once.
  11371. auto listen_sock = svr_sock_.exchange(INVALID_SOCKET);
  11372. if (listen_sock != INVALID_SOCKET) {
  11373. detail::close_socket(listen_sock);
  11374. ret = false;
  11375. output_error_log(Error::Connection, nullptr);
  11376. } else {
  11377. ; // The server socket was closed by user.
  11378. }
  11379. break;
  11380. }
  11381. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  11382. read_timeout_sec_, read_timeout_usec_);
  11383. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  11384. write_timeout_sec_, write_timeout_usec_);
  11385. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  11386. if (!task_queue->enqueue(
  11387. [this, sock]() { process_and_close_socket(sock); })) {
  11388. output_error_log(Error::ResourceExhaustion, nullptr);
  11389. detail::shutdown_socket(sock);
  11390. detail::close_socket(sock);
  11391. }
  11392. }
  11393. task_queue->shutdown();
  11394. }
  11395. is_decommissioned = !ret;
  11396. return ret;
  11397. }
  11398. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  11399. if (pre_routing_handler_ &&
  11400. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  11401. return true;
  11402. }
  11403. // File handler
  11404. if ((req.method == "GET" || req.method == "HEAD") &&
  11405. handle_file_request(req, res)) {
  11406. return true;
  11407. }
  11408. const auto *custom = find_custom_entry(req.method);
  11409. // The second clause mirrors what expect_content() does unconditionally for
  11410. // POST/PUT/PATCH/DELETE: a content reader route fires even when the request
  11411. // carries no body. Without it a body-less PROPFIND (RFC 4918 treats one as
  11412. // `allprop`) would skip its handler and fall through to 404.
  11413. if (detail::expect_content(req) ||
  11414. (custom && !custom->handlers_for_content_reader.empty())) {
  11415. // Content reader handler
  11416. {
  11417. // Track whether the ContentReader was aborted due to the decompressed
  11418. // payload exceeding `payload_max_length_`.
  11419. // The user handler runs after the lambda returns, so we must restore the
  11420. // 413 status if the handler overwrites it.
  11421. bool content_reader_payload_too_large = false;
  11422. ContentReader reader(
  11423. [&](ContentReceiver receiver) {
  11424. auto result = read_content_with_content_receiver(
  11425. strm, req, res, std::move(receiver), nullptr, nullptr);
  11426. if (!result) {
  11427. output_error_log(Error::Read, &req);
  11428. if (res.status == StatusCode::PayloadTooLarge_413) {
  11429. content_reader_payload_too_large = true;
  11430. }
  11431. }
  11432. return result;
  11433. },
  11434. [&](FormDataHeader header, ContentReceiver receiver) {
  11435. auto result = read_content_with_content_receiver(
  11436. strm, req, res, nullptr, std::move(header),
  11437. std::move(receiver));
  11438. if (!result) {
  11439. output_error_log(Error::Read, &req);
  11440. if (res.status == StatusCode::PayloadTooLarge_413) {
  11441. content_reader_payload_too_large = true;
  11442. }
  11443. }
  11444. return result;
  11445. });
  11446. bool dispatched = false;
  11447. if (req.method == "POST") {
  11448. dispatched = dispatch_request_for_content_reader(
  11449. req, res, std::move(reader), post_handlers_for_content_reader_);
  11450. } else if (req.method == "PUT") {
  11451. dispatched = dispatch_request_for_content_reader(
  11452. req, res, std::move(reader), put_handlers_for_content_reader_);
  11453. } else if (req.method == "PATCH") {
  11454. dispatched = dispatch_request_for_content_reader(
  11455. req, res, std::move(reader), patch_handlers_for_content_reader_);
  11456. } else if (req.method == "DELETE") {
  11457. dispatched = dispatch_request_for_content_reader(
  11458. req, res, std::move(reader), delete_handlers_for_content_reader_);
  11459. } else if (custom) {
  11460. dispatched = dispatch_request_for_content_reader(
  11461. req, res, std::move(reader), custom->handlers_for_content_reader);
  11462. }
  11463. if (dispatched) {
  11464. if (content_reader_payload_too_large) {
  11465. // Enforce the limit: override any status the handler may have set
  11466. // and return false so the error path sends a plain 413 response.
  11467. res.status = StatusCode::PayloadTooLarge_413;
  11468. res.body.clear();
  11469. res.content_length_ = 0;
  11470. res.content_provider_ = nullptr;
  11471. return false;
  11472. }
  11473. return true;
  11474. }
  11475. }
  11476. // NOTE: `req.body` is not read here. For a regular handler the body is
  11477. // read inside dispatch_request(), after the route has matched and the
  11478. // pre-request handler has approved the request, so that a rejected
  11479. // request (e.g. failed authentication) never forces us to buffer a
  11480. // potentially large body.
  11481. }
  11482. // Regular handler
  11483. if (req.method == "GET" || req.method == "HEAD") {
  11484. return dispatch_request(req, res, get_handlers_, strm);
  11485. } else if (req.method == "POST") {
  11486. return dispatch_request(req, res, post_handlers_, strm);
  11487. } else if (req.method == "PUT") {
  11488. return dispatch_request(req, res, put_handlers_, strm);
  11489. } else if (req.method == "DELETE") {
  11490. return dispatch_request(req, res, delete_handlers_, strm);
  11491. } else if (req.method == "OPTIONS") {
  11492. return dispatch_request(req, res, options_handlers_, strm);
  11493. } else if (req.method == "PATCH") {
  11494. return dispatch_request(req, res, patch_handlers_, strm);
  11495. } else if (custom) {
  11496. return dispatch_request(req, res, custom->handlers, strm);
  11497. }
  11498. res.status = StatusCode::BadRequest_400;
  11499. return false;
  11500. }
  11501. inline bool Server::dispatch_request(Request &req, Response &res,
  11502. const Handlers &handlers, Stream &strm) {
  11503. for (const auto &x : handlers) {
  11504. const auto &matcher = x.first;
  11505. const auto &handler = x.second;
  11506. if (matcher->match(req)) {
  11507. req.matched_route = matcher->pattern();
  11508. // Run the pre-request handler before reading the body so a rejected
  11509. // request (e.g. failed authentication) never forces us to buffer a
  11510. // potentially large body. `req.matched_route` is available here.
  11511. if (pre_request_handler_ &&
  11512. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  11513. return true;
  11514. }
  11515. // The route matched and the request was approved; read the body now.
  11516. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  11517. output_error_log(Error::Read, &req);
  11518. return false;
  11519. }
  11520. handler(req, res);
  11521. return true;
  11522. }
  11523. }
  11524. return false;
  11525. }
  11526. inline void Server::apply_ranges(const Request &req, Response &res,
  11527. std::string &content_type,
  11528. std::string &boundary) const {
  11529. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  11530. auto it = res.headers.find("Content-Type");
  11531. if (it != res.headers.end()) {
  11532. content_type = it->second;
  11533. res.headers.erase(it);
  11534. }
  11535. boundary = detail::make_multipart_data_boundary();
  11536. res.set_header("Content-Type",
  11537. "multipart/byteranges; boundary=" + boundary);
  11538. }
  11539. auto type = detail::encoding_type(req, res);
  11540. if (res.body.empty()) {
  11541. if (res.content_length_ > 0) {
  11542. size_t length = 0;
  11543. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  11544. length = res.content_length_;
  11545. } else if (req.ranges.size() == 1) {
  11546. auto offset_and_length = detail::get_range_offset_and_length(
  11547. req.ranges[0], res.content_length_);
  11548. length = offset_and_length.second;
  11549. auto content_range = detail::make_content_range_header_field(
  11550. offset_and_length, res.content_length_);
  11551. res.set_header("Content-Range", content_range);
  11552. } else {
  11553. length = detail::get_multipart_ranges_data_length(
  11554. req, boundary, content_type, res.content_length_);
  11555. }
  11556. res.set_header("Content-Length", std::to_string(length));
  11557. } else {
  11558. if (res.content_provider_) {
  11559. if (res.is_chunked_content_provider_) {
  11560. res.set_header("Transfer-Encoding", "chunked");
  11561. if (type != detail::EncodingType::None) {
  11562. res.set_header("Content-Encoding", detail::encoding_name(type));
  11563. res.set_header("Vary", "Accept-Encoding");
  11564. }
  11565. }
  11566. }
  11567. }
  11568. } else {
  11569. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  11570. ;
  11571. } else if (req.ranges.size() == 1) {
  11572. auto offset_and_length =
  11573. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  11574. auto offset = offset_and_length.first;
  11575. auto length = offset_and_length.second;
  11576. auto content_range = detail::make_content_range_header_field(
  11577. offset_and_length, res.body.size());
  11578. res.set_header("Content-Range", content_range);
  11579. assert(offset + length <= res.body.size());
  11580. res.body = res.body.substr(offset, length);
  11581. } else {
  11582. std::string data;
  11583. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  11584. res.body.size(), data);
  11585. res.body.swap(data);
  11586. }
  11587. if (type != detail::EncodingType::None) {
  11588. output_pre_compression_log(req, res);
  11589. if (auto compressor = detail::make_compressor(type)) {
  11590. std::string compressed;
  11591. if (compressor->compress(res.body.data(), res.body.size(), true,
  11592. [&](const char *data, size_t data_len) {
  11593. compressed.append(data, data_len);
  11594. return true;
  11595. })) {
  11596. res.body.swap(compressed);
  11597. res.set_header("Content-Encoding", detail::encoding_name(type));
  11598. res.set_header("Vary", "Accept-Encoding");
  11599. }
  11600. }
  11601. }
  11602. res.content_length_ = res.body.size();
  11603. res.set_header("Content-Length", std::to_string(res.content_length_));
  11604. }
  11605. }
  11606. inline bool Server::dispatch_request_for_content_reader(
  11607. Request &req, Response &res, ContentReader content_reader,
  11608. const HandlersForContentReader &handlers) const {
  11609. for (const auto &x : handlers) {
  11610. const auto &matcher = x.first;
  11611. const auto &handler = x.second;
  11612. if (matcher->match(req)) {
  11613. req.matched_route = matcher->pattern();
  11614. if (!pre_request_handler_ ||
  11615. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  11616. handler(req, res, content_reader);
  11617. }
  11618. return true;
  11619. }
  11620. }
  11621. return false;
  11622. }
  11623. inline std::string
  11624. get_client_ip(const std::string &x_forwarded_for,
  11625. const std::vector<std::string> &trusted_proxies) {
  11626. // X-Forwarded-For is a comma-separated list per RFC 7239
  11627. std::vector<std::string> ip_list;
  11628. detail::split(x_forwarded_for.data(),
  11629. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  11630. [&](const char *b, const char *e) {
  11631. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  11632. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  11633. });
  11634. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  11635. // no segments. Signal "no client IP derived" with an empty string so the
  11636. // caller can fall back to the connection-level remote address.
  11637. if (ip_list.empty()) { return std::string(); }
  11638. // Each hop appends the address it received the request from, so the rightmost
  11639. // entries are the ones written by our own infrastructure while the leftmost
  11640. // are whatever the original client chose to send. Walk from the right and
  11641. // skip trusted proxies; the first address that is not a trusted proxy is the
  11642. // furthest point still attributable to a real hop, i.e. the client. Scanning
  11643. // from the left instead lets a client forge an arbitrary address by following
  11644. // it with a trusted proxy's address, which the left-to-right scan then
  11645. // returned as the client.
  11646. for (size_t i = ip_list.size(); i-- > 0;) {
  11647. const auto &ip = ip_list[i];
  11648. auto is_trusted_proxy =
  11649. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  11650. [&](const std::string &proxy) { return ip == proxy; });
  11651. if (!is_trusted_proxy) { return ip; }
  11652. }
  11653. // Every hop was a trusted proxy; fall back to the first entry.
  11654. return ip_list.front();
  11655. }
  11656. inline bool
  11657. Server::process_request(Stream &strm, const std::string &remote_addr,
  11658. int remote_port, const std::string &local_addr,
  11659. int local_port, bool close_connection,
  11660. bool &connection_closed,
  11661. const std::function<void(Request &)> &setup_request,
  11662. bool *websocket_upgraded) {
  11663. std::array<char, 2048> buf{};
  11664. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  11665. // Connection has been closed on client
  11666. if (!line_reader.getline()) { return false; }
  11667. Request req;
  11668. req.start_time_ = std::chrono::steady_clock::now();
  11669. req.remote_addr = remote_addr;
  11670. req.remote_port = remote_port;
  11671. req.local_addr = local_addr;
  11672. req.local_port = local_port;
  11673. Response res;
  11674. res.version = "HTTP/1.1";
  11675. res.headers = default_headers_;
  11676. // Request line and headers
  11677. if (!parse_request_line(line_reader.ptr(), req)) {
  11678. res.status = StatusCode::BadRequest_400;
  11679. output_error_log(Error::InvalidRequestLine, &req);
  11680. return write_response(strm, close_connection, req, res);
  11681. }
  11682. // Request headers
  11683. if (!detail::read_headers(strm, req.headers)) {
  11684. res.status = StatusCode::BadRequest_400;
  11685. output_error_log(Error::InvalidHeaders, &req);
  11686. return write_response(strm, close_connection, req, res);
  11687. }
  11688. // RFC 9112 §6.3: Reject requests whose framing is ambiguous, which would
  11689. // otherwise let an intermediary and this parser disagree on where the body
  11690. // ends and enable request smuggling. Two cases: a non-zero Content-Length
  11691. // alongside any Transfer-Encoding (Content-Length: 0 is tolerated for
  11692. // compatibility with existing clients), and a Transfer-Encoding whose final
  11693. // coding is not chunked, which leaves the body length undeterminable. The
  11694. // latter must not fall through to the "no body" path, or the body bytes are
  11695. // parsed as the next request on a persistent connection.
  11696. if (req.has_header("Transfer-Encoding") &&
  11697. (req.get_header_value_u64("Content-Length") > 0 ||
  11698. !detail::is_chunked_transfer_encoding(req.headers))) {
  11699. connection_closed = true;
  11700. res.status = StatusCode::BadRequest_400;
  11701. return write_response(strm, close_connection, req, res);
  11702. }
  11703. // Check if the request URI doesn't exceed the limit
  11704. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11705. connection_closed = true;
  11706. res.status = StatusCode::UriTooLong_414;
  11707. output_error_log(Error::ExceedUriMaxLength, &req);
  11708. return write_response(strm, close_connection, req, res);
  11709. }
  11710. if (detail::has_header_token(req.headers, "Connection", "close")) {
  11711. connection_closed = true;
  11712. }
  11713. if (req.version == "HTTP/1.0" &&
  11714. !detail::has_header_token(req.headers, "Connection", "keep-alive")) {
  11715. connection_closed = true;
  11716. }
  11717. // Only honor X-Forwarded-For if the peer on the actual TCP connection is
  11718. // itself a trusted proxy. Otherwise any direct client could spoof
  11719. // remote_addr simply by sending an arbitrary X-Forwarded-For header.
  11720. auto is_trusted_peer = std::any_of(
  11721. trusted_proxies_.begin(), trusted_proxies_.end(),
  11722. [&](const std::string &proxy) { return proxy == remote_addr; });
  11723. if (is_trusted_peer && req.has_header("X-Forwarded-For")) {
  11724. // Some proxies append the address they observed as a separate
  11725. // X-Forwarded-For field line instead of extending the one the client sent
  11726. // (e.g. HAProxy's "option forwardfor"), so the whole combined value has to
  11727. // be scanned. Reading only the first occurrence would hand back the
  11728. // client-supplied, and therefore forgeable, value.
  11729. auto x_forwarded_for =
  11730. detail::get_combined_header_value(req.headers, "X-Forwarded-For");
  11731. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  11732. req.remote_addr = derived.empty() ? remote_addr : derived;
  11733. } else {
  11734. req.remote_addr = remote_addr;
  11735. }
  11736. req.remote_port = remote_port;
  11737. req.local_addr = local_addr;
  11738. req.local_port = local_port;
  11739. if (req.has_header("Accept")) {
  11740. auto accept_header =
  11741. detail::get_combined_header_value(req.headers, "Accept");
  11742. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  11743. connection_closed = true;
  11744. res.status = StatusCode::BadRequest_400;
  11745. output_error_log(Error::HTTPParsing, &req);
  11746. return write_response(strm, close_connection, req, res);
  11747. }
  11748. }
  11749. if (req.has_header("Range")) {
  11750. const auto &range_header_value = req.get_header_value("Range");
  11751. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  11752. connection_closed = true;
  11753. res.status = StatusCode::RangeNotSatisfiable_416;
  11754. output_error_log(Error::InvalidRangeHeader, &req);
  11755. return write_response(strm, close_connection, req, res);
  11756. }
  11757. }
  11758. if (setup_request) { setup_request(req); }
  11759. // RFC 9110 10.1.1: Expect is a comma-separated list whose value is
  11760. // case-insensitive, and a 100-continue expectation in an HTTP/1.0 request
  11761. // must be ignored. An expectation we do not recognize is left alone; the
  11762. // 417 the section allows for one is a MAY, not a requirement.
  11763. if (req.version != "HTTP/1.0" &&
  11764. detail::has_header_token(req.headers, "Expect", "100-continue")) {
  11765. int status = StatusCode::Continue_100;
  11766. if (expect_100_continue_handler_) {
  11767. status = expect_100_continue_handler_(req, res);
  11768. }
  11769. switch (status) {
  11770. case StatusCode::Continue_100:
  11771. case StatusCode::ExpectationFailed_417:
  11772. detail::write_response_line(strm, status);
  11773. strm.write("\r\n");
  11774. break;
  11775. default:
  11776. connection_closed = true;
  11777. return write_response(strm, true, req, res);
  11778. }
  11779. }
  11780. // Setup `is_connection_closed` method
  11781. auto sock = strm.socket();
  11782. req.is_connection_closed = [sock]() {
  11783. return !detail::is_socket_alive(sock);
  11784. };
  11785. // WebSocket upgrade
  11786. // Check pre_routing_handler_ before upgrading so that authentication
  11787. // and other middleware can reject the request with an HTTP response
  11788. // (e.g., 401) before the protocol switches.
  11789. if (detail::is_websocket_upgrade(req)) {
  11790. if (pre_routing_handler_ &&
  11791. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  11792. if (res.status == -1) { res.status = StatusCode::OK_200; }
  11793. return write_response(strm, close_connection, req, res);
  11794. }
  11795. // Find matching WebSocket handler
  11796. for (const auto &entry : websocket_handlers_) {
  11797. if (entry.matcher->match(req)) {
  11798. // Compute accept key
  11799. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  11800. auto accept_key = detail::websocket_accept_key(client_key);
  11801. // Negotiate subprotocol
  11802. std::string selected_subprotocol;
  11803. if (entry.sub_protocol_selector) {
  11804. auto protocol_header = detail::get_combined_header_value(
  11805. req.headers, "Sec-WebSocket-Protocol");
  11806. if (!protocol_header.empty()) {
  11807. std::vector<std::string> protocols;
  11808. detail::split(protocol_header.data(),
  11809. protocol_header.data() + protocol_header.size(), ',',
  11810. [&](const char *b, const char *e) {
  11811. protocols.emplace_back(b, e);
  11812. });
  11813. selected_subprotocol = entry.sub_protocol_selector(protocols);
  11814. }
  11815. }
  11816. // Send 101 Switching Protocols
  11817. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  11818. "Upgrade: websocket\r\n"
  11819. "Connection: Upgrade\r\n"
  11820. "Sec-WebSocket-Accept: " +
  11821. accept_key + "\r\n";
  11822. if (!selected_subprotocol.empty()) {
  11823. if (!detail::fields::is_field_value(selected_subprotocol)) {
  11824. return false;
  11825. }
  11826. handshake_response +=
  11827. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  11828. }
  11829. handshake_response += "\r\n";
  11830. if (strm.write(handshake_response.data(), handshake_response.size()) <
  11831. 0) {
  11832. return false;
  11833. }
  11834. connection_closed = true;
  11835. if (websocket_upgraded) { *websocket_upgraded = true; }
  11836. {
  11837. #ifdef CPPHTTPLIB_SSL_ENABLED
  11838. if (req.ssl) {
  11839. // wss: the heartbeat ping thread and the read path enter the same
  11840. // TLS session from different threads. Hand the WebSocket a stream
  11841. // that serializes every TLS call, so the shared SSLSocketStream on
  11842. // the plain HTTP/HTTPS paths stays untouched.
  11843. auto ws_strm =
  11844. std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  11845. strm.socket(), const_cast<tls::session_t>(req.ssl),
  11846. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0,
  11847. write_timeout_sec_, write_timeout_usec_));
  11848. ws::WebSocket ws(std::move(ws_strm), req, true,
  11849. websocket_ping_interval_sec_,
  11850. websocket_max_missed_pongs_);
  11851. entry.handler(req, ws);
  11852. return true;
  11853. }
  11854. #endif
  11855. // Use WebSocket-specific read timeout instead of HTTP timeout
  11856. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  11857. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  11858. websocket_max_missed_pongs_);
  11859. entry.handler(req, ws);
  11860. }
  11861. return true;
  11862. }
  11863. }
  11864. // No matching handler - fall through to 404
  11865. }
  11866. // Routing
  11867. auto routed = false;
  11868. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11869. routed = routing(req, res, strm);
  11870. #else
  11871. try {
  11872. routed = routing(req, res, strm);
  11873. } catch (std::exception &) {
  11874. if (exception_handler_) {
  11875. auto ep = std::current_exception();
  11876. exception_handler_(req, res, ep);
  11877. routed = true;
  11878. } else {
  11879. res.status = StatusCode::InternalServerError_500;
  11880. }
  11881. } catch (...) {
  11882. if (exception_handler_) {
  11883. auto ep = std::current_exception();
  11884. exception_handler_(req, res, ep);
  11885. routed = true;
  11886. } else {
  11887. res.status = StatusCode::InternalServerError_500;
  11888. }
  11889. }
  11890. #endif
  11891. auto ret = false;
  11892. if (routed) {
  11893. if (res.status == -1) {
  11894. res.status = req.ranges.empty() ? StatusCode::OK_200
  11895. : StatusCode::PartialContent_206;
  11896. }
  11897. // Serve file content by using a content provider
  11898. auto file_open_error = false;
  11899. if (!res.file_content_path_.empty()) {
  11900. const auto &path = res.file_content_path_;
  11901. auto mm = std::make_shared<detail::mmap>(path.c_str());
  11902. if (!mm->is_open()) {
  11903. res.body.clear();
  11904. res.content_length_ = 0;
  11905. res.content_provider_ = nullptr;
  11906. res.status = StatusCode::NotFound_404;
  11907. output_error_log(Error::OpenFile, &req);
  11908. file_open_error = true;
  11909. } else {
  11910. auto content_type = res.file_content_content_type_;
  11911. if (content_type.empty()) {
  11912. content_type = detail::find_content_type(
  11913. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  11914. }
  11915. res.set_content_provider(
  11916. mm->size(), content_type,
  11917. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  11918. sink.write(mm->data() + offset, length);
  11919. return true;
  11920. });
  11921. }
  11922. }
  11923. if (file_open_error) {
  11924. ret = write_response(strm, close_connection, req, res);
  11925. } else if (detail::range_error(req, res)) {
  11926. res.body.clear();
  11927. res.content_length_ = 0;
  11928. res.content_provider_ = nullptr;
  11929. res.status = StatusCode::RangeNotSatisfiable_416;
  11930. ret = write_response(strm, close_connection, req, res);
  11931. } else {
  11932. ret = write_response_with_content(strm, close_connection, req, res);
  11933. }
  11934. } else {
  11935. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  11936. ret = write_response(strm, close_connection, req, res);
  11937. }
  11938. // Drain any unconsumed framed body to prevent request smuggling on
  11939. // keep-alive. Without framing there is no body to drain — reading would
  11940. // consume the next request (issue #2450). If the response has committed the
  11941. // connection to close, there is no next request to protect.
  11942. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  11943. if (detail::has_header_token(res.headers, "Connection", "close")) {
  11944. connection_closed = true;
  11945. } else {
  11946. int dummy_status;
  11947. if (!detail::read_content(
  11948. strm, req, payload_max_length_, dummy_status, nullptr,
  11949. [](const char *, size_t, size_t, size_t) { return true; },
  11950. false)) {
  11951. connection_closed = true;
  11952. }
  11953. }
  11954. }
  11955. return ret;
  11956. }
  11957. inline bool Server::is_valid() const { return !has_invalid_registration_; }
  11958. inline bool Server::process_and_close_socket(socket_t sock) {
  11959. std::string remote_addr;
  11960. int remote_port = 0;
  11961. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  11962. std::string local_addr;
  11963. int local_port = 0;
  11964. detail::get_local_ip_and_port(sock, local_addr, local_port);
  11965. bool websocket_upgraded = false;
  11966. auto ret = detail::process_server_socket(
  11967. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  11968. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11969. write_timeout_usec_,
  11970. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  11971. return process_request(strm, remote_addr, remote_port, local_addr,
  11972. local_port, close_connection, connection_closed,
  11973. nullptr, &websocket_upgraded);
  11974. });
  11975. detail::drain_and_close_socket(sock);
  11976. return ret;
  11977. }
  11978. inline void Server::output_log(const Request &req, const Response &res) const {
  11979. if (logger_) {
  11980. std::lock_guard<std::mutex> guard(logger_mutex_);
  11981. logger_(req, res);
  11982. }
  11983. }
  11984. inline void Server::output_pre_compression_log(const Request &req,
  11985. const Response &res) const {
  11986. if (pre_compression_logger_) {
  11987. std::lock_guard<std::mutex> guard(logger_mutex_);
  11988. pre_compression_logger_(req, res);
  11989. }
  11990. }
  11991. inline void Server::output_error_log(const Error &err,
  11992. const Request *req) const {
  11993. if (error_logger_) {
  11994. std::lock_guard<std::mutex> guard(logger_mutex_);
  11995. error_logger_(err, req);
  11996. }
  11997. }
  11998. /*
  11999. * Group 5: ClientImpl and Client (Universal) implementation
  12000. */
  12001. // HTTP client implementation
  12002. inline ClientImpl::ClientImpl(const std::string &host)
  12003. : ClientImpl(host, 80, std::string(), std::string()) {}
  12004. inline ClientImpl::ClientImpl(const std::string &host, int port)
  12005. : ClientImpl(host, port, std::string(), std::string()) {}
  12006. inline ClientImpl::ClientImpl(const std::string &host, int port,
  12007. const std::string &client_cert_path,
  12008. const std::string &client_key_path)
  12009. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  12010. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  12011. inline ClientImpl::~ClientImpl() {
  12012. // Wait until all the requests in flight are handled.
  12013. size_t retry_count = 10;
  12014. while (retry_count-- > 0) {
  12015. {
  12016. std::lock_guard<std::mutex> guard(socket_mutex_);
  12017. if (socket_requests_in_flight_ == 0) { break; }
  12018. }
  12019. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  12020. }
  12021. std::lock_guard<std::mutex> guard(socket_mutex_);
  12022. shutdown_socket(socket_);
  12023. close_socket(socket_);
  12024. }
  12025. inline bool ClientImpl::is_valid() const { return true; }
  12026. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  12027. client_cert_path_ = rhs.client_cert_path_;
  12028. client_key_path_ = rhs.client_key_path_;
  12029. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  12030. read_timeout_sec_ = rhs.read_timeout_sec_;
  12031. read_timeout_usec_ = rhs.read_timeout_usec_;
  12032. write_timeout_sec_ = rhs.write_timeout_sec_;
  12033. write_timeout_usec_ = rhs.write_timeout_usec_;
  12034. max_timeout_msec_ = rhs.max_timeout_msec_;
  12035. basic_auth_username_ = rhs.basic_auth_username_;
  12036. basic_auth_password_ = rhs.basic_auth_password_;
  12037. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  12038. keep_alive_ = rhs.keep_alive_;
  12039. follow_location_ = rhs.follow_location_;
  12040. path_encode_ = rhs.path_encode_;
  12041. address_family_ = rhs.address_family_;
  12042. tcp_nodelay_ = rhs.tcp_nodelay_;
  12043. ipv6_v6only_ = rhs.ipv6_v6only_;
  12044. socket_options_ = rhs.socket_options_;
  12045. compress_ = rhs.compress_;
  12046. decompress_ = rhs.decompress_;
  12047. payload_max_length_ = rhs.payload_max_length_;
  12048. has_payload_max_length_ = rhs.has_payload_max_length_;
  12049. interface_ = rhs.interface_;
  12050. proxy_host_ = rhs.proxy_host_;
  12051. proxy_port_ = rhs.proxy_port_;
  12052. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  12053. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  12054. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  12055. no_proxy_entries_ = rhs.no_proxy_entries_;
  12056. logger_ = rhs.logger_;
  12057. error_logger_ = rhs.error_logger_;
  12058. #ifdef CPPHTTPLIB_SSL_ENABLED
  12059. digest_auth_username_ = rhs.digest_auth_username_;
  12060. digest_auth_password_ = rhs.digest_auth_password_;
  12061. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  12062. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  12063. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  12064. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  12065. server_certificate_verification_ = rhs.server_certificate_verification_;
  12066. server_hostname_verification_ = rhs.server_hostname_verification_;
  12067. system_ca_mode_ = rhs.system_ca_mode_;
  12068. #endif
  12069. }
  12070. inline bool
  12071. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  12072. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  12073. if (no_proxy_entries_.empty()) { return true; }
  12074. // host_ is const so its normalized form is invariant; cache it. The
  12075. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  12076. if (host == host_) {
  12077. if (!host_normalized_valid_) {
  12078. host_normalized_ = detail::normalize_target(host_);
  12079. host_normalized_valid_ = true;
  12080. }
  12081. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  12082. }
  12083. auto target = detail::normalize_target(host);
  12084. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  12085. }
  12086. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  12087. if (is_proxy_enabled_for_host(host_)) {
  12088. return detail::create_client_socket(
  12089. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  12090. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  12091. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  12092. write_timeout_sec_, write_timeout_usec_, interface_, error);
  12093. }
  12094. // Check is custom IP or hostname specified for host_
  12095. std::string connect_host;
  12096. std::string ip;
  12097. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  12098. return detail::create_client_socket(
  12099. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  12100. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  12101. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12102. write_timeout_usec_, interface_, error);
  12103. }
  12104. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  12105. Error &error) {
  12106. auto sock = create_client_socket(error);
  12107. if (sock == INVALID_SOCKET) { return false; }
  12108. socket.sock = sock;
  12109. return true;
  12110. }
  12111. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  12112. return create_and_connect_socket(socket, error);
  12113. }
  12114. inline bool ClientImpl::setup_proxy_connection(
  12115. Socket & /*socket*/,
  12116. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  12117. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  12118. return true;
  12119. }
  12120. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  12121. bool /*shutdown_gracefully*/) {
  12122. // If there are any requests in flight from threads other than us, then it's
  12123. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  12124. assert(socket_requests_in_flight_ == 0 ||
  12125. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12126. }
  12127. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  12128. if (socket.sock == INVALID_SOCKET) { return; }
  12129. detail::shutdown_socket(socket.sock);
  12130. }
  12131. inline void ClientImpl::close_socket(Socket &socket) {
  12132. // If there are requests in flight in another thread, usually closing
  12133. // the socket will be fine and they will simply receive an error when
  12134. // using the closed socket, but it is still a bug since rarely the OS
  12135. // may reassign the socket id to be used for a new socket, and then
  12136. // suddenly they will be operating on a live socket that is different
  12137. // than the one they intended!
  12138. assert(socket_requests_in_flight_ == 0 ||
  12139. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12140. // It is also a bug if this happens while SSL is still active
  12141. #ifdef CPPHTTPLIB_SSL_ENABLED
  12142. assert(socket.ssl == nullptr);
  12143. #endif
  12144. if (socket.sock == INVALID_SOCKET) { return; }
  12145. detail::close_socket(socket.sock);
  12146. socket.sock = INVALID_SOCKET;
  12147. }
  12148. inline void ClientImpl::disconnect(bool gracefully) {
  12149. shutdown_ssl(socket_, gracefully);
  12150. shutdown_socket(socket_);
  12151. close_socket(socket_);
  12152. }
  12153. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  12154. Response &res,
  12155. bool skip_100_continue) const {
  12156. std::array<char, 2048> buf{};
  12157. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  12158. if (!line_reader.getline()) { return false; }
  12159. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12160. res.reason)) {
  12161. return req.method == "CONNECT";
  12162. }
  12163. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  12164. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  12165. if (!line_reader.getline()) { return false; } // CRLF
  12166. if (!line_reader.getline()) { return false; } // next response line
  12167. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12168. res.reason)) {
  12169. return false;
  12170. }
  12171. }
  12172. return true;
  12173. }
  12174. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  12175. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  12176. auto ret = send_(req, res, error);
  12177. if (error == Error::SSLPeerCouldBeClosed_) {
  12178. assert(!ret);
  12179. ret = send_(req, res, error);
  12180. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  12181. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  12182. }
  12183. return ret;
  12184. }
  12185. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  12186. {
  12187. std::lock_guard<std::mutex> guard(socket_mutex_);
  12188. // Set this to false immediately - if it ever gets set to true by the end
  12189. // of the request, we know another thread instructed us to close the
  12190. // socket.
  12191. socket_should_be_closed_when_request_is_done_ = false;
  12192. auto is_alive = false;
  12193. if (socket_.is_open()) {
  12194. is_alive = detail::is_socket_alive(socket_.sock);
  12195. #ifdef CPPHTTPLIB_SSL_ENABLED
  12196. if (is_alive && is_ssl()) {
  12197. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12198. is_alive = false;
  12199. }
  12200. }
  12201. #endif
  12202. if (!is_alive) {
  12203. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  12204. disconnect(/*gracefully=*/false);
  12205. }
  12206. }
  12207. if (!is_alive) {
  12208. if (!ensure_socket_connection(socket_, error)) {
  12209. output_error_log(error, &req);
  12210. return false;
  12211. }
  12212. {
  12213. auto success = true;
  12214. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  12215. error)) {
  12216. if (!success) { output_error_log(error, &req); }
  12217. return success;
  12218. }
  12219. }
  12220. }
  12221. // Mark the current socket as being in use so that it cannot be closed by
  12222. // anyone else while this request is ongoing, even though we will be
  12223. // releasing the mutex.
  12224. if (socket_requests_in_flight_ > 1) {
  12225. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  12226. }
  12227. socket_requests_in_flight_ += 1;
  12228. socket_requests_are_from_thread_ = std::this_thread::get_id();
  12229. }
  12230. for (const auto &header : default_headers_) {
  12231. if (req.headers.find(header.first) == req.headers.end()) {
  12232. req.headers.insert(header);
  12233. }
  12234. }
  12235. auto ret = false;
  12236. auto close_connection = !keep_alive_;
  12237. auto se = detail::scope_exit([&]() {
  12238. // Briefly lock mutex in order to mark that a request is no longer ongoing
  12239. std::lock_guard<std::mutex> guard(socket_mutex_);
  12240. socket_requests_in_flight_ -= 1;
  12241. if (socket_requests_in_flight_ <= 0) {
  12242. assert(socket_requests_in_flight_ == 0);
  12243. socket_requests_are_from_thread_ = std::thread::id();
  12244. }
  12245. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  12246. !ret) {
  12247. disconnect(/*gracefully=*/true);
  12248. }
  12249. });
  12250. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  12251. return handle_request(strm, req, res, close_connection, error);
  12252. });
  12253. if (!ret) {
  12254. if (error == Error::Success) {
  12255. error = Error::Unknown;
  12256. output_error_log(error, &req);
  12257. }
  12258. }
  12259. return ret;
  12260. }
  12261. inline Result ClientImpl::send(const Request &req) {
  12262. auto req2 = req;
  12263. return send_(std::move(req2));
  12264. }
  12265. inline Result ClientImpl::send_(Request &&req) {
  12266. auto res = detail::make_unique<Response>();
  12267. auto error = Error::Success;
  12268. auto ret = send(req, *res, error);
  12269. #ifdef CPPHTTPLIB_SSL_ENABLED
  12270. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  12271. last_ssl_error_, last_backend_error_};
  12272. #else
  12273. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  12274. #endif
  12275. }
  12276. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  12277. const std::string &ct) {
  12278. (void)for_stream;
  12279. for (const auto &header : default_headers_) {
  12280. if (!r.has_header(header.first)) { r.headers.insert(header); }
  12281. }
  12282. // RFC 9110 5.3 recommends sending control data such as Host first, so
  12283. // prepend it rather than appending it after the caller's own fields.
  12284. if (!r.has_header("Host")) {
  12285. r.headers.emplace_front(
  12286. "Host", detail::make_default_host_header_value(host_, port_, is_ssl(),
  12287. address_family_));
  12288. }
  12289. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  12290. if (!r.content_receiver) {
  12291. if (!r.has_header("Accept-Encoding")) {
  12292. std::string accept_encoding;
  12293. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12294. accept_encoding = "br";
  12295. #endif
  12296. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12297. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  12298. accept_encoding += "gzip, deflate";
  12299. #endif
  12300. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12301. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  12302. accept_encoding += "zstd";
  12303. #endif
  12304. r.set_header("Accept-Encoding", accept_encoding);
  12305. }
  12306. detail::add_default_user_agent_header(r);
  12307. }
  12308. if (!r.body.empty()) {
  12309. if (!ct.empty() && !r.has_header("Content-Type")) {
  12310. r.headers.emplace("Content-Type", ct);
  12311. }
  12312. if (!r.has_header("Content-Length")) {
  12313. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  12314. }
  12315. }
  12316. }
  12317. inline ClientImpl::StreamHandle
  12318. ClientImpl::open_stream(const std::string &method, const std::string &path,
  12319. const Params &params, const Headers &headers,
  12320. const std::string &body,
  12321. const std::string &content_type) {
  12322. StreamHandle handle;
  12323. handle.response = detail::make_unique<Response>();
  12324. handle.error = Error::Success;
  12325. // Encode the target exactly like the buffered send path does, so that the
  12326. // same `path` produces the same request line through either API.
  12327. auto raw_query_path =
  12328. params.empty() ? path : append_query_params(path, params);
  12329. auto query_path = detail::encode_request_target(raw_query_path, path_encode_);
  12330. handle.connection_ = detail::make_unique<ClientConnection>();
  12331. {
  12332. std::lock_guard<std::mutex> guard(socket_mutex_);
  12333. auto is_alive = false;
  12334. if (socket_.is_open()) {
  12335. is_alive = detail::is_socket_alive(socket_.sock);
  12336. #ifdef CPPHTTPLIB_SSL_ENABLED
  12337. if (is_alive && is_ssl()) {
  12338. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12339. is_alive = false;
  12340. }
  12341. }
  12342. #endif
  12343. if (!is_alive) { disconnect(/*gracefully=*/false); }
  12344. }
  12345. if (!is_alive) {
  12346. if (!ensure_socket_connection(socket_, handle.error)) {
  12347. handle.response.reset();
  12348. return handle;
  12349. }
  12350. {
  12351. auto success = true;
  12352. auto start_time = std::chrono::steady_clock::now();
  12353. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  12354. success, handle.error)) {
  12355. if (!success) { handle.response.reset(); }
  12356. return handle;
  12357. }
  12358. }
  12359. }
  12360. transfer_socket_ownership_to_handle(handle);
  12361. }
  12362. #ifdef CPPHTTPLIB_SSL_ENABLED
  12363. if (is_ssl() && handle.connection_->session) {
  12364. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  12365. handle.connection_->sock, handle.connection_->session,
  12366. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12367. write_timeout_usec_);
  12368. } else {
  12369. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  12370. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  12371. write_timeout_sec_, write_timeout_usec_);
  12372. }
  12373. #else
  12374. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  12375. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  12376. write_timeout_sec_, write_timeout_usec_);
  12377. #endif
  12378. handle.stream_ = handle.socket_stream_.get();
  12379. Request req;
  12380. req.method = method;
  12381. req.path = query_path;
  12382. req.headers = headers;
  12383. req.body = body;
  12384. prepare_default_headers(req, true, content_type);
  12385. auto &strm = *handle.stream_;
  12386. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  12387. handle.error = Error::Write;
  12388. handle.response.reset();
  12389. return handle;
  12390. }
  12391. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  12392. handle.error)) {
  12393. handle.response.reset();
  12394. return handle;
  12395. }
  12396. if (!body.empty()) {
  12397. if (strm.write(body.data(), body.size()) < 0) {
  12398. handle.error = Error::Write;
  12399. handle.response.reset();
  12400. return handle;
  12401. }
  12402. }
  12403. if (!read_response_line(strm, req, *handle.response) ||
  12404. !detail::read_headers(strm, handle.response->headers)) {
  12405. handle.error = Error::Read;
  12406. handle.response.reset();
  12407. return handle;
  12408. }
  12409. handle.body_reader_.stream = handle.stream_;
  12410. handle.body_reader_.payload_max_length = payload_max_length_;
  12411. if (handle.response->has_header("Content-Length")) {
  12412. bool is_invalid = false;
  12413. auto content_length = detail::get_header_value_u64(
  12414. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  12415. if (is_invalid) {
  12416. handle.error = Error::Read;
  12417. handle.response.reset();
  12418. return handle;
  12419. }
  12420. handle.body_reader_.has_content_length = true;
  12421. handle.body_reader_.content_length = content_length;
  12422. }
  12423. handle.body_reader_.chunked =
  12424. detail::is_chunked_transfer_encoding(handle.response->headers);
  12425. auto content_encoding = detail::get_combined_header_value(
  12426. handle.response->headers, "Content-Encoding");
  12427. if (!content_encoding.empty()) {
  12428. // Same policy as prepare_content_receiver(): reject a coding we know about
  12429. // but were not built with, pass an unrecognized one through as-is.
  12430. handle.decompressor_ = detail::create_decompressor(content_encoding);
  12431. if (!handle.decompressor_) {
  12432. if (detail::is_known_content_encoding(content_encoding)) {
  12433. handle.error = Error::UnsupportedContentEncoding;
  12434. handle.response.reset();
  12435. return handle;
  12436. }
  12437. } else if (!handle.decompressor_->is_valid()) {
  12438. handle.error = Error::Compression;
  12439. handle.response.reset();
  12440. return handle;
  12441. }
  12442. }
  12443. return handle;
  12444. }
  12445. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  12446. if (!is_valid() || !response) { return -1; }
  12447. if (decompressor_) { return read_with_decompression(buf, len); }
  12448. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  12449. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  12450. trailers_parsed_ = true;
  12451. if (body_reader_.chunked_decoder) {
  12452. if (!body_reader_.chunked_decoder->parse_trailers_into(
  12453. response->trailers, response->headers)) {
  12454. return n;
  12455. }
  12456. } else {
  12457. detail::ChunkedDecoder dec(*stream_);
  12458. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  12459. return n;
  12460. }
  12461. }
  12462. }
  12463. return n;
  12464. }
  12465. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  12466. size_t len) {
  12467. if (decompress_offset_ < decompress_buffer_.size()) {
  12468. auto available = decompress_buffer_.size() - decompress_offset_;
  12469. auto to_copy = (std::min)(len, available);
  12470. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  12471. decompress_offset_ += to_copy;
  12472. decompressed_bytes_read_ += to_copy;
  12473. return static_cast<ssize_t>(to_copy);
  12474. }
  12475. decompress_buffer_.clear();
  12476. decompress_offset_ = 0;
  12477. constexpr size_t kDecompressionBufferSize = 8192;
  12478. char compressed_buf[kDecompressionBufferSize];
  12479. while (true) {
  12480. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  12481. sizeof(compressed_buf));
  12482. if (n <= 0) { return n; }
  12483. bool decompress_ok = decompressor_->decompress(
  12484. compressed_buf, static_cast<size_t>(n),
  12485. [this](const char *data, size_t data_len) {
  12486. decompress_buffer_.append(data, data_len);
  12487. auto limit = body_reader_.payload_max_length;
  12488. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  12489. return false;
  12490. }
  12491. return true;
  12492. });
  12493. if (!decompress_ok) {
  12494. body_reader_.last_error = Error::Read;
  12495. return -1;
  12496. }
  12497. if (!decompress_buffer_.empty()) { break; }
  12498. }
  12499. auto to_copy = (std::min)(len, decompress_buffer_.size());
  12500. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  12501. decompress_offset_ = to_copy;
  12502. decompressed_bytes_read_ += to_copy;
  12503. return static_cast<ssize_t>(to_copy);
  12504. }
  12505. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  12506. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  12507. return;
  12508. }
  12509. trailers_parsed_ = true;
  12510. const auto bufsiz = 128;
  12511. char line_buf[bufsiz];
  12512. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  12513. if (!line_reader.getline()) { return; }
  12514. if (!detail::parse_trailers(line_reader, response->trailers,
  12515. response->headers)) {
  12516. return;
  12517. }
  12518. }
  12519. namespace detail {
  12520. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  12521. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  12522. size_t &out_chunk_offset,
  12523. size_t &out_chunk_total) {
  12524. if (finished) { return 0; }
  12525. if (chunk_remaining == 0) {
  12526. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  12527. if (!lr.getline()) { return -1; }
  12528. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  12529. const char *p = lr.ptr();
  12530. int v = 0;
  12531. if (!is_hex(*p, v)) { return -1; }
  12532. size_t chunk_len = 0;
  12533. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  12534. for (; is_hex(*p, v); ++p) {
  12535. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  12536. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  12537. }
  12538. while (is_space_or_tab(*p)) {
  12539. ++p;
  12540. }
  12541. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  12542. if (chunk_len == 0) {
  12543. chunk_remaining = 0;
  12544. finished = true;
  12545. out_chunk_offset = 0;
  12546. out_chunk_total = 0;
  12547. return 0;
  12548. }
  12549. chunk_remaining = chunk_len;
  12550. last_chunk_total = chunk_remaining;
  12551. last_chunk_offset = 0;
  12552. }
  12553. auto to_read = (std::min)(chunk_remaining, len);
  12554. auto n = strm.read(buf, to_read);
  12555. if (n <= 0) { return -1; }
  12556. auto offset_before = last_chunk_offset;
  12557. last_chunk_offset += static_cast<size_t>(n);
  12558. chunk_remaining -= static_cast<size_t>(n);
  12559. out_chunk_offset = offset_before;
  12560. out_chunk_total = last_chunk_total;
  12561. if (chunk_remaining == 0) {
  12562. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  12563. if (!lr.getline()) { return -1; }
  12564. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  12565. }
  12566. return n;
  12567. }
  12568. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  12569. const Headers &src_headers) {
  12570. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  12571. if (!lr.getline()) { return false; }
  12572. return parse_trailers(lr, dest, src_headers);
  12573. }
  12574. } // namespace detail
  12575. inline void
  12576. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  12577. handle.connection_->sock = socket_.sock;
  12578. #ifdef CPPHTTPLIB_SSL_ENABLED
  12579. handle.connection_->session = socket_.ssl;
  12580. socket_.ssl = nullptr;
  12581. #endif
  12582. socket_.sock = INVALID_SOCKET;
  12583. }
  12584. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  12585. Response &res, bool close_connection,
  12586. Error &error) {
  12587. if (req.path.empty()) {
  12588. error = Error::Connection;
  12589. output_error_log(error, &req);
  12590. return false;
  12591. }
  12592. auto req_save = req;
  12593. bool ret;
  12594. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  12595. auto req2 = req;
  12596. req2.path = "http://" +
  12597. detail::make_host_and_port_string(host_, port_, false) +
  12598. req.path;
  12599. ret = process_request(strm, req2, res, close_connection, error);
  12600. req = std::move(req2);
  12601. req.path = req_save.path;
  12602. } else {
  12603. ret = process_request(strm, req, res, close_connection, error);
  12604. }
  12605. if (!ret) { return false; }
  12606. if (detail::has_header_token(res.headers, "Connection", "close") ||
  12607. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  12608. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  12609. // for this to be safe.
  12610. // This is safe to call because handle_request is only called by send_
  12611. // which locks the request mutex during the process. It would be a bug
  12612. // to call it from a different thread since it's a thread-safety issue
  12613. // to do these things to the socket if another thread is using the socket.
  12614. std::lock_guard<std::mutex> guard(socket_mutex_);
  12615. disconnect(/*gracefully=*/true);
  12616. }
  12617. if (300 < res.status && res.status < 400 && follow_location_) {
  12618. req = std::move(req_save);
  12619. ret = redirect(req, res, error);
  12620. }
  12621. #ifdef CPPHTTPLIB_SSL_ENABLED
  12622. if ((res.status == StatusCode::Unauthorized_401 ||
  12623. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  12624. req.authorization_count_ < 5) {
  12625. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  12626. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  12627. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  12628. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  12629. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  12630. return ret;
  12631. }
  12632. const auto &username =
  12633. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  12634. const auto &password =
  12635. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  12636. if (!username.empty() && !password.empty()) {
  12637. std::map<std::string, std::string> auth;
  12638. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  12639. Request new_req = req;
  12640. new_req.authorization_count_ += 1;
  12641. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  12642. : "Authorization");
  12643. new_req.headers.insert(detail::make_digest_authentication_header(
  12644. req, auth, new_req.authorization_count_, detail::random_string(10),
  12645. username, password, is_proxy));
  12646. Response new_res;
  12647. ret = send(new_req, new_res, error);
  12648. if (ret) { res = std::move(new_res); }
  12649. }
  12650. }
  12651. }
  12652. #endif
  12653. return ret;
  12654. }
  12655. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  12656. if (req.redirect_count_ == 0) {
  12657. error = Error::ExceedRedirectCount;
  12658. output_error_log(error, &req);
  12659. return false;
  12660. }
  12661. auto location = res.get_header_value("location");
  12662. if (location.empty()) { return false; }
  12663. detail::UrlComponents uc;
  12664. if (!detail::parse_url(location, uc)) { return false; }
  12665. // Only follow http/https redirects
  12666. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  12667. return false;
  12668. }
  12669. auto scheme = is_ssl() ? "https" : "http";
  12670. auto next_scheme = std::move(uc.scheme);
  12671. auto next_host = std::move(uc.host);
  12672. auto port_str = std::move(uc.port);
  12673. auto next_path = std::move(uc.path);
  12674. auto next_query = std::move(uc.query);
  12675. auto next_port = port_;
  12676. if (!port_str.empty()) {
  12677. if (!detail::parse_port(port_str, next_port)) { return false; }
  12678. } else if (!next_scheme.empty()) {
  12679. next_port = next_scheme == "https" ? 443 : 80;
  12680. }
  12681. if (next_scheme.empty()) { next_scheme = scheme; }
  12682. if (next_host.empty()) { next_host = host_; }
  12683. if (next_path.empty()) { next_path = "/"; }
  12684. auto path = decode_path_component(next_path) + next_query;
  12685. // Same host redirect - use current client
  12686. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  12687. return detail::redirect(*this, req, res, path, location, error);
  12688. }
  12689. // Cross-host/scheme redirect - create new client with robust setup
  12690. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  12691. path, location, error);
  12692. }
  12693. // New method for robust redirect client creation
  12694. inline bool ClientImpl::create_redirect_client(
  12695. const std::string &scheme, const std::string &host, int port, Request &req,
  12696. Response &res, const std::string &path, const std::string &location,
  12697. Error &error) {
  12698. // Determine if we need SSL
  12699. auto need_ssl = (scheme == "https");
  12700. // Clean up request headers that are host/client specific
  12701. // Remove headers that should not be carried over to new host
  12702. auto headers_to_remove = std::vector<std::string>{
  12703. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  12704. for (const auto &header_name : headers_to_remove) {
  12705. auto it = req.headers.find(header_name);
  12706. while (it != req.headers.end()) {
  12707. it = req.headers.erase(it);
  12708. it = req.headers.find(header_name);
  12709. }
  12710. }
  12711. // Create appropriate client type and handle redirect
  12712. if (need_ssl) {
  12713. #ifdef CPPHTTPLIB_SSL_ENABLED
  12714. // Create SSL client for HTTPS redirect
  12715. SSLClient redirect_client(host, port);
  12716. // Setup basic client configuration first
  12717. setup_redirect_client(redirect_client);
  12718. redirect_client.enable_server_certificate_verification(
  12719. server_certificate_verification_);
  12720. redirect_client.enable_server_hostname_verification(
  12721. server_hostname_verification_);
  12722. redirect_client.system_ca_mode_ = system_ca_mode_;
  12723. // Transfer CA certificate to redirect client
  12724. if (!ca_cert_pem_.empty()) {
  12725. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  12726. ca_cert_pem_.size());
  12727. }
  12728. if (!ca_cert_file_path_.empty()) {
  12729. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  12730. }
  12731. // Client certificates are set through constructor for SSLClient
  12732. // NOTE: SSLClient constructor already takes client_cert_path and
  12733. // client_key_path so we need to create it properly if client certs are
  12734. // needed
  12735. // Execute the redirect
  12736. return detail::redirect(redirect_client, req, res, path, location, error);
  12737. #else
  12738. // SSL not supported - set appropriate error
  12739. error = Error::SSLConnection;
  12740. output_error_log(error, &req);
  12741. return false;
  12742. #endif
  12743. } else {
  12744. // HTTP redirect
  12745. ClientImpl redirect_client(host, port);
  12746. // Setup client with robust configuration
  12747. setup_redirect_client(redirect_client);
  12748. // Execute the redirect
  12749. return detail::redirect(redirect_client, req, res, path, location, error);
  12750. }
  12751. }
  12752. // New method for robust client setup (based on basic_manual_redirect.cpp
  12753. // logic)
  12754. template <typename ClientType>
  12755. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  12756. // Copy basic settings first
  12757. client.set_connection_timeout(connection_timeout_sec_);
  12758. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  12759. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  12760. client.set_keep_alive(keep_alive_);
  12761. client.set_follow_location(
  12762. true); // Enable redirects to handle multi-step redirects
  12763. client.set_path_encode(path_encode_);
  12764. client.set_compress(compress_);
  12765. client.set_decompress(decompress_);
  12766. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  12767. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  12768. // 15.4, credentials must not be forwarded when redirecting to a different
  12769. // host. This function is only called for cross-host redirects; same-host
  12770. // redirects are handled directly in ClientImpl::redirect().
  12771. // Copy the proxy configuration unconditionally; the per-target bypass is
  12772. // re-evaluated at send time, so a later hop to a non-bypassed host can
  12773. // still use the proxy.
  12774. client.no_proxy_entries_ = no_proxy_entries_;
  12775. if (!proxy_host_.empty() && proxy_port_ != -1) {
  12776. client.set_proxy(proxy_host_, proxy_port_);
  12777. if (!proxy_basic_auth_username_.empty()) {
  12778. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  12779. proxy_basic_auth_password_);
  12780. }
  12781. if (!proxy_bearer_token_auth_token_.empty()) {
  12782. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  12783. }
  12784. #ifdef CPPHTTPLIB_SSL_ENABLED
  12785. if (!proxy_digest_auth_username_.empty()) {
  12786. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  12787. proxy_digest_auth_password_);
  12788. }
  12789. #endif
  12790. }
  12791. // Copy network and socket settings
  12792. client.set_address_family(address_family_);
  12793. client.set_tcp_nodelay(tcp_nodelay_);
  12794. client.set_ipv6_v6only(ipv6_v6only_);
  12795. if (socket_options_) { client.set_socket_options(socket_options_); }
  12796. if (!interface_.empty()) { client.set_interface(interface_); }
  12797. // Copy logging and headers
  12798. if (logger_) { client.set_logger(logger_); }
  12799. if (error_logger_) { client.set_error_logger(error_logger_); }
  12800. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  12801. // Each new client should generate its own headers based on its target host
  12802. }
  12803. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  12804. const Request &req,
  12805. Error &error) const {
  12806. auto is_shutting_down = []() { return false; };
  12807. if (req.is_chunked_content_provider_) {
  12808. auto compressor = compress_ ? detail::create_compressor().first
  12809. : std::unique_ptr<detail::compressor>();
  12810. if (!compressor) {
  12811. compressor = detail::make_unique<detail::nocompressor>();
  12812. }
  12813. return detail::write_content_chunked(strm, req.content_provider_,
  12814. is_shutting_down, *compressor, error);
  12815. } else {
  12816. return detail::write_content_with_progress(
  12817. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  12818. req.upload_progress, error);
  12819. }
  12820. }
  12821. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  12822. bool close_connection, Error &error,
  12823. bool skip_body) {
  12824. // Prepare additional headers
  12825. if (close_connection) {
  12826. if (!req.has_header("Connection")) {
  12827. req.set_header("Connection", "close");
  12828. }
  12829. }
  12830. std::string ct_for_defaults;
  12831. if (!req.has_header("Content-Type") && !req.body.empty()) {
  12832. ct_for_defaults = "text/plain";
  12833. }
  12834. prepare_default_headers(req, false, ct_for_defaults);
  12835. if (req.body.empty()) {
  12836. if (req.content_provider_) {
  12837. if (!req.is_chunked_content_provider_) {
  12838. if (!req.has_header("Content-Length")) {
  12839. auto length = std::to_string(req.content_length_);
  12840. req.set_header("Content-Length", length);
  12841. }
  12842. }
  12843. } else {
  12844. if (req.method == "POST" || req.method == "PUT" ||
  12845. req.method == "PATCH") {
  12846. req.set_header("Content-Length", "0");
  12847. }
  12848. }
  12849. }
  12850. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  12851. if (!req.has_header("Authorization")) {
  12852. req.headers.insert(make_basic_authentication_header(
  12853. basic_auth_username_, basic_auth_password_, false));
  12854. }
  12855. }
  12856. if (!bearer_token_auth_token_.empty()) {
  12857. if (!req.has_header("Authorization")) {
  12858. req.headers.insert(make_bearer_token_authentication_header(
  12859. bearer_token_auth_token_, false));
  12860. }
  12861. }
  12862. // Proxy-Authorization is only sent when the proxy is actually used for
  12863. // this target — otherwise NO_PROXY-matched requests would leak proxy
  12864. // credentials directly to the destination server.
  12865. if (is_proxy_enabled_for_host(host_)) {
  12866. if (!proxy_basic_auth_username_.empty() &&
  12867. !proxy_basic_auth_password_.empty() &&
  12868. !req.has_header("Proxy-Authorization")) {
  12869. req.headers.insert(make_basic_authentication_header(
  12870. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  12871. }
  12872. if (!proxy_bearer_token_auth_token_.empty() &&
  12873. !req.has_header("Proxy-Authorization")) {
  12874. req.headers.insert(make_bearer_token_authentication_header(
  12875. proxy_bearer_token_auth_token_, true));
  12876. }
  12877. }
  12878. // Request line and headers
  12879. {
  12880. detail::BufferStream bstrm;
  12881. // Extract the query from req.path. The encoding itself is delegated to
  12882. // `encode_request_target`; the raw query is still needed here to decide
  12883. // between populating `req.params` from it and falling back to building a
  12884. // query out of caller-supplied `req.params`.
  12885. auto query_pos = req.path.find('?');
  12886. auto query_part = query_pos == std::string::npos
  12887. ? std::string()
  12888. : req.path.substr(query_pos + 1);
  12889. auto path_with_query =
  12890. detail::encode_request_target(req.path, path_encode_);
  12891. if (!query_part.empty()) {
  12892. // The query already came in through `req.path`; still populate
  12893. // `req.params` for handlers/users who read them.
  12894. detail::parse_query_text(query_part, req.params);
  12895. } else if (!req.params.empty()) {
  12896. // No query in `req.path`; build one from `req.params` so existing
  12897. // callers that pass `Params` separately continue to work.
  12898. path_with_query = append_query_params(path_with_query, req.params);
  12899. }
  12900. // Write request line and headers
  12901. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  12902. // A rejected target (e.g. CR/LF smuggled in via a decoded redirect
  12903. // Location under set_path_encode(false)) must fail the request cleanly
  12904. // instead of emitting a request-line-less, header-injecting request.
  12905. error = Error::Write;
  12906. output_error_log(error, &req);
  12907. return false;
  12908. }
  12909. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  12910. error)) {
  12911. output_error_log(error, &req);
  12912. return false;
  12913. }
  12914. // Flush buffer
  12915. auto &data = bstrm.get_buffer();
  12916. if (!detail::write_data(strm, data.data(), data.size())) {
  12917. error = Error::Write;
  12918. output_error_log(error, &req);
  12919. return false;
  12920. }
  12921. }
  12922. // After sending request line and headers, wait briefly for an early server
  12923. // response (e.g. 4xx) and avoid sending a potentially large request body
  12924. // unnecessarily. This workaround is only enabled on Windows because Unix
  12925. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  12926. // buffering can accept large writes even when the peer already responded.
  12927. // Check the stream first (which covers SSL via `is_readable()`), then
  12928. // fall back to select on the socket. Only perform the wait for very large
  12929. // request bodies to avoid interfering with normal small requests and
  12930. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  12931. // response. Skip this check when using Expect: 100-continue, as the protocol
  12932. // handles early responses properly.
  12933. #if defined(_WIN32)
  12934. if (!skip_body &&
  12935. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  12936. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  12937. auto start = std::chrono::high_resolution_clock::now();
  12938. for (;;) {
  12939. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  12940. // from SSL internals. If the underlying socket is readable, assume an
  12941. // early response may be present.
  12942. auto sock = strm.socket();
  12943. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  12944. return false;
  12945. }
  12946. // Fallback to stream-level check for non-socket streams or when the
  12947. // socket isn't reporting readable. Avoid using `is_readable()` for
  12948. // SSL, since `SSL_pending()` may report buffered records that do not
  12949. // indicate a complete application-level response yet.
  12950. if (!is_ssl() && strm.is_readable()) { return false; }
  12951. auto now = std::chrono::high_resolution_clock::now();
  12952. auto elapsed =
  12953. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  12954. .count();
  12955. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  12956. break;
  12957. }
  12958. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  12959. }
  12960. }
  12961. #endif
  12962. // Body
  12963. if (skip_body) { return true; }
  12964. return write_request_body(strm, req, error);
  12965. }
  12966. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  12967. Error &error) {
  12968. if (req.body.empty()) {
  12969. return write_content_with_provider(strm, req, error);
  12970. }
  12971. if (req.upload_progress) {
  12972. auto body_size = req.body.size();
  12973. size_t written = 0;
  12974. auto data = req.body.data();
  12975. while (written < body_size) {
  12976. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  12977. if (!detail::write_data(strm, data + written, to_write)) {
  12978. error = Error::Write;
  12979. output_error_log(error, &req);
  12980. return false;
  12981. }
  12982. written += to_write;
  12983. if (!req.upload_progress(written, body_size)) {
  12984. error = Error::Canceled;
  12985. output_error_log(error, &req);
  12986. return false;
  12987. }
  12988. }
  12989. } else {
  12990. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  12991. error = Error::Write;
  12992. output_error_log(error, &req);
  12993. return false;
  12994. }
  12995. }
  12996. return true;
  12997. }
  12998. inline std::unique_ptr<Response>
  12999. ClientImpl::send_with_content_provider_and_receiver(
  13000. Request &req, const char *body, size_t content_length,
  13001. ContentProvider content_provider,
  13002. ContentProviderWithoutLength content_provider_without_length,
  13003. const std::string &content_type, ContentReceiver content_receiver,
  13004. Error &error) {
  13005. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  13006. auto enc = compress_
  13007. ? detail::create_compressor()
  13008. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  13009. nullptr, nullptr);
  13010. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  13011. if (enc.first && !content_provider_without_length) {
  13012. auto &compressor = enc.first;
  13013. if (content_provider) {
  13014. auto ok = true;
  13015. size_t offset = 0;
  13016. DataSink data_sink;
  13017. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  13018. if (ok) {
  13019. auto last = offset + data_len == content_length;
  13020. auto ret = compressor->compress(
  13021. data, data_len, last,
  13022. [&](const char *compressed_data, size_t compressed_data_len) {
  13023. req.body.append(compressed_data, compressed_data_len);
  13024. return true;
  13025. });
  13026. if (ret) {
  13027. offset += data_len;
  13028. } else {
  13029. ok = false;
  13030. }
  13031. }
  13032. return ok;
  13033. };
  13034. while (ok && offset < content_length) {
  13035. if (!content_provider(offset, content_length - offset, data_sink)) {
  13036. error = Error::Canceled;
  13037. output_error_log(error, &req);
  13038. return nullptr;
  13039. }
  13040. }
  13041. } else {
  13042. if (!compressor->compress(body, content_length, true,
  13043. [&](const char *data, size_t data_len) {
  13044. req.body.append(data, data_len);
  13045. return true;
  13046. })) {
  13047. error = Error::Compression;
  13048. output_error_log(error, &req);
  13049. return nullptr;
  13050. }
  13051. }
  13052. } else {
  13053. if (content_provider) {
  13054. req.content_length_ = content_length;
  13055. req.content_provider_ = std::move(content_provider);
  13056. req.is_chunked_content_provider_ = false;
  13057. } else if (content_provider_without_length) {
  13058. req.content_length_ = 0;
  13059. req.content_provider_ = detail::ContentProviderAdapter(
  13060. std::move(content_provider_without_length));
  13061. req.is_chunked_content_provider_ = true;
  13062. req.set_header("Transfer-Encoding", "chunked");
  13063. } else {
  13064. req.body.assign(body, content_length);
  13065. }
  13066. }
  13067. if (content_receiver) {
  13068. req.content_receiver =
  13069. [content_receiver](const char *data, size_t data_length,
  13070. size_t /*offset*/, size_t /*total_length*/) {
  13071. return content_receiver(data, data_length);
  13072. };
  13073. }
  13074. auto res = detail::make_unique<Response>();
  13075. return send(req, *res, error) ? std::move(res) : nullptr;
  13076. }
  13077. inline Result ClientImpl::send_with_content_provider_and_receiver(
  13078. const std::string &method, const std::string &path, const Headers &headers,
  13079. const char *body, size_t content_length, ContentProvider content_provider,
  13080. ContentProviderWithoutLength content_provider_without_length,
  13081. const std::string &content_type, ContentReceiver content_receiver,
  13082. UploadProgress progress) {
  13083. Request req;
  13084. req.method = method;
  13085. req.headers = headers;
  13086. req.path = path;
  13087. req.upload_progress = std::move(progress);
  13088. if (max_timeout_msec_ > 0) {
  13089. req.start_time_ = std::chrono::steady_clock::now();
  13090. }
  13091. auto error = Error::Success;
  13092. auto res = send_with_content_provider_and_receiver(
  13093. req, body, content_length, std::move(content_provider),
  13094. std::move(content_provider_without_length), content_type,
  13095. std::move(content_receiver), error);
  13096. #ifdef CPPHTTPLIB_SSL_ENABLED
  13097. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  13098. last_backend_error_};
  13099. #else
  13100. return Result{std::move(res), error, std::move(req.headers)};
  13101. #endif
  13102. }
  13103. inline void ClientImpl::output_log(const Request &req,
  13104. const Response &res) const {
  13105. if (logger_) {
  13106. std::lock_guard<std::mutex> guard(logger_mutex_);
  13107. logger_(req, res);
  13108. }
  13109. }
  13110. inline void ClientImpl::output_error_log(const Error &err,
  13111. const Request *req) const {
  13112. if (error_logger_) {
  13113. std::lock_guard<std::mutex> guard(logger_mutex_);
  13114. error_logger_(err, req);
  13115. }
  13116. }
  13117. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  13118. Response &res, bool close_connection,
  13119. Error &error) {
  13120. // Auto-add Expect: 100-continue for large bodies
  13121. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  13122. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  13123. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  13124. req.set_header("Expect", "100-continue");
  13125. }
  13126. }
  13127. // Check for Expect: 100-continue
  13128. auto expect_100_continue =
  13129. detail::has_header_token(req.headers, "Expect", "100-continue");
  13130. // Send request (skip body if using Expect: 100-continue)
  13131. auto write_request_success =
  13132. write_request(strm, req, close_connection, error, expect_100_continue);
  13133. #ifdef CPPHTTPLIB_SSL_ENABLED
  13134. if (is_ssl() && !expect_100_continue) {
  13135. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  13136. if (!is_proxy_enabled) {
  13137. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  13138. error = Error::SSLPeerCouldBeClosed_;
  13139. output_error_log(error, &req);
  13140. return false;
  13141. }
  13142. }
  13143. }
  13144. #endif
  13145. // Handle Expect: 100-continue.
  13146. //
  13147. // Wait for an interim/early response by attempting to read the status line
  13148. // under a short timeout, instead of trusting raw socket readability. Over
  13149. // TLS, post-handshake records (e.g. session tickets) make the socket
  13150. // readable without any HTTP response being available; relying on
  13151. // `select_read` there caused the body to be withheld forever and the
  13152. // request to fail with `Read` (#2458). If no status line arrives within the
  13153. // timeout, send the body anyway (matching curl's behavior).
  13154. auto status_line_read = false;
  13155. if (expect_100_continue && write_request_success) {
  13156. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  13157. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  13158. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  13159. strm.set_read_timeout(sec, usec);
  13160. status_line_read = read_response_line(strm, req, res, false);
  13161. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  13162. }
  13163. if (!status_line_read) {
  13164. // No interim response within the timeout: send the body and handle the
  13165. // response as usual.
  13166. if (!write_request_body(strm, req, error)) { return false; }
  13167. expect_100_continue = false; // Switch to normal response handling
  13168. }
  13169. }
  13170. // Receive response and headers
  13171. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  13172. if ((!status_line_read &&
  13173. !read_response_line(strm, req, res, !expect_100_continue)) ||
  13174. !detail::read_headers(strm, res.headers)) {
  13175. if (write_request_success) { error = Error::Read; }
  13176. output_error_log(error, &req);
  13177. return false;
  13178. }
  13179. if (!write_request_success) { return false; }
  13180. // Handle Expect: 100-continue response
  13181. if (expect_100_continue) {
  13182. if (res.status == StatusCode::Continue_100) {
  13183. // Server accepted, send the body
  13184. if (!write_request_body(strm, req, error)) { return false; }
  13185. // Read the actual response
  13186. res.headers.clear();
  13187. res.body.clear();
  13188. if (!read_response_line(strm, req, res) ||
  13189. !detail::read_headers(strm, res.headers)) {
  13190. error = Error::Read;
  13191. output_error_log(error, &req);
  13192. return false;
  13193. }
  13194. }
  13195. // If not 100 Continue, server returned an error; proceed with that response
  13196. }
  13197. // Body
  13198. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  13199. req.method != "CONNECT") {
  13200. auto redirect = 300 < res.status && res.status < 400 &&
  13201. res.status != StatusCode::NotModified_304 &&
  13202. follow_location_;
  13203. if (req.response_handler && !redirect) {
  13204. if (!req.response_handler(res)) {
  13205. error = Error::Canceled;
  13206. output_error_log(error, &req);
  13207. return false;
  13208. }
  13209. }
  13210. auto out =
  13211. req.content_receiver
  13212. ? static_cast<ContentReceiverWithProgress>(
  13213. [&](const char *buf, size_t n, size_t off, size_t len) {
  13214. if (redirect) { return true; }
  13215. auto ret = req.content_receiver(buf, n, off, len);
  13216. if (!ret) {
  13217. error = Error::Canceled;
  13218. output_error_log(error, &req);
  13219. }
  13220. return ret;
  13221. })
  13222. : static_cast<ContentReceiverWithProgress>(
  13223. [&](const char *buf, size_t n, size_t /*off*/,
  13224. size_t /*len*/) {
  13225. assert(res.body.size() + n <= res.body.max_size());
  13226. if (payload_max_length_ > 0 &&
  13227. (res.body.size() >= payload_max_length_ ||
  13228. n > payload_max_length_ - res.body.size())) {
  13229. return false;
  13230. }
  13231. res.body.append(buf, n);
  13232. return true;
  13233. });
  13234. auto progress = [&](size_t current, size_t total) {
  13235. if (!req.download_progress || redirect) { return true; }
  13236. auto ret = req.download_progress(current, total);
  13237. if (!ret) {
  13238. error = Error::Canceled;
  13239. output_error_log(error, &req);
  13240. }
  13241. return ret;
  13242. };
  13243. if (res.has_header("Content-Length")) {
  13244. if (!req.content_receiver) {
  13245. auto len = res.get_header_value_u64("Content-Length");
  13246. if (len > res.body.max_size()) {
  13247. error = Error::Read;
  13248. output_error_log(error, &req);
  13249. return false;
  13250. }
  13251. // Cap the reservation by payload_max_length_ to avoid OOM when a
  13252. // hostile or malformed server sends an enormous Content-Length.
  13253. // The actual body read below is bounded by payload_max_length_,
  13254. // so reserving more than that is never useful.
  13255. auto reserve_len = static_cast<size_t>(len);
  13256. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  13257. reserve_len = payload_max_length_;
  13258. }
  13259. res.body.reserve(reserve_len);
  13260. }
  13261. }
  13262. if (res.status != StatusCode::NotModified_304) {
  13263. auto content_status = 0;
  13264. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  13265. ? (std::numeric_limits<size_t>::max)()
  13266. : payload_max_length_;
  13267. if (!detail::read_content(strm, res, max_length, content_status,
  13268. std::move(progress), std::move(out),
  13269. decompress_)) {
  13270. if (error != Error::Canceled) {
  13271. // Tell the caller apart from a plain read failure when the body could
  13272. // not be decoded because of its Content-Encoding.
  13273. switch (content_status) {
  13274. case StatusCode::UnsupportedMediaType_415:
  13275. error = Error::UnsupportedContentEncoding;
  13276. break;
  13277. case StatusCode::InternalServerError_500:
  13278. error = Error::Compression;
  13279. break;
  13280. default: error = Error::Read; break;
  13281. }
  13282. }
  13283. output_error_log(error, &req);
  13284. return false;
  13285. }
  13286. }
  13287. }
  13288. // Log
  13289. output_log(req, res);
  13290. return true;
  13291. }
  13292. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  13293. const std::string &boundary, const UploadFormDataItems &items,
  13294. const FormDataProviderItems &provider_items) const {
  13295. size_t cur_item = 0;
  13296. size_t cur_start = 0;
  13297. // cur_item and cur_start are copied to within the std::function and
  13298. // maintain state between successive calls
  13299. return [&, cur_item, cur_start](size_t offset,
  13300. DataSink &sink) mutable -> bool {
  13301. if (!offset && !items.empty()) {
  13302. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  13303. return true;
  13304. } else if (cur_item < provider_items.size()) {
  13305. if (!cur_start) {
  13306. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  13307. provider_items[cur_item], boundary);
  13308. offset += begin.size();
  13309. cur_start = offset;
  13310. sink.os << begin;
  13311. }
  13312. DataSink cur_sink;
  13313. auto has_data = true;
  13314. cur_sink.write = sink.write;
  13315. cur_sink.done = [&]() { has_data = false; };
  13316. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  13317. return false;
  13318. }
  13319. if (!has_data) {
  13320. sink.os << detail::serialize_multipart_formdata_item_end();
  13321. cur_item++;
  13322. cur_start = 0;
  13323. }
  13324. return true;
  13325. } else {
  13326. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  13327. sink.done();
  13328. return true;
  13329. }
  13330. };
  13331. }
  13332. inline bool ClientImpl::process_socket(
  13333. const Socket &socket,
  13334. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13335. std::function<bool(Stream &strm)> callback) {
  13336. return detail::process_client_socket(
  13337. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13338. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  13339. }
  13340. inline bool ClientImpl::is_ssl() const { return false; }
  13341. inline Result ClientImpl::Get(const std::string &path,
  13342. DownloadProgress progress) {
  13343. return Get(path, Headers(), std::move(progress));
  13344. }
  13345. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13346. DownloadProgress progress) {
  13347. return Get(path, params, Headers(), std::move(progress));
  13348. }
  13349. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13350. const Headers &headers,
  13351. DownloadProgress progress) {
  13352. if (params.empty()) { return Get(path, headers); }
  13353. std::string path_with_query = append_query_params(path, params);
  13354. return Get(path_with_query, headers, std::move(progress));
  13355. }
  13356. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13357. DownloadProgress progress) {
  13358. Request req;
  13359. req.method = "GET";
  13360. req.path = path;
  13361. req.headers = headers;
  13362. req.download_progress = std::move(progress);
  13363. if (max_timeout_msec_ > 0) {
  13364. req.start_time_ = std::chrono::steady_clock::now();
  13365. }
  13366. return send_(std::move(req));
  13367. }
  13368. inline Result ClientImpl::Get(const std::string &path,
  13369. ContentReceiver content_receiver,
  13370. DownloadProgress progress) {
  13371. return Get(path, Headers(), nullptr, std::move(content_receiver),
  13372. std::move(progress));
  13373. }
  13374. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13375. ContentReceiver content_receiver,
  13376. DownloadProgress progress) {
  13377. return Get(path, headers, nullptr, std::move(content_receiver),
  13378. std::move(progress));
  13379. }
  13380. inline Result ClientImpl::Get(const std::string &path,
  13381. ResponseHandler response_handler,
  13382. ContentReceiver content_receiver,
  13383. DownloadProgress progress) {
  13384. return Get(path, Headers(), std::move(response_handler),
  13385. std::move(content_receiver), std::move(progress));
  13386. }
  13387. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13388. ResponseHandler response_handler,
  13389. ContentReceiver content_receiver,
  13390. DownloadProgress progress) {
  13391. Request req;
  13392. req.method = "GET";
  13393. req.path = path;
  13394. req.headers = headers;
  13395. req.response_handler = std::move(response_handler);
  13396. req.content_receiver =
  13397. [content_receiver](const char *data, size_t data_length,
  13398. size_t /*offset*/, size_t /*total_length*/) {
  13399. return content_receiver(data, data_length);
  13400. };
  13401. req.download_progress = std::move(progress);
  13402. if (max_timeout_msec_ > 0) {
  13403. req.start_time_ = std::chrono::steady_clock::now();
  13404. }
  13405. return send_(std::move(req));
  13406. }
  13407. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13408. const Headers &headers,
  13409. ContentReceiver content_receiver,
  13410. DownloadProgress progress) {
  13411. return Get(path, params, headers, nullptr, std::move(content_receiver),
  13412. std::move(progress));
  13413. }
  13414. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13415. const Headers &headers,
  13416. ResponseHandler response_handler,
  13417. ContentReceiver content_receiver,
  13418. DownloadProgress progress) {
  13419. if (params.empty()) {
  13420. return Get(path, headers, std::move(response_handler),
  13421. std::move(content_receiver), std::move(progress));
  13422. }
  13423. std::string path_with_query = append_query_params(path, params);
  13424. return Get(path_with_query, headers, std::move(response_handler),
  13425. std::move(content_receiver), std::move(progress));
  13426. }
  13427. inline Result ClientImpl::Head(const std::string &path) {
  13428. return Head(path, Headers());
  13429. }
  13430. inline Result ClientImpl::Head(const std::string &path,
  13431. const Headers &headers) {
  13432. Request req;
  13433. req.method = "HEAD";
  13434. req.headers = headers;
  13435. req.path = path;
  13436. if (max_timeout_msec_ > 0) {
  13437. req.start_time_ = std::chrono::steady_clock::now();
  13438. }
  13439. return send_(std::move(req));
  13440. }
  13441. inline Result ClientImpl::Post(const std::string &path) {
  13442. return Post(path, std::string(), std::string());
  13443. }
  13444. inline Result ClientImpl::Post(const std::string &path,
  13445. const Headers &headers) {
  13446. return Post(path, headers, nullptr, 0, std::string());
  13447. }
  13448. inline Result ClientImpl::Post(const std::string &path, const char *body,
  13449. size_t content_length,
  13450. const std::string &content_type,
  13451. UploadProgress progress) {
  13452. return Post(path, Headers(), body, content_length, content_type, progress);
  13453. }
  13454. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  13455. const std::string &content_type,
  13456. UploadProgress progress) {
  13457. return Post(path, Headers(), body, content_type, progress);
  13458. }
  13459. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  13460. return Post(path, Headers(), params);
  13461. }
  13462. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  13463. ContentProvider content_provider,
  13464. const std::string &content_type,
  13465. UploadProgress progress) {
  13466. return Post(path, Headers(), content_length, std::move(content_provider),
  13467. content_type, progress);
  13468. }
  13469. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  13470. ContentProvider content_provider,
  13471. const std::string &content_type,
  13472. ContentReceiver content_receiver,
  13473. UploadProgress progress) {
  13474. return Post(path, Headers(), content_length, std::move(content_provider),
  13475. content_type, std::move(content_receiver), progress);
  13476. }
  13477. inline Result ClientImpl::Post(const std::string &path,
  13478. ContentProviderWithoutLength content_provider,
  13479. const std::string &content_type,
  13480. UploadProgress progress) {
  13481. return Post(path, Headers(), std::move(content_provider), content_type,
  13482. progress);
  13483. }
  13484. inline Result ClientImpl::Post(const std::string &path,
  13485. ContentProviderWithoutLength content_provider,
  13486. const std::string &content_type,
  13487. ContentReceiver content_receiver,
  13488. UploadProgress progress) {
  13489. return Post(path, Headers(), std::move(content_provider), content_type,
  13490. std::move(content_receiver), progress);
  13491. }
  13492. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13493. const Params &params) {
  13494. auto query = detail::params_to_query_str(params);
  13495. return Post(path, headers, query, "application/x-www-form-urlencoded");
  13496. }
  13497. inline Result ClientImpl::Post(const std::string &path,
  13498. const UploadFormDataItems &items,
  13499. UploadProgress progress) {
  13500. return Post(path, Headers(), items, progress);
  13501. }
  13502. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13503. const UploadFormDataItems &items,
  13504. UploadProgress progress) {
  13505. const auto &boundary = detail::make_multipart_data_boundary();
  13506. const auto &content_type =
  13507. detail::serialize_multipart_formdata_get_content_type(boundary);
  13508. auto content_length = detail::get_multipart_content_length(items, boundary);
  13509. return Post(path, headers, content_length,
  13510. detail::make_multipart_content_provider(items, boundary),
  13511. content_type, progress);
  13512. }
  13513. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13514. const UploadFormDataItems &items,
  13515. const std::string &boundary,
  13516. UploadProgress progress) {
  13517. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  13518. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  13519. }
  13520. const auto &content_type =
  13521. detail::serialize_multipart_formdata_get_content_type(boundary);
  13522. auto content_length = detail::get_multipart_content_length(items, boundary);
  13523. return Post(path, headers, content_length,
  13524. detail::make_multipart_content_provider(items, boundary),
  13525. content_type, progress);
  13526. }
  13527. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13528. const char *body, size_t content_length,
  13529. const std::string &content_type,
  13530. UploadProgress progress) {
  13531. return send_with_content_provider_and_receiver(
  13532. "POST", path, headers, body, content_length, nullptr, nullptr,
  13533. content_type, nullptr, progress);
  13534. }
  13535. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13536. const std::string &body,
  13537. const std::string &content_type,
  13538. UploadProgress progress) {
  13539. return send_with_content_provider_and_receiver(
  13540. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  13541. content_type, nullptr, progress);
  13542. }
  13543. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13544. size_t content_length,
  13545. ContentProvider content_provider,
  13546. const std::string &content_type,
  13547. UploadProgress progress) {
  13548. return send_with_content_provider_and_receiver(
  13549. "POST", path, headers, nullptr, content_length,
  13550. std::move(content_provider), nullptr, content_type, nullptr, progress);
  13551. }
  13552. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13553. size_t content_length,
  13554. ContentProvider content_provider,
  13555. const std::string &content_type,
  13556. ContentReceiver content_receiver,
  13557. DownloadProgress progress) {
  13558. return send_with_content_provider_and_receiver(
  13559. "POST", path, headers, nullptr, content_length,
  13560. std::move(content_provider), nullptr, content_type,
  13561. std::move(content_receiver), std::move(progress));
  13562. }
  13563. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13564. ContentProviderWithoutLength content_provider,
  13565. const std::string &content_type,
  13566. UploadProgress progress) {
  13567. return send_with_content_provider_and_receiver(
  13568. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  13569. content_type, nullptr, progress);
  13570. }
  13571. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13572. ContentProviderWithoutLength content_provider,
  13573. const std::string &content_type,
  13574. ContentReceiver content_receiver,
  13575. DownloadProgress progress) {
  13576. return send_with_content_provider_and_receiver(
  13577. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  13578. content_type, std::move(content_receiver), std::move(progress));
  13579. }
  13580. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13581. const UploadFormDataItems &items,
  13582. const FormDataProviderItems &provider_items,
  13583. UploadProgress progress) {
  13584. const auto &boundary = detail::make_multipart_data_boundary();
  13585. const auto &content_type =
  13586. detail::serialize_multipart_formdata_get_content_type(boundary);
  13587. return send_with_content_provider_and_receiver(
  13588. "POST", path, headers, nullptr, 0, nullptr,
  13589. get_multipart_content_provider(boundary, items, provider_items),
  13590. content_type, nullptr, progress);
  13591. }
  13592. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13593. const std::string &body,
  13594. const std::string &content_type,
  13595. ContentReceiver content_receiver,
  13596. DownloadProgress progress) {
  13597. Request req;
  13598. req.method = "POST";
  13599. req.path = path;
  13600. req.headers = headers;
  13601. req.body = body;
  13602. req.content_receiver =
  13603. [content_receiver](const char *data, size_t data_length,
  13604. size_t /*offset*/, size_t /*total_length*/) {
  13605. return content_receiver(data, data_length);
  13606. };
  13607. req.download_progress = std::move(progress);
  13608. if (max_timeout_msec_ > 0) {
  13609. req.start_time_ = std::chrono::steady_clock::now();
  13610. }
  13611. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  13612. return send_(std::move(req));
  13613. }
  13614. inline Result ClientImpl::Put(const std::string &path) {
  13615. return Put(path, std::string(), std::string());
  13616. }
  13617. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  13618. return Put(path, headers, nullptr, 0, std::string());
  13619. }
  13620. inline Result ClientImpl::Put(const std::string &path, const char *body,
  13621. size_t content_length,
  13622. const std::string &content_type,
  13623. UploadProgress progress) {
  13624. return Put(path, Headers(), body, content_length, content_type, progress);
  13625. }
  13626. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  13627. const std::string &content_type,
  13628. UploadProgress progress) {
  13629. return Put(path, Headers(), body, content_type, progress);
  13630. }
  13631. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  13632. return Put(path, Headers(), params);
  13633. }
  13634. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  13635. ContentProvider content_provider,
  13636. const std::string &content_type,
  13637. UploadProgress progress) {
  13638. return Put(path, Headers(), content_length, std::move(content_provider),
  13639. content_type, progress);
  13640. }
  13641. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  13642. ContentProvider content_provider,
  13643. const std::string &content_type,
  13644. ContentReceiver content_receiver,
  13645. UploadProgress progress) {
  13646. return Put(path, Headers(), content_length, std::move(content_provider),
  13647. content_type, std::move(content_receiver), progress);
  13648. }
  13649. inline Result ClientImpl::Put(const std::string &path,
  13650. ContentProviderWithoutLength content_provider,
  13651. const std::string &content_type,
  13652. UploadProgress progress) {
  13653. return Put(path, Headers(), std::move(content_provider), content_type,
  13654. progress);
  13655. }
  13656. inline Result ClientImpl::Put(const std::string &path,
  13657. ContentProviderWithoutLength content_provider,
  13658. const std::string &content_type,
  13659. ContentReceiver content_receiver,
  13660. UploadProgress progress) {
  13661. return Put(path, Headers(), std::move(content_provider), content_type,
  13662. std::move(content_receiver), progress);
  13663. }
  13664. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13665. const Params &params) {
  13666. auto query = detail::params_to_query_str(params);
  13667. return Put(path, headers, query, "application/x-www-form-urlencoded");
  13668. }
  13669. inline Result ClientImpl::Put(const std::string &path,
  13670. const UploadFormDataItems &items,
  13671. UploadProgress progress) {
  13672. return Put(path, Headers(), items, progress);
  13673. }
  13674. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13675. const UploadFormDataItems &items,
  13676. UploadProgress progress) {
  13677. const auto &boundary = detail::make_multipart_data_boundary();
  13678. const auto &content_type =
  13679. detail::serialize_multipart_formdata_get_content_type(boundary);
  13680. auto content_length = detail::get_multipart_content_length(items, boundary);
  13681. return Put(path, headers, content_length,
  13682. detail::make_multipart_content_provider(items, boundary),
  13683. content_type, progress);
  13684. }
  13685. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13686. const UploadFormDataItems &items,
  13687. const std::string &boundary,
  13688. UploadProgress progress) {
  13689. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  13690. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  13691. }
  13692. const auto &content_type =
  13693. detail::serialize_multipart_formdata_get_content_type(boundary);
  13694. auto content_length = detail::get_multipart_content_length(items, boundary);
  13695. return Put(path, headers, content_length,
  13696. detail::make_multipart_content_provider(items, boundary),
  13697. content_type, progress);
  13698. }
  13699. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13700. const char *body, size_t content_length,
  13701. const std::string &content_type,
  13702. UploadProgress progress) {
  13703. return send_with_content_provider_and_receiver(
  13704. "PUT", path, headers, body, content_length, nullptr, nullptr,
  13705. content_type, nullptr, progress);
  13706. }
  13707. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13708. const std::string &body,
  13709. const std::string &content_type,
  13710. UploadProgress progress) {
  13711. return send_with_content_provider_and_receiver(
  13712. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  13713. content_type, nullptr, progress);
  13714. }
  13715. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13716. size_t content_length,
  13717. ContentProvider content_provider,
  13718. const std::string &content_type,
  13719. UploadProgress progress) {
  13720. return send_with_content_provider_and_receiver(
  13721. "PUT", path, headers, nullptr, content_length,
  13722. std::move(content_provider), nullptr, content_type, nullptr, progress);
  13723. }
  13724. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13725. size_t content_length,
  13726. ContentProvider content_provider,
  13727. const std::string &content_type,
  13728. ContentReceiver content_receiver,
  13729. UploadProgress progress) {
  13730. return send_with_content_provider_and_receiver(
  13731. "PUT", path, headers, nullptr, content_length,
  13732. std::move(content_provider), nullptr, content_type,
  13733. std::move(content_receiver), progress);
  13734. }
  13735. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13736. ContentProviderWithoutLength content_provider,
  13737. const std::string &content_type,
  13738. UploadProgress progress) {
  13739. return send_with_content_provider_and_receiver(
  13740. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  13741. content_type, nullptr, progress);
  13742. }
  13743. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13744. ContentProviderWithoutLength content_provider,
  13745. const std::string &content_type,
  13746. ContentReceiver content_receiver,
  13747. UploadProgress progress) {
  13748. return send_with_content_provider_and_receiver(
  13749. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  13750. content_type, std::move(content_receiver), progress);
  13751. }
  13752. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13753. const UploadFormDataItems &items,
  13754. const FormDataProviderItems &provider_items,
  13755. UploadProgress progress) {
  13756. const auto &boundary = detail::make_multipart_data_boundary();
  13757. const auto &content_type =
  13758. detail::serialize_multipart_formdata_get_content_type(boundary);
  13759. return send_with_content_provider_and_receiver(
  13760. "PUT", path, headers, nullptr, 0, nullptr,
  13761. get_multipart_content_provider(boundary, items, provider_items),
  13762. content_type, nullptr, progress);
  13763. }
  13764. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  13765. const std::string &body,
  13766. const std::string &content_type,
  13767. ContentReceiver content_receiver,
  13768. DownloadProgress progress) {
  13769. Request req;
  13770. req.method = "PUT";
  13771. req.path = path;
  13772. req.headers = headers;
  13773. req.body = body;
  13774. req.content_receiver =
  13775. [content_receiver](const char *data, size_t data_length,
  13776. size_t /*offset*/, size_t /*total_length*/) {
  13777. return content_receiver(data, data_length);
  13778. };
  13779. req.download_progress = std::move(progress);
  13780. if (max_timeout_msec_ > 0) {
  13781. req.start_time_ = std::chrono::steady_clock::now();
  13782. }
  13783. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  13784. return send_(std::move(req));
  13785. }
  13786. inline Result ClientImpl::Patch(const std::string &path) {
  13787. return Patch(path, std::string(), std::string());
  13788. }
  13789. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13790. UploadProgress progress) {
  13791. return Patch(path, headers, nullptr, 0, std::string(), progress);
  13792. }
  13793. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  13794. size_t content_length,
  13795. const std::string &content_type,
  13796. UploadProgress progress) {
  13797. return Patch(path, Headers(), body, content_length, content_type, progress);
  13798. }
  13799. inline Result ClientImpl::Patch(const std::string &path,
  13800. const std::string &body,
  13801. const std::string &content_type,
  13802. UploadProgress progress) {
  13803. return Patch(path, Headers(), body, content_type, progress);
  13804. }
  13805. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  13806. return Patch(path, Headers(), params);
  13807. }
  13808. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  13809. ContentProvider content_provider,
  13810. const std::string &content_type,
  13811. UploadProgress progress) {
  13812. return Patch(path, Headers(), content_length, std::move(content_provider),
  13813. content_type, progress);
  13814. }
  13815. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  13816. ContentProvider content_provider,
  13817. const std::string &content_type,
  13818. ContentReceiver content_receiver,
  13819. UploadProgress progress) {
  13820. return Patch(path, Headers(), content_length, std::move(content_provider),
  13821. content_type, std::move(content_receiver), progress);
  13822. }
  13823. inline Result ClientImpl::Patch(const std::string &path,
  13824. ContentProviderWithoutLength content_provider,
  13825. const std::string &content_type,
  13826. UploadProgress progress) {
  13827. return Patch(path, Headers(), std::move(content_provider), content_type,
  13828. progress);
  13829. }
  13830. inline Result ClientImpl::Patch(const std::string &path,
  13831. ContentProviderWithoutLength content_provider,
  13832. const std::string &content_type,
  13833. ContentReceiver content_receiver,
  13834. UploadProgress progress) {
  13835. return Patch(path, Headers(), std::move(content_provider), content_type,
  13836. std::move(content_receiver), progress);
  13837. }
  13838. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13839. const Params &params) {
  13840. auto query = detail::params_to_query_str(params);
  13841. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  13842. }
  13843. inline Result ClientImpl::Patch(const std::string &path,
  13844. const UploadFormDataItems &items,
  13845. UploadProgress progress) {
  13846. return Patch(path, Headers(), items, progress);
  13847. }
  13848. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13849. const UploadFormDataItems &items,
  13850. UploadProgress progress) {
  13851. const auto &boundary = detail::make_multipart_data_boundary();
  13852. const auto &content_type =
  13853. detail::serialize_multipart_formdata_get_content_type(boundary);
  13854. auto content_length = detail::get_multipart_content_length(items, boundary);
  13855. return Patch(path, headers, content_length,
  13856. detail::make_multipart_content_provider(items, boundary),
  13857. content_type, progress);
  13858. }
  13859. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13860. const UploadFormDataItems &items,
  13861. const std::string &boundary,
  13862. UploadProgress progress) {
  13863. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  13864. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  13865. }
  13866. const auto &content_type =
  13867. detail::serialize_multipart_formdata_get_content_type(boundary);
  13868. auto content_length = detail::get_multipart_content_length(items, boundary);
  13869. return Patch(path, headers, content_length,
  13870. detail::make_multipart_content_provider(items, boundary),
  13871. content_type, progress);
  13872. }
  13873. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13874. const char *body, size_t content_length,
  13875. const std::string &content_type,
  13876. UploadProgress progress) {
  13877. return send_with_content_provider_and_receiver(
  13878. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  13879. content_type, nullptr, progress);
  13880. }
  13881. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13882. const std::string &body,
  13883. const std::string &content_type,
  13884. UploadProgress progress) {
  13885. return send_with_content_provider_and_receiver(
  13886. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  13887. content_type, nullptr, progress);
  13888. }
  13889. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13890. size_t content_length,
  13891. ContentProvider content_provider,
  13892. const std::string &content_type,
  13893. UploadProgress progress) {
  13894. return send_with_content_provider_and_receiver(
  13895. "PATCH", path, headers, nullptr, content_length,
  13896. std::move(content_provider), nullptr, content_type, nullptr, progress);
  13897. }
  13898. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13899. size_t content_length,
  13900. ContentProvider content_provider,
  13901. const std::string &content_type,
  13902. ContentReceiver content_receiver,
  13903. UploadProgress progress) {
  13904. return send_with_content_provider_and_receiver(
  13905. "PATCH", path, headers, nullptr, content_length,
  13906. std::move(content_provider), nullptr, content_type,
  13907. std::move(content_receiver), progress);
  13908. }
  13909. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13910. ContentProviderWithoutLength content_provider,
  13911. const std::string &content_type,
  13912. UploadProgress progress) {
  13913. return send_with_content_provider_and_receiver(
  13914. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  13915. content_type, nullptr, progress);
  13916. }
  13917. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13918. ContentProviderWithoutLength content_provider,
  13919. const std::string &content_type,
  13920. ContentReceiver content_receiver,
  13921. UploadProgress progress) {
  13922. return send_with_content_provider_and_receiver(
  13923. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  13924. content_type, std::move(content_receiver), progress);
  13925. }
  13926. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13927. const UploadFormDataItems &items,
  13928. const FormDataProviderItems &provider_items,
  13929. UploadProgress progress) {
  13930. const auto &boundary = detail::make_multipart_data_boundary();
  13931. const auto &content_type =
  13932. detail::serialize_multipart_formdata_get_content_type(boundary);
  13933. return send_with_content_provider_and_receiver(
  13934. "PATCH", path, headers, nullptr, 0, nullptr,
  13935. get_multipart_content_provider(boundary, items, provider_items),
  13936. content_type, nullptr, progress);
  13937. }
  13938. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  13939. const std::string &body,
  13940. const std::string &content_type,
  13941. ContentReceiver content_receiver,
  13942. DownloadProgress progress) {
  13943. Request req;
  13944. req.method = "PATCH";
  13945. req.path = path;
  13946. req.headers = headers;
  13947. req.body = body;
  13948. req.content_receiver =
  13949. [content_receiver](const char *data, size_t data_length,
  13950. size_t /*offset*/, size_t /*total_length*/) {
  13951. return content_receiver(data, data_length);
  13952. };
  13953. req.download_progress = std::move(progress);
  13954. if (max_timeout_msec_ > 0) {
  13955. req.start_time_ = std::chrono::steady_clock::now();
  13956. }
  13957. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  13958. return send_(std::move(req));
  13959. }
  13960. inline Result ClientImpl::Delete(const std::string &path,
  13961. DownloadProgress progress) {
  13962. return Delete(path, Headers(), std::string(), std::string(), progress);
  13963. }
  13964. inline Result ClientImpl::Delete(const std::string &path,
  13965. const Headers &headers,
  13966. DownloadProgress progress) {
  13967. return Delete(path, headers, std::string(), std::string(), progress);
  13968. }
  13969. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  13970. size_t content_length,
  13971. const std::string &content_type,
  13972. DownloadProgress progress) {
  13973. return Delete(path, Headers(), body, content_length, content_type, progress);
  13974. }
  13975. inline Result ClientImpl::Delete(const std::string &path,
  13976. const std::string &body,
  13977. const std::string &content_type,
  13978. DownloadProgress progress) {
  13979. return Delete(path, Headers(), body.data(), body.size(), content_type,
  13980. progress);
  13981. }
  13982. inline Result ClientImpl::Delete(const std::string &path,
  13983. const Headers &headers,
  13984. const std::string &body,
  13985. const std::string &content_type,
  13986. DownloadProgress progress) {
  13987. return Delete(path, headers, body.data(), body.size(), content_type,
  13988. progress);
  13989. }
  13990. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  13991. DownloadProgress progress) {
  13992. return Delete(path, Headers(), params, progress);
  13993. }
  13994. inline Result ClientImpl::Delete(const std::string &path,
  13995. const Headers &headers, const Params &params,
  13996. DownloadProgress progress) {
  13997. auto query = detail::params_to_query_str(params);
  13998. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  13999. progress);
  14000. }
  14001. inline Result ClientImpl::Delete(const std::string &path,
  14002. const Headers &headers, const char *body,
  14003. size_t content_length,
  14004. const std::string &content_type,
  14005. DownloadProgress progress) {
  14006. Request req;
  14007. req.method = "DELETE";
  14008. req.headers = headers;
  14009. req.path = path;
  14010. req.download_progress = std::move(progress);
  14011. if (max_timeout_msec_ > 0) {
  14012. req.start_time_ = std::chrono::steady_clock::now();
  14013. }
  14014. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14015. req.body.assign(body, content_length);
  14016. return send_(std::move(req));
  14017. }
  14018. inline Result ClientImpl::Options(const std::string &path) {
  14019. return Options(path, Headers());
  14020. }
  14021. inline Result ClientImpl::Options(const std::string &path,
  14022. const Headers &headers) {
  14023. Request req;
  14024. req.method = "OPTIONS";
  14025. req.headers = headers;
  14026. req.path = path;
  14027. if (max_timeout_msec_ > 0) {
  14028. req.start_time_ = std::chrono::steady_clock::now();
  14029. }
  14030. return send_(std::move(req));
  14031. }
  14032. inline void ClientImpl::stop() {
  14033. std::lock_guard<std::mutex> guard(socket_mutex_);
  14034. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  14035. // do is to shutdown_socket, so that threads using this socket suddenly
  14036. // discover they can't read/write any more and error out. Everything else
  14037. // (closing the socket, shutting ssl down) is unsafe because these actions
  14038. // are not thread-safe.
  14039. if (socket_requests_in_flight_ > 0) {
  14040. shutdown_socket(socket_);
  14041. // Aside from that, we set a flag for the socket to be closed when we're
  14042. // done.
  14043. socket_should_be_closed_when_request_is_done_ = true;
  14044. return;
  14045. }
  14046. disconnect(/*gracefully=*/true);
  14047. }
  14048. inline std::string ClientImpl::host() const { return host_; }
  14049. inline int ClientImpl::port() const { return port_; }
  14050. inline size_t ClientImpl::is_socket_open() const {
  14051. std::lock_guard<std::mutex> guard(socket_mutex_);
  14052. return socket_.is_open();
  14053. }
  14054. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  14055. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  14056. connection_timeout_sec_ = sec;
  14057. connection_timeout_usec_ = usec;
  14058. }
  14059. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  14060. read_timeout_sec_ = sec;
  14061. read_timeout_usec_ = usec;
  14062. }
  14063. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  14064. write_timeout_sec_ = sec;
  14065. write_timeout_usec_ = usec;
  14066. }
  14067. inline void ClientImpl::set_max_timeout(time_t msec) {
  14068. max_timeout_msec_ = msec;
  14069. }
  14070. inline void ClientImpl::set_basic_auth(const std::string &username,
  14071. const std::string &password) {
  14072. basic_auth_username_ = username;
  14073. basic_auth_password_ = password;
  14074. }
  14075. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  14076. bearer_token_auth_token_ = token;
  14077. }
  14078. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  14079. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  14080. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  14081. inline void
  14082. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14083. addr_map_ = std::move(addr_map);
  14084. }
  14085. inline void ClientImpl::set_default_headers(Headers headers) {
  14086. default_headers_ = std::move(headers);
  14087. }
  14088. inline void ClientImpl::set_header_writer(
  14089. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14090. header_writer_ = writer;
  14091. }
  14092. inline void ClientImpl::set_address_family(int family) {
  14093. address_family_ = family;
  14094. }
  14095. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  14096. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  14097. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  14098. socket_options_ = std::move(socket_options);
  14099. }
  14100. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  14101. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  14102. inline void ClientImpl::set_payload_max_length(size_t length) {
  14103. payload_max_length_ = length;
  14104. has_payload_max_length_ = true;
  14105. }
  14106. inline void ClientImpl::set_interface(const std::string &intf) {
  14107. interface_ = intf;
  14108. }
  14109. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  14110. proxy_host_ = host;
  14111. proxy_port_ = port;
  14112. std::lock_guard<std::mutex> guard(socket_mutex_);
  14113. disconnect(/*gracefully=*/true);
  14114. }
  14115. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  14116. const std::string &password) {
  14117. proxy_basic_auth_username_ = username;
  14118. proxy_basic_auth_password_ = password;
  14119. }
  14120. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  14121. proxy_bearer_token_auth_token_ = token;
  14122. }
  14123. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  14124. std::vector<detail::NoProxyEntry> parsed;
  14125. parsed.reserve(patterns.size());
  14126. for (const auto &p : patterns) {
  14127. auto trimmed = detail::trim_copy(p);
  14128. if (trimmed.empty()) { continue; }
  14129. detail::NoProxyEntry entry;
  14130. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  14131. parsed.push_back(std::move(entry));
  14132. }
  14133. }
  14134. no_proxy_entries_ = std::move(parsed);
  14135. std::lock_guard<std::mutex> guard(socket_mutex_);
  14136. disconnect(/*gracefully=*/true);
  14137. }
  14138. #ifdef CPPHTTPLIB_SSL_ENABLED
  14139. inline void ClientImpl::set_digest_auth(const std::string &username,
  14140. const std::string &password) {
  14141. digest_auth_username_ = username;
  14142. digest_auth_password_ = password;
  14143. }
  14144. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  14145. const std::string &ca_cert_dir_path) {
  14146. ca_cert_file_path_ = ca_cert_file_path;
  14147. ca_cert_dir_path_ = ca_cert_dir_path;
  14148. }
  14149. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  14150. const std::string &password) {
  14151. proxy_digest_auth_username_ = username;
  14152. proxy_digest_auth_password_ = password;
  14153. }
  14154. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  14155. server_certificate_verification_ = enabled;
  14156. }
  14157. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  14158. server_hostname_verification_ = enabled;
  14159. }
  14160. inline void ClientImpl::enable_system_ca(bool enabled) {
  14161. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  14162. }
  14163. #endif
  14164. inline void ClientImpl::set_logger(Logger logger) {
  14165. logger_ = std::move(logger);
  14166. }
  14167. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  14168. error_logger_ = std::move(error_logger);
  14169. }
  14170. /*
  14171. * SSL/TLS Common Implementation
  14172. */
  14173. inline ClientConnection::~ClientConnection() {
  14174. #ifdef CPPHTTPLIB_SSL_ENABLED
  14175. if (session) {
  14176. tls::shutdown(session, true);
  14177. tls::free_session(session);
  14178. session = nullptr;
  14179. }
  14180. #endif
  14181. if (sock != INVALID_SOCKET) {
  14182. detail::close_socket(sock);
  14183. sock = INVALID_SOCKET;
  14184. }
  14185. }
  14186. // Universal client implementation
  14187. inline Client::Client(const std::string &scheme_host_port)
  14188. : Client(scheme_host_port, std::string(), std::string()) {}
  14189. inline Client::Client(const std::string &scheme_host_port,
  14190. const std::string &client_cert_path,
  14191. const std::string &client_key_path) {
  14192. detail::UrlComponents uc;
  14193. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  14194. auto &scheme = uc.scheme;
  14195. #ifdef CPPHTTPLIB_SSL_ENABLED
  14196. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  14197. #else
  14198. if (!scheme.empty() && scheme != "http") {
  14199. #endif
  14200. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14201. std::string msg = "'" + scheme + "' scheme is not supported.";
  14202. throw std::invalid_argument(msg);
  14203. #endif
  14204. return;
  14205. }
  14206. auto is_ssl = scheme == "https";
  14207. auto host = std::move(uc.host);
  14208. auto port = is_ssl ? 443 : 80;
  14209. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  14210. if (is_ssl) {
  14211. #ifdef CPPHTTPLIB_SSL_ENABLED
  14212. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  14213. client_key_path);
  14214. is_ssl_ = is_ssl;
  14215. #endif
  14216. } else {
  14217. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  14218. client_key_path);
  14219. }
  14220. } else {
  14221. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  14222. // if port param below changes.
  14223. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  14224. client_cert_path, client_key_path);
  14225. }
  14226. }
  14227. inline Client::Client(const std::string &host, int port)
  14228. : Client(host, port, std::string(), std::string()) {}
  14229. inline Client::Client(const std::string &host, int port,
  14230. const std::string &client_cert_path,
  14231. const std::string &client_key_path)
  14232. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  14233. client_key_path)) {}
  14234. inline Client::~Client() = default;
  14235. inline bool Client::is_valid() const {
  14236. return cli_ != nullptr && cli_->is_valid();
  14237. }
  14238. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  14239. return cli_->Get(path, std::move(progress));
  14240. }
  14241. inline Result Client::Get(const std::string &path, const Headers &headers,
  14242. DownloadProgress progress) {
  14243. return cli_->Get(path, headers, std::move(progress));
  14244. }
  14245. inline Result Client::Get(const std::string &path,
  14246. ContentReceiver content_receiver,
  14247. DownloadProgress progress) {
  14248. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  14249. }
  14250. inline Result Client::Get(const std::string &path, const Headers &headers,
  14251. ContentReceiver content_receiver,
  14252. DownloadProgress progress) {
  14253. return cli_->Get(path, headers, std::move(content_receiver),
  14254. std::move(progress));
  14255. }
  14256. inline Result Client::Get(const std::string &path,
  14257. ResponseHandler response_handler,
  14258. ContentReceiver content_receiver,
  14259. DownloadProgress progress) {
  14260. return cli_->Get(path, std::move(response_handler),
  14261. std::move(content_receiver), std::move(progress));
  14262. }
  14263. inline Result Client::Get(const std::string &path, const Headers &headers,
  14264. ResponseHandler response_handler,
  14265. ContentReceiver content_receiver,
  14266. DownloadProgress progress) {
  14267. return cli_->Get(path, headers, std::move(response_handler),
  14268. std::move(content_receiver), std::move(progress));
  14269. }
  14270. inline Result Client::Get(const std::string &path, const Params &params,
  14271. DownloadProgress progress) {
  14272. return cli_->Get(path, params, std::move(progress));
  14273. }
  14274. inline Result Client::Get(const std::string &path, const Params &params,
  14275. const Headers &headers, DownloadProgress progress) {
  14276. return cli_->Get(path, params, headers, std::move(progress));
  14277. }
  14278. inline Result Client::Get(const std::string &path, const Params &params,
  14279. const Headers &headers,
  14280. ContentReceiver content_receiver,
  14281. DownloadProgress progress) {
  14282. return cli_->Get(path, params, headers, std::move(content_receiver),
  14283. std::move(progress));
  14284. }
  14285. inline Result Client::Get(const std::string &path, const Params &params,
  14286. const Headers &headers,
  14287. ResponseHandler response_handler,
  14288. ContentReceiver content_receiver,
  14289. DownloadProgress progress) {
  14290. return cli_->Get(path, params, headers, std::move(response_handler),
  14291. std::move(content_receiver), std::move(progress));
  14292. }
  14293. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  14294. inline Result Client::Head(const std::string &path, const Headers &headers) {
  14295. return cli_->Head(path, headers);
  14296. }
  14297. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  14298. inline Result Client::Post(const std::string &path, const Headers &headers) {
  14299. return cli_->Post(path, headers);
  14300. }
  14301. inline Result Client::Post(const std::string &path, const char *body,
  14302. size_t content_length,
  14303. const std::string &content_type,
  14304. UploadProgress progress) {
  14305. return cli_->Post(path, body, content_length, content_type, progress);
  14306. }
  14307. inline Result Client::Post(const std::string &path, const Headers &headers,
  14308. const char *body, size_t content_length,
  14309. const std::string &content_type,
  14310. UploadProgress progress) {
  14311. return cli_->Post(path, headers, body, content_length, content_type,
  14312. progress);
  14313. }
  14314. inline Result Client::Post(const std::string &path, const std::string &body,
  14315. const std::string &content_type,
  14316. UploadProgress progress) {
  14317. return cli_->Post(path, body, content_type, progress);
  14318. }
  14319. inline Result Client::Post(const std::string &path, const Headers &headers,
  14320. const std::string &body,
  14321. const std::string &content_type,
  14322. UploadProgress progress) {
  14323. return cli_->Post(path, headers, body, content_type, progress);
  14324. }
  14325. inline Result Client::Post(const std::string &path, size_t content_length,
  14326. ContentProvider content_provider,
  14327. const std::string &content_type,
  14328. UploadProgress progress) {
  14329. return cli_->Post(path, content_length, std::move(content_provider),
  14330. content_type, progress);
  14331. }
  14332. inline Result Client::Post(const std::string &path, size_t content_length,
  14333. ContentProvider content_provider,
  14334. const std::string &content_type,
  14335. ContentReceiver content_receiver,
  14336. UploadProgress progress) {
  14337. return cli_->Post(path, content_length, std::move(content_provider),
  14338. content_type, std::move(content_receiver), progress);
  14339. }
  14340. inline Result Client::Post(const std::string &path,
  14341. ContentProviderWithoutLength content_provider,
  14342. const std::string &content_type,
  14343. UploadProgress progress) {
  14344. return cli_->Post(path, std::move(content_provider), content_type, progress);
  14345. }
  14346. inline Result Client::Post(const std::string &path,
  14347. ContentProviderWithoutLength content_provider,
  14348. const std::string &content_type,
  14349. ContentReceiver content_receiver,
  14350. UploadProgress progress) {
  14351. return cli_->Post(path, std::move(content_provider), content_type,
  14352. std::move(content_receiver), progress);
  14353. }
  14354. inline Result Client::Post(const std::string &path, const Headers &headers,
  14355. size_t content_length,
  14356. ContentProvider content_provider,
  14357. const std::string &content_type,
  14358. UploadProgress progress) {
  14359. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14360. content_type, progress);
  14361. }
  14362. inline Result Client::Post(const std::string &path, const Headers &headers,
  14363. size_t content_length,
  14364. ContentProvider content_provider,
  14365. const std::string &content_type,
  14366. ContentReceiver content_receiver,
  14367. DownloadProgress progress) {
  14368. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14369. content_type, std::move(content_receiver), progress);
  14370. }
  14371. inline Result Client::Post(const std::string &path, const Headers &headers,
  14372. ContentProviderWithoutLength content_provider,
  14373. const std::string &content_type,
  14374. UploadProgress progress) {
  14375. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14376. progress);
  14377. }
  14378. inline Result Client::Post(const std::string &path, const Headers &headers,
  14379. ContentProviderWithoutLength content_provider,
  14380. const std::string &content_type,
  14381. ContentReceiver content_receiver,
  14382. DownloadProgress progress) {
  14383. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14384. std::move(content_receiver), progress);
  14385. }
  14386. inline Result Client::Post(const std::string &path, const Params &params) {
  14387. return cli_->Post(path, params);
  14388. }
  14389. inline Result Client::Post(const std::string &path, const Headers &headers,
  14390. const Params &params) {
  14391. return cli_->Post(path, headers, params);
  14392. }
  14393. inline Result Client::Post(const std::string &path,
  14394. const UploadFormDataItems &items,
  14395. UploadProgress progress) {
  14396. return cli_->Post(path, items, progress);
  14397. }
  14398. inline Result Client::Post(const std::string &path, const Headers &headers,
  14399. const UploadFormDataItems &items,
  14400. UploadProgress progress) {
  14401. return cli_->Post(path, headers, items, progress);
  14402. }
  14403. inline Result Client::Post(const std::string &path, const Headers &headers,
  14404. const UploadFormDataItems &items,
  14405. const std::string &boundary,
  14406. UploadProgress progress) {
  14407. return cli_->Post(path, headers, items, boundary, progress);
  14408. }
  14409. inline Result Client::Post(const std::string &path, const Headers &headers,
  14410. const UploadFormDataItems &items,
  14411. const FormDataProviderItems &provider_items,
  14412. UploadProgress progress) {
  14413. return cli_->Post(path, headers, items, provider_items, progress);
  14414. }
  14415. inline Result Client::Post(const std::string &path, const Headers &headers,
  14416. const std::string &body,
  14417. const std::string &content_type,
  14418. ContentReceiver content_receiver,
  14419. DownloadProgress progress) {
  14420. return cli_->Post(path, headers, body, content_type,
  14421. std::move(content_receiver), progress);
  14422. }
  14423. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  14424. inline Result Client::Put(const std::string &path, const Headers &headers) {
  14425. return cli_->Put(path, headers);
  14426. }
  14427. inline Result Client::Put(const std::string &path, const char *body,
  14428. size_t content_length,
  14429. const std::string &content_type,
  14430. UploadProgress progress) {
  14431. return cli_->Put(path, body, content_length, content_type, progress);
  14432. }
  14433. inline Result Client::Put(const std::string &path, const Headers &headers,
  14434. const char *body, size_t content_length,
  14435. const std::string &content_type,
  14436. UploadProgress progress) {
  14437. return cli_->Put(path, headers, body, content_length, content_type, progress);
  14438. }
  14439. inline Result Client::Put(const std::string &path, const std::string &body,
  14440. const std::string &content_type,
  14441. UploadProgress progress) {
  14442. return cli_->Put(path, body, content_type, progress);
  14443. }
  14444. inline Result Client::Put(const std::string &path, const Headers &headers,
  14445. const std::string &body,
  14446. const std::string &content_type,
  14447. UploadProgress progress) {
  14448. return cli_->Put(path, headers, body, content_type, progress);
  14449. }
  14450. inline Result Client::Put(const std::string &path, size_t content_length,
  14451. ContentProvider content_provider,
  14452. const std::string &content_type,
  14453. UploadProgress progress) {
  14454. return cli_->Put(path, content_length, std::move(content_provider),
  14455. content_type, progress);
  14456. }
  14457. inline Result Client::Put(const std::string &path, size_t content_length,
  14458. ContentProvider content_provider,
  14459. const std::string &content_type,
  14460. ContentReceiver content_receiver,
  14461. UploadProgress progress) {
  14462. return cli_->Put(path, content_length, std::move(content_provider),
  14463. content_type, std::move(content_receiver), progress);
  14464. }
  14465. inline Result Client::Put(const std::string &path,
  14466. ContentProviderWithoutLength content_provider,
  14467. const std::string &content_type,
  14468. UploadProgress progress) {
  14469. return cli_->Put(path, std::move(content_provider), content_type, progress);
  14470. }
  14471. inline Result Client::Put(const std::string &path,
  14472. ContentProviderWithoutLength content_provider,
  14473. const std::string &content_type,
  14474. ContentReceiver content_receiver,
  14475. UploadProgress progress) {
  14476. return cli_->Put(path, std::move(content_provider), content_type,
  14477. std::move(content_receiver), progress);
  14478. }
  14479. inline Result Client::Put(const std::string &path, const Headers &headers,
  14480. size_t content_length,
  14481. ContentProvider content_provider,
  14482. const std::string &content_type,
  14483. UploadProgress progress) {
  14484. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14485. content_type, progress);
  14486. }
  14487. inline Result Client::Put(const std::string &path, const Headers &headers,
  14488. size_t content_length,
  14489. ContentProvider content_provider,
  14490. const std::string &content_type,
  14491. ContentReceiver content_receiver,
  14492. UploadProgress progress) {
  14493. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14494. content_type, std::move(content_receiver), progress);
  14495. }
  14496. inline Result Client::Put(const std::string &path, const Headers &headers,
  14497. ContentProviderWithoutLength content_provider,
  14498. const std::string &content_type,
  14499. UploadProgress progress) {
  14500. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14501. progress);
  14502. }
  14503. inline Result Client::Put(const std::string &path, const Headers &headers,
  14504. ContentProviderWithoutLength content_provider,
  14505. const std::string &content_type,
  14506. ContentReceiver content_receiver,
  14507. UploadProgress progress) {
  14508. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14509. std::move(content_receiver), progress);
  14510. }
  14511. inline Result Client::Put(const std::string &path, const Params &params) {
  14512. return cli_->Put(path, params);
  14513. }
  14514. inline Result Client::Put(const std::string &path, const Headers &headers,
  14515. const Params &params) {
  14516. return cli_->Put(path, headers, params);
  14517. }
  14518. inline Result Client::Put(const std::string &path,
  14519. const UploadFormDataItems &items,
  14520. UploadProgress progress) {
  14521. return cli_->Put(path, items, progress);
  14522. }
  14523. inline Result Client::Put(const std::string &path, const Headers &headers,
  14524. const UploadFormDataItems &items,
  14525. UploadProgress progress) {
  14526. return cli_->Put(path, headers, items, progress);
  14527. }
  14528. inline Result Client::Put(const std::string &path, const Headers &headers,
  14529. const UploadFormDataItems &items,
  14530. const std::string &boundary,
  14531. UploadProgress progress) {
  14532. return cli_->Put(path, headers, items, boundary, progress);
  14533. }
  14534. inline Result Client::Put(const std::string &path, const Headers &headers,
  14535. const UploadFormDataItems &items,
  14536. const FormDataProviderItems &provider_items,
  14537. UploadProgress progress) {
  14538. return cli_->Put(path, headers, items, provider_items, progress);
  14539. }
  14540. inline Result Client::Put(const std::string &path, const Headers &headers,
  14541. const std::string &body,
  14542. const std::string &content_type,
  14543. ContentReceiver content_receiver,
  14544. DownloadProgress progress) {
  14545. return cli_->Put(path, headers, body, content_type, content_receiver,
  14546. progress);
  14547. }
  14548. inline Result Client::Patch(const std::string &path) {
  14549. return cli_->Patch(path);
  14550. }
  14551. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  14552. return cli_->Patch(path, headers);
  14553. }
  14554. inline Result Client::Patch(const std::string &path, const char *body,
  14555. size_t content_length,
  14556. const std::string &content_type,
  14557. UploadProgress progress) {
  14558. return cli_->Patch(path, body, content_length, content_type, progress);
  14559. }
  14560. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14561. const char *body, size_t content_length,
  14562. const std::string &content_type,
  14563. UploadProgress progress) {
  14564. return cli_->Patch(path, headers, body, content_length, content_type,
  14565. progress);
  14566. }
  14567. inline Result Client::Patch(const std::string &path, const std::string &body,
  14568. const std::string &content_type,
  14569. UploadProgress progress) {
  14570. return cli_->Patch(path, body, content_type, progress);
  14571. }
  14572. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14573. const std::string &body,
  14574. const std::string &content_type,
  14575. UploadProgress progress) {
  14576. return cli_->Patch(path, headers, body, content_type, progress);
  14577. }
  14578. inline Result Client::Patch(const std::string &path, size_t content_length,
  14579. ContentProvider content_provider,
  14580. const std::string &content_type,
  14581. UploadProgress progress) {
  14582. return cli_->Patch(path, content_length, std::move(content_provider),
  14583. content_type, progress);
  14584. }
  14585. inline Result Client::Patch(const std::string &path, size_t content_length,
  14586. ContentProvider content_provider,
  14587. const std::string &content_type,
  14588. ContentReceiver content_receiver,
  14589. UploadProgress progress) {
  14590. return cli_->Patch(path, content_length, std::move(content_provider),
  14591. content_type, std::move(content_receiver), progress);
  14592. }
  14593. inline Result Client::Patch(const std::string &path,
  14594. ContentProviderWithoutLength content_provider,
  14595. const std::string &content_type,
  14596. UploadProgress progress) {
  14597. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  14598. }
  14599. inline Result Client::Patch(const std::string &path,
  14600. ContentProviderWithoutLength content_provider,
  14601. const std::string &content_type,
  14602. ContentReceiver content_receiver,
  14603. UploadProgress progress) {
  14604. return cli_->Patch(path, std::move(content_provider), content_type,
  14605. std::move(content_receiver), progress);
  14606. }
  14607. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14608. size_t content_length,
  14609. ContentProvider content_provider,
  14610. const std::string &content_type,
  14611. UploadProgress progress) {
  14612. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14613. content_type, progress);
  14614. }
  14615. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14616. size_t content_length,
  14617. ContentProvider content_provider,
  14618. const std::string &content_type,
  14619. ContentReceiver content_receiver,
  14620. UploadProgress progress) {
  14621. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14622. content_type, std::move(content_receiver), progress);
  14623. }
  14624. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14625. ContentProviderWithoutLength content_provider,
  14626. const std::string &content_type,
  14627. UploadProgress progress) {
  14628. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14629. progress);
  14630. }
  14631. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14632. ContentProviderWithoutLength content_provider,
  14633. const std::string &content_type,
  14634. ContentReceiver content_receiver,
  14635. UploadProgress progress) {
  14636. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14637. std::move(content_receiver), progress);
  14638. }
  14639. inline Result Client::Patch(const std::string &path, const Params &params) {
  14640. return cli_->Patch(path, params);
  14641. }
  14642. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14643. const Params &params) {
  14644. return cli_->Patch(path, headers, params);
  14645. }
  14646. inline Result Client::Patch(const std::string &path,
  14647. const UploadFormDataItems &items,
  14648. UploadProgress progress) {
  14649. return cli_->Patch(path, items, progress);
  14650. }
  14651. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14652. const UploadFormDataItems &items,
  14653. UploadProgress progress) {
  14654. return cli_->Patch(path, headers, items, progress);
  14655. }
  14656. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14657. const UploadFormDataItems &items,
  14658. const std::string &boundary,
  14659. UploadProgress progress) {
  14660. return cli_->Patch(path, headers, items, boundary, progress);
  14661. }
  14662. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14663. const UploadFormDataItems &items,
  14664. const FormDataProviderItems &provider_items,
  14665. UploadProgress progress) {
  14666. return cli_->Patch(path, headers, items, provider_items, progress);
  14667. }
  14668. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14669. const std::string &body,
  14670. const std::string &content_type,
  14671. ContentReceiver content_receiver,
  14672. DownloadProgress progress) {
  14673. return cli_->Patch(path, headers, body, content_type, content_receiver,
  14674. progress);
  14675. }
  14676. inline Result Client::Delete(const std::string &path,
  14677. DownloadProgress progress) {
  14678. return cli_->Delete(path, progress);
  14679. }
  14680. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14681. DownloadProgress progress) {
  14682. return cli_->Delete(path, headers, progress);
  14683. }
  14684. inline Result Client::Delete(const std::string &path, const char *body,
  14685. size_t content_length,
  14686. const std::string &content_type,
  14687. DownloadProgress progress) {
  14688. return cli_->Delete(path, body, content_length, content_type, progress);
  14689. }
  14690. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14691. const char *body, size_t content_length,
  14692. const std::string &content_type,
  14693. DownloadProgress progress) {
  14694. return cli_->Delete(path, headers, body, content_length, content_type,
  14695. progress);
  14696. }
  14697. inline Result Client::Delete(const std::string &path, const std::string &body,
  14698. const std::string &content_type,
  14699. DownloadProgress progress) {
  14700. return cli_->Delete(path, body, content_type, progress);
  14701. }
  14702. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14703. const std::string &body,
  14704. const std::string &content_type,
  14705. DownloadProgress progress) {
  14706. return cli_->Delete(path, headers, body, content_type, progress);
  14707. }
  14708. inline Result Client::Delete(const std::string &path, const Params &params,
  14709. DownloadProgress progress) {
  14710. return cli_->Delete(path, params, progress);
  14711. }
  14712. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14713. const Params &params, DownloadProgress progress) {
  14714. return cli_->Delete(path, headers, params, progress);
  14715. }
  14716. inline Result Client::Options(const std::string &path) {
  14717. return cli_->Options(path);
  14718. }
  14719. inline Result Client::Options(const std::string &path, const Headers &headers) {
  14720. return cli_->Options(path, headers);
  14721. }
  14722. inline ClientImpl::StreamHandle
  14723. Client::open_stream(const std::string &method, const std::string &path,
  14724. const Params &params, const Headers &headers,
  14725. const std::string &body, const std::string &content_type) {
  14726. return cli_->open_stream(method, path, params, headers, body, content_type);
  14727. }
  14728. inline bool Client::send(Request &req, Response &res, Error &error) {
  14729. return cli_->send(req, res, error);
  14730. }
  14731. inline Result Client::send(const Request &req) { return cli_->send(req); }
  14732. inline void Client::stop() { cli_->stop(); }
  14733. inline std::string Client::host() const { return cli_->host(); }
  14734. inline int Client::port() const { return cli_->port(); }
  14735. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  14736. inline socket_t Client::socket() const { return cli_->socket(); }
  14737. inline void
  14738. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14739. cli_->set_hostname_addr_map(std::move(addr_map));
  14740. }
  14741. inline void Client::set_default_headers(Headers headers) {
  14742. cli_->set_default_headers(std::move(headers));
  14743. }
  14744. inline void Client::set_header_writer(
  14745. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14746. cli_->set_header_writer(writer);
  14747. }
  14748. inline void Client::set_address_family(int family) {
  14749. cli_->set_address_family(family);
  14750. }
  14751. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  14752. inline void Client::set_socket_options(SocketOptions socket_options) {
  14753. cli_->set_socket_options(std::move(socket_options));
  14754. }
  14755. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  14756. cli_->set_connection_timeout(sec, usec);
  14757. }
  14758. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  14759. cli_->set_read_timeout(sec, usec);
  14760. }
  14761. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  14762. cli_->set_write_timeout(sec, usec);
  14763. }
  14764. inline void Client::set_basic_auth(const std::string &username,
  14765. const std::string &password) {
  14766. cli_->set_basic_auth(username, password);
  14767. }
  14768. inline void Client::set_bearer_token_auth(const std::string &token) {
  14769. cli_->set_bearer_token_auth(token);
  14770. }
  14771. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  14772. inline void Client::set_follow_location(bool on) {
  14773. cli_->set_follow_location(on);
  14774. }
  14775. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  14776. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  14777. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  14778. inline void Client::set_payload_max_length(size_t length) {
  14779. cli_->set_payload_max_length(length);
  14780. }
  14781. inline void Client::set_interface(const std::string &intf) {
  14782. cli_->set_interface(intf);
  14783. }
  14784. inline void Client::set_proxy(const std::string &host, int port) {
  14785. cli_->set_proxy(host, port);
  14786. }
  14787. inline void Client::set_proxy_basic_auth(const std::string &username,
  14788. const std::string &password) {
  14789. cli_->set_proxy_basic_auth(username, password);
  14790. }
  14791. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  14792. cli_->set_proxy_bearer_token_auth(token);
  14793. }
  14794. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  14795. cli_->set_no_proxy(patterns);
  14796. }
  14797. inline void Client::set_logger(Logger logger) {
  14798. cli_->set_logger(std::move(logger));
  14799. }
  14800. inline void Client::set_error_logger(ErrorLogger error_logger) {
  14801. cli_->set_error_logger(std::move(error_logger));
  14802. }
  14803. /*
  14804. * Group 6: SSL Server and Client implementation
  14805. */
  14806. #ifdef CPPHTTPLIB_SSL_ENABLED
  14807. // SSL HTTP server implementation
  14808. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  14809. const char *client_ca_cert_file_path,
  14810. const char *client_ca_cert_dir_path,
  14811. const char *private_key_password) {
  14812. using namespace tls;
  14813. ctx_ = create_server_context();
  14814. if (!ctx_) { return; }
  14815. // Load server certificate and private key
  14816. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  14817. private_key_password)) {
  14818. last_ssl_error_ = static_cast<int>(get_error());
  14819. free_context(ctx_);
  14820. ctx_ = nullptr;
  14821. return;
  14822. }
  14823. // Load client CA certificates for client authentication
  14824. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  14825. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  14826. client_ca_cert_dir_path)) {
  14827. last_ssl_error_ = static_cast<int>(get_error());
  14828. free_context(ctx_);
  14829. ctx_ = nullptr;
  14830. return;
  14831. }
  14832. // Enable client certificate verification
  14833. set_verify_client(ctx_, true);
  14834. }
  14835. }
  14836. inline SSLServer::SSLServer(const PemMemory &pem) {
  14837. using namespace tls;
  14838. ctx_ = create_server_context();
  14839. if (ctx_) {
  14840. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  14841. pem.private_key_password)) {
  14842. last_ssl_error_ = static_cast<int>(get_error());
  14843. free_context(ctx_);
  14844. ctx_ = nullptr;
  14845. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  14846. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  14847. last_ssl_error_ = static_cast<int>(get_error());
  14848. free_context(ctx_);
  14849. ctx_ = nullptr;
  14850. } else {
  14851. set_verify_client(ctx_, true);
  14852. }
  14853. }
  14854. }
  14855. }
  14856. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  14857. using namespace tls;
  14858. ctx_ = create_server_context();
  14859. if (ctx_) {
  14860. if (!setup_callback(ctx_)) {
  14861. free_context(ctx_);
  14862. ctx_ = nullptr;
  14863. }
  14864. }
  14865. }
  14866. inline SSLServer::~SSLServer() {
  14867. if (ctx_) { tls::free_context(ctx_); }
  14868. }
  14869. inline bool SSLServer::is_valid() const {
  14870. return ctx_ != nullptr && Server::is_valid();
  14871. }
  14872. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  14873. using namespace tls;
  14874. // Create TLS session with mutex protection
  14875. session_t session = nullptr;
  14876. {
  14877. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14878. session = create_session(static_cast<ctx_t>(ctx_), sock);
  14879. }
  14880. if (!session) {
  14881. last_ssl_error_ = static_cast<int>(get_error());
  14882. detail::shutdown_socket(sock);
  14883. detail::close_socket(sock);
  14884. return false;
  14885. }
  14886. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  14887. bool handshake_done = false;
  14888. bool ret = false;
  14889. bool websocket_upgraded = false;
  14890. auto cleanup = detail::scope_exit([&] {
  14891. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  14892. free_session(session);
  14893. detail::shutdown_socket(sock);
  14894. detail::close_socket(sock);
  14895. });
  14896. // Perform TLS accept handshake with timeout
  14897. TlsError tls_err;
  14898. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  14899. &tls_err)) {
  14900. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14901. // Map TlsError to legacy ssl_error for backward compatibility
  14902. if (tls_err.code == ErrorCode::WantRead) {
  14903. last_ssl_error_ = SSL_ERROR_WANT_READ;
  14904. } else if (tls_err.code == ErrorCode::WantWrite) {
  14905. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  14906. } else {
  14907. last_ssl_error_ = SSL_ERROR_SSL;
  14908. }
  14909. #else
  14910. last_ssl_error_ = static_cast<int>(get_error());
  14911. #endif
  14912. return false;
  14913. }
  14914. handshake_done = true;
  14915. std::string remote_addr;
  14916. int remote_port = 0;
  14917. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  14918. std::string local_addr;
  14919. int local_port = 0;
  14920. detail::get_local_ip_and_port(sock, local_addr, local_port);
  14921. ret = detail::process_server_socket_ssl(
  14922. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  14923. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14924. write_timeout_usec_,
  14925. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  14926. return process_request(
  14927. strm, remote_addr, remote_port, local_addr, local_port,
  14928. close_connection, connection_closed,
  14929. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  14930. });
  14931. return ret;
  14932. }
  14933. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  14934. const char *key_pem,
  14935. const char *client_ca_pem,
  14936. const char *password) {
  14937. if (!ctx_) { return false; }
  14938. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14939. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  14940. return false;
  14941. }
  14942. if (client_ca_pem) {
  14943. return tls::update_server_client_ca(ctx_, client_ca_pem);
  14944. }
  14945. return true;
  14946. }
  14947. // SSL HTTP client implementation
  14948. inline SSLClient::~SSLClient() {
  14949. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  14950. // base function rather than the derived function once we get to the
  14951. // base class destructor, and won't free the SSL (causing a leak).
  14952. // This must happen before the context is freed below: some backends
  14953. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  14954. // context, so freeing the context first leaves close_notify reading
  14955. // freed memory.
  14956. shutdown_ssl_impl(socket_, true);
  14957. if (ctx_) {
  14958. tls::free_context(ctx_);
  14959. ctx_ = nullptr;
  14960. }
  14961. }
  14962. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  14963. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  14964. shutdown_ssl_impl(socket, shutdown_gracefully);
  14965. }
  14966. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  14967. bool shutdown_gracefully) {
  14968. if (socket.sock == INVALID_SOCKET) {
  14969. assert(socket.ssl == nullptr);
  14970. return;
  14971. }
  14972. if (socket.ssl) {
  14973. tls::shutdown(socket.ssl, shutdown_gracefully);
  14974. {
  14975. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14976. tls::free_session(socket.ssl);
  14977. }
  14978. socket.ssl = nullptr;
  14979. }
  14980. assert(socket.ssl == nullptr);
  14981. }
  14982. inline bool SSLClient::process_socket(
  14983. const Socket &socket,
  14984. std::chrono::time_point<std::chrono::steady_clock> start_time,
  14985. std::function<bool(Stream &strm)> callback) {
  14986. assert(socket.ssl);
  14987. return detail::process_client_socket_ssl(
  14988. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  14989. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  14990. std::move(callback));
  14991. }
  14992. inline bool SSLClient::is_ssl() const { return true; }
  14993. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  14994. if (!is_valid()) {
  14995. error = Error::SSLConnection;
  14996. return false;
  14997. }
  14998. return ClientImpl::create_and_connect_socket(socket, error);
  14999. }
  15000. inline bool SSLClient::setup_proxy_connection(
  15001. Socket &socket,
  15002. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15003. Response &res, bool &success, Error &error) {
  15004. if (!is_proxy_enabled_for_host(host_)) { return true; }
  15005. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  15006. return false;
  15007. }
  15008. if (!initialize_ssl(socket, error)) {
  15009. success = false;
  15010. return false;
  15011. }
  15012. return true;
  15013. }
  15014. // Assumes that socket_mutex_ is locked and that there are no requests in
  15015. // flight
  15016. inline bool SSLClient::connect_with_proxy(
  15017. Socket &socket,
  15018. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15019. Response &res, bool &success, Error &error) {
  15020. success = true;
  15021. Response proxy_res;
  15022. if (!detail::process_client_socket(
  15023. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15024. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15025. start_time, [&](Stream &strm) {
  15026. Request req2;
  15027. req2.method = "CONNECT";
  15028. req2.path =
  15029. detail::make_host_and_port_string_always_port(host_, port_);
  15030. if (max_timeout_msec_ > 0) {
  15031. req2.start_time_ = std::chrono::steady_clock::now();
  15032. }
  15033. return process_request(strm, req2, proxy_res, false, error);
  15034. })) {
  15035. // Thread-safe to close everything because we are assuming there are no
  15036. // requests in flight
  15037. shutdown_ssl(socket, true);
  15038. shutdown_socket(socket);
  15039. close_socket(socket);
  15040. success = false;
  15041. return false;
  15042. }
  15043. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  15044. if (!proxy_digest_auth_username_.empty() &&
  15045. !proxy_digest_auth_password_.empty()) {
  15046. std::map<std::string, std::string> auth;
  15047. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  15048. // Close the current socket and create a new one for the authenticated
  15049. // request
  15050. shutdown_ssl(socket, true);
  15051. shutdown_socket(socket);
  15052. close_socket(socket);
  15053. // Create a new socket for the authenticated CONNECT request
  15054. if (!ensure_socket_connection(socket, error)) {
  15055. success = false;
  15056. output_error_log(error, nullptr);
  15057. return false;
  15058. }
  15059. proxy_res = Response();
  15060. if (!detail::process_client_socket(
  15061. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15062. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15063. start_time, [&](Stream &strm) {
  15064. Request req3;
  15065. req3.method = "CONNECT";
  15066. req3.path = detail::make_host_and_port_string_always_port(
  15067. host_, port_);
  15068. req3.headers.insert(detail::make_digest_authentication_header(
  15069. req3, auth, 1, detail::random_string(10),
  15070. proxy_digest_auth_username_, proxy_digest_auth_password_,
  15071. true));
  15072. if (max_timeout_msec_ > 0) {
  15073. req3.start_time_ = std::chrono::steady_clock::now();
  15074. }
  15075. return process_request(strm, req3, proxy_res, false, error);
  15076. })) {
  15077. // Thread-safe to close everything because we are assuming there are
  15078. // no requests in flight
  15079. shutdown_ssl(socket, true);
  15080. shutdown_socket(socket);
  15081. close_socket(socket);
  15082. success = false;
  15083. return false;
  15084. }
  15085. }
  15086. }
  15087. }
  15088. // If status code is not 200, proxy request is failed.
  15089. // Set error to ProxyConnection and return proxy response
  15090. // as the response of the request
  15091. if (proxy_res.status != StatusCode::OK_200) {
  15092. error = Error::ProxyConnection;
  15093. output_error_log(error, nullptr);
  15094. res = std::move(proxy_res);
  15095. // Thread-safe to close everything because we are assuming there are
  15096. // no requests in flight
  15097. shutdown_ssl(socket, true);
  15098. shutdown_socket(socket);
  15099. close_socket(socket);
  15100. return false;
  15101. }
  15102. return true;
  15103. }
  15104. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  15105. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  15106. if (is_proxy_enabled_for_host(host_)) { return true; }
  15107. if (!initialize_ssl(socket, error)) {
  15108. shutdown_socket(socket);
  15109. close_socket(socket);
  15110. return false;
  15111. }
  15112. return true;
  15113. }
  15114. // SSL HTTP client implementation
  15115. inline SSLClient::SSLClient(const std::string &host)
  15116. : SSLClient(host, 443, std::string(), std::string()) {}
  15117. inline SSLClient::SSLClient(const std::string &host, int port)
  15118. : SSLClient(host, port, std::string(), std::string()) {}
  15119. inline void SSLClient::init_ctx() {
  15120. ctx_ = tls::create_client_context();
  15121. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  15122. }
  15123. inline void SSLClient::reset_ctx_on_error() {
  15124. last_backend_error_ = tls::get_error();
  15125. tls::free_context(ctx_);
  15126. ctx_ = nullptr;
  15127. }
  15128. inline SSLClient::SSLClient(const std::string &host, int port,
  15129. const std::string &client_cert_path,
  15130. const std::string &client_key_path,
  15131. const std::string &private_key_password)
  15132. : ClientImpl(host, port, client_cert_path, client_key_path) {
  15133. init_ctx();
  15134. if (!ctx_) { return; }
  15135. if (!client_cert_path.empty() && !client_key_path.empty()) {
  15136. const char *password =
  15137. private_key_password.empty() ? nullptr : private_key_password.c_str();
  15138. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  15139. client_key_path.c_str(), password)) {
  15140. reset_ctx_on_error();
  15141. }
  15142. }
  15143. }
  15144. inline SSLClient::SSLClient(const std::string &host, int port,
  15145. const PemMemory &pem)
  15146. : ClientImpl(host, port) {
  15147. init_ctx();
  15148. if (!ctx_) { return; }
  15149. if (pem.cert_pem && pem.key_pem) {
  15150. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  15151. pem.private_key_password)) {
  15152. reset_ctx_on_error();
  15153. }
  15154. }
  15155. }
  15156. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  15157. if (ca_cert_store && ctx_) {
  15158. // set_ca_store takes ownership of ca_cert_store
  15159. tls::set_ca_store(ctx_, ca_cert_store);
  15160. ca_cert_store_set_ = true;
  15161. } else if (ca_cert_store) {
  15162. tls::free_ca_store(ca_cert_store);
  15163. }
  15164. }
  15165. inline void
  15166. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  15167. if (!ctx_) { return; }
  15168. tls::set_verify_callback(ctx_, verifier);
  15169. }
  15170. inline void SSLClient::set_session_verifier(
  15171. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  15172. session_verifier_ = std::move(verifier);
  15173. }
  15174. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15175. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  15176. enable_windows_cert_verification_ = enabled;
  15177. }
  15178. #endif
  15179. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  15180. std::size_t size) {
  15181. if (ctx_ && ca_cert && size > 0) {
  15182. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  15183. tls::load_ca_pem(ctx_, ca_cert, size);
  15184. }
  15185. }
  15186. inline bool SSLClient::load_certs() {
  15187. auto ret = true;
  15188. // call_once rather than the plain flag WebSocketClient::create_stream() uses:
  15189. // one client is shared across concurrent requests here.
  15190. std::call_once(initialize_cert_, [&]() {
  15191. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15192. ret = detail::load_client_ca_config(
  15193. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  15194. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  15195. last_backend_error_);
  15196. });
  15197. return ret;
  15198. }
  15199. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  15200. // Load CA certificates if server verification is enabled
  15201. if (server_certificate_verification_) {
  15202. if (!load_certs()) {
  15203. error = Error::SSLLoadingCerts;
  15204. output_error_log(error, nullptr);
  15205. return false;
  15206. }
  15207. }
  15208. detail::ClientTlsSessionOptions options;
  15209. options.server_hostname_verification = server_hostname_verification_;
  15210. options.session_verifier = session_verifier_;
  15211. options.ctx_mutex = &ctx_mutex_;
  15212. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15213. // Skip Schannel when a custom CA cert is specified, as the Windows
  15214. // certificate store would not know about user-provided CA certificates.
  15215. // Also skip when system CA trust is explicitly disabled.
  15216. options.windows_cert_verification =
  15217. enable_windows_cert_verification_ &&
  15218. system_ca_mode_ != SystemCAMode::Disabled && ca_cert_file_path_.empty() &&
  15219. ca_cert_dir_path_.empty() && ca_cert_pem_.empty() && !ca_cert_store_set_;
  15220. #endif
  15221. tls::session_t session = nullptr;
  15222. // Use scope_exit to ensure session is freed on error paths
  15223. bool success = false;
  15224. auto session_guard = detail::scope_exit([&] {
  15225. if (!success) { tls::free_session(session); }
  15226. });
  15227. detail::ClientTlsSessionError tls_error;
  15228. if (!detail::setup_client_tls_session(
  15229. host_, ctx_, session, socket.sock, server_certificate_verification_,
  15230. connection_timeout_sec_, connection_timeout_usec_, &tls_error,
  15231. options)) {
  15232. error = tls_error.error;
  15233. last_ssl_error_ = tls_error.ssl_error;
  15234. last_backend_error_ = tls_error.backend_error;
  15235. output_error_log(error, nullptr);
  15236. return false;
  15237. }
  15238. success = true;
  15239. socket.ssl = session;
  15240. return true;
  15241. }
  15242. inline void Client::set_digest_auth(const std::string &username,
  15243. const std::string &password) {
  15244. cli_->set_digest_auth(username, password);
  15245. }
  15246. inline void Client::set_proxy_digest_auth(const std::string &username,
  15247. const std::string &password) {
  15248. cli_->set_proxy_digest_auth(username, password);
  15249. }
  15250. inline void Client::enable_server_certificate_verification(bool enabled) {
  15251. cli_->enable_server_certificate_verification(enabled);
  15252. }
  15253. inline void Client::enable_server_hostname_verification(bool enabled) {
  15254. cli_->enable_server_hostname_verification(enabled);
  15255. }
  15256. inline void Client::enable_system_ca(bool enabled) {
  15257. cli_->enable_system_ca(enabled);
  15258. }
  15259. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15260. inline void Client::enable_windows_certificate_verification(bool enabled) {
  15261. if (is_ssl_) {
  15262. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  15263. enabled);
  15264. }
  15265. }
  15266. #endif
  15267. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  15268. const std::string &ca_cert_dir_path) {
  15269. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  15270. }
  15271. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  15272. if (is_ssl_) {
  15273. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  15274. } else if (ca_cert_store) {
  15275. tls::free_ca_store(ca_cert_store);
  15276. }
  15277. }
  15278. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  15279. if (is_ssl_) {
  15280. // Use the PEM-based path so the CA data is retained for redirect transfer
  15281. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  15282. }
  15283. }
  15284. inline void
  15285. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  15286. if (is_ssl_) {
  15287. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  15288. std::move(verifier));
  15289. }
  15290. }
  15291. inline void Client::set_session_verifier(
  15292. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  15293. if (is_ssl_) {
  15294. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  15295. }
  15296. }
  15297. inline tls::ctx_t Client::tls_context() const {
  15298. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  15299. return nullptr;
  15300. }
  15301. #endif // CPPHTTPLIB_SSL_ENABLED
  15302. /*
  15303. * Group 7: TLS abstraction layer - Common API
  15304. */
  15305. #ifdef CPPHTTPLIB_SSL_ENABLED
  15306. namespace tls {
  15307. // Helper for PeerCert construction
  15308. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  15309. return PeerCert(get_peer_cert(session));
  15310. }
  15311. namespace impl {
  15312. inline VerifyCallback &get_verify_callback() {
  15313. static thread_local VerifyCallback callback;
  15314. return callback;
  15315. }
  15316. inline VerifyCallback &get_mbedtls_verify_callback() {
  15317. static thread_local VerifyCallback callback;
  15318. return callback;
  15319. }
  15320. // Check if a string is an IPv4 address
  15321. inline bool is_ipv4_address(const std::string &str) {
  15322. int dots = 0;
  15323. for (char c : str) {
  15324. if (c == '.') {
  15325. dots++;
  15326. } else if (!detail::is_ascii_digit(c)) {
  15327. return false;
  15328. }
  15329. }
  15330. return dots == 3;
  15331. }
  15332. // Parse IPv4 address string to bytes
  15333. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  15334. const char *p = str.c_str();
  15335. for (int i = 0; i < 4; i++) {
  15336. if (i > 0) {
  15337. if (*p != '.') { return false; }
  15338. p++;
  15339. }
  15340. int val = 0;
  15341. int digits = 0;
  15342. while (detail::is_ascii_digit(*p)) {
  15343. val = val * 10 + (*p - '0');
  15344. if (val > 255) { return false; }
  15345. p++;
  15346. digits++;
  15347. }
  15348. if (digits == 0) { return false; }
  15349. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  15350. if (digits > 1 && *(p - digits) == '0') { return false; }
  15351. out[i] = static_cast<unsigned char>(val);
  15352. }
  15353. return *p == '\0';
  15354. }
  15355. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  15356. // `out` must have room for at least 16 bytes. Returns the address length
  15357. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  15358. // literal. Used to match a host against iPAddress SANs the same way the
  15359. // OpenSSL backend does via X509_check_ip.
  15360. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  15361. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  15362. struct in6_addr addr6 = {};
  15363. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  15364. memcpy(out, &addr6, 16);
  15365. return 16;
  15366. }
  15367. return 0;
  15368. }
  15369. #ifdef _WIN32
  15370. // Enumerate Windows system certificates and call callback with DER data
  15371. template <typename Callback>
  15372. inline bool enumerate_windows_system_certs(Callback cb) {
  15373. bool loaded = false;
  15374. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  15375. for (auto store_name : store_names) {
  15376. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  15377. if (hStore) {
  15378. PCCERT_CONTEXT pContext = nullptr;
  15379. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  15380. nullptr) {
  15381. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  15382. loaded = true;
  15383. }
  15384. }
  15385. CertCloseStore(hStore, 0);
  15386. }
  15387. }
  15388. return loaded;
  15389. }
  15390. #endif
  15391. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15392. // Enumerate macOS Keychain certificates and call callback with DER data
  15393. template <typename Callback>
  15394. inline bool enumerate_macos_keychain_certs(Callback cb) {
  15395. bool loaded = false;
  15396. const SecTrustSettingsDomain domains[] = {
  15397. kSecTrustSettingsDomainSystem,
  15398. kSecTrustSettingsDomainAdmin,
  15399. kSecTrustSettingsDomainUser,
  15400. };
  15401. for (auto domain : domains) {
  15402. CFArrayRef certs = nullptr;
  15403. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  15404. if (status != errSecSuccess || !certs) {
  15405. if (certs) CFRelease(certs);
  15406. continue;
  15407. }
  15408. CFIndex count = CFArrayGetCount(certs);
  15409. for (CFIndex i = 0; i < count; i++) {
  15410. SecCertificateRef cert =
  15411. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  15412. CFDataRef data = SecCertificateCopyData(cert);
  15413. if (data) {
  15414. if (cb(CFDataGetBytePtr(data),
  15415. static_cast<size_t>(CFDataGetLength(data)))) {
  15416. loaded = true;
  15417. }
  15418. CFRelease(data);
  15419. }
  15420. }
  15421. CFRelease(certs);
  15422. }
  15423. return loaded;
  15424. }
  15425. #endif
  15426. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  15427. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  15428. // Common CA certificate file paths on Linux/Unix
  15429. inline const char **system_ca_paths() {
  15430. static const char *paths[] = {
  15431. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  15432. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  15433. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  15434. "/etc/pki/tls/cacert.pem", // OpenELEC
  15435. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  15436. nullptr};
  15437. return paths;
  15438. }
  15439. // Common CA certificate directory paths on Linux/Unix
  15440. inline const char **system_ca_dirs() {
  15441. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  15442. "/etc/pki/tls/certs", // RHEL/CentOS
  15443. "/usr/share/ca-certificates", // Other
  15444. nullptr};
  15445. return dirs;
  15446. }
  15447. #endif
  15448. } // namespace impl
  15449. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  15450. const char *ca_dir) {
  15451. if (!ctx) { return false; }
  15452. bool success = true;
  15453. if (ca_file && *ca_file) {
  15454. if (!load_ca_file(ctx, ca_file)) { success = false; }
  15455. }
  15456. if (ca_dir && *ca_dir) {
  15457. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  15458. }
  15459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15460. // Set CA list for client certificate request (CertificateRequest message)
  15461. if (ca_file && *ca_file) {
  15462. auto list = SSL_load_client_CA_file(ca_file);
  15463. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  15464. }
  15465. #endif
  15466. return success;
  15467. }
  15468. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15469. const char *password) {
  15470. return set_client_cert_pem(ctx, cert, key, password);
  15471. }
  15472. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  15473. const char *key_path, const char *password) {
  15474. return set_client_cert_file(ctx, cert_path, key_path, password);
  15475. }
  15476. // PeerCert implementation
  15477. inline PeerCert::PeerCert() = default;
  15478. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  15479. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  15480. other.cert_ = nullptr;
  15481. }
  15482. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  15483. if (this != &other) {
  15484. if (cert_) { free_cert(cert_); }
  15485. cert_ = other.cert_;
  15486. other.cert_ = nullptr;
  15487. }
  15488. return *this;
  15489. }
  15490. inline PeerCert::~PeerCert() {
  15491. if (cert_) { free_cert(cert_); }
  15492. }
  15493. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  15494. inline std::string PeerCert::subject_cn() const {
  15495. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  15496. }
  15497. inline std::string PeerCert::issuer_name() const {
  15498. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  15499. }
  15500. inline bool PeerCert::check_hostname(const char *hostname) const {
  15501. return cert_ ? verify_hostname(cert_, hostname) : false;
  15502. }
  15503. inline std::vector<SanEntry> PeerCert::sans() const {
  15504. std::vector<SanEntry> result;
  15505. if (cert_) { get_cert_sans(cert_, result); }
  15506. return result;
  15507. }
  15508. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  15509. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  15510. }
  15511. inline std::string PeerCert::serial() const {
  15512. return cert_ ? get_cert_serial(cert_) : std::string();
  15513. }
  15514. // VerifyContext method implementations
  15515. inline std::string VerifyContext::subject_cn() const {
  15516. return cert ? get_cert_subject_cn(cert) : std::string();
  15517. }
  15518. inline std::string VerifyContext::issuer_name() const {
  15519. return cert ? get_cert_issuer_name(cert) : std::string();
  15520. }
  15521. inline bool VerifyContext::check_hostname(const char *hostname) const {
  15522. return cert ? verify_hostname(cert, hostname) : false;
  15523. }
  15524. inline std::vector<SanEntry> VerifyContext::sans() const {
  15525. std::vector<SanEntry> result;
  15526. if (cert) { get_cert_sans(cert, result); }
  15527. return result;
  15528. }
  15529. inline bool VerifyContext::validity(time_t &not_before,
  15530. time_t &not_after) const {
  15531. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  15532. }
  15533. inline std::string VerifyContext::serial() const {
  15534. return cert ? get_cert_serial(cert) : std::string();
  15535. }
  15536. // TlsError static method implementation
  15537. inline std::string TlsError::verify_error_to_string(long error_code) {
  15538. return verify_error_string(error_code);
  15539. }
  15540. } // namespace tls
  15541. // Request::peer_cert() implementation
  15542. inline tls::PeerCert Request::peer_cert() const {
  15543. return tls::get_peer_cert_from_session(ssl);
  15544. }
  15545. // Request::sni() implementation
  15546. inline std::string Request::sni() const {
  15547. if (!ssl) { return std::string(); }
  15548. const char *s = tls::get_sni(ssl);
  15549. return s ? std::string(s) : std::string();
  15550. }
  15551. #endif // CPPHTTPLIB_SSL_ENABLED
  15552. /*
  15553. * Group 8: TLS abstraction layer - OpenSSL backend
  15554. */
  15555. /*
  15556. * OpenSSL Backend Implementation
  15557. */
  15558. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15559. namespace tls {
  15560. namespace impl {
  15561. // Helper to map OpenSSL SSL_get_error to ErrorCode
  15562. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  15563. switch (ssl_error) {
  15564. case SSL_ERROR_NONE: return ErrorCode::Success;
  15565. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  15566. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  15567. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  15568. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  15569. case SSL_ERROR_SSL:
  15570. default: return ErrorCode::Fatal;
  15571. }
  15572. }
  15573. // Helper: Create client CA list from PEM string
  15574. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  15575. // Caller takes ownership of returned list
  15576. inline STACK_OF(X509_NAME) *
  15577. create_client_ca_list_from_pem(const char *ca_pem) {
  15578. if (!ca_pem) { return nullptr; }
  15579. auto ca_list = sk_X509_NAME_new_null();
  15580. if (!ca_list) { return nullptr; }
  15581. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  15582. if (!bio) {
  15583. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  15584. return nullptr;
  15585. }
  15586. X509 *cert = nullptr;
  15587. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  15588. nullptr) {
  15589. const X509_NAME *name = X509_get_subject_name(cert);
  15590. if (name) {
  15591. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  15592. }
  15593. X509_free(cert);
  15594. }
  15595. BIO_free(bio);
  15596. return ca_list;
  15597. }
  15598. // OpenSSL verify callback wrapper
  15599. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  15600. auto &callback = get_verify_callback();
  15601. if (!callback) { return preverify_ok; }
  15602. // Get SSL object from X509_STORE_CTX
  15603. auto ssl = static_cast<SSL *>(
  15604. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  15605. if (!ssl) { return preverify_ok; }
  15606. // Get current certificate and depth
  15607. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  15608. int depth = X509_STORE_CTX_get_error_depth(ctx);
  15609. int error = X509_STORE_CTX_get_error(ctx);
  15610. // Build context
  15611. VerifyContext verify_ctx;
  15612. verify_ctx.session = static_cast<session_t>(ssl);
  15613. verify_ctx.cert = static_cast<cert_t>(cert);
  15614. verify_ctx.depth = depth;
  15615. verify_ctx.preverify_ok = (preverify_ok != 0);
  15616. verify_ctx.error_code = error;
  15617. verify_ctx.error_string =
  15618. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  15619. return callback(verify_ctx) ? 1 : 0;
  15620. }
  15621. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  15622. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  15623. // that must be released with release_store_objects
  15624. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  15625. OPENSSL_VERSION_NUMBER >= 0x30300000L
  15626. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  15627. #endif
  15628. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  15629. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  15630. return X509_STORE_get1_objects(store);
  15631. #else
  15632. return X509_STORE_get0_objects(store);
  15633. #endif
  15634. }
  15635. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  15636. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  15637. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  15638. #else
  15639. (void)objs; // get0 variant returns an internal pointer; nothing to free
  15640. #endif
  15641. }
  15642. } // namespace impl
  15643. inline ctx_t create_client_context() {
  15644. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  15645. if (ctx) {
  15646. // Disable auto-retry to properly handle non-blocking I/O
  15647. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  15648. // Set minimum TLS version
  15649. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  15650. }
  15651. return static_cast<ctx_t>(ctx);
  15652. }
  15653. inline void free_context(ctx_t ctx) {
  15654. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  15655. }
  15656. inline bool set_min_version(ctx_t ctx, Version version) {
  15657. if (!ctx) return false;
  15658. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  15659. static_cast<int>(version)) == 1;
  15660. }
  15661. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15662. if (!ctx || !pem || len == 0) return false;
  15663. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15664. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15665. if (!store) return false;
  15666. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  15667. if (!bio) return false;
  15668. bool ok = true;
  15669. X509 *cert = nullptr;
  15670. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  15671. nullptr) {
  15672. if (X509_STORE_add_cert(store, cert) != 1) {
  15673. // Ignore duplicate errors
  15674. auto err = ERR_peek_last_error();
  15675. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  15676. ok = false;
  15677. }
  15678. }
  15679. X509_free(cert);
  15680. if (!ok) break;
  15681. }
  15682. BIO_free(bio);
  15683. // Clear any "no more certificates" errors
  15684. ERR_clear_error();
  15685. return ok;
  15686. }
  15687. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15688. if (!ctx || !file_path) return false;
  15689. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  15690. nullptr) == 1;
  15691. }
  15692. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15693. if (!ctx || !dir_path) return false;
  15694. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  15695. dir_path) == 1;
  15696. }
  15697. inline bool load_system_certs(ctx_t ctx) {
  15698. if (!ctx) return false;
  15699. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15700. #ifdef _WIN32
  15701. // Windows: Load from system certificate store (ROOT and CA)
  15702. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15703. if (!store) return false;
  15704. bool loaded_any = false;
  15705. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  15706. for (auto store_name : store_names) {
  15707. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  15708. if (!hStore) continue;
  15709. PCCERT_CONTEXT pContext = nullptr;
  15710. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  15711. nullptr) {
  15712. const unsigned char *data = pContext->pbCertEncoded;
  15713. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  15714. if (x509) {
  15715. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  15716. X509_free(x509);
  15717. }
  15718. }
  15719. CertCloseStore(hStore, 0);
  15720. }
  15721. return loaded_any;
  15722. #elif defined(__APPLE__)
  15723. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15724. // macOS: Load from Keychain
  15725. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15726. if (!store) return false;
  15727. bool loaded_any = false;
  15728. const SecTrustSettingsDomain domains[] = {
  15729. kSecTrustSettingsDomainSystem,
  15730. kSecTrustSettingsDomainAdmin,
  15731. kSecTrustSettingsDomainUser,
  15732. };
  15733. for (auto domain : domains) {
  15734. CFArrayRef certs = nullptr;
  15735. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  15736. !certs) {
  15737. if (certs) CFRelease(certs);
  15738. continue;
  15739. }
  15740. auto count = CFArrayGetCount(certs);
  15741. for (CFIndex i = 0; i < count; i++) {
  15742. auto cert = reinterpret_cast<SecCertificateRef>(
  15743. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  15744. CFDataRef der = SecCertificateCopyData(cert);
  15745. if (der) {
  15746. const unsigned char *data = CFDataGetBytePtr(der);
  15747. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  15748. if (x509) {
  15749. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  15750. X509_free(x509);
  15751. }
  15752. CFRelease(der);
  15753. }
  15754. }
  15755. CFRelease(certs);
  15756. }
  15757. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  15758. #else
  15759. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  15760. #endif
  15761. #else
  15762. // Other Unix: use default verify paths
  15763. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  15764. #endif
  15765. }
  15766. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15767. const char *password) {
  15768. if (!ctx || !cert || !key) return false;
  15769. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15770. // Load certificate
  15771. auto cert_bio = BIO_new_mem_buf(cert, -1);
  15772. if (!cert_bio) return false;
  15773. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15774. BIO_free(cert_bio);
  15775. if (!x509) return false;
  15776. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  15777. X509_free(x509);
  15778. if (!cert_ok) return false;
  15779. // Load private key
  15780. auto key_bio = BIO_new_mem_buf(key, -1);
  15781. if (!key_bio) return false;
  15782. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15783. password ? const_cast<char *>(password)
  15784. : nullptr);
  15785. BIO_free(key_bio);
  15786. if (!pkey) return false;
  15787. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  15788. EVP_PKEY_free(pkey);
  15789. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  15790. }
  15791. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15792. const char *key_path, const char *password) {
  15793. if (!ctx || !cert_path || !key_path) return false;
  15794. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15795. if (password && password[0] != '\0') {
  15796. SSL_CTX_set_default_passwd_cb_userdata(
  15797. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  15798. }
  15799. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  15800. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  15801. }
  15802. inline ctx_t create_server_context() {
  15803. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15804. if (ctx) {
  15805. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  15806. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15807. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  15808. }
  15809. return static_cast<ctx_t>(ctx);
  15810. }
  15811. inline void set_verify_client(ctx_t ctx, bool require) {
  15812. if (!ctx) return;
  15813. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  15814. require
  15815. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  15816. : SSL_VERIFY_NONE,
  15817. nullptr);
  15818. }
  15819. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15820. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  15821. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15822. SSL *ssl = SSL_new(ssl_ctx);
  15823. if (!ssl) return nullptr;
  15824. // Disable auto-retry for proper non-blocking I/O handling
  15825. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  15826. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  15827. if (!bio) {
  15828. SSL_free(ssl);
  15829. return nullptr;
  15830. }
  15831. SSL_set_bio(ssl, bio, bio);
  15832. return static_cast<session_t>(ssl);
  15833. }
  15834. inline void free_session(session_t session) {
  15835. if (session) { SSL_free(static_cast<SSL *>(session)); }
  15836. }
  15837. inline bool set_sni(session_t session, const char *hostname,
  15838. bool /*verify_hostname*/) {
  15839. if (!session || !hostname) return false;
  15840. auto ssl = static_cast<SSL *>(session);
  15841. // Set SNI (Server Name Indication) only - does not enable verification.
  15842. // OpenSSL never binds identity checking to SNI (that happens post-
  15843. // handshake in setup_client_tls_session()), so verify_hostname is unused.
  15844. #if defined(OPENSSL_IS_BORINGSSL)
  15845. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  15846. #else
  15847. // Direct call instead of macro to suppress -Wold-style-cast warning
  15848. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  15849. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  15850. #endif
  15851. }
  15852. inline TlsError connect(session_t session) {
  15853. if (!session) { return TlsError(); }
  15854. auto ssl = static_cast<SSL *>(session);
  15855. auto ret = SSL_connect(ssl);
  15856. TlsError err;
  15857. if (ret == 1) {
  15858. err.code = ErrorCode::Success;
  15859. } else {
  15860. auto ssl_err = SSL_get_error(ssl, ret);
  15861. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  15862. err.backend_code = ERR_get_error();
  15863. }
  15864. return err;
  15865. }
  15866. inline TlsError accept(session_t session) {
  15867. if (!session) { return TlsError(); }
  15868. auto ssl = static_cast<SSL *>(session);
  15869. auto ret = SSL_accept(ssl);
  15870. TlsError err;
  15871. if (ret == 1) {
  15872. err.code = ErrorCode::Success;
  15873. } else {
  15874. auto ssl_err = SSL_get_error(ssl, ret);
  15875. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  15876. err.backend_code = ERR_get_error();
  15877. }
  15878. return err;
  15879. }
  15880. inline bool connect_nonblocking(session_t session, socket_t sock,
  15881. time_t timeout_sec, time_t timeout_usec,
  15882. TlsError *err) {
  15883. if (!session) {
  15884. if (err) { err->code = ErrorCode::Fatal; }
  15885. return false;
  15886. }
  15887. auto ssl = static_cast<SSL *>(session);
  15888. auto bio = SSL_get_rbio(ssl);
  15889. // Set non-blocking mode for handshake
  15890. detail::set_nonblocking(sock, true);
  15891. if (bio) { BIO_set_nbio(bio, 1); }
  15892. auto cleanup = detail::scope_exit([&]() {
  15893. // Restore blocking mode after handshake
  15894. if (bio) { BIO_set_nbio(bio, 0); }
  15895. detail::set_nonblocking(sock, false);
  15896. });
  15897. auto res = 0;
  15898. while ((res = SSL_connect(ssl)) != 1) {
  15899. auto ssl_err = SSL_get_error(ssl, res);
  15900. switch (ssl_err) {
  15901. case SSL_ERROR_WANT_READ:
  15902. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15903. continue;
  15904. }
  15905. break;
  15906. case SSL_ERROR_WANT_WRITE:
  15907. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15908. continue;
  15909. }
  15910. break;
  15911. default: break;
  15912. }
  15913. if (err) {
  15914. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  15915. err->backend_code = ERR_get_error();
  15916. }
  15917. return false;
  15918. }
  15919. if (err) { err->code = ErrorCode::Success; }
  15920. return true;
  15921. }
  15922. inline bool accept_nonblocking(session_t session, socket_t sock,
  15923. time_t timeout_sec, time_t timeout_usec,
  15924. TlsError *err) {
  15925. if (!session) {
  15926. if (err) { err->code = ErrorCode::Fatal; }
  15927. return false;
  15928. }
  15929. auto ssl = static_cast<SSL *>(session);
  15930. auto bio = SSL_get_rbio(ssl);
  15931. // Set non-blocking mode for handshake
  15932. detail::set_nonblocking(sock, true);
  15933. if (bio) { BIO_set_nbio(bio, 1); }
  15934. auto cleanup = detail::scope_exit([&]() {
  15935. // Restore blocking mode after handshake
  15936. if (bio) { BIO_set_nbio(bio, 0); }
  15937. detail::set_nonblocking(sock, false);
  15938. });
  15939. auto res = 0;
  15940. while ((res = SSL_accept(ssl)) != 1) {
  15941. auto ssl_err = SSL_get_error(ssl, res);
  15942. switch (ssl_err) {
  15943. case SSL_ERROR_WANT_READ:
  15944. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15945. continue;
  15946. }
  15947. break;
  15948. case SSL_ERROR_WANT_WRITE:
  15949. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15950. continue;
  15951. }
  15952. break;
  15953. default: break;
  15954. }
  15955. if (err) {
  15956. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  15957. err->backend_code = ERR_get_error();
  15958. }
  15959. return false;
  15960. }
  15961. if (err) { err->code = ErrorCode::Success; }
  15962. return true;
  15963. }
  15964. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15965. if (!session || !buf) {
  15966. err.code = ErrorCode::Fatal;
  15967. return -1;
  15968. }
  15969. auto ssl = static_cast<SSL *>(session);
  15970. constexpr auto max_len =
  15971. static_cast<size_t>((std::numeric_limits<int>::max)());
  15972. if (len > max_len) { len = max_len; }
  15973. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  15974. if (ret > 0) {
  15975. err.code = ErrorCode::Success;
  15976. return ret;
  15977. }
  15978. auto ssl_err = SSL_get_error(ssl, ret);
  15979. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  15980. if (err.code == ErrorCode::PeerClosed) {
  15981. return 0;
  15982. } // Gracefully handle the peer closed state.
  15983. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  15984. return -1;
  15985. }
  15986. inline ssize_t write(session_t session, const void *buf, size_t len,
  15987. TlsError &err) {
  15988. if (!session || !buf) {
  15989. err.code = ErrorCode::Fatal;
  15990. return -1;
  15991. }
  15992. auto ssl = static_cast<SSL *>(session);
  15993. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  15994. if (ret > 0) {
  15995. err.code = ErrorCode::Success;
  15996. return ret;
  15997. }
  15998. auto ssl_err = SSL_get_error(ssl, ret);
  15999. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16000. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  16001. return -1;
  16002. }
  16003. inline int pending(const_session_t session) {
  16004. if (!session) return 0;
  16005. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  16006. }
  16007. inline void shutdown(session_t session, bool graceful) {
  16008. if (!session) return;
  16009. auto ssl = static_cast<SSL *>(session);
  16010. if (graceful) {
  16011. // First call sends close_notify
  16012. if (SSL_shutdown(ssl) == 0) {
  16013. // Second call waits for peer's close_notify
  16014. SSL_shutdown(ssl);
  16015. }
  16016. }
  16017. }
  16018. inline bool is_peer_closed(session_t session, socket_t sock) {
  16019. if (!session) return true;
  16020. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  16021. detail::set_nonblocking(sock, true);
  16022. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16023. auto ssl = static_cast<SSL *>(session);
  16024. char buf;
  16025. auto ret = SSL_peek(ssl, &buf, 1);
  16026. if (ret > 0) return false;
  16027. auto err = SSL_get_error(ssl, ret);
  16028. return err == SSL_ERROR_ZERO_RETURN;
  16029. }
  16030. inline cert_t get_peer_cert(const_session_t session) {
  16031. if (!session) return nullptr;
  16032. return static_cast<cert_t>(SSL_get1_peer_certificate(
  16033. static_cast<SSL *>(const_cast<void *>(session))));
  16034. }
  16035. inline void free_cert(cert_t cert) {
  16036. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  16037. }
  16038. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16039. if (!cert || !hostname) return false;
  16040. auto x509 = static_cast<X509 *>(cert);
  16041. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  16042. if (detail::is_ip_address(hostname)) {
  16043. return X509_check_ip_asc(x509, hostname, 0) == 1;
  16044. }
  16045. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  16046. }
  16047. inline uint64_t hostname_mismatch_code() {
  16048. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  16049. }
  16050. inline long get_verify_result(const_session_t session) {
  16051. if (!session) return X509_V_ERR_UNSPECIFIED;
  16052. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  16053. }
  16054. inline std::string get_cert_subject_cn(cert_t cert) {
  16055. if (!cert) return "";
  16056. auto x509 = static_cast<X509 *>(cert);
  16057. auto subject_name = X509_get_subject_name(x509);
  16058. if (!subject_name) return "";
  16059. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  16060. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  16061. if (idx < 0) return "";
  16062. auto entry = X509_NAME_get_entry(subject_name, idx);
  16063. if (!entry) return "";
  16064. auto data = X509_NAME_ENTRY_get_data(entry);
  16065. if (!data) return "";
  16066. return std::string(
  16067. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  16068. static_cast<size_t>(ASN1_STRING_length(data)));
  16069. }
  16070. inline std::string get_cert_issuer_name(cert_t cert) {
  16071. if (!cert) return "";
  16072. auto x509 = static_cast<X509 *>(cert);
  16073. auto issuer_name = X509_get_issuer_name(x509);
  16074. if (!issuer_name) return "";
  16075. char buf[256];
  16076. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  16077. return std::string(buf);
  16078. }
  16079. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16080. sans.clear();
  16081. if (!cert) return false;
  16082. auto x509 = static_cast<X509 *>(cert);
  16083. auto names = static_cast<GENERAL_NAMES *>(
  16084. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16085. if (!names) return true; // No SANs is valid
  16086. auto count = sk_GENERAL_NAME_num(names);
  16087. for (decltype(count) i = 0; i < count; i++) {
  16088. auto gen = sk_GENERAL_NAME_value(names, i);
  16089. if (!gen) continue;
  16090. SanEntry entry;
  16091. switch (gen->type) {
  16092. case GEN_DNS:
  16093. entry.type = SanType::DNS;
  16094. if (gen->d.dNSName) {
  16095. entry.value = std::string(
  16096. reinterpret_cast<const char *>(
  16097. ASN1_STRING_get0_data(gen->d.dNSName)),
  16098. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  16099. }
  16100. break;
  16101. case GEN_IPADD:
  16102. entry.type = SanType::IP;
  16103. if (gen->d.iPAddress) {
  16104. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  16105. auto len = ASN1_STRING_length(gen->d.iPAddress);
  16106. if (len == 4) {
  16107. // IPv4
  16108. char buf[INET_ADDRSTRLEN];
  16109. inet_ntop(AF_INET, data, buf, sizeof(buf));
  16110. entry.value = buf;
  16111. } else if (len == 16) {
  16112. // IPv6
  16113. char buf[INET6_ADDRSTRLEN];
  16114. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  16115. entry.value = buf;
  16116. }
  16117. }
  16118. break;
  16119. case GEN_EMAIL:
  16120. entry.type = SanType::EMAIL;
  16121. if (gen->d.rfc822Name) {
  16122. entry.value = std::string(
  16123. reinterpret_cast<const char *>(
  16124. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  16125. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  16126. }
  16127. break;
  16128. case GEN_URI:
  16129. entry.type = SanType::URI;
  16130. if (gen->d.uniformResourceIdentifier) {
  16131. entry.value = std::string(
  16132. reinterpret_cast<const char *>(
  16133. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  16134. static_cast<size_t>(
  16135. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  16136. }
  16137. break;
  16138. default: entry.type = SanType::OTHER; break;
  16139. }
  16140. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16141. }
  16142. GENERAL_NAMES_free(names);
  16143. return true;
  16144. }
  16145. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16146. time_t &not_after) {
  16147. if (!cert) return false;
  16148. auto x509 = static_cast<X509 *>(cert);
  16149. auto nb = X509_get0_notBefore(x509);
  16150. auto na = X509_get0_notAfter(x509);
  16151. if (!nb || !na) return false;
  16152. ASN1_TIME *epoch = ASN1_TIME_new();
  16153. if (!epoch) return false;
  16154. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  16155. if (!ASN1_TIME_set(epoch, 0)) return false;
  16156. int pday, psec;
  16157. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  16158. not_before = 86400 * (time_t)pday + psec;
  16159. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  16160. not_after = 86400 * (time_t)pday + psec;
  16161. return true;
  16162. }
  16163. inline std::string get_cert_serial(cert_t cert) {
  16164. if (!cert) return "";
  16165. auto x509 = static_cast<X509 *>(cert);
  16166. auto serial = X509_get_serialNumber(x509);
  16167. if (!serial) return "";
  16168. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  16169. if (!bn) return "";
  16170. auto hex = BN_bn2hex(bn);
  16171. BN_free(bn);
  16172. if (!hex) return "";
  16173. std::string result(hex);
  16174. OPENSSL_free(hex);
  16175. return result;
  16176. }
  16177. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16178. if (!cert) return false;
  16179. auto x509 = static_cast<X509 *>(cert);
  16180. auto len = i2d_X509(x509, nullptr);
  16181. if (len < 0) return false;
  16182. der.resize(static_cast<size_t>(len));
  16183. auto p = der.data();
  16184. i2d_X509(x509, &p);
  16185. return true;
  16186. }
  16187. inline const char *get_sni(const_session_t session) {
  16188. if (!session) return nullptr;
  16189. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  16190. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  16191. }
  16192. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  16193. inline uint64_t get_error() { return ERR_get_error(); }
  16194. inline std::string error_string(uint64_t code) {
  16195. char buf[256];
  16196. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  16197. return std::string(buf);
  16198. }
  16199. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16200. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  16201. if (!mem) { return nullptr; }
  16202. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  16203. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  16204. if (!inf) { return nullptr; }
  16205. auto store = X509_STORE_new();
  16206. if (store) {
  16207. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  16208. auto itmp = sk_X509_INFO_value(inf, i);
  16209. if (!itmp) { continue; }
  16210. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  16211. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  16212. }
  16213. }
  16214. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  16215. return static_cast<ca_store_t>(store);
  16216. }
  16217. inline void free_ca_store(ca_store_t store) {
  16218. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  16219. }
  16220. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16221. if (!ctx || !store) { return false; }
  16222. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16223. auto x509_store = static_cast<X509_STORE *>(store);
  16224. // Check if same store is already set
  16225. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  16226. // SSL_CTX_set_cert_store takes ownership and frees the old store
  16227. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  16228. return true;
  16229. }
  16230. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16231. certs.clear();
  16232. if (!ctx) { return 0; }
  16233. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16234. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16235. if (!store) { return 0; }
  16236. auto objs = impl::get_store_objects(store);
  16237. if (!objs) { return 0; }
  16238. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  16239. auto count = sk_X509_OBJECT_num(objs);
  16240. for (decltype(count) i = 0; i < count; i++) {
  16241. auto obj = sk_X509_OBJECT_value(objs, i);
  16242. if (!obj) { continue; }
  16243. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  16244. auto x509 = X509_OBJECT_get0_X509(obj);
  16245. if (x509) {
  16246. // Increment reference count so caller can free it
  16247. X509_up_ref(x509);
  16248. certs.push_back(static_cast<cert_t>(x509));
  16249. }
  16250. }
  16251. }
  16252. return certs.size();
  16253. }
  16254. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16255. std::vector<std::string> names;
  16256. if (!ctx) { return names; }
  16257. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16258. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16259. if (!store) { return names; }
  16260. auto objs = impl::get_store_objects(store);
  16261. if (!objs) { return names; }
  16262. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  16263. auto count = sk_X509_OBJECT_num(objs);
  16264. for (decltype(count) i = 0; i < count; i++) {
  16265. auto obj = sk_X509_OBJECT_value(objs, i);
  16266. if (!obj) { continue; }
  16267. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  16268. auto x509 = X509_OBJECT_get0_X509(obj);
  16269. if (x509) {
  16270. auto subject = X509_get_subject_name(x509);
  16271. if (subject) {
  16272. char buf[512];
  16273. X509_NAME_oneline(subject, buf, sizeof(buf));
  16274. names.push_back(buf);
  16275. }
  16276. }
  16277. }
  16278. }
  16279. return names;
  16280. }
  16281. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16282. const char *key_pem, const char *password) {
  16283. if (!ctx || !cert_pem || !key_pem) { return false; }
  16284. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16285. // Load certificate from PEM
  16286. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  16287. if (!cert_bio) { return false; }
  16288. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  16289. BIO_free(cert_bio);
  16290. if (!cert) { return false; }
  16291. // Load private key from PEM
  16292. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  16293. if (!key_bio) {
  16294. X509_free(cert);
  16295. return false;
  16296. }
  16297. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  16298. password ? const_cast<char *>(password)
  16299. : nullptr);
  16300. BIO_free(key_bio);
  16301. if (!key) {
  16302. X509_free(cert);
  16303. return false;
  16304. }
  16305. // Update certificate and key
  16306. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  16307. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  16308. X509_free(cert);
  16309. EVP_PKEY_free(key);
  16310. return ret;
  16311. }
  16312. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16313. if (!ctx || !ca_pem) { return false; }
  16314. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16315. // Create new X509_STORE from PEM
  16316. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  16317. if (!store) { return false; }
  16318. // SSL_CTX_set_cert_store takes ownership
  16319. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  16320. // Set client CA list for client certificate request
  16321. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  16322. if (ca_list) {
  16323. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  16324. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  16325. }
  16326. return true;
  16327. }
  16328. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16329. if (!ctx) { return false; }
  16330. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16331. impl::get_verify_callback() = std::move(callback);
  16332. if (impl::get_verify_callback()) {
  16333. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  16334. } else {
  16335. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  16336. }
  16337. return true;
  16338. }
  16339. inline long get_verify_error(const_session_t session) {
  16340. if (!session) { return -1; }
  16341. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  16342. return SSL_get_verify_result(ssl);
  16343. }
  16344. inline std::string verify_error_string(long error_code) {
  16345. if (error_code == X509_V_OK) { return ""; }
  16346. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  16347. return str ? str : "unknown error";
  16348. }
  16349. } // namespace tls
  16350. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  16351. /*
  16352. * Group 9: TLS abstraction layer - Mbed TLS backend
  16353. */
  16354. /*
  16355. * Mbed TLS Backend Implementation
  16356. */
  16357. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16358. namespace tls {
  16359. namespace impl {
  16360. // Mbed TLS session wrapper
  16361. struct MbedTlsSession {
  16362. mbedtls_ssl_context ssl;
  16363. socket_t sock = INVALID_SOCKET;
  16364. std::string hostname; // For client: set via set_sni
  16365. std::string sni_hostname; // For server: received from client via SNI callback
  16366. // Mbed TLS has no SSL_peek() equivalent, so is_peer_closed() must probe with
  16367. // a real 1-byte mbedtls_ssl_read(). If that probe lands on application data
  16368. // (e.g. a response that arrived while this side was still in its post-write
  16369. // check), the byte is pushed back here and served by the next read().
  16370. unsigned char peeked_byte = 0;
  16371. bool has_peeked_byte = false;
  16372. // Set by set_sni() when the caller disabled hostname verification, so the
  16373. // verify callback can clear the CN/SAN mismatch flag while still enforcing
  16374. // the rest of the chain (Mbed TLS ties SNI and identity checking together;
  16375. // OpenSSL and wolfSSL keep them independent).
  16376. bool suppress_hostname_mismatch = false;
  16377. // Copied from the owning MbedTlsContext at creation. set_sni() uses this to
  16378. // decide which verify callback to install when hostname verification is
  16379. // disabled: mbedtls_verify_callback() when a user callback is genuinely
  16380. // wired for this context, or a self-contained one otherwise, so a session
  16381. // that never opted into a callback never consults the process-wide
  16382. // set_verify_callback() slot (which some other, unrelated client may have
  16383. // populated).
  16384. bool has_verify_callback = false;
  16385. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  16386. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  16387. MbedTlsSession(const MbedTlsSession &) = delete;
  16388. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  16389. };
  16390. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  16391. // queue)
  16392. inline int &mbedtls_last_error() {
  16393. static thread_local int err = 0;
  16394. return err;
  16395. }
  16396. // Helper to map Mbed TLS error to ErrorCode
  16397. inline ErrorCode map_mbedtls_error(int ret, int &out_errno,
  16398. uint32_t verify_flags) {
  16399. if (ret == 0) { return ErrorCode::Success; }
  16400. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  16401. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  16402. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  16403. return ErrorCode::PeerClosed;
  16404. }
  16405. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  16406. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  16407. out_errno = errno;
  16408. return ErrorCode::SyscallError;
  16409. }
  16410. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  16411. // Unlike OpenSSL/wolfSSL, Mbed TLS folds the CN/SAN identity check into
  16412. // the handshake's chain verification (see set_sni()); a mismatch there
  16413. // is reported the same way as any other verify_flags bit. Report it as
  16414. // HostnameMismatch, matching the other backends and the post-handshake
  16415. // identity check below, but only when naming is the sole problem -
  16416. // if the chain itself is also untrusted/expired/etc., that takes
  16417. // priority over the naming detail.
  16418. if (verify_flags == static_cast<uint32_t>(hostname_mismatch_code())) {
  16419. return ErrorCode::HostnameMismatch;
  16420. }
  16421. return ErrorCode::CertVerifyFailed;
  16422. }
  16423. return ErrorCode::Fatal;
  16424. }
  16425. // Populates a TlsError from a failed (non-zero) mbedtls_ssl_handshake()
  16426. // return value, including the verify-flags-dependent HostnameMismatch
  16427. // mapping; shared by connect() and connect_nonblocking() so the
  16428. // backend_code policy for that mapping only lives in one place.
  16429. inline void fill_mbedtls_tls_error(TlsError &err, mbedtls_ssl_context &ssl,
  16430. int ret) {
  16431. auto verify_flags = mbedtls_ssl_get_verify_result(&ssl);
  16432. err.code = map_mbedtls_error(ret, err.sys_errno, verify_flags);
  16433. err.backend_code = err.code == ErrorCode::HostnameMismatch
  16434. ? static_cast<uint64_t>(verify_flags)
  16435. : static_cast<uint64_t>(-ret);
  16436. }
  16437. // A TLS 1.3 NewSessionTicket (signaled by default on Mbed TLS 4.x) is a
  16438. // non-fatal notification delivered between records, not an error and not
  16439. // application data, so I/O calls that see it should just be retried. Kept in
  16440. // one helper so the retry loops keep an intact "do { } while (...)" instead of
  16441. // splitting the closing brace across an #if.
  16442. inline bool mbedtls_is_session_ticket(int ret) {
  16443. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  16444. return ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
  16445. #else
  16446. (void)ret;
  16447. return false;
  16448. #endif
  16449. }
  16450. // BIO-like send callback for Mbed TLS
  16451. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  16452. size_t len) {
  16453. auto sock = *static_cast<socket_t *>(ctx);
  16454. #ifdef _WIN32
  16455. auto ret =
  16456. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  16457. if (ret == SOCKET_ERROR) {
  16458. int err = WSAGetLastError();
  16459. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  16460. return MBEDTLS_ERR_NET_SEND_FAILED;
  16461. }
  16462. #else
  16463. auto ret = send(sock, buf, len, 0);
  16464. if (ret < 0) {
  16465. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  16466. return MBEDTLS_ERR_SSL_WANT_WRITE;
  16467. }
  16468. return MBEDTLS_ERR_NET_SEND_FAILED;
  16469. }
  16470. #endif
  16471. return static_cast<int>(ret);
  16472. }
  16473. // BIO-like recv callback for Mbed TLS
  16474. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  16475. auto sock = *static_cast<socket_t *>(ctx);
  16476. #ifdef _WIN32
  16477. auto ret =
  16478. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  16479. if (ret == SOCKET_ERROR) {
  16480. int err = WSAGetLastError();
  16481. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  16482. return MBEDTLS_ERR_NET_RECV_FAILED;
  16483. }
  16484. #else
  16485. auto ret = recv(sock, buf, len, 0);
  16486. if (ret < 0) {
  16487. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  16488. return MBEDTLS_ERR_SSL_WANT_READ;
  16489. }
  16490. return MBEDTLS_ERR_NET_RECV_FAILED;
  16491. }
  16492. #endif
  16493. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  16494. return static_cast<int>(ret);
  16495. }
  16496. // MbedTlsContext constructor/destructor implementations
  16497. inline MbedTlsContext::MbedTlsContext() {
  16498. mbedtls_ssl_config_init(&conf);
  16499. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16500. mbedtls_entropy_init(&entropy);
  16501. mbedtls_ctr_drbg_init(&ctr_drbg);
  16502. #endif
  16503. mbedtls_x509_crt_init(&ca_chain);
  16504. mbedtls_x509_crt_init(&own_cert);
  16505. mbedtls_pk_init(&own_key);
  16506. }
  16507. inline MbedTlsContext::~MbedTlsContext() {
  16508. mbedtls_pk_free(&own_key);
  16509. mbedtls_x509_crt_free(&own_cert);
  16510. mbedtls_x509_crt_free(&ca_chain);
  16511. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16512. mbedtls_ctr_drbg_free(&ctr_drbg);
  16513. mbedtls_entropy_free(&entropy);
  16514. #endif
  16515. mbedtls_ssl_config_free(&conf);
  16516. }
  16517. // Thread-local storage for SNI captured during handshake
  16518. // This is needed because the SNI callback doesn't have a way to pass
  16519. // session-specific data before the session is fully set up
  16520. inline std::string &mbedpending_sni() {
  16521. static thread_local std::string sni;
  16522. return sni;
  16523. }
  16524. // SNI callback for Mbed TLS server to capture client's SNI hostname
  16525. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  16526. const unsigned char *name, size_t name_len) {
  16527. (void)p_ctx;
  16528. (void)ssl;
  16529. // Store SNI name in thread-local storage
  16530. // It will be retrieved and stored in the session after handshake
  16531. if (name && name_len > 0) {
  16532. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  16533. } else {
  16534. mbedpending_sni().clear();
  16535. }
  16536. return 0; // Accept any SNI
  16537. }
  16538. inline void mbedtls_clear_cn_mismatch(uint32_t *flags) {
  16539. *flags &= ~static_cast<uint32_t>(hostname_mismatch_code());
  16540. }
  16541. // Verify callback used when hostname verification is disabled for a session
  16542. // that has no user-supplied verify callback of its own (MbedTlsSession::
  16543. // has_verify_callback is false). Deliberately does not consult
  16544. // get_verify_callback(): that slot is process-wide, so reading it here would
  16545. // pick up whatever another, unrelated client last installed there.
  16546. inline int mbedtls_mask_hostname_mismatch_callback(void *data,
  16547. mbedtls_x509_crt *, int,
  16548. uint32_t *flags) {
  16549. (void)data;
  16550. mbedtls_clear_cn_mismatch(flags);
  16551. return 0;
  16552. }
  16553. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  16554. int cert_depth, uint32_t *flags);
  16555. // MbedTLS verify callback wrapper
  16556. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  16557. int cert_depth, uint32_t *flags) {
  16558. // data points to the MbedTlsSession
  16559. auto *session = static_cast<MbedTlsSession *>(data);
  16560. // set_sni() disabled hostname verification for this session: drop the
  16561. // CN/SAN mismatch flag so it doesn't fail the chain check below, mirroring
  16562. // the OpenSSL/wolfSSL backends where identity checking is independent of
  16563. // SNI. The final pass/fail decision still comes from the remaining flags
  16564. // (or, below, from the user's own verify callback).
  16565. if (session && session->suppress_hostname_mismatch) {
  16566. mbedtls_clear_cn_mismatch(flags);
  16567. }
  16568. auto &callback = get_verify_callback();
  16569. if (!callback) { return 0; } // Continue with default verification
  16570. // Build context
  16571. VerifyContext verify_ctx;
  16572. verify_ctx.session = static_cast<session_t>(session);
  16573. verify_ctx.cert = static_cast<cert_t>(crt);
  16574. verify_ctx.depth = cert_depth;
  16575. verify_ctx.preverify_ok = (*flags == 0);
  16576. verify_ctx.error_code = static_cast<long>(*flags);
  16577. // Convert Mbed TLS flags to error string
  16578. static thread_local char error_buf[256];
  16579. if (*flags != 0) {
  16580. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  16581. verify_ctx.error_string = error_buf;
  16582. } else {
  16583. verify_ctx.error_string = nullptr;
  16584. }
  16585. bool accepted = callback(verify_ctx);
  16586. if (accepted) {
  16587. *flags = 0; // Clear all error flags
  16588. return 0;
  16589. }
  16590. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  16591. }
  16592. } // namespace impl
  16593. inline ctx_t create_client_context() {
  16594. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  16595. if (!ctx) { return nullptr; }
  16596. ctx->is_server = false;
  16597. #ifdef CPPHTTPLIB_MBEDTLS_V4
  16598. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  16599. if (!detail::ensure_mbedtls_psa_crypto()) {
  16600. delete ctx;
  16601. return nullptr;
  16602. }
  16603. int ret;
  16604. #else
  16605. // Seed the random number generator
  16606. const char *pers = "httplib_client";
  16607. int ret = mbedtls_ctr_drbg_seed(
  16608. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  16609. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  16610. if (ret != 0) {
  16611. impl::mbedtls_last_error() = ret;
  16612. delete ctx;
  16613. return nullptr;
  16614. }
  16615. #endif
  16616. // Set up SSL config for client
  16617. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  16618. MBEDTLS_SSL_TRANSPORT_STREAM,
  16619. MBEDTLS_SSL_PRESET_DEFAULT);
  16620. if (ret != 0) {
  16621. impl::mbedtls_last_error() = ret;
  16622. delete ctx;
  16623. return nullptr;
  16624. }
  16625. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16626. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  16627. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  16628. #endif
  16629. // Default: verify peer certificate
  16630. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16631. // Set minimum TLS version to 1.2
  16632. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16633. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16634. #else
  16635. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16636. MBEDTLS_SSL_MINOR_VERSION_3);
  16637. #endif
  16638. return static_cast<ctx_t>(ctx);
  16639. }
  16640. inline ctx_t create_server_context() {
  16641. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  16642. if (!ctx) { return nullptr; }
  16643. ctx->is_server = true;
  16644. #ifdef CPPHTTPLIB_MBEDTLS_V4
  16645. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  16646. if (!detail::ensure_mbedtls_psa_crypto()) {
  16647. delete ctx;
  16648. return nullptr;
  16649. }
  16650. int ret;
  16651. #else
  16652. // Seed the random number generator
  16653. const char *pers = "httplib_server";
  16654. int ret = mbedtls_ctr_drbg_seed(
  16655. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  16656. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  16657. if (ret != 0) {
  16658. impl::mbedtls_last_error() = ret;
  16659. delete ctx;
  16660. return nullptr;
  16661. }
  16662. #endif
  16663. // Set up SSL config for server
  16664. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  16665. MBEDTLS_SSL_TRANSPORT_STREAM,
  16666. MBEDTLS_SSL_PRESET_DEFAULT);
  16667. if (ret != 0) {
  16668. impl::mbedtls_last_error() = ret;
  16669. delete ctx;
  16670. return nullptr;
  16671. }
  16672. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16673. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  16674. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  16675. #endif
  16676. // Default: don't verify client
  16677. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  16678. // Set minimum TLS version to 1.2
  16679. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16680. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16681. #else
  16682. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16683. MBEDTLS_SSL_MINOR_VERSION_3);
  16684. #endif
  16685. // Set SNI callback to capture client's SNI hostname
  16686. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  16687. return static_cast<ctx_t>(ctx);
  16688. }
  16689. inline void free_context(ctx_t ctx) {
  16690. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  16691. }
  16692. inline bool set_min_version(ctx_t ctx, Version version) {
  16693. if (!ctx) { return false; }
  16694. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16695. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16696. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  16697. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  16698. if (version >= Version::TLS1_3) {
  16699. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  16700. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  16701. #endif
  16702. }
  16703. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  16704. #else
  16705. // Mbed TLS 2.x uses major/minor version numbers
  16706. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  16707. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  16708. if (version >= Version::TLS1_3) {
  16709. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  16710. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  16711. #else
  16712. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  16713. #endif
  16714. }
  16715. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  16716. #endif
  16717. return true;
  16718. }
  16719. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16720. if (!ctx || !pem) { return false; }
  16721. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16722. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  16723. // Add null terminator if not present
  16724. std::string pem_str(pem, len);
  16725. int ret = mbedtls_x509_crt_parse(
  16726. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  16727. pem_str.size() + 1);
  16728. if (ret != 0) {
  16729. impl::mbedtls_last_error() = ret;
  16730. return false;
  16731. }
  16732. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  16733. return true;
  16734. }
  16735. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16736. if (!ctx || !file_path) { return false; }
  16737. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16738. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  16739. if (ret != 0) {
  16740. impl::mbedtls_last_error() = ret;
  16741. return false;
  16742. }
  16743. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  16744. return true;
  16745. }
  16746. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16747. if (!ctx || !dir_path) { return false; }
  16748. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16749. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  16750. if (ret < 0) { // Returns number of certs on success, negative on error
  16751. impl::mbedtls_last_error() = ret;
  16752. return false;
  16753. }
  16754. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  16755. return true;
  16756. }
  16757. inline bool load_system_certs(ctx_t ctx) {
  16758. if (!ctx) { return false; }
  16759. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16760. bool loaded = false;
  16761. #ifdef _WIN32
  16762. loaded = impl::enumerate_windows_system_certs(
  16763. [&](const unsigned char *data, size_t len) {
  16764. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  16765. });
  16766. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16767. loaded = impl::enumerate_macos_keychain_certs(
  16768. [&](const unsigned char *data, size_t len) {
  16769. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  16770. });
  16771. #else
  16772. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16773. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  16774. loaded = true;
  16775. break;
  16776. }
  16777. }
  16778. if (!loaded) {
  16779. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16780. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  16781. loaded = true;
  16782. break;
  16783. }
  16784. }
  16785. }
  16786. #endif
  16787. if (loaded) {
  16788. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  16789. }
  16790. return loaded;
  16791. }
  16792. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16793. const char *password) {
  16794. if (!ctx || !cert || !key) { return false; }
  16795. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16796. // Parse certificate
  16797. std::string cert_str(cert);
  16798. int ret = mbedtls_x509_crt_parse(
  16799. &mctx->own_cert,
  16800. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  16801. cert_str.size() + 1);
  16802. if (ret != 0) {
  16803. impl::mbedtls_last_error() = ret;
  16804. return false;
  16805. }
  16806. // Parse private key
  16807. std::string key_str(key);
  16808. const unsigned char *pwd =
  16809. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  16810. size_t pwd_len = password ? strlen(password) : 0;
  16811. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  16812. ret = mbedtls_pk_parse_key(
  16813. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  16814. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  16815. &mctx->ctr_drbg);
  16816. #else
  16817. ret = mbedtls_pk_parse_key(
  16818. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  16819. key_str.size() + 1, pwd, pwd_len);
  16820. #endif
  16821. if (ret != 0) {
  16822. impl::mbedtls_last_error() = ret;
  16823. return false;
  16824. }
  16825. // Verify that the certificate and private key match.
  16826. // Mbed TLS 4.x: mbedtls_pk_check_pair() reports a spurious mismatch for
  16827. // PSA-backed keys, so skip it and let the handshake surface a real mismatch.
  16828. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16829. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16830. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  16831. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  16832. #else
  16833. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  16834. #endif
  16835. if (ret != 0) {
  16836. impl::mbedtls_last_error() = ret;
  16837. return false;
  16838. }
  16839. #endif
  16840. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  16841. if (ret != 0) {
  16842. impl::mbedtls_last_error() = ret;
  16843. return false;
  16844. }
  16845. return true;
  16846. }
  16847. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16848. const char *key_path, const char *password) {
  16849. if (!ctx || !cert_path || !key_path) { return false; }
  16850. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16851. // Parse certificate file
  16852. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  16853. if (ret != 0) {
  16854. impl::mbedtls_last_error() = ret;
  16855. return false;
  16856. }
  16857. // Parse private key file
  16858. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  16859. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  16860. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  16861. #else
  16862. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  16863. #endif
  16864. if (ret != 0) {
  16865. impl::mbedtls_last_error() = ret;
  16866. return false;
  16867. }
  16868. // Verify that the certificate and private key match.
  16869. // Mbed TLS 4.x: see set_client_cert() — skip the spurious check_pair.
  16870. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16871. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16872. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  16873. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  16874. #else
  16875. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  16876. #endif
  16877. if (ret != 0) {
  16878. impl::mbedtls_last_error() = ret;
  16879. return false;
  16880. }
  16881. #endif
  16882. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  16883. if (ret != 0) {
  16884. impl::mbedtls_last_error() = ret;
  16885. return false;
  16886. }
  16887. return true;
  16888. }
  16889. inline void set_verify_client(ctx_t ctx, bool require) {
  16890. if (!ctx) { return; }
  16891. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16892. mctx->verify_client = require;
  16893. if (require) {
  16894. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16895. } else {
  16896. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  16897. // is called (matching OpenSSL behavior). Otherwise use NONE.
  16898. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  16899. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  16900. : MBEDTLS_SSL_VERIFY_NONE);
  16901. }
  16902. }
  16903. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16904. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16905. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  16906. auto session = new (std::nothrow) impl::MbedTlsSession();
  16907. if (!session) { return nullptr; }
  16908. session->sock = sock;
  16909. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  16910. if (ret != 0) {
  16911. impl::mbedtls_last_error() = ret;
  16912. delete session;
  16913. return nullptr;
  16914. }
  16915. // Explicitly opt out of in-handshake hostname verification by default;
  16916. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  16917. // fails outright when no hostname was set. set_sni() installs the real
  16918. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  16919. // caller verifies the certificate identity post-handshake via
  16920. // verify_hostname().
  16921. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  16922. // Set BIO callbacks
  16923. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  16924. impl::mbedtls_net_recv_cb, nullptr);
  16925. // Set per-session verify callback with session pointer if callback is
  16926. // registered
  16927. session->has_verify_callback = mctx->has_verify_callback;
  16928. if (mctx->has_verify_callback) {
  16929. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  16930. session);
  16931. }
  16932. return static_cast<session_t>(session);
  16933. }
  16934. inline void free_session(session_t session) {
  16935. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  16936. }
  16937. inline bool set_sni(session_t session, const char *hostname,
  16938. bool verify_hostname) {
  16939. if (!session || !hostname) { return false; }
  16940. auto msession = static_cast<impl::MbedTlsSession *>(session);
  16941. // mbedtls_ssl_set_hostname() both sends the SNI extension and binds the
  16942. // handshake-time CN/SAN check to `hostname`; the two can't be requested
  16943. // independently, so a disabled hostname check is handled below by masking
  16944. // the resulting mismatch flag instead of skipping this call.
  16945. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  16946. if (ret != 0) {
  16947. impl::mbedtls_last_error() = ret;
  16948. return false;
  16949. }
  16950. msession->hostname = hostname;
  16951. if (!verify_hostname) {
  16952. msession->suppress_hostname_mismatch = true;
  16953. // If a user verify callback is already wired for this session,
  16954. // mbedtls_verify_callback() masks the mismatch flag itself before
  16955. // consulting it (see suppress_hostname_mismatch above) - reinstalling it
  16956. // here would be redundant. Otherwise install the self-contained masking
  16957. // callback, which never touches the process-wide callback slot.
  16958. if (!msession->has_verify_callback) {
  16959. mbedtls_ssl_set_verify(&msession->ssl,
  16960. impl::mbedtls_mask_hostname_mismatch_callback,
  16961. msession);
  16962. }
  16963. }
  16964. return true;
  16965. }
  16966. inline TlsError connect(session_t session) {
  16967. TlsError err;
  16968. if (!session) {
  16969. err.code = ErrorCode::Fatal;
  16970. return err;
  16971. }
  16972. auto msession = static_cast<impl::MbedTlsSession *>(session);
  16973. int ret;
  16974. do {
  16975. ret = mbedtls_ssl_handshake(&msession->ssl);
  16976. } while (impl::mbedtls_is_session_ticket(ret));
  16977. if (ret == 0) {
  16978. err.code = ErrorCode::Success;
  16979. } else {
  16980. impl::fill_mbedtls_tls_error(err, msession->ssl, ret);
  16981. impl::mbedtls_last_error() = ret;
  16982. }
  16983. return err;
  16984. }
  16985. inline TlsError accept(session_t session) {
  16986. // Same as connect for Mbed TLS - handshake works for both client and server
  16987. auto result = connect(session);
  16988. // After successful handshake, capture SNI from thread-local storage
  16989. if (result.code == ErrorCode::Success && session) {
  16990. auto msession = static_cast<impl::MbedTlsSession *>(session);
  16991. msession->sni_hostname = std::move(impl::mbedpending_sni());
  16992. impl::mbedpending_sni().clear();
  16993. }
  16994. return result;
  16995. }
  16996. inline bool connect_nonblocking(session_t session, socket_t sock,
  16997. time_t timeout_sec, time_t timeout_usec,
  16998. TlsError *err) {
  16999. if (!session) {
  17000. if (err) { err->code = ErrorCode::Fatal; }
  17001. return false;
  17002. }
  17003. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17004. // Set socket to non-blocking mode
  17005. detail::set_nonblocking(sock, true);
  17006. auto cleanup =
  17007. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17008. int ret;
  17009. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  17010. // Non-fatal TLS 1.3 ticket; retry immediately.
  17011. if (impl::mbedtls_is_session_ticket(ret)) { continue; }
  17012. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  17013. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  17014. continue;
  17015. }
  17016. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  17017. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  17018. continue;
  17019. }
  17020. }
  17021. // TlsError or timeout
  17022. if (err) { impl::fill_mbedtls_tls_error(*err, msession->ssl, ret); }
  17023. impl::mbedtls_last_error() = ret;
  17024. return false;
  17025. }
  17026. if (err) { err->code = ErrorCode::Success; }
  17027. return true;
  17028. }
  17029. inline bool accept_nonblocking(session_t session, socket_t sock,
  17030. time_t timeout_sec, time_t timeout_usec,
  17031. TlsError *err) {
  17032. // Same implementation as connect for Mbed TLS
  17033. bool result =
  17034. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  17035. // After successful handshake, capture SNI from thread-local storage
  17036. if (result && session) {
  17037. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17038. msession->sni_hostname = std::move(impl::mbedpending_sni());
  17039. impl::mbedpending_sni().clear();
  17040. }
  17041. return result;
  17042. }
  17043. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  17044. if (!session || !buf) {
  17045. err.code = ErrorCode::Fatal;
  17046. return -1;
  17047. }
  17048. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17049. // Serve a byte consumed by the is_peer_closed() probe before reading more.
  17050. if (msession->has_peeked_byte) {
  17051. if (len == 0) { return 0; }
  17052. auto p = static_cast<unsigned char *>(buf);
  17053. p[0] = msession->peeked_byte;
  17054. msession->has_peeked_byte = false;
  17055. size_t n = 1;
  17056. // Top up with any already-decrypted bytes without risking a block.
  17057. if (len > 1 && mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17058. int extra = mbedtls_ssl_read(&msession->ssl, p + 1, len - 1);
  17059. if (extra > 0) { n += static_cast<size_t>(extra); }
  17060. }
  17061. err.code = ErrorCode::Success;
  17062. return static_cast<ssize_t>(n);
  17063. }
  17064. int ret;
  17065. do {
  17066. ret = mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf),
  17067. len);
  17068. } while (impl::mbedtls_is_session_ticket(ret));
  17069. if (ret > 0) {
  17070. err.code = ErrorCode::Success;
  17071. return static_cast<ssize_t>(ret);
  17072. }
  17073. if (ret == 0) {
  17074. err.code = ErrorCode::PeerClosed;
  17075. return 0;
  17076. }
  17077. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17078. err.backend_code = static_cast<uint64_t>(-ret);
  17079. impl::mbedtls_last_error() = ret;
  17080. // mbedTLS signals a clean close_notify via a negative error code rather
  17081. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  17082. if (err.code == ErrorCode::PeerClosed) { return 0; }
  17083. return -1;
  17084. }
  17085. inline ssize_t write(session_t session, const void *buf, size_t len,
  17086. TlsError &err) {
  17087. if (!session || !buf) {
  17088. err.code = ErrorCode::Fatal;
  17089. return -1;
  17090. }
  17091. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17092. int ret;
  17093. do {
  17094. ret = mbedtls_ssl_write(&msession->ssl,
  17095. static_cast<const unsigned char *>(buf), len);
  17096. } while (impl::mbedtls_is_session_ticket(ret));
  17097. if (ret > 0) {
  17098. err.code = ErrorCode::Success;
  17099. return static_cast<ssize_t>(ret);
  17100. }
  17101. if (ret == 0) {
  17102. err.code = ErrorCode::PeerClosed;
  17103. return 0;
  17104. }
  17105. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17106. err.backend_code = static_cast<uint64_t>(-ret);
  17107. impl::mbedtls_last_error() = ret;
  17108. return -1;
  17109. }
  17110. inline int pending(const_session_t session) {
  17111. if (!session) { return 0; }
  17112. auto msession =
  17113. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17114. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl)) +
  17115. (msession->has_peeked_byte ? 1 : 0);
  17116. }
  17117. inline void shutdown(session_t session, bool graceful) {
  17118. if (!session) { return; }
  17119. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17120. if (graceful) {
  17121. // Try to send close_notify, but don't block forever
  17122. int ret;
  17123. int attempts = 0;
  17124. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  17125. attempts < 3) {
  17126. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  17127. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  17128. break;
  17129. }
  17130. attempts++;
  17131. }
  17132. }
  17133. }
  17134. inline bool is_peer_closed(session_t session, socket_t sock) {
  17135. if (!session || sock == INVALID_SOCKET) { return true; }
  17136. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17137. // Check if there's already decrypted or pushed-back data available.
  17138. // If so, the connection is definitely alive.
  17139. if (msession->has_peeked_byte ||
  17140. mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17141. return false;
  17142. }
  17143. // Set socket to non-blocking to avoid blocking on read
  17144. detail::set_nonblocking(sock, true);
  17145. auto cleanup =
  17146. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17147. // Probe with a 1-byte read (Mbed TLS has no peek API). If the probe lands
  17148. // on application data — e.g. a response that already arrived — push the
  17149. // byte back so the next read() delivers it instead of losing it.
  17150. unsigned char buf;
  17151. int ret;
  17152. do {
  17153. ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  17154. } while (impl::mbedtls_is_session_ticket(ret));
  17155. // If we got data or WANT_READ (would block), connection is alive
  17156. if (ret > 0) {
  17157. msession->peeked_byte = buf;
  17158. msession->has_peeked_byte = true;
  17159. return false;
  17160. }
  17161. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  17162. // If we get a peer close notify or a connection reset, the peer is closed
  17163. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  17164. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  17165. }
  17166. inline cert_t get_peer_cert(const_session_t session) {
  17167. if (!session) { return nullptr; }
  17168. auto msession =
  17169. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17170. // Mbed TLS returns a pointer to the internal peer cert chain.
  17171. // WARNING: This pointer is only valid while the session is active.
  17172. // Do not use the certificate after calling free_session().
  17173. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  17174. return const_cast<mbedtls_x509_crt *>(cert);
  17175. }
  17176. inline void free_cert(cert_t cert) {
  17177. // Mbed TLS: peer certificate is owned by the SSL context.
  17178. // No-op here, but callers should still call this for cross-backend
  17179. // portability.
  17180. (void)cert;
  17181. }
  17182. inline bool verify_hostname(cert_t cert, const char *hostname) {
  17183. if (!cert || !hostname) { return false; }
  17184. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  17185. std::string host_str(hostname);
  17186. // Check if hostname is an IP address (IPv4 or IPv6)
  17187. unsigned char ip_bytes[16];
  17188. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  17189. auto is_ip = ip_len > 0;
  17190. // Check Subject Alternative Names (SAN)
  17191. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  17192. // - DNS names: raw string bytes
  17193. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  17194. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  17195. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  17196. const unsigned char *p = san->buf.p;
  17197. size_t len = san->buf.len;
  17198. if (is_ip) {
  17199. // For an IP host, only a matching iPAddress SAN of the same family
  17200. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  17201. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  17202. } else {
  17203. // Check if this SAN is a DNS name (printable ASCII string)
  17204. bool is_dns = len > 0;
  17205. for (size_t i = 0; i < len && is_dns; i++) {
  17206. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  17207. }
  17208. if (is_dns) {
  17209. std::string san_name(reinterpret_cast<const char *>(p), len);
  17210. if (detail::match_hostname(san_name, host_str)) { return true; }
  17211. }
  17212. }
  17213. san = san->next;
  17214. }
  17215. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  17216. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  17217. // the OpenSSL backend's X509_check_ip behaves the same way).
  17218. if (!is_ip) {
  17219. char cn[256];
  17220. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  17221. if (ret > 0) {
  17222. std::string cn_str(cn);
  17223. // Look for "CN=" in the DN string
  17224. size_t cn_pos = cn_str.find("CN=");
  17225. if (cn_pos != std::string::npos) {
  17226. size_t start = cn_pos + 3;
  17227. size_t end = cn_str.find(',', start);
  17228. std::string cn_value =
  17229. cn_str.substr(start, end == std::string::npos ? end : end - start);
  17230. if (detail::match_hostname(cn_value, host_str)) { return true; }
  17231. }
  17232. }
  17233. }
  17234. return false;
  17235. }
  17236. inline uint64_t hostname_mismatch_code() {
  17237. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  17238. }
  17239. inline long get_verify_result(const_session_t session) {
  17240. if (!session) { return -1; }
  17241. auto msession =
  17242. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17243. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  17244. // Return 0 (X509_V_OK equivalent) if verification passed
  17245. return flags == 0 ? 0 : static_cast<long>(flags);
  17246. }
  17247. inline std::string get_cert_subject_cn(cert_t cert) {
  17248. if (!cert) return "";
  17249. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17250. // Find the CN in the subject
  17251. const mbedtls_x509_name *name = &x509->subject;
  17252. while (name != nullptr) {
  17253. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  17254. return std::string(reinterpret_cast<const char *>(name->val.p),
  17255. name->val.len);
  17256. }
  17257. name = name->next;
  17258. }
  17259. return "";
  17260. }
  17261. inline std::string get_cert_issuer_name(cert_t cert) {
  17262. if (!cert) return "";
  17263. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17264. // Build a human-readable issuer name string
  17265. char buf[512];
  17266. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  17267. if (ret < 0) return "";
  17268. return std::string(buf);
  17269. }
  17270. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  17271. sans.clear();
  17272. if (!cert) return false;
  17273. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17274. // Parse the Subject Alternative Name extension
  17275. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  17276. while (cur != nullptr) {
  17277. if (cur->buf.len > 0) {
  17278. // Mbed TLS stores SAN as ASN.1 sequences
  17279. // The tag byte indicates the type
  17280. const unsigned char *p = cur->buf.p;
  17281. size_t len = cur->buf.len;
  17282. // First byte is the tag
  17283. unsigned char tag = *p;
  17284. p++;
  17285. len--;
  17286. // Parse length (simple single-byte length assumed)
  17287. if (len > 0 && *p < 0x80) {
  17288. size_t value_len = *p;
  17289. p++;
  17290. len--;
  17291. if (value_len <= len) {
  17292. SanEntry entry;
  17293. // ASN.1 context tags for GeneralName
  17294. switch (tag & 0x1F) {
  17295. case 2: // dNSName
  17296. entry.type = SanType::DNS;
  17297. entry.value =
  17298. std::string(reinterpret_cast<const char *>(p), value_len);
  17299. break;
  17300. case 7: // iPAddress
  17301. entry.type = SanType::IP;
  17302. if (value_len == 4) {
  17303. // IPv4
  17304. char buf[16];
  17305. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  17306. entry.value = buf;
  17307. } else if (value_len == 16) {
  17308. // IPv6
  17309. char buf[64];
  17310. snprintf(buf, sizeof(buf),
  17311. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  17312. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  17313. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  17314. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  17315. entry.value = buf;
  17316. }
  17317. break;
  17318. case 1: // rfc822Name (email)
  17319. entry.type = SanType::EMAIL;
  17320. entry.value =
  17321. std::string(reinterpret_cast<const char *>(p), value_len);
  17322. break;
  17323. case 6: // uniformResourceIdentifier
  17324. entry.type = SanType::URI;
  17325. entry.value =
  17326. std::string(reinterpret_cast<const char *>(p), value_len);
  17327. break;
  17328. default: entry.type = SanType::OTHER; break;
  17329. }
  17330. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17331. }
  17332. }
  17333. }
  17334. cur = cur->next;
  17335. }
  17336. return true;
  17337. }
  17338. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17339. time_t &not_after) {
  17340. if (!cert) return false;
  17341. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17342. // Convert mbedtls_x509_time to time_t
  17343. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  17344. struct tm tm_time = {};
  17345. tm_time.tm_year = t.year - 1900;
  17346. tm_time.tm_mon = t.mon - 1;
  17347. tm_time.tm_mday = t.day;
  17348. tm_time.tm_hour = t.hour;
  17349. tm_time.tm_min = t.min;
  17350. tm_time.tm_sec = t.sec;
  17351. #ifdef _WIN32
  17352. return _mkgmtime(&tm_time);
  17353. #else
  17354. return timegm(&tm_time);
  17355. #endif
  17356. };
  17357. not_before = to_time_t(x509->valid_from);
  17358. not_after = to_time_t(x509->valid_to);
  17359. return true;
  17360. }
  17361. inline std::string get_cert_serial(cert_t cert) {
  17362. if (!cert) return "";
  17363. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17364. // Convert serial number to hex string
  17365. std::string result;
  17366. result.reserve(x509->serial.len * 2);
  17367. for (size_t i = 0; i < x509->serial.len; i++) {
  17368. char hex[3];
  17369. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  17370. result += hex;
  17371. }
  17372. return result;
  17373. }
  17374. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17375. if (!cert) return false;
  17376. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  17377. if (!crt->raw.p || crt->raw.len == 0) return false;
  17378. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  17379. return true;
  17380. }
  17381. inline const char *get_sni(const_session_t session) {
  17382. if (!session) return nullptr;
  17383. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  17384. // For server: return SNI received from client during handshake
  17385. if (!msession->sni_hostname.empty()) {
  17386. return msession->sni_hostname.c_str();
  17387. }
  17388. // For client: return the hostname set via set_sni
  17389. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  17390. return nullptr;
  17391. }
  17392. inline uint64_t peek_error() {
  17393. // Mbed TLS doesn't have an error queue, return the last error
  17394. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  17395. }
  17396. inline uint64_t get_error() {
  17397. // Mbed TLS doesn't have an error queue, return and clear the last error
  17398. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  17399. impl::mbedtls_last_error() = 0;
  17400. return err;
  17401. }
  17402. inline std::string error_string(uint64_t code) {
  17403. char buf[256];
  17404. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  17405. return std::string(buf);
  17406. }
  17407. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17408. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  17409. if (!ca_chain) { return nullptr; }
  17410. mbedtls_x509_crt_init(ca_chain);
  17411. // mbedtls_x509_crt_parse expects null-terminated PEM
  17412. int ret = mbedtls_x509_crt_parse(ca_chain,
  17413. reinterpret_cast<const unsigned char *>(pem),
  17414. len + 1); // +1 for null terminator
  17415. if (ret != 0) {
  17416. // Try without +1 in case PEM is already null-terminated
  17417. ret = mbedtls_x509_crt_parse(
  17418. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  17419. if (ret != 0) {
  17420. mbedtls_x509_crt_free(ca_chain);
  17421. delete ca_chain;
  17422. return nullptr;
  17423. }
  17424. }
  17425. return static_cast<ca_store_t>(ca_chain);
  17426. }
  17427. inline void free_ca_store(ca_store_t store) {
  17428. if (store) {
  17429. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  17430. mbedtls_x509_crt_free(ca_chain);
  17431. delete ca_chain;
  17432. }
  17433. }
  17434. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17435. if (!ctx || !store) { return false; }
  17436. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17437. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  17438. // Free existing CA chain
  17439. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  17440. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  17441. // Copy the CA chain (deep copy)
  17442. // Parse from the raw data of the source cert
  17443. mbedtls_x509_crt *src = ca_chain;
  17444. while (src != nullptr) {
  17445. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  17446. src->raw.len);
  17447. if (ret != 0) {
  17448. free_ca_store(store);
  17449. return false;
  17450. }
  17451. src = src->next;
  17452. }
  17453. // This function takes ownership of the store; the chain was deep-copied
  17454. // above, so release the source
  17455. free_ca_store(store);
  17456. // Update the SSL config to use the new CA chain
  17457. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  17458. return true;
  17459. }
  17460. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17461. certs.clear();
  17462. if (!ctx) { return 0; }
  17463. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17464. // Iterate through the CA chain
  17465. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  17466. while (cert != nullptr && cert->raw.len > 0) {
  17467. // Create a copy of the certificate for the caller
  17468. auto *copy = new mbedtls_x509_crt;
  17469. mbedtls_x509_crt_init(copy);
  17470. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  17471. if (ret == 0) {
  17472. certs.push_back(static_cast<cert_t>(copy));
  17473. } else {
  17474. mbedtls_x509_crt_free(copy);
  17475. delete copy;
  17476. }
  17477. cert = cert->next;
  17478. }
  17479. return certs.size();
  17480. }
  17481. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17482. std::vector<std::string> names;
  17483. if (!ctx) { return names; }
  17484. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17485. // Iterate through the CA chain
  17486. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  17487. while (cert != nullptr && cert->raw.len > 0) {
  17488. char buf[512];
  17489. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  17490. if (ret > 0) { names.push_back(buf); }
  17491. cert = cert->next;
  17492. }
  17493. return names;
  17494. }
  17495. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17496. const char *key_pem, const char *password) {
  17497. if (!ctx || !cert_pem || !key_pem) { return false; }
  17498. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17499. // Free existing certificate and key
  17500. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  17501. mbedtls_pk_free(&mbed_ctx->own_key);
  17502. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  17503. mbedtls_pk_init(&mbed_ctx->own_key);
  17504. // Parse certificate PEM
  17505. int ret = mbedtls_x509_crt_parse(
  17506. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  17507. strlen(cert_pem) + 1);
  17508. if (ret != 0) {
  17509. impl::mbedtls_last_error() = ret;
  17510. return false;
  17511. }
  17512. // Parse private key PEM
  17513. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17514. ret = mbedtls_pk_parse_key(
  17515. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  17516. strlen(key_pem) + 1,
  17517. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  17518. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  17519. &mbed_ctx->ctr_drbg);
  17520. #else
  17521. ret = mbedtls_pk_parse_key(
  17522. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  17523. strlen(key_pem) + 1,
  17524. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  17525. password ? strlen(password) : 0);
  17526. #endif
  17527. if (ret != 0) {
  17528. impl::mbedtls_last_error() = ret;
  17529. return false;
  17530. }
  17531. // Configure SSL to use the new certificate and key
  17532. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  17533. &mbed_ctx->own_key);
  17534. if (ret != 0) {
  17535. impl::mbedtls_last_error() = ret;
  17536. return false;
  17537. }
  17538. return true;
  17539. }
  17540. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17541. if (!ctx || !ca_pem) { return false; }
  17542. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17543. // Free existing CA chain
  17544. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  17545. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  17546. // Parse CA PEM
  17547. int ret = mbedtls_x509_crt_parse(
  17548. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  17549. strlen(ca_pem) + 1);
  17550. if (ret != 0) {
  17551. impl::mbedtls_last_error() = ret;
  17552. return false;
  17553. }
  17554. // Update SSL config to use new CA chain
  17555. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  17556. return true;
  17557. }
  17558. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17559. if (!ctx) { return false; }
  17560. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17561. impl::get_verify_callback() = std::move(callback);
  17562. mbed_ctx->has_verify_callback =
  17563. static_cast<bool>(impl::get_verify_callback());
  17564. if (mbed_ctx->has_verify_callback) {
  17565. // Set OPTIONAL mode to ensure callback is called even when verification
  17566. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  17567. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  17568. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  17569. nullptr);
  17570. } else {
  17571. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  17572. }
  17573. return true;
  17574. }
  17575. inline long get_verify_error(const_session_t session) {
  17576. if (!session) { return -1; }
  17577. auto *msession =
  17578. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17579. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  17580. }
  17581. inline std::string verify_error_string(long error_code) {
  17582. if (error_code == 0) { return ""; }
  17583. char buf[256];
  17584. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  17585. static_cast<uint32_t>(error_code));
  17586. // Remove trailing newline if present
  17587. std::string result(buf);
  17588. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  17589. result.pop_back();
  17590. }
  17591. return result;
  17592. }
  17593. } // namespace tls
  17594. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  17595. /*
  17596. * Group 10: TLS abstraction layer - wolfSSL backend
  17597. */
  17598. /*
  17599. * wolfSSL Backend Implementation
  17600. */
  17601. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  17602. namespace tls {
  17603. namespace impl {
  17604. // wolfSSL session wrapper
  17605. struct WolfSSLSession {
  17606. WOLFSSL *ssl = nullptr;
  17607. socket_t sock = INVALID_SOCKET;
  17608. std::string hostname; // For client: set via set_sni
  17609. std::string sni_hostname; // For server: received from client via SNI callback
  17610. WolfSSLSession() = default;
  17611. ~WolfSSLSession() {
  17612. if (ssl) { wolfSSL_free(ssl); }
  17613. }
  17614. WolfSSLSession(const WolfSSLSession &) = delete;
  17615. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  17616. };
  17617. // Thread-local error code accessor for wolfSSL
  17618. inline uint64_t &wolfssl_last_error() {
  17619. static thread_local uint64_t err = 0;
  17620. return err;
  17621. }
  17622. // Helper to map wolfSSL error to ErrorCode.
  17623. // ssl_error is the value from wolfSSL_get_error().
  17624. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  17625. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  17626. int &out_errno) {
  17627. switch (ssl_error) {
  17628. case SSL_ERROR_NONE: return ErrorCode::Success;
  17629. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  17630. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  17631. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  17632. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  17633. default:
  17634. if (ssl) {
  17635. // wolfSSL stores the low-level error code as a negative value.
  17636. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  17637. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  17638. if (low_err == DOMAIN_NAME_MISMATCH) {
  17639. return ErrorCode::HostnameMismatch;
  17640. }
  17641. // Check verify result to distinguish cert verification from generic SSL
  17642. // errors.
  17643. long vr = wolfSSL_get_verify_result(ssl);
  17644. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  17645. }
  17646. return ErrorCode::Fatal;
  17647. }
  17648. }
  17649. // WolfSSLContext constructor/destructor implementations
  17650. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  17651. inline WolfSSLContext::~WolfSSLContext() {
  17652. if (ctx) { wolfSSL_CTX_free(ctx); }
  17653. }
  17654. // Thread-local storage for SNI captured during handshake
  17655. inline std::string &wolfssl_pending_sni() {
  17656. static thread_local std::string sni;
  17657. return sni;
  17658. }
  17659. // SNI callback for wolfSSL server to capture client's SNI hostname
  17660. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  17661. (void)ret;
  17662. (void)exArg;
  17663. void *name_data = nullptr;
  17664. unsigned short name_len =
  17665. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  17666. if (name_data && name_len > 0) {
  17667. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  17668. name_len);
  17669. } else {
  17670. wolfssl_pending_sni().clear();
  17671. }
  17672. return 0; // Continue regardless
  17673. }
  17674. // wolfSSL verify callback wrapper
  17675. inline int wolfssl_verify_callback(int preverify_ok,
  17676. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  17677. auto &callback = get_verify_callback();
  17678. if (!callback) { return preverify_ok; }
  17679. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  17680. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  17681. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  17682. // Get the WOLFSSL object from the X509_STORE_CTX
  17683. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  17684. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  17685. VerifyContext verify_ctx;
  17686. verify_ctx.session = static_cast<session_t>(ssl);
  17687. verify_ctx.cert = static_cast<cert_t>(cert);
  17688. verify_ctx.depth = depth;
  17689. verify_ctx.preverify_ok = (preverify_ok != 0);
  17690. verify_ctx.error_code = static_cast<long>(err);
  17691. if (err != 0) {
  17692. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  17693. } else {
  17694. verify_ctx.error_string = nullptr;
  17695. }
  17696. bool accepted = callback(verify_ctx);
  17697. return accepted ? 1 : 0;
  17698. }
  17699. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  17700. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  17701. wolfSSL_CTX_set_default_passwd_cb(
  17702. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  17703. auto *pwd = static_cast<const char *>(userdata);
  17704. if (!pwd) return 0;
  17705. auto len = static_cast<int>(strlen(pwd));
  17706. if (len > size) len = size;
  17707. memcpy(buf, pwd, static_cast<size_t>(len));
  17708. return len;
  17709. });
  17710. }
  17711. } // namespace impl
  17712. inline ctx_t create_client_context() {
  17713. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  17714. if (!ctx) { return nullptr; }
  17715. ctx->is_server = false;
  17716. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  17717. if (!method) {
  17718. delete ctx;
  17719. return nullptr;
  17720. }
  17721. ctx->ctx = wolfSSL_CTX_new(method);
  17722. if (!ctx->ctx) {
  17723. delete ctx;
  17724. return nullptr;
  17725. }
  17726. // Default: verify peer certificate
  17727. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  17728. return static_cast<ctx_t>(ctx);
  17729. }
  17730. inline ctx_t create_server_context() {
  17731. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  17732. if (!ctx) { return nullptr; }
  17733. ctx->is_server = true;
  17734. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  17735. if (!method) {
  17736. delete ctx;
  17737. return nullptr;
  17738. }
  17739. ctx->ctx = wolfSSL_CTX_new(method);
  17740. if (!ctx->ctx) {
  17741. delete ctx;
  17742. return nullptr;
  17743. }
  17744. // Default: don't verify client
  17745. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  17746. // Enable SNI on server
  17747. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  17748. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  17749. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  17750. return static_cast<ctx_t>(ctx);
  17751. }
  17752. inline void free_context(ctx_t ctx) {
  17753. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  17754. }
  17755. inline bool set_min_version(ctx_t ctx, Version version) {
  17756. if (!ctx) { return false; }
  17757. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17758. int min_ver = WOLFSSL_TLSV1_2;
  17759. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  17760. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  17761. }
  17762. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  17763. if (!ctx || !pem) { return false; }
  17764. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17765. int ret = wolfSSL_CTX_load_verify_buffer(
  17766. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  17767. static_cast<long>(len), SSL_FILETYPE_PEM);
  17768. if (ret != SSL_SUCCESS) {
  17769. impl::wolfssl_last_error() =
  17770. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17771. return false;
  17772. }
  17773. wctx->ca_pem_data_.append(pem, len);
  17774. return true;
  17775. }
  17776. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  17777. if (!ctx || !file_path) { return false; }
  17778. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17779. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  17780. if (ret != SSL_SUCCESS) {
  17781. impl::wolfssl_last_error() =
  17782. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17783. return false;
  17784. }
  17785. return true;
  17786. }
  17787. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  17788. if (!ctx || !dir_path) { return false; }
  17789. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17790. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  17791. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  17792. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  17793. // immediately. Return true even on failure since the CA file may have
  17794. // already been loaded, matching OpenSSL's lenient behavior.
  17795. (void)ret;
  17796. return true;
  17797. }
  17798. inline bool load_system_certs(ctx_t ctx) {
  17799. if (!ctx) { return false; }
  17800. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17801. bool loaded = false;
  17802. #ifdef _WIN32
  17803. loaded = impl::enumerate_windows_system_certs(
  17804. [&](const unsigned char *data, size_t len) {
  17805. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  17806. static_cast<long>(len),
  17807. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  17808. });
  17809. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  17810. loaded = impl::enumerate_macos_keychain_certs(
  17811. [&](const unsigned char *data, size_t len) {
  17812. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  17813. static_cast<long>(len),
  17814. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  17815. });
  17816. #else
  17817. for (auto path = impl::system_ca_paths(); *path; ++path) {
  17818. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  17819. SSL_SUCCESS) {
  17820. loaded = true;
  17821. break;
  17822. }
  17823. }
  17824. if (!loaded) {
  17825. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  17826. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  17827. SSL_SUCCESS) {
  17828. loaded = true;
  17829. break;
  17830. }
  17831. }
  17832. }
  17833. #endif
  17834. return loaded;
  17835. }
  17836. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  17837. const char *password) {
  17838. if (!ctx || !cert || !key) { return false; }
  17839. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17840. // Load certificate
  17841. int ret = wolfSSL_CTX_use_certificate_buffer(
  17842. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  17843. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  17844. if (ret != SSL_SUCCESS) {
  17845. impl::wolfssl_last_error() =
  17846. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17847. return false;
  17848. }
  17849. // Set password callback if password is provided
  17850. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17851. // Load private key
  17852. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17853. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  17854. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  17855. if (ret != SSL_SUCCESS) {
  17856. impl::wolfssl_last_error() =
  17857. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17858. return false;
  17859. }
  17860. // Verify that the certificate and private key match
  17861. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  17862. }
  17863. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  17864. const char *key_path, const char *password) {
  17865. if (!ctx || !cert_path || !key_path) { return false; }
  17866. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17867. // Load certificate file
  17868. int ret =
  17869. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  17870. if (ret != SSL_SUCCESS) {
  17871. impl::wolfssl_last_error() =
  17872. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17873. return false;
  17874. }
  17875. // Set password callback if password is provided
  17876. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17877. // Load private key file
  17878. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  17879. if (ret != SSL_SUCCESS) {
  17880. impl::wolfssl_last_error() =
  17881. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17882. return false;
  17883. }
  17884. // Verify that the certificate and private key match
  17885. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  17886. }
  17887. inline void set_verify_client(ctx_t ctx, bool require) {
  17888. if (!ctx) { return; }
  17889. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17890. wctx->verify_client = require;
  17891. if (require) {
  17892. wolfSSL_CTX_set_verify(
  17893. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  17894. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  17895. } else {
  17896. if (wctx->has_verify_callback) {
  17897. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17898. impl::wolfssl_verify_callback);
  17899. } else {
  17900. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  17901. }
  17902. }
  17903. }
  17904. inline session_t create_session(ctx_t ctx, socket_t sock) {
  17905. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  17906. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17907. auto session = new (std::nothrow) impl::WolfSSLSession();
  17908. if (!session) { return nullptr; }
  17909. session->sock = sock;
  17910. session->ssl = wolfSSL_new(wctx->ctx);
  17911. if (!session->ssl) {
  17912. impl::wolfssl_last_error() =
  17913. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17914. delete session;
  17915. return nullptr;
  17916. }
  17917. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  17918. return static_cast<session_t>(session);
  17919. }
  17920. inline void free_session(session_t session) {
  17921. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  17922. }
  17923. inline bool set_sni(session_t session, const char *hostname,
  17924. bool verify_hostname) {
  17925. if (!session || !hostname) { return false; }
  17926. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  17927. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  17928. static_cast<word16>(strlen(hostname)));
  17929. if (ret != WOLFSSL_SUCCESS) {
  17930. impl::wolfssl_last_error() =
  17931. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17932. return false;
  17933. }
  17934. // wolfSSL_check_domain_name binds identity checking to the handshake,
  17935. // separately from the SNI extension sent above; skip it when hostname
  17936. // verification is disabled so only the chain is checked, matching OpenSSL.
  17937. if (verify_hostname) { wolfSSL_check_domain_name(wsession->ssl, hostname); }
  17938. wsession->hostname = hostname;
  17939. return true;
  17940. }
  17941. inline TlsError connect(session_t session) {
  17942. TlsError err;
  17943. if (!session) {
  17944. err.code = ErrorCode::Fatal;
  17945. return err;
  17946. }
  17947. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  17948. int ret = wolfSSL_connect(wsession->ssl);
  17949. if (ret == SSL_SUCCESS) {
  17950. err.code = ErrorCode::Success;
  17951. } else {
  17952. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  17953. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  17954. err.backend_code = static_cast<uint64_t>(ssl_error);
  17955. impl::wolfssl_last_error() = err.backend_code;
  17956. }
  17957. return err;
  17958. }
  17959. inline TlsError accept(session_t session) {
  17960. TlsError err;
  17961. if (!session) {
  17962. err.code = ErrorCode::Fatal;
  17963. return err;
  17964. }
  17965. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  17966. int ret = wolfSSL_accept(wsession->ssl);
  17967. if (ret == SSL_SUCCESS) {
  17968. err.code = ErrorCode::Success;
  17969. // Capture SNI from thread-local storage after successful handshake
  17970. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  17971. impl::wolfssl_pending_sni().clear();
  17972. } else {
  17973. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  17974. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  17975. err.backend_code = static_cast<uint64_t>(ssl_error);
  17976. impl::wolfssl_last_error() = err.backend_code;
  17977. }
  17978. return err;
  17979. }
  17980. inline bool connect_nonblocking(session_t session, socket_t sock,
  17981. time_t timeout_sec, time_t timeout_usec,
  17982. TlsError *err) {
  17983. if (!session) {
  17984. if (err) { err->code = ErrorCode::Fatal; }
  17985. return false;
  17986. }
  17987. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  17988. // Set socket to non-blocking mode
  17989. detail::set_nonblocking(sock, true);
  17990. auto cleanup =
  17991. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17992. int ret;
  17993. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  17994. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  17995. if (ssl_error == SSL_ERROR_WANT_READ) {
  17996. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  17997. continue;
  17998. }
  17999. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18000. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18001. continue;
  18002. }
  18003. }
  18004. // Error or timeout
  18005. if (err) {
  18006. err->code =
  18007. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18008. err->backend_code = static_cast<uint64_t>(ssl_error);
  18009. }
  18010. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18011. return false;
  18012. }
  18013. if (err) { err->code = ErrorCode::Success; }
  18014. return true;
  18015. }
  18016. inline bool accept_nonblocking(session_t session, socket_t sock,
  18017. time_t timeout_sec, time_t timeout_usec,
  18018. TlsError *err) {
  18019. if (!session) {
  18020. if (err) { err->code = ErrorCode::Fatal; }
  18021. return false;
  18022. }
  18023. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18024. // Set socket to non-blocking mode
  18025. detail::set_nonblocking(sock, true);
  18026. auto cleanup =
  18027. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18028. int ret;
  18029. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  18030. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18031. if (ssl_error == SSL_ERROR_WANT_READ) {
  18032. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  18033. continue;
  18034. }
  18035. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18036. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18037. continue;
  18038. }
  18039. }
  18040. // Error or timeout
  18041. if (err) {
  18042. err->code =
  18043. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18044. err->backend_code = static_cast<uint64_t>(ssl_error);
  18045. }
  18046. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18047. return false;
  18048. }
  18049. if (err) { err->code = ErrorCode::Success; }
  18050. // Capture SNI from thread-local storage after successful handshake
  18051. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  18052. impl::wolfssl_pending_sni().clear();
  18053. return true;
  18054. }
  18055. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  18056. if (!session || !buf) {
  18057. err.code = ErrorCode::Fatal;
  18058. return -1;
  18059. }
  18060. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18061. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  18062. if (ret > 0) {
  18063. err.code = ErrorCode::Success;
  18064. return static_cast<ssize_t>(ret);
  18065. }
  18066. if (ret == 0) {
  18067. err.code = ErrorCode::PeerClosed;
  18068. return 0;
  18069. }
  18070. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18071. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18072. err.backend_code = static_cast<uint64_t>(ssl_error);
  18073. impl::wolfssl_last_error() = err.backend_code;
  18074. return -1;
  18075. }
  18076. inline ssize_t write(session_t session, const void *buf, size_t len,
  18077. TlsError &err) {
  18078. if (!session || !buf) {
  18079. err.code = ErrorCode::Fatal;
  18080. return -1;
  18081. }
  18082. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18083. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  18084. if (ret > 0) {
  18085. err.code = ErrorCode::Success;
  18086. return static_cast<ssize_t>(ret);
  18087. }
  18088. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  18089. // Treat this as an error (return -1) so callers don't spin in a
  18090. // write loop adding zero to the offset.
  18091. if (ret == 0) {
  18092. err.code = ErrorCode::PeerClosed;
  18093. return -1;
  18094. }
  18095. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18096. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18097. err.backend_code = static_cast<uint64_t>(ssl_error);
  18098. impl::wolfssl_last_error() = err.backend_code;
  18099. return -1;
  18100. }
  18101. inline int pending(const_session_t session) {
  18102. if (!session) { return 0; }
  18103. auto wsession =
  18104. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18105. return wolfSSL_pending(wsession->ssl);
  18106. }
  18107. inline void shutdown(session_t session, bool graceful) {
  18108. if (!session) { return; }
  18109. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18110. if (graceful) {
  18111. int ret;
  18112. int attempts = 0;
  18113. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  18114. attempts < 3) {
  18115. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18116. if (ssl_error != SSL_ERROR_WANT_READ &&
  18117. ssl_error != SSL_ERROR_WANT_WRITE) {
  18118. break;
  18119. }
  18120. attempts++;
  18121. }
  18122. } else {
  18123. wolfSSL_shutdown(wsession->ssl);
  18124. }
  18125. }
  18126. inline bool is_peer_closed(session_t session, socket_t sock) {
  18127. if (!session || sock == INVALID_SOCKET) { return true; }
  18128. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18129. // Check if there's already decrypted data available
  18130. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  18131. // Set socket to non-blocking to avoid blocking on read
  18132. detail::set_nonblocking(sock, true);
  18133. auto cleanup =
  18134. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18135. // Peek 1 byte to check connection status without consuming data
  18136. unsigned char buf;
  18137. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  18138. // If we got data or WANT_READ (would block), connection is alive
  18139. if (ret > 0) { return false; }
  18140. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18141. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  18142. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  18143. ret == 0;
  18144. }
  18145. inline cert_t get_peer_cert(const_session_t session) {
  18146. if (!session) { return nullptr; }
  18147. auto wsession =
  18148. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18149. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  18150. return static_cast<cert_t>(cert);
  18151. }
  18152. inline void free_cert(cert_t cert) {
  18153. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  18154. }
  18155. inline bool verify_hostname(cert_t cert, const char *hostname) {
  18156. if (!cert || !hostname) { return false; }
  18157. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18158. std::string host_str(hostname);
  18159. // Check if hostname is an IP address (IPv4 or IPv6)
  18160. unsigned char ip_bytes[16];
  18161. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  18162. auto is_ip = ip_len > 0;
  18163. // Check Subject Alternative Names
  18164. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  18165. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18166. if (san_names) {
  18167. int san_count = wolfSSL_sk_num(san_names);
  18168. for (int i = 0; i < san_count; i++) {
  18169. auto *names =
  18170. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  18171. if (!names) continue;
  18172. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  18173. // DNS name
  18174. unsigned char *dns_name = nullptr;
  18175. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  18176. if (dns_name && dns_len > 0) {
  18177. std::string san_name(reinterpret_cast<char *>(dns_name),
  18178. static_cast<size_t>(dns_len));
  18179. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  18180. if (detail::match_hostname(san_name, host_str)) {
  18181. wolfSSL_sk_free(san_names);
  18182. return true;
  18183. }
  18184. }
  18185. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  18186. // IP address: only an iPAddress SAN of the same family (4 bytes for
  18187. // IPv4, 16 bytes for IPv6) may authenticate the host.
  18188. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  18189. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  18190. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  18191. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  18192. wolfSSL_sk_free(san_names);
  18193. return true;
  18194. }
  18195. }
  18196. }
  18197. wolfSSL_sk_free(san_names);
  18198. }
  18199. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  18200. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  18201. // the OpenSSL backend's X509_check_ip behaves the same way).
  18202. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  18203. if (subject) {
  18204. char cn[256] = {};
  18205. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  18206. sizeof(cn));
  18207. if (cn_len > 0) {
  18208. std::string cn_str(cn, static_cast<size_t>(cn_len));
  18209. if (detail::match_hostname(cn_str, host_str)) { return true; }
  18210. }
  18211. }
  18212. return false;
  18213. }
  18214. inline uint64_t hostname_mismatch_code() {
  18215. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  18216. }
  18217. inline long get_verify_result(const_session_t session) {
  18218. if (!session) { return -1; }
  18219. auto wsession =
  18220. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18221. long result = wolfSSL_get_verify_result(wsession->ssl);
  18222. return result;
  18223. }
  18224. inline std::string get_cert_subject_cn(cert_t cert) {
  18225. if (!cert) return "";
  18226. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18227. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  18228. if (!subject) return "";
  18229. char cn[256] = {};
  18230. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  18231. sizeof(cn));
  18232. if (cn_len <= 0) return "";
  18233. return std::string(cn, static_cast<size_t>(cn_len));
  18234. }
  18235. inline std::string get_cert_issuer_name(cert_t cert) {
  18236. if (!cert) return "";
  18237. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18238. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  18239. if (!issuer) return "";
  18240. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  18241. if (!name_str) return "";
  18242. std::string result(name_str);
  18243. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  18244. return result;
  18245. }
  18246. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  18247. sans.clear();
  18248. if (!cert) return false;
  18249. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18250. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  18251. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18252. if (!san_names) return true; // No SANs is not an error
  18253. int count = wolfSSL_sk_num(san_names);
  18254. for (int i = 0; i < count; i++) {
  18255. auto *name =
  18256. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  18257. if (!name) continue;
  18258. SanEntry entry;
  18259. switch (name->type) {
  18260. case WOLFSSL_GEN_DNS: {
  18261. entry.type = SanType::DNS;
  18262. unsigned char *dns_name = nullptr;
  18263. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  18264. if (dns_name && dns_len > 0) {
  18265. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  18266. static_cast<size_t>(dns_len));
  18267. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  18268. }
  18269. break;
  18270. }
  18271. case WOLFSSL_GEN_IPADD: {
  18272. entry.type = SanType::IP;
  18273. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  18274. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  18275. if (ip_data && ip_len == 4) {
  18276. char buf[16];
  18277. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  18278. ip_data[2], ip_data[3]);
  18279. entry.value = buf;
  18280. } else if (ip_data && ip_len == 16) {
  18281. char buf[64];
  18282. snprintf(buf, sizeof(buf),
  18283. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  18284. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  18285. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  18286. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  18287. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  18288. ip_data[14], ip_data[15]);
  18289. entry.value = buf;
  18290. }
  18291. break;
  18292. }
  18293. case WOLFSSL_GEN_EMAIL:
  18294. entry.type = SanType::EMAIL;
  18295. {
  18296. unsigned char *email = nullptr;
  18297. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  18298. if (email && email_len > 0) {
  18299. entry.value = std::string(reinterpret_cast<char *>(email),
  18300. static_cast<size_t>(email_len));
  18301. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  18302. }
  18303. }
  18304. break;
  18305. case WOLFSSL_GEN_URI:
  18306. entry.type = SanType::URI;
  18307. {
  18308. unsigned char *uri = nullptr;
  18309. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  18310. &uri, name->d.uniformResourceIdentifier);
  18311. if (uri && uri_len > 0) {
  18312. entry.value = std::string(reinterpret_cast<char *>(uri),
  18313. static_cast<size_t>(uri_len));
  18314. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  18315. }
  18316. }
  18317. break;
  18318. default: entry.type = SanType::OTHER; break;
  18319. }
  18320. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  18321. }
  18322. wolfSSL_sk_free(san_names);
  18323. return true;
  18324. }
  18325. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  18326. time_t &not_after) {
  18327. if (!cert) return false;
  18328. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18329. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  18330. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  18331. if (!nb || !na) return false;
  18332. // wolfSSL_ASN1_TIME_to_tm is available
  18333. struct tm tm_nb = {}, tm_na = {};
  18334. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  18335. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  18336. #ifdef _WIN32
  18337. not_before = _mkgmtime(&tm_nb);
  18338. not_after = _mkgmtime(&tm_na);
  18339. #else
  18340. not_before = timegm(&tm_nb);
  18341. not_after = timegm(&tm_na);
  18342. #endif
  18343. return true;
  18344. }
  18345. inline std::string get_cert_serial(cert_t cert) {
  18346. if (!cert) return "";
  18347. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18348. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  18349. if (!serial_asn1) return "";
  18350. // Get the serial number data
  18351. int len = serial_asn1->length;
  18352. unsigned char *data = serial_asn1->data;
  18353. if (!data || len <= 0) return "";
  18354. std::string result;
  18355. result.reserve(static_cast<size_t>(len) * 2);
  18356. for (int i = 0; i < len; i++) {
  18357. char hex[3];
  18358. snprintf(hex, sizeof(hex), "%02X", data[i]);
  18359. result += hex;
  18360. }
  18361. return result;
  18362. }
  18363. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  18364. if (!cert) return false;
  18365. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18366. int der_len = 0;
  18367. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  18368. if (!der_data || der_len <= 0) return false;
  18369. der.assign(der_data, der_data + der_len);
  18370. return true;
  18371. }
  18372. inline const char *get_sni(const_session_t session) {
  18373. if (!session) return nullptr;
  18374. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  18375. // For server: return SNI received from client during handshake
  18376. if (!wsession->sni_hostname.empty()) {
  18377. return wsession->sni_hostname.c_str();
  18378. }
  18379. // For client: return the hostname set via set_sni
  18380. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  18381. return nullptr;
  18382. }
  18383. inline uint64_t peek_error() {
  18384. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18385. }
  18386. inline uint64_t get_error() {
  18387. uint64_t err = impl::wolfssl_last_error();
  18388. impl::wolfssl_last_error() = 0;
  18389. return err;
  18390. }
  18391. inline std::string error_string(uint64_t code) {
  18392. char buf[256];
  18393. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  18394. return std::string(buf);
  18395. }
  18396. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  18397. if (!pem || len == 0) { return nullptr; }
  18398. // Validate by attempting to load into a temporary ctx
  18399. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  18400. if (!tmp_ctx) { return nullptr; }
  18401. int ret = wolfSSL_CTX_load_verify_buffer(
  18402. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  18403. static_cast<long>(len), SSL_FILETYPE_PEM);
  18404. wolfSSL_CTX_free(tmp_ctx);
  18405. if (ret != SSL_SUCCESS) { return nullptr; }
  18406. return static_cast<ca_store_t>(
  18407. new impl::WolfSSLCAStore{std::string(pem, len)});
  18408. }
  18409. inline void free_ca_store(ca_store_t store) {
  18410. delete static_cast<impl::WolfSSLCAStore *>(store);
  18411. }
  18412. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  18413. if (!ctx || !store) { return false; }
  18414. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18415. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  18416. int ret = wolfSSL_CTX_load_verify_buffer(
  18417. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  18418. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  18419. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  18420. // This function takes ownership of the store; the PEM data was copied into
  18421. // the context, so release the source
  18422. free_ca_store(store);
  18423. return ret == SSL_SUCCESS;
  18424. }
  18425. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  18426. certs.clear();
  18427. if (!ctx) { return 0; }
  18428. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18429. if (wctx->ca_pem_data_.empty()) { return 0; }
  18430. const std::string &pem = wctx->ca_pem_data_;
  18431. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  18432. const std::string end_marker = "-----END CERTIFICATE-----";
  18433. size_t pos = 0;
  18434. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  18435. size_t end_pos = pem.find(end_marker, pos);
  18436. if (end_pos == std::string::npos) { break; }
  18437. end_pos += end_marker.size();
  18438. std::string cert_pem = pem.substr(pos, end_pos - pos);
  18439. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  18440. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  18441. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  18442. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  18443. pos = end_pos;
  18444. }
  18445. return certs.size();
  18446. }
  18447. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  18448. std::vector<std::string> names;
  18449. if (!ctx) { return names; }
  18450. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18451. if (wctx->ca_pem_data_.empty()) { return names; }
  18452. const std::string &pem = wctx->ca_pem_data_;
  18453. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  18454. const std::string end_marker = "-----END CERTIFICATE-----";
  18455. size_t pos = 0;
  18456. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  18457. size_t end_pos = pem.find(end_marker, pos);
  18458. if (end_pos == std::string::npos) { break; }
  18459. end_pos += end_marker.size();
  18460. std::string cert_pem = pem.substr(pos, end_pos - pos);
  18461. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  18462. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  18463. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  18464. if (x509) {
  18465. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  18466. if (subject) {
  18467. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  18468. if (name_str) {
  18469. names.push_back(name_str);
  18470. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  18471. }
  18472. }
  18473. wolfSSL_X509_free(x509);
  18474. }
  18475. pos = end_pos;
  18476. }
  18477. return names;
  18478. }
  18479. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  18480. const char *key_pem, const char *password) {
  18481. if (!ctx || !cert_pem || !key_pem) { return false; }
  18482. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18483. // Load new certificate
  18484. int ret = wolfSSL_CTX_use_certificate_buffer(
  18485. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  18486. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  18487. if (ret != SSL_SUCCESS) {
  18488. impl::wolfssl_last_error() =
  18489. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18490. return false;
  18491. }
  18492. // Set password if provided
  18493. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18494. // Load new private key
  18495. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  18496. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  18497. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  18498. if (ret != SSL_SUCCESS) {
  18499. impl::wolfssl_last_error() =
  18500. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18501. return false;
  18502. }
  18503. return true;
  18504. }
  18505. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  18506. if (!ctx || !ca_pem) { return false; }
  18507. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18508. int ret = wolfSSL_CTX_load_verify_buffer(
  18509. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  18510. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  18511. if (ret != SSL_SUCCESS) {
  18512. impl::wolfssl_last_error() =
  18513. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18514. return false;
  18515. }
  18516. return true;
  18517. }
  18518. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  18519. if (!ctx) { return false; }
  18520. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18521. impl::get_verify_callback() = std::move(callback);
  18522. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  18523. if (wctx->has_verify_callback) {
  18524. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  18525. impl::wolfssl_verify_callback);
  18526. } else {
  18527. wolfSSL_CTX_set_verify(
  18528. wctx->ctx,
  18529. wctx->verify_client
  18530. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  18531. : SSL_VERIFY_NONE,
  18532. nullptr);
  18533. }
  18534. return true;
  18535. }
  18536. inline long get_verify_error(const_session_t session) {
  18537. if (!session) { return -1; }
  18538. auto *wsession =
  18539. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18540. return wolfSSL_get_verify_result(wsession->ssl);
  18541. }
  18542. inline std::string verify_error_string(long error_code) {
  18543. if (error_code == 0) { return ""; }
  18544. const char *str =
  18545. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  18546. return str ? std::string(str) : std::string();
  18547. }
  18548. } // namespace tls
  18549. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  18550. // WebSocket implementation
  18551. namespace ws {
  18552. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  18553. bool fin) {
  18554. std::lock_guard<std::mutex> lock(write_mutex_);
  18555. if (closed_) { return false; }
  18556. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  18557. }
  18558. inline ReadResult WebSocket::read(std::string &msg) {
  18559. std::unique_lock<std::mutex> read_lock(read_mutex_);
  18560. while (!closed_) {
  18561. Opcode opcode;
  18562. std::string payload;
  18563. bool fin;
  18564. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  18565. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  18566. closed_ = true;
  18567. return Fail;
  18568. }
  18569. switch (opcode) {
  18570. case Opcode::Ping: {
  18571. std::lock_guard<std::mutex> lock(write_mutex_);
  18572. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  18573. payload.size(), true, !is_server_);
  18574. continue;
  18575. }
  18576. case Opcode::Pong: {
  18577. std::lock_guard<std::mutex> lock(ping_mutex_);
  18578. unacked_pings_ = 0;
  18579. continue;
  18580. }
  18581. case Opcode::Close: {
  18582. if (!closed_.exchange(true)) {
  18583. // Echo close frame back
  18584. std::lock_guard<std::mutex> lock(write_mutex_);
  18585. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  18586. payload.size(), true, !is_server_);
  18587. }
  18588. return Fail;
  18589. }
  18590. case Opcode::Text:
  18591. case Opcode::Binary: {
  18592. auto result = opcode == Opcode::Text ? Text : Binary;
  18593. msg = std::move(payload);
  18594. // Handle fragmentation
  18595. if (!fin) {
  18596. while (true) {
  18597. Opcode cont_opcode;
  18598. std::string cont_payload;
  18599. bool cont_fin;
  18600. if (!impl::read_websocket_frame(
  18601. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  18602. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  18603. closed_ = true;
  18604. return Fail;
  18605. }
  18606. if (cont_opcode == Opcode::Ping) {
  18607. std::lock_guard<std::mutex> lock(write_mutex_);
  18608. detail::write_websocket_frame(
  18609. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  18610. true, !is_server_);
  18611. continue;
  18612. }
  18613. if (cont_opcode == Opcode::Pong) {
  18614. std::lock_guard<std::mutex> lock(ping_mutex_);
  18615. unacked_pings_ = 0;
  18616. continue;
  18617. }
  18618. if (cont_opcode == Opcode::Close) {
  18619. if (!closed_.exchange(true)) {
  18620. std::lock_guard<std::mutex> lock(write_mutex_);
  18621. detail::write_websocket_frame(
  18622. strm_, Opcode::Close, cont_payload.data(),
  18623. cont_payload.size(), true, !is_server_);
  18624. }
  18625. return Fail;
  18626. }
  18627. // RFC 6455: continuation frames must use opcode 0x0
  18628. if (cont_opcode != Opcode::Continuation) {
  18629. closed_ = true;
  18630. return Fail;
  18631. }
  18632. msg += cont_payload;
  18633. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  18634. closed_ = true;
  18635. return Fail;
  18636. }
  18637. if (cont_fin) { break; }
  18638. }
  18639. }
  18640. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  18641. if (result == Text && !impl::is_valid_utf8(msg)) {
  18642. // close() takes the read lock to wait for the peer's Close reply, so
  18643. // it must not run while this thread still holds it.
  18644. read_lock.unlock();
  18645. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  18646. return Fail;
  18647. }
  18648. return result;
  18649. }
  18650. default: closed_ = true; return Fail;
  18651. }
  18652. }
  18653. return Fail;
  18654. }
  18655. inline bool WebSocket::send(const std::string &data) {
  18656. return send_frame(Opcode::Text, data.data(), data.size());
  18657. }
  18658. inline bool WebSocket::send(const char *data, size_t len) {
  18659. return send_frame(Opcode::Binary, data, len);
  18660. }
  18661. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  18662. if (closed_.exchange(true)) { return; }
  18663. ping_cv_.notify_all();
  18664. std::string payload;
  18665. auto code = static_cast<uint16_t>(status);
  18666. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  18667. payload.push_back(static_cast<char>(code & 0xFF));
  18668. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  18669. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  18670. payload += reason.substr(0, 123);
  18671. {
  18672. std::lock_guard<std::mutex> lock(write_mutex_);
  18673. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  18674. payload.size(), true, !is_server_);
  18675. }
  18676. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  18677. // Close response before closing the TCP connection.
  18678. //
  18679. // Wait only when no other thread is parsing frames. When one is, it is the
  18680. // thread positioned to see the peer's reply, and reading here would take
  18681. // bytes out of the message it is assembling. Bailing out also leaves the
  18682. // stream, including its read timeout, entirely to that thread.
  18683. std::unique_lock<std::mutex> read_lock(read_mutex_, std::try_to_lock);
  18684. if (!read_lock.owns_lock()) { return; }
  18685. // Use a short timeout to avoid hanging if the peer doesn't respond.
  18686. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  18687. Opcode op;
  18688. std::string resp;
  18689. bool fin;
  18690. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  18691. if (op == Opcode::Close) { break; }
  18692. }
  18693. }
  18694. inline WebSocket::~WebSocket() {
  18695. {
  18696. std::lock_guard<std::mutex> lock(ping_mutex_);
  18697. closed_ = true;
  18698. }
  18699. ping_cv_.notify_all();
  18700. if (ping_thread_.joinable()) { ping_thread_.join(); }
  18701. }
  18702. inline void WebSocket::start_heartbeat() {
  18703. if (ping_interval_sec_ == 0) { return; }
  18704. ping_thread_ = std::thread([this]() {
  18705. std::unique_lock<std::mutex> lock(ping_mutex_);
  18706. while (!closed_) {
  18707. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  18708. if (closed_) { break; }
  18709. // If the peer has failed to respond to the previous pings, give up.
  18710. // RFC 6455 does not define a pong-timeout mechanism; this is an
  18711. // opt-in liveness check controlled by max_missed_pongs_.
  18712. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  18713. lock.unlock();
  18714. close(CloseStatus::GoingAway, "pong timeout");
  18715. return;
  18716. }
  18717. lock.unlock();
  18718. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  18719. lock.lock();
  18720. closed_ = true;
  18721. break;
  18722. }
  18723. lock.lock();
  18724. unacked_pings_++;
  18725. }
  18726. });
  18727. }
  18728. inline const Request &WebSocket::request() const { return req_; }
  18729. inline bool WebSocket::is_open() const { return !closed_; }
  18730. // WebSocketClient implementation
  18731. inline WebSocketClient::WebSocketClient(
  18732. const std::string &scheme_host_port_path, const Headers &headers)
  18733. : headers_(headers) {
  18734. detail::UrlComponents uc;
  18735. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  18736. !uc.host.empty() && !uc.path.empty()) {
  18737. auto &scheme = uc.scheme;
  18738. #ifdef CPPHTTPLIB_SSL_ENABLED
  18739. if (scheme != "ws" && scheme != "wss") {
  18740. #else
  18741. if (scheme != "ws") {
  18742. #endif
  18743. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  18744. std::string msg = "'" + scheme + "' scheme is not supported.";
  18745. throw std::invalid_argument(msg);
  18746. #endif
  18747. return;
  18748. }
  18749. auto is_ssl = scheme == "wss";
  18750. host_ = std::move(uc.host);
  18751. port_ = is_ssl ? 443 : 80;
  18752. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  18753. path_ = std::move(uc.path);
  18754. if (!uc.query.empty()) { path_ += uc.query; }
  18755. #ifdef CPPHTTPLIB_SSL_ENABLED
  18756. is_ssl_ = is_ssl;
  18757. if (is_ssl_) {
  18758. // The context lives as long as the client so that CA configuration
  18759. // survives reconnects; sessions are created per connection.
  18760. tls_ctx_ = tls::create_client_context();
  18761. if (!tls_ctx_) { return; }
  18762. }
  18763. #else
  18764. if (is_ssl) { return; }
  18765. #endif
  18766. is_valid_ = true;
  18767. }
  18768. }
  18769. #ifdef CPPHTTPLIB_SSL_ENABLED
  18770. inline WebSocketClient::WebSocketClient(
  18771. const std::string &scheme_host_port_path, const PemMemory &pem,
  18772. const Headers &headers)
  18773. : WebSocketClient(scheme_host_port_path, headers) {
  18774. // For ws:// URLs the client certificate is silently ignored, consistent
  18775. // with the TLS-only setters such as set_ca_cert_path().
  18776. if (is_valid_ && is_ssl_ && pem.cert_pem && pem.key_pem) {
  18777. if (!tls::set_client_cert_pem(tls_ctx_, pem.cert_pem, pem.key_pem,
  18778. pem.private_key_password)) {
  18779. tls::free_context(tls_ctx_);
  18780. tls_ctx_ = nullptr;
  18781. is_valid_ = false;
  18782. }
  18783. }
  18784. }
  18785. #endif
  18786. inline WebSocketClient::~WebSocketClient() {
  18787. shutdown_and_close();
  18788. #ifdef CPPHTTPLIB_SSL_ENABLED
  18789. if (tls_ctx_) {
  18790. tls::free_context(tls_ctx_);
  18791. tls_ctx_ = nullptr;
  18792. }
  18793. #endif
  18794. }
  18795. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  18796. inline void WebSocketClient::shutdown_and_close() {
  18797. // Send the close frame while the TLS session is still alive: ws_ holds an
  18798. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  18799. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  18800. if (ws_ && ws_->is_open()) { ws_->close(); }
  18801. ws_.reset();
  18802. #ifdef CPPHTTPLIB_SSL_ENABLED
  18803. if (is_ssl_) {
  18804. if (tls_session_) {
  18805. tls::shutdown(tls_session_, true);
  18806. tls::free_session(tls_session_);
  18807. tls_session_ = nullptr;
  18808. }
  18809. }
  18810. #endif
  18811. if (sock_ != INVALID_SOCKET) {
  18812. detail::shutdown_socket(sock_);
  18813. detail::close_socket(sock_);
  18814. sock_ = INVALID_SOCKET;
  18815. }
  18816. }
  18817. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm,
  18818. Error &error, int &ssl_error,
  18819. uint64_t &ssl_backend_error) {
  18820. #ifdef CPPHTTPLIB_SSL_ENABLED
  18821. if (is_ssl_) {
  18822. // A plain flag rather than SSLClient::load_certs()'s call_once: connect()
  18823. // is not safe to call concurrently on one client to begin with, since
  18824. // nothing else here is guarded either.
  18825. if (server_certificate_verification_ && !certs_loaded_) {
  18826. uint64_t backend_error = 0;
  18827. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_,
  18828. ca_cert_dir_path_, custom_ca_loaded_,
  18829. system_ca_mode_, backend_error);
  18830. certs_loaded_ = true;
  18831. }
  18832. detail::ClientTlsSessionOptions options;
  18833. options.server_hostname_verification = server_hostname_verification_;
  18834. detail::ClientTlsSessionError tls_error;
  18835. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  18836. server_certificate_verification_,
  18837. read_timeout_sec_, read_timeout_usec_,
  18838. &tls_error, options)) {
  18839. error = tls_error.error;
  18840. ssl_error = tls_error.ssl_error;
  18841. ssl_backend_error = tls_error.backend_error;
  18842. return false;
  18843. }
  18844. strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  18845. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  18846. write_timeout_sec_, write_timeout_usec_));
  18847. return true;
  18848. }
  18849. #else
  18850. (void)error;
  18851. (void)ssl_error;
  18852. (void)ssl_backend_error;
  18853. #endif
  18854. strm = std::unique_ptr<Stream>(
  18855. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  18856. write_timeout_sec_, write_timeout_usec_));
  18857. return true;
  18858. }
  18859. inline void WebSocketClient::prepare_default_headers(Request &req) {
  18860. #ifdef CPPHTTPLIB_SSL_ENABLED
  18861. auto is_ssl = is_ssl_;
  18862. #else
  18863. auto is_ssl = false;
  18864. #endif
  18865. if (!req.has_header("Host")) {
  18866. req.headers.emplace("Host", detail::make_default_host_header_value(
  18867. host_, port_, is_ssl, address_family_));
  18868. }
  18869. detail::add_default_user_agent_header(req);
  18870. }
  18871. inline Result WebSocketClient::connect() {
  18872. if (!is_valid_) { return Result{Error::Connection, -1, Headers{}}; }
  18873. shutdown_and_close();
  18874. // Check is custom IP or hostname specified for host_
  18875. std::string connect_host;
  18876. std::string ip;
  18877. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  18878. auto error = Error::Success;
  18879. sock_ = detail::create_client_socket(
  18880. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  18881. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  18882. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  18883. write_timeout_usec_, interface_, error);
  18884. if (sock_ == INVALID_SOCKET) {
  18885. if (error == Error::Success) { error = Error::Connection; }
  18886. return Result{error, -1, Headers{}};
  18887. }
  18888. std::unique_ptr<Stream> strm;
  18889. auto stream_error = Error::SSLConnection;
  18890. int ssl_error = 0;
  18891. uint64_t ssl_backend_error = 0;
  18892. if (!create_stream(strm, stream_error, ssl_error, ssl_backend_error)) {
  18893. shutdown_and_close();
  18894. #ifdef CPPHTTPLIB_SSL_ENABLED
  18895. return Result{stream_error, -1, Headers{}, ssl_error, ssl_backend_error};
  18896. #else
  18897. return Result{stream_error, -1, Headers{}};
  18898. #endif
  18899. }
  18900. Request req;
  18901. req.method = "GET";
  18902. req.path = path_;
  18903. req.headers = headers_;
  18904. prepare_default_headers(req);
  18905. detail::WebSocketUpgradeResponse upgrade;
  18906. if (!detail::perform_websocket_handshake(*strm, req, upgrade)) {
  18907. shutdown_and_close();
  18908. return Result{upgrade.error, upgrade.status, std::move(upgrade.headers)};
  18909. }
  18910. subprotocol_ = std::move(upgrade.selected_subprotocol);
  18911. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  18912. websocket_ping_interval_sec_,
  18913. websocket_max_missed_pongs_));
  18914. return Result{Error::Success, upgrade.status, std::move(upgrade.headers)};
  18915. }
  18916. inline ReadResult WebSocketClient::read(std::string &msg) {
  18917. if (!ws_) { return Fail; }
  18918. return ws_->read(msg);
  18919. }
  18920. inline bool WebSocketClient::send(const std::string &data) {
  18921. if (!ws_) { return false; }
  18922. return ws_->send(data);
  18923. }
  18924. inline bool WebSocketClient::send(const char *data, size_t len) {
  18925. if (!ws_) { return false; }
  18926. return ws_->send(data, len);
  18927. }
  18928. inline void WebSocketClient::close(CloseStatus status,
  18929. const std::string &reason) {
  18930. if (ws_) { ws_->close(status, reason); }
  18931. }
  18932. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  18933. inline const std::string &WebSocketClient::subprotocol() const {
  18934. return subprotocol_;
  18935. }
  18936. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  18937. read_timeout_sec_ = sec;
  18938. read_timeout_usec_ = usec;
  18939. }
  18940. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  18941. write_timeout_sec_ = sec;
  18942. write_timeout_usec_ = usec;
  18943. }
  18944. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  18945. websocket_ping_interval_sec_ = sec;
  18946. }
  18947. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  18948. websocket_max_missed_pongs_ = count;
  18949. }
  18950. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  18951. inline void WebSocketClient::set_address_family(int family) {
  18952. address_family_ = family;
  18953. }
  18954. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  18955. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  18956. socket_options_ = std::move(socket_options);
  18957. }
  18958. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  18959. connection_timeout_sec_ = sec;
  18960. connection_timeout_usec_ = usec;
  18961. }
  18962. inline void WebSocketClient::set_interface(const std::string &intf) {
  18963. interface_ = intf;
  18964. }
  18965. inline void WebSocketClient::set_hostname_addr_map(
  18966. std::map<std::string, std::string> addr_map) {
  18967. addr_map_ = std::move(addr_map);
  18968. }
  18969. #ifdef CPPHTTPLIB_SSL_ENABLED
  18970. inline void
  18971. WebSocketClient::set_ca_cert_path(const std::string &ca_cert_file_path,
  18972. const std::string &ca_cert_dir_path) {
  18973. ca_cert_file_path_ = ca_cert_file_path;
  18974. ca_cert_dir_path_ = ca_cert_dir_path;
  18975. }
  18976. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  18977. if (store && tls_ctx_) {
  18978. // set_ca_store takes ownership of store
  18979. tls::set_ca_store(tls_ctx_, store);
  18980. custom_ca_loaded_ = true;
  18981. } else if (store) {
  18982. tls::free_ca_store(store);
  18983. }
  18984. }
  18985. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  18986. std::size_t size) {
  18987. if (tls_ctx_ && ca_cert && size > 0) {
  18988. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  18989. custom_ca_loaded_ = true;
  18990. }
  18991. }
  18992. inline void
  18993. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  18994. server_certificate_verification_ = enabled;
  18995. }
  18996. inline void WebSocketClient::enable_server_hostname_verification(bool enabled) {
  18997. server_hostname_verification_ = enabled;
  18998. }
  18999. inline void WebSocketClient::enable_system_ca(bool enabled) {
  19000. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  19001. }
  19002. #endif // CPPHTTPLIB_SSL_ENABLED
  19003. } // namespace ws
  19004. // ----------------------------------------------------------------------------
  19005. } // namespace httplib
  19006. #endif // CPPHTTPLIB_HTTPLIB_H