httplib.h 796 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307
  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.61.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003d00"
  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_STATIC_FILE_COMPRESSION_MIN_LENGTH
  106. // 1400 rather than a round number: a body that already fits in one 1500-byte
  107. // MTU gains nothing from being made smaller.
  108. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH 1400
  109. #endif
  110. #ifndef CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH
  111. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH (4 * 1024 * 1024) // 4MB
  112. #endif
  113. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  114. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  115. #endif
  116. // std::regex_match's backtracking implementation (most acutely on libstdc++)
  117. // recurses roughly once per matched character for quantified patterns such
  118. // as "(.*)", so a long enough path can exhaust the calling thread's stack; on
  119. // a default ~8MB thread stack that has been observed to take on the order of
  120. // a couple thousand characters for a simple pattern. 256 leaves a wide safety
  121. // margin below that (well under the 8192-byte request URI limit) while still
  122. // fitting any realistic route segment; raise it if a route legitimately needs
  123. // longer paths. Regex routes are never applied to paths longer than this.
  124. #ifndef CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH
  125. #define CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH 256
  126. #endif
  127. #ifndef CPPHTTPLIB_TCP_NODELAY
  128. #define CPPHTTPLIB_TCP_NODELAY false
  129. #endif
  130. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  131. #define CPPHTTPLIB_IPV6_V6ONLY false
  132. #endif
  133. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  134. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  135. #endif
  136. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  137. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  138. #endif
  139. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  140. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  141. #endif
  142. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  143. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  144. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  145. ? std::thread::hardware_concurrency() - 1 \
  146. : 0))
  147. #endif
  148. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  149. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  150. #endif
  151. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  152. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  153. #endif
  154. #ifndef CPPHTTPLIB_RECV_FLAGS
  155. #define CPPHTTPLIB_RECV_FLAGS 0
  156. #endif
  157. #ifndef CPPHTTPLIB_SEND_FLAGS
  158. #define CPPHTTPLIB_SEND_FLAGS 0
  159. #endif
  160. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  161. #define CPPHTTPLIB_LISTEN_BACKLOG 128
  162. #endif
  163. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  164. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  165. #endif
  166. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  167. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  168. #endif
  169. // One macro used to set the read timeout for both sides. They want different
  170. // defaults: a client's read timeout is the caller's own tool (it waits forever
  171. // until asked not to), while a server keeps a ceiling that reclaims a worker
  172. // from a peer that has gone quiet. The old name still works and sets both.
  173. #ifdef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  174. #pragma message( \
  175. "CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND is deprecated; define " \
  176. "CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND and/or " \
  177. "CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND instead")
  178. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  179. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND \
  180. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  181. #endif
  182. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  183. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND \
  184. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  185. #endif
  186. #endif
  187. // 0 waits forever. A read timeout is how a caller gets control back to send on
  188. // the same connection; it is not a liveness check (that is ping/pong). Only a
  189. // timeout set at runtime through set_read_timeout() is reported as
  190. // ws::Timeout; when one of these compile-time defaults elapses, read() returns
  191. // ws::Fail and closes the connection.
  192. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  193. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND 0
  194. #endif
  195. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  196. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND 300
  197. #endif
  198. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  199. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  200. #endif
  201. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  202. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  203. #endif
  204. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  205. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  206. #endif
  207. /*
  208. * Headers
  209. */
  210. #ifdef _WIN32
  211. #ifndef _CRT_SECURE_NO_WARNINGS
  212. #define _CRT_SECURE_NO_WARNINGS
  213. #endif //_CRT_SECURE_NO_WARNINGS
  214. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  215. #define _CRT_NONSTDC_NO_DEPRECATE
  216. #endif //_CRT_NONSTDC_NO_DEPRECATE
  217. #if defined(_MSC_VER)
  218. #if _MSC_VER < 1900
  219. #error Sorry, Visual Studio versions prior to 2015 are not supported
  220. #endif
  221. #pragma comment(lib, "ws2_32.lib")
  222. #ifndef _SSIZE_T_DEFINED
  223. using ssize_t = __int64;
  224. #define _SSIZE_T_DEFINED
  225. #endif
  226. #endif // _MSC_VER
  227. #ifndef S_ISREG
  228. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  229. #endif // S_ISREG
  230. #ifndef S_ISDIR
  231. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  232. #endif // S_ISDIR
  233. #ifndef NOMINMAX
  234. #define NOMINMAX
  235. #endif // NOMINMAX
  236. #include <io.h>
  237. #include <winsock2.h>
  238. #include <ws2tcpip.h>
  239. #if defined(__has_include)
  240. #if __has_include(<afunix.h>)
  241. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  242. #include <afunix.h>
  243. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  244. #endif
  245. #endif
  246. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  247. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  248. #endif
  249. using nfds_t = unsigned long;
  250. using socket_t = SOCKET;
  251. using socklen_t = int;
  252. #else // not _WIN32
  253. #include <arpa/inet.h>
  254. #if !defined(_AIX) && !defined(__MVS__)
  255. #include <ifaddrs.h>
  256. #endif
  257. #ifdef __MVS__
  258. #include <strings.h>
  259. #ifndef NI_MAXHOST
  260. #define NI_MAXHOST 1025
  261. #endif
  262. #endif
  263. #include <net/if.h>
  264. #include <netdb.h>
  265. #include <netinet/in.h>
  266. #ifdef __linux__
  267. #include <resolv.h>
  268. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  269. #endif
  270. #include <csignal>
  271. #include <netinet/tcp.h>
  272. #include <poll.h>
  273. #include <pthread.h>
  274. #include <sys/mman.h>
  275. #include <sys/socket.h>
  276. #include <sys/un.h>
  277. #include <unistd.h>
  278. using socket_t = int;
  279. #ifndef INVALID_SOCKET
  280. #define INVALID_SOCKET (-1)
  281. #endif
  282. #endif //_WIN32
  283. #if defined(__APPLE__)
  284. #include <TargetConditionals.h>
  285. #endif
  286. #include <algorithm>
  287. #include <array>
  288. #include <atomic>
  289. #include <cassert>
  290. #include <chrono>
  291. #include <climits>
  292. #include <condition_variable>
  293. #include <cstdlib>
  294. #include <cstring>
  295. #include <errno.h>
  296. #include <exception>
  297. #include <fcntl.h>
  298. #include <fstream>
  299. #include <functional>
  300. #include <iomanip>
  301. #include <iostream>
  302. #include <iterator>
  303. #include <list>
  304. #include <map>
  305. #include <memory>
  306. #include <mutex>
  307. #include <random>
  308. #include <regex>
  309. #include <set>
  310. #include <sstream>
  311. #include <string>
  312. #include <sys/stat.h>
  313. #include <system_error>
  314. #include <thread>
  315. #include <type_traits>
  316. #include <unordered_map>
  317. #include <unordered_set>
  318. #include <utility>
  319. #include <vector>
  320. // On macOS with a TLS backend, enable Keychain root certificates by default
  321. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  322. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  323. // only; on those platforms the user must provide a CA bundle explicitly.
  324. #if defined(__APPLE__) && defined(__clang__) && \
  325. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  326. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  327. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  328. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  329. #if TARGET_OS_OSX
  330. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  331. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  332. #endif
  333. #endif
  334. #endif
  335. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  336. defined(__APPLE__) && !TARGET_OS_OSX
  337. #error \
  338. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  339. #endif
  340. // On Windows, enable Schannel certificate verification by default
  341. // unless the user explicitly opts out.
  342. #if defined(_WIN32) && \
  343. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  344. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  345. #endif
  346. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  347. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  348. #if TARGET_OS_MAC && defined(__clang__)
  349. #include <CFNetwork/CFHost.h>
  350. #include <CoreFoundation/CoreFoundation.h>
  351. #endif
  352. #endif
  353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  354. #ifdef _WIN32
  355. #include <wincrypt.h>
  356. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  357. // used
  358. #undef X509_NAME
  359. #undef X509_CERT_PAIR
  360. #undef X509_EXTENSIONS
  361. #undef PKCS7_SIGNER_INFO
  362. #ifdef _MSC_VER
  363. #pragma comment(lib, "crypt32.lib")
  364. #endif
  365. #endif // _WIN32
  366. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  367. #if TARGET_OS_OSX
  368. #include <Security/Security.h>
  369. #endif
  370. #endif
  371. #include <openssl/err.h>
  372. #include <openssl/evp.h>
  373. #include <openssl/ssl.h>
  374. #include <openssl/x509v3.h>
  375. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  376. #include <openssl/applink.c>
  377. #endif
  378. #include <iostream>
  379. #include <sstream>
  380. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  381. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  382. #error Please use OpenSSL or a current version of BoringSSL
  383. #endif
  384. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  385. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  386. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  387. #endif
  388. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  389. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  390. // version.h defines MBEDTLS_VERSION_MAJOR (on 2.x/3.x/4.x alike); it is pulled
  391. // in with this first include group so the version gating below can use it.
  392. #include <mbedtls/error.h>
  393. #include <mbedtls/net_sockets.h>
  394. #include <mbedtls/oid.h>
  395. #include <mbedtls/pk.h>
  396. #include <mbedtls/ssl.h>
  397. #include <mbedtls/version.h>
  398. #include <mbedtls/x509_crt.h>
  399. #if MBEDTLS_VERSION_MAJOR >= 4
  400. // Mbed TLS 4.x moved hashing/RNG to PSA Crypto and removed these headers.
  401. #include <psa/crypto.h>
  402. #else
  403. #include <mbedtls/ctr_drbg.h>
  404. #include <mbedtls/entropy.h>
  405. #include <mbedtls/md5.h>
  406. #include <mbedtls/sha1.h>
  407. #include <mbedtls/sha256.h>
  408. #include <mbedtls/sha512.h>
  409. #endif
  410. #ifdef _WIN32
  411. #include <wincrypt.h>
  412. #ifdef _MSC_VER
  413. #pragma comment(lib, "crypt32.lib")
  414. #endif
  415. #endif // _WIN32
  416. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  417. #if TARGET_OS_OSX
  418. #include <Security/Security.h>
  419. #endif
  420. #endif
  421. // Mbed TLS version API compatibility. Note: V4 implies V3 (both defined on
  422. // 4.x), so version-specific 3.x-only code must check V3 && !V4.
  423. #if MBEDTLS_VERSION_MAJOR >= 4
  424. #define CPPHTTPLIB_MBEDTLS_V4
  425. #endif
  426. #if MBEDTLS_VERSION_MAJOR >= 3
  427. #define CPPHTTPLIB_MBEDTLS_V3
  428. #endif
  429. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  430. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  431. #include <wolfssl/options.h>
  432. #include <wolfssl/openssl/x509v3.h>
  433. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  434. #ifndef WOLFSSL_GEN_EMAIL
  435. #define WOLFSSL_GEN_EMAIL 1
  436. #endif
  437. #ifndef WOLFSSL_GEN_DNS
  438. #define WOLFSSL_GEN_DNS 2
  439. #endif
  440. #ifndef WOLFSSL_GEN_URI
  441. #define WOLFSSL_GEN_URI 6
  442. #endif
  443. #ifndef WOLFSSL_GEN_IPADD
  444. #define WOLFSSL_GEN_IPADD 7
  445. #endif
  446. #include <wolfssl/ssl.h>
  447. #include <wolfssl/wolfcrypt/hash.h>
  448. #include <wolfssl/wolfcrypt/md5.h>
  449. #include <wolfssl/wolfcrypt/sha256.h>
  450. #include <wolfssl/wolfcrypt/sha512.h>
  451. #ifdef _WIN32
  452. #include <wincrypt.h>
  453. #ifdef _MSC_VER
  454. #pragma comment(lib, "crypt32.lib")
  455. #endif
  456. #endif // _WIN32
  457. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  458. #if TARGET_OS_OSX
  459. #include <Security/Security.h>
  460. #endif
  461. #endif
  462. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  463. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  464. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  465. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  466. #define CPPHTTPLIB_SSL_ENABLED
  467. #endif
  468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  469. #include <zlib.h>
  470. #endif
  471. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  472. #include <brotli/decode.h>
  473. #include <brotli/encode.h>
  474. #endif
  475. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  476. #include <zstd.h>
  477. #endif
  478. /*
  479. * Declaration
  480. */
  481. namespace httplib {
  482. namespace ws {
  483. class WebSocket;
  484. } // namespace ws
  485. namespace detail {
  486. /*
  487. * Backport std::make_unique from C++14.
  488. *
  489. * NOTE: This code came up with the following stackoverflow post:
  490. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  491. *
  492. */
  493. template <class T, class... Args>
  494. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  495. make_unique(Args &&...args) {
  496. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  497. }
  498. template <class T>
  499. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  500. make_unique(std::size_t n) {
  501. typedef typename std::remove_extent<T>::type RT;
  502. return std::unique_ptr<T>(new RT[n]);
  503. }
  504. // Locale-independent ASCII character classification. The <cctype>
  505. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  506. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  507. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  508. // classified without regard to the locale.
  509. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  510. inline bool is_ascii_alpha(char c) {
  511. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  512. }
  513. inline bool is_ascii_alnum(char c) {
  514. return is_ascii_digit(c) || is_ascii_alpha(c);
  515. }
  516. namespace case_ignore {
  517. inline unsigned char to_lower(int c) {
  518. const static unsigned char table[256] = {
  519. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  520. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  521. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  522. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  523. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  524. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  525. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  526. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  527. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  528. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  529. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  530. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  531. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  532. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  533. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  534. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  535. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  536. 255,
  537. };
  538. return table[(unsigned char)(char)c];
  539. }
  540. inline std::string to_lower(const std::string &s) {
  541. std::string result = s;
  542. std::transform(
  543. result.begin(), result.end(), result.begin(),
  544. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  545. return result;
  546. }
  547. inline bool equal(const std::string &a, const std::string &b) {
  548. return a.size() == b.size() &&
  549. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  550. return to_lower(ca) == to_lower(cb);
  551. });
  552. }
  553. struct equal_to {
  554. bool operator()(const std::string &a, const std::string &b) const {
  555. return equal(a, b);
  556. }
  557. };
  558. struct hash {
  559. size_t operator()(const std::string &key) const {
  560. return hash_core(key.data(), key.size(), 0);
  561. }
  562. size_t hash_core(const char *s, size_t l, size_t h) const {
  563. return (l == 0) ? h
  564. : hash_core(s + 1, l - 1,
  565. // Unsets the 6 high bits of h, therefore no
  566. // overflow happens
  567. (((std::numeric_limits<size_t>::max)() >> 6) &
  568. h * 33) ^
  569. static_cast<unsigned char>(to_lower(*s)));
  570. }
  571. };
  572. template <typename T>
  573. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  574. detail::case_ignore::equal_to>;
  575. } // namespace case_ignore
  576. // This is based on
  577. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  578. struct scope_exit {
  579. explicit scope_exit(std::function<void(void)> &&f)
  580. : exit_function(std::move(f)), execute_on_destruction{true} {}
  581. scope_exit(scope_exit &&rhs) noexcept
  582. : exit_function(std::move(rhs.exit_function)),
  583. execute_on_destruction{rhs.execute_on_destruction} {
  584. rhs.release();
  585. }
  586. ~scope_exit() {
  587. if (execute_on_destruction) { this->exit_function(); }
  588. }
  589. void release() { this->execute_on_destruction = false; }
  590. private:
  591. scope_exit(const scope_exit &) = delete;
  592. void operator=(const scope_exit &) = delete;
  593. scope_exit &operator=(scope_exit &&) = delete;
  594. std::function<void(void)> exit_function;
  595. bool execute_on_destruction;
  596. };
  597. // Simple from_chars implementation for integer and double types (C++17
  598. // substitute)
  599. template <typename T> struct from_chars_result {
  600. const char *ptr;
  601. std::errc ec;
  602. };
  603. template <typename T>
  604. inline from_chars_result<T> from_chars(const char *first, const char *last,
  605. T &value, int base = 10) {
  606. value = 0;
  607. const char *p = first;
  608. bool negative = false;
  609. if (p != last && *p == '-') {
  610. negative = true;
  611. ++p;
  612. }
  613. if (p == last) { return {first, std::errc::invalid_argument}; }
  614. T result = 0;
  615. for (; p != last; ++p) {
  616. char c = *p;
  617. int digit = -1;
  618. if (is_ascii_digit(c)) {
  619. digit = c - '0';
  620. } else if ('a' <= c && c <= 'z') {
  621. digit = c - 'a' + 10;
  622. } else if ('A' <= c && c <= 'Z') {
  623. digit = c - 'A' + 10;
  624. } else {
  625. break;
  626. }
  627. if (digit < 0 || digit >= base) { break; }
  628. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  629. return {p, std::errc::result_out_of_range};
  630. }
  631. result = result * base + digit;
  632. }
  633. if (p == first || (negative && p == first + 1)) {
  634. return {first, std::errc::invalid_argument};
  635. }
  636. value = negative ? T(0) - result : result;
  637. return {p, std::errc{}};
  638. }
  639. // from_chars for double (hand-written, locale-independent)
  640. //
  641. // The only double consumed by this library is the HTTP quality value, whose
  642. // grammar is (RFC 9110 12.4.2):
  643. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  644. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  645. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  646. // '.' always the decimal separator (std::strtod would instead read it from the
  647. // global C locale, mis-parsing q-values once an embedder calls
  648. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  649. // the result to [0, 1], so inputs outside that range need not be distinguished
  650. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  651. // cases that exponent and wide-range handling would introduce.
  652. inline from_chars_result<double> from_chars(const char *first, const char *last,
  653. double &value) {
  654. value = 0.0;
  655. const char *p = first;
  656. // Each 1eN is exactly representable, so a single final division by the
  657. // matching entry yields a correctly-rounded result.
  658. static const double powers_of_ten[] = {
  659. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  660. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  661. const int max_frac_digits =
  662. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  663. // Accumulate digits into a 64-bit integer and remember how many were
  664. // fractional. Two independent caps keep this bounded and safe:
  665. // * accumulation saturates before mantissa could overflow uint64_t, and
  666. // * frac_digits is capped at max_frac_digits so it is always a valid index
  667. // into powers_of_ten (without this an input like "0.000...0" would never
  668. // grow mantissa, so the saturation cap alone would not bound it).
  669. // Both caps only drop digits far beyond the precision a q-value needs; any
  670. // value they would change is well outside [0, 1] and rejected by the caller.
  671. uint64_t mantissa = 0;
  672. int frac_digits = 0;
  673. bool seen_digit = false;
  674. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  675. auto accumulate = [&](char c) {
  676. if (mantissa <= limit) {
  677. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  678. return true;
  679. }
  680. return false;
  681. };
  682. for (; p != last && is_ascii_digit(*p); ++p) {
  683. seen_digit = true;
  684. accumulate(*p);
  685. }
  686. if (p != last && *p == '.') {
  687. ++p;
  688. for (; p != last && is_ascii_digit(*p); ++p) {
  689. seen_digit = true;
  690. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  691. }
  692. }
  693. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  694. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  695. return {p, std::errc{}};
  696. }
  697. inline bool parse_int_in_range(const char *s, size_t len, int lo, int hi,
  698. int &out) {
  699. int val = 0;
  700. auto r = from_chars(s, s + len, val);
  701. if (r.ec != std::errc{} || r.ptr != s + len || val < lo || val > hi) {
  702. return false;
  703. }
  704. out = val;
  705. return true;
  706. }
  707. inline bool parse_port(const char *s, size_t len, int &port) {
  708. return parse_int_in_range(s, len, 1, 65535, port);
  709. }
  710. inline bool parse_port(const std::string &s, int &port) {
  711. return parse_port(s.data(), s.size(), port);
  712. }
  713. struct UrlComponents {
  714. std::string scheme;
  715. std::string host;
  716. std::string port;
  717. std::string path;
  718. std::string query;
  719. };
  720. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  721. uc = {};
  722. size_t pos = 0;
  723. auto sep = url.find("://");
  724. if (sep != std::string::npos) {
  725. uc.scheme = url.substr(0, sep);
  726. // Scheme must be [a-z]+ only
  727. if (uc.scheme.empty()) { return false; }
  728. for (auto c : uc.scheme) {
  729. if (c < 'a' || c > 'z') { return false; }
  730. }
  731. pos = sep + 3;
  732. } else if (url.compare(0, 2, "//") == 0) {
  733. pos = 2;
  734. }
  735. auto has_authority_prefix = pos > 0;
  736. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  737. url[0] != '?' && url[0] != '#');
  738. if (has_authority) {
  739. if (pos < url.size() && url[pos] == '[') {
  740. auto close = url.find(']', pos);
  741. if (close == std::string::npos) { return false; }
  742. uc.host = url.substr(pos + 1, close - pos - 1);
  743. // IPv6 host must be [a-fA-F0-9:]+ only
  744. if (uc.host.empty()) { return false; }
  745. for (auto c : uc.host) {
  746. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  747. (c >= 'A' && c <= 'F') || c == ':')) {
  748. return false;
  749. }
  750. }
  751. pos = close + 1;
  752. // The IPv6 literal is the whole host, so ']' must be followed by a port,
  753. // path, query or fragment delimiter (or the end of input). Otherwise the
  754. // trailing bytes would be folded into the path while the connection
  755. // still targets the bracketed address.
  756. if (pos < url.size()) {
  757. auto c = url[pos];
  758. if (c != ':' && c != '/' && c != '?' && c != '#') { return false; }
  759. }
  760. } else {
  761. auto end = url.find_first_of(":/?#", pos);
  762. if (end == std::string::npos) { end = url.size(); }
  763. uc.host = url.substr(pos, end - pos);
  764. pos = end;
  765. }
  766. if (pos < url.size() && url[pos] == ':') {
  767. ++pos;
  768. auto end = url.find_first_of("/?#", pos);
  769. if (end == std::string::npos) { end = url.size(); }
  770. uc.port = url.substr(pos, end - pos);
  771. pos = end;
  772. }
  773. // Without :// or //, the entire input must be consumed as host[:port].
  774. // If there is leftover (path, query, etc.), this is not a valid
  775. // host[:port] string — clear and reparse as a plain path.
  776. if (!has_authority_prefix && pos < url.size()) {
  777. uc.host.clear();
  778. uc.port.clear();
  779. pos = 0;
  780. }
  781. }
  782. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  783. auto end = url.find_first_of("?#", pos);
  784. if (end == std::string::npos) { end = url.size(); }
  785. uc.path = url.substr(pos, end - pos);
  786. pos = end;
  787. }
  788. if (pos < url.size() && url[pos] == '?') {
  789. auto end = url.find('#', pos);
  790. if (end == std::string::npos) { end = url.size(); }
  791. uc.query = url.substr(pos, end - pos);
  792. }
  793. return true;
  794. }
  795. // Resolves a relative-path or query-only Location value against the path of
  796. // the request being redirected (RFC 3986 section 5.2). Absolute URIs and
  797. // references starting with '/' are returned unchanged.
  798. inline std::string resolve_relative_location(const std::string &location,
  799. const std::string &base) {
  800. if (location.empty() || location[0] == '/') { return location; }
  801. // A ':' in the first segment means the value has a scheme.
  802. if (location.find(':') < location.find_first_of("/?#")) { return location; }
  803. if (location[0] == '#') { return base.substr(0, base.find('#')) + location; }
  804. auto base_path = base.substr(0, base.find_first_of("?#"));
  805. if (location[0] == '?') { return base_path + location; }
  806. if (base_path.empty() || base_path[0] != '/') { base_path = "/"; }
  807. auto merged = base_path.substr(0, base_path.rfind('/') + 1) + location;
  808. // Remove "." and ".." segments from the merged path.
  809. auto path_end = (std::min)(merged.find_first_of("?#"), merged.size());
  810. std::string path;
  811. size_t i = 0;
  812. while (i < path_end) {
  813. auto next = (std::min)(merged.find('/', i + 1), path_end);
  814. auto segment = merged.substr(i + 1, next - i - 1);
  815. auto is_last = next == path_end;
  816. if (segment == "." || segment == "..") {
  817. if (segment == "..") {
  818. path.erase((std::min)(path.rfind('/'), path.size()));
  819. }
  820. if (is_last) { path += '/'; }
  821. } else {
  822. path += '/';
  823. path += segment;
  824. }
  825. i = next;
  826. }
  827. if (path.empty()) { path = "/"; }
  828. return path + merged.substr(path_end);
  829. }
  830. } // namespace detail
  831. enum class SSLVerifierResponse {
  832. // no decision has been made, use the built-in certificate verifier
  833. NoDecisionMade,
  834. // connection certificate is verified and accepted
  835. CertificateAccepted,
  836. // connection certificate was processed but is rejected
  837. CertificateRejected
  838. };
  839. // System CA loading policy for SSL clients. Auto (the default) loads system
  840. // CA certs only when no custom CA is configured; enable_system_ca() switches
  841. // to an explicit policy.
  842. enum class SystemCAMode { Auto, Enabled, Disabled };
  843. enum StatusCode {
  844. // Information responses
  845. Continue_100 = 100,
  846. SwitchingProtocol_101 = 101,
  847. Processing_102 = 102,
  848. EarlyHints_103 = 103,
  849. // Successful responses
  850. OK_200 = 200,
  851. Created_201 = 201,
  852. Accepted_202 = 202,
  853. NonAuthoritativeInformation_203 = 203,
  854. NoContent_204 = 204,
  855. ResetContent_205 = 205,
  856. PartialContent_206 = 206,
  857. MultiStatus_207 = 207,
  858. AlreadyReported_208 = 208,
  859. IMUsed_226 = 226,
  860. // Redirection messages
  861. MultipleChoices_300 = 300,
  862. MovedPermanently_301 = 301,
  863. Found_302 = 302,
  864. SeeOther_303 = 303,
  865. NotModified_304 = 304,
  866. UseProxy_305 = 305,
  867. unused_306 = 306,
  868. TemporaryRedirect_307 = 307,
  869. PermanentRedirect_308 = 308,
  870. // Client error responses
  871. BadRequest_400 = 400,
  872. Unauthorized_401 = 401,
  873. PaymentRequired_402 = 402,
  874. Forbidden_403 = 403,
  875. NotFound_404 = 404,
  876. MethodNotAllowed_405 = 405,
  877. NotAcceptable_406 = 406,
  878. ProxyAuthenticationRequired_407 = 407,
  879. RequestTimeout_408 = 408,
  880. Conflict_409 = 409,
  881. Gone_410 = 410,
  882. LengthRequired_411 = 411,
  883. PreconditionFailed_412 = 412,
  884. PayloadTooLarge_413 = 413,
  885. UriTooLong_414 = 414,
  886. UnsupportedMediaType_415 = 415,
  887. RangeNotSatisfiable_416 = 416,
  888. ExpectationFailed_417 = 417,
  889. ImATeapot_418 = 418,
  890. MisdirectedRequest_421 = 421,
  891. UnprocessableContent_422 = 422,
  892. Locked_423 = 423,
  893. FailedDependency_424 = 424,
  894. TooEarly_425 = 425,
  895. UpgradeRequired_426 = 426,
  896. PreconditionRequired_428 = 428,
  897. TooManyRequests_429 = 429,
  898. RequestHeaderFieldsTooLarge_431 = 431,
  899. UnavailableForLegalReasons_451 = 451,
  900. // Server error responses
  901. InternalServerError_500 = 500,
  902. NotImplemented_501 = 501,
  903. BadGateway_502 = 502,
  904. ServiceUnavailable_503 = 503,
  905. GatewayTimeout_504 = 504,
  906. HttpVersionNotSupported_505 = 505,
  907. VariantAlsoNegotiates_506 = 506,
  908. InsufficientStorage_507 = 507,
  909. LoopDetected_508 = 508,
  910. NotExtended_510 = 510,
  911. NetworkAuthenticationRequired_511 = 511,
  912. };
  913. namespace detail {
  914. // A multimap that keeps its entries in the order they were inserted.
  915. //
  916. // HTTP needs that order in two places. RFC 9110 5.3 makes the order of header
  917. // fields sharing a field name significant and forbids a proxy from reordering
  918. // them, and a query string's parameters are meaningful in the order the caller
  919. // wrote them. Neither standard container expresses it: std::unordered_multimap
  920. // gives no ordering guarantee at all for equivalent keys (libstdc++ yields
  921. // reverse insertion order, libc++ insertion order), and std::multimap sorts by
  922. // key, which would drop control data such as Host behind whatever else the
  923. // message carries and alphabetise a query string.
  924. //
  925. // Entries are therefore kept in a flat vector, in order. Lookup is a linear
  926. // scan, which beats hashing for the handful of entries a message carries
  927. // (headers are capped at CPPHTTPLIB_HEADER_MAX_COUNT).
  928. //
  929. // KeyEqual compares keys; it is what makes Headers case-insensitive and
  930. // Params, whose parameter names are case-sensitive, not.
  931. template <typename Mapped, typename KeyEqual> class insertion_ordered_multimap {
  932. public:
  933. using key_type = std::string;
  934. using mapped_type = Mapped;
  935. using value_type = std::pair<std::string, Mapped>;
  936. using size_type = std::size_t;
  937. using difference_type = std::ptrdiff_t;
  938. using reference = value_type &;
  939. using const_reference = const value_type &;
  940. private:
  941. static size_type npos() { return static_cast<size_type>(-1); }
  942. static bool keys_equal(const std::string &a, const std::string &b) {
  943. return KeyEqual()(a, b);
  944. }
  945. // Iterating yields every entry in insertion order, but equal_range() and
  946. // find() have to walk only the entries sharing one key, which are not
  947. // adjacent. Both are the same iterator type: key_idx_ selects between the
  948. // two traversals, and since equality compares only the position, an iterator
  949. // restricted to one key still compares equal to end().
  950. template <typename V> class iterator_t {
  951. public:
  952. using iterator_category = std::bidirectional_iterator_tag;
  953. using value_type = insertion_ordered_multimap::value_type;
  954. using difference_type = insertion_ordered_multimap::difference_type;
  955. using pointer = V *;
  956. using reference = V &;
  957. iterator_t() : data_(nullptr), idx_(0), size_(0), key_idx_(npos()) {}
  958. template <typename U,
  959. typename std::enable_if<std::is_convertible<U *, V *>::value,
  960. int>::type = 0>
  961. iterator_t(const iterator_t<U> &rhs)
  962. : data_(rhs.data_), idx_(rhs.idx_), size_(rhs.size_),
  963. key_idx_(rhs.key_idx_) {}
  964. reference operator*() const { return data_[idx_]; }
  965. pointer operator->() const { return data_ + idx_; }
  966. iterator_t &operator++() {
  967. // Saturating, so that advancing past the last entry of a key stays at
  968. // end() instead of running off the container.
  969. if (idx_ >= size_) { return *this; }
  970. ++idx_;
  971. if (key_idx_ != npos()) {
  972. while (idx_ < size_ && !matches(idx_)) {
  973. ++idx_;
  974. }
  975. }
  976. return *this;
  977. }
  978. iterator_t operator++(int) {
  979. auto tmp = *this;
  980. ++*this;
  981. return tmp;
  982. }
  983. iterator_t &operator--() {
  984. if (idx_ == 0) { return *this; }
  985. --idx_;
  986. if (key_idx_ != npos()) {
  987. while (idx_ > 0 && !matches(idx_)) {
  988. --idx_;
  989. }
  990. }
  991. return *this;
  992. }
  993. iterator_t operator--(int) {
  994. auto tmp = *this;
  995. --*this;
  996. return tmp;
  997. }
  998. template <typename U> bool operator==(const iterator_t<U> &rhs) const {
  999. return idx_ == rhs.idx_;
  1000. }
  1001. template <typename U> bool operator!=(const iterator_t<U> &rhs) const {
  1002. return idx_ != rhs.idx_;
  1003. }
  1004. private:
  1005. friend class insertion_ordered_multimap;
  1006. template <typename> friend class iterator_t;
  1007. iterator_t(V *data, size_type idx, size_type size, size_type key_idx)
  1008. : data_(data), idx_(idx), size_(size), key_idx_(key_idx) {}
  1009. bool matches(size_type i) const {
  1010. return keys_equal(data_[i].first, data_[key_idx_].first);
  1011. }
  1012. V *data_;
  1013. size_type idx_;
  1014. size_type size_;
  1015. size_type key_idx_;
  1016. };
  1017. public:
  1018. using iterator = iterator_t<value_type>;
  1019. using const_iterator = iterator_t<const value_type>;
  1020. insertion_ordered_multimap() = default;
  1021. insertion_ordered_multimap(std::initializer_list<value_type> il)
  1022. : entries_(il) {}
  1023. template <typename InputIt>
  1024. insertion_ordered_multimap(InputIt first, InputIt last)
  1025. : entries_(first, last) {}
  1026. iterator begin() { return make_iter(0, npos()); }
  1027. iterator end() { return make_iter(entries_.size(), npos()); }
  1028. const_iterator begin() const { return make_citer(0, npos()); }
  1029. const_iterator end() const { return make_citer(entries_.size(), npos()); }
  1030. const_iterator cbegin() const { return begin(); }
  1031. const_iterator cend() const { return end(); }
  1032. bool empty() const { return entries_.empty(); }
  1033. size_type size() const { return entries_.size(); }
  1034. void clear() { entries_.clear(); }
  1035. void swap(insertion_ordered_multimap &rhs) { entries_.swap(rhs.entries_); }
  1036. iterator insert(const value_type &val) {
  1037. entries_.push_back(val);
  1038. return make_iter(entries_.size() - 1, npos());
  1039. }
  1040. iterator insert(value_type &&val) {
  1041. entries_.push_back(std::move(val));
  1042. return make_iter(entries_.size() - 1, npos());
  1043. }
  1044. template <typename... Args> iterator emplace(Args &&...args) {
  1045. entries_.emplace_back(std::forward<Args>(args)...);
  1046. return make_iter(entries_.size() - 1, npos());
  1047. }
  1048. // For entries that have to lead the message, such as the Host header field
  1049. // (RFC 9110 5.3 recommends sending control data first).
  1050. template <typename... Args> iterator emplace_front(Args &&...args) {
  1051. entries_.emplace(entries_.begin(), std::forward<Args>(args)...);
  1052. return make_iter(0, npos());
  1053. }
  1054. iterator find(const std::string &key) {
  1055. auto i = index_of(key);
  1056. return i == npos() ? end() : make_iter(i, i);
  1057. }
  1058. const_iterator find(const std::string &key) const {
  1059. auto i = index_of(key);
  1060. return i == npos() ? end() : make_citer(i, i);
  1061. }
  1062. size_type count(const std::string &key) const {
  1063. size_type n = 0;
  1064. for (const auto &entry : entries_) {
  1065. if (keys_equal(entry.first, key)) { n++; }
  1066. }
  1067. return n;
  1068. }
  1069. std::pair<iterator, iterator> equal_range(const std::string &key) {
  1070. auto i = index_of(key);
  1071. return i == npos() ? std::make_pair(end(), end())
  1072. : std::make_pair(make_iter(i, i), end());
  1073. }
  1074. std::pair<const_iterator, const_iterator>
  1075. equal_range(const std::string &key) const {
  1076. auto i = index_of(key);
  1077. return i == npos() ? std::make_pair(end(), end())
  1078. : std::make_pair(make_citer(i, i), end());
  1079. }
  1080. size_type erase(const std::string &key) {
  1081. auto before = entries_.size();
  1082. entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
  1083. [&](const value_type &entry) {
  1084. return keys_equal(entry.first, key);
  1085. }),
  1086. entries_.end());
  1087. return before - entries_.size();
  1088. }
  1089. iterator erase(const_iterator pos) {
  1090. entries_.erase(entries_.begin() + static_cast<difference_type>(pos.idx_));
  1091. return make_iter(pos.idx_, npos());
  1092. }
  1093. // Erases what iterating [first, last) would actually visit, so erasing an
  1094. // equal_range() removes only the entries with that key, not everything
  1095. // positioned between them.
  1096. iterator erase(const_iterator first, const_iterator last) {
  1097. auto from = first.idx_;
  1098. auto to = last.idx_;
  1099. if (from >= to) { return make_iter(from, npos()); }
  1100. auto begin_it = entries_.begin();
  1101. auto from_it = begin_it + static_cast<difference_type>(from);
  1102. auto to_it = begin_it + static_cast<difference_type>(to);
  1103. if (first.key_idx_ == npos()) {
  1104. entries_.erase(from_it, to_it);
  1105. } else {
  1106. auto key = entries_[first.key_idx_].first;
  1107. auto keep = from_it;
  1108. for (auto it = from_it; it != to_it; ++it) {
  1109. if (!keys_equal(it->first, key)) {
  1110. if (keep != it) { *keep = std::move(*it); }
  1111. ++keep;
  1112. }
  1113. }
  1114. if (keep != to_it) {
  1115. keep = std::move(to_it, entries_.end(), keep);
  1116. } else {
  1117. keep = entries_.end();
  1118. }
  1119. entries_.erase(keep, entries_.end());
  1120. }
  1121. return make_iter(from, npos());
  1122. }
  1123. friend bool operator==(const insertion_ordered_multimap &lhs,
  1124. const insertion_ordered_multimap &rhs) {
  1125. return lhs.entries_ == rhs.entries_;
  1126. }
  1127. friend bool operator!=(const insertion_ordered_multimap &lhs,
  1128. const insertion_ordered_multimap &rhs) {
  1129. return !(lhs == rhs);
  1130. }
  1131. private:
  1132. size_type index_of(const std::string &key) const {
  1133. for (size_type i = 0; i < entries_.size(); i++) {
  1134. if (keys_equal(entries_[i].first, key)) { return i; }
  1135. }
  1136. return npos();
  1137. }
  1138. iterator make_iter(size_type idx, size_type key_idx) {
  1139. return iterator(entries_.data(), idx, entries_.size(), key_idx);
  1140. }
  1141. const_iterator make_citer(size_type idx, size_type key_idx) const {
  1142. return const_iterator(entries_.data(), idx, entries_.size(), key_idx);
  1143. }
  1144. std::vector<value_type> entries_;
  1145. };
  1146. } // namespace detail
  1147. using Headers =
  1148. detail::insertion_ordered_multimap<std::string,
  1149. detail::case_ignore::equal_to>;
  1150. // Query parameter names are case-sensitive, unlike header field names.
  1151. using Params =
  1152. detail::insertion_ordered_multimap<std::string, std::equal_to<std::string>>;
  1153. using Match = std::smatch;
  1154. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  1155. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  1156. /*
  1157. * detail: type-erased storage used by UserData.
  1158. * ABI-stable regardless of C++ standard — always uses this custom
  1159. * implementation instead of std::any.
  1160. */
  1161. namespace detail {
  1162. using any_type_id = const void *;
  1163. template <typename T> any_type_id any_typeid() noexcept {
  1164. static const char id = 0;
  1165. return &id;
  1166. }
  1167. struct any_storage {
  1168. virtual ~any_storage() = default;
  1169. virtual std::unique_ptr<any_storage> clone() const = 0;
  1170. virtual any_type_id type_id() const noexcept = 0;
  1171. };
  1172. template <typename T> struct any_value final : any_storage {
  1173. T value;
  1174. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  1175. std::unique_ptr<any_storage> clone() const override {
  1176. return std::unique_ptr<any_storage>(new any_value<T>(value));
  1177. }
  1178. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  1179. };
  1180. } // namespace detail
  1181. class UserData {
  1182. public:
  1183. UserData() = default;
  1184. UserData(UserData &&) noexcept = default;
  1185. UserData &operator=(UserData &&) noexcept = default;
  1186. UserData(const UserData &o) {
  1187. for (const auto &e : o.entries_) {
  1188. if (e.second) { entries_[e.first] = e.second->clone(); }
  1189. }
  1190. }
  1191. UserData &operator=(const UserData &o) {
  1192. if (this != &o) {
  1193. entries_.clear();
  1194. for (const auto &e : o.entries_) {
  1195. if (e.second) { entries_[e.first] = e.second->clone(); }
  1196. }
  1197. }
  1198. return *this;
  1199. }
  1200. template <typename T> void set(const std::string &key, T &&value) {
  1201. using D = typename std::decay<T>::type;
  1202. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  1203. }
  1204. template <typename T> T *get(const std::string &key) noexcept {
  1205. auto it = entries_.find(key);
  1206. if (it == entries_.end() || !it->second) { return nullptr; }
  1207. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1208. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  1209. }
  1210. template <typename T> const T *get(const std::string &key) const noexcept {
  1211. auto it = entries_.find(key);
  1212. if (it == entries_.end() || !it->second) { return nullptr; }
  1213. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1214. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  1215. }
  1216. bool has(const std::string &key) const noexcept {
  1217. return entries_.find(key) != entries_.end();
  1218. }
  1219. void erase(const std::string &key) { entries_.erase(key); }
  1220. void clear() noexcept { entries_.clear(); }
  1221. private:
  1222. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  1223. entries_;
  1224. };
  1225. struct Response;
  1226. using ResponseHandler = std::function<bool(const Response &response)>;
  1227. struct FormData {
  1228. std::string name;
  1229. std::string content;
  1230. std::string filename;
  1231. std::string content_type;
  1232. Headers headers;
  1233. };
  1234. struct FormField {
  1235. std::string name;
  1236. std::string content;
  1237. Headers headers;
  1238. };
  1239. // RFC 7578 5.2: a form processor "SHOULD send back results in order" and
  1240. // "Intermediaries MUST NOT reorder the results", so a handler walking these
  1241. // should see the parts as they were sent. A std::multimap sorts by field name
  1242. // and loses that. Field names are case-sensitive, hence std::equal_to rather
  1243. // than the case-insensitive predicate Headers uses.
  1244. using FormFields =
  1245. detail::insertion_ordered_multimap<FormField, std::equal_to<std::string>>;
  1246. using FormFiles =
  1247. detail::insertion_ordered_multimap<FormData, std::equal_to<std::string>>;
  1248. struct MultipartFormData {
  1249. FormFields fields; // Text fields from multipart
  1250. FormFiles files; // Files from multipart
  1251. // Text field access
  1252. std::string get_field(const std::string &key, size_t id = 0) const;
  1253. std::vector<std::string> get_fields(const std::string &key) const;
  1254. bool has_field(const std::string &key) const;
  1255. size_t get_field_count(const std::string &key) const;
  1256. // File access
  1257. FormData get_file(const std::string &key, size_t id = 0) const;
  1258. std::vector<FormData> get_files(const std::string &key) const;
  1259. bool has_file(const std::string &key) const;
  1260. size_t get_file_count(const std::string &key) const;
  1261. };
  1262. struct UploadFormData {
  1263. std::string name;
  1264. std::string content;
  1265. std::string filename;
  1266. std::string content_type;
  1267. };
  1268. using UploadFormDataItems = std::vector<UploadFormData>;
  1269. class DataSink {
  1270. public:
  1271. DataSink() : os(&sb_), sb_(*this) {}
  1272. DataSink(const DataSink &) = delete;
  1273. DataSink &operator=(const DataSink &) = delete;
  1274. DataSink(DataSink &&) = delete;
  1275. DataSink &operator=(DataSink &&) = delete;
  1276. std::function<bool(const char *data, size_t data_len)> write;
  1277. // Only `write` is mandatory. The rest are defaulted so that a provider
  1278. // calling one on a writer that does not set it gets sensible behaviour
  1279. // rather than std::bad_function_call thrown from a worker thread. Capturing
  1280. // `this` is safe: DataSink is neither copyable nor movable.
  1281. std::function<bool()> is_writable = []() { return true; };
  1282. std::function<void()> done = []() {};
  1283. std::function<void(const Headers &trailer)> done_with_trailer =
  1284. [this](const Headers & /*trailer*/) { done(); };
  1285. std::ostream os;
  1286. private:
  1287. class data_sink_streambuf final : public std::streambuf {
  1288. public:
  1289. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  1290. protected:
  1291. std::streamsize xsputn(const char *s, std::streamsize n) override {
  1292. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  1293. return 0;
  1294. }
  1295. private:
  1296. DataSink &sink_;
  1297. };
  1298. data_sink_streambuf sb_;
  1299. };
  1300. using ContentProvider =
  1301. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  1302. using ContentProviderWithoutLength =
  1303. std::function<bool(size_t offset, DataSink &sink)>;
  1304. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  1305. struct FormDataProvider {
  1306. std::string name;
  1307. ContentProviderWithoutLength provider;
  1308. std::string filename;
  1309. std::string content_type;
  1310. };
  1311. using FormDataProviderItems = std::vector<FormDataProvider>;
  1312. inline FormDataProvider
  1313. make_file_provider(const std::string &name, const std::string &filepath,
  1314. const std::string &filename = std::string(),
  1315. const std::string &content_type = std::string()) {
  1316. FormDataProvider fdp;
  1317. fdp.name = name;
  1318. fdp.filename = filename.empty() ? filepath : filename;
  1319. fdp.content_type = content_type;
  1320. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  1321. std::ifstream f(filepath, std::ios::binary);
  1322. if (!f) { return false; }
  1323. if (offset > 0) {
  1324. f.seekg(static_cast<std::streamoff>(offset));
  1325. if (!f.good()) {
  1326. sink.done();
  1327. return true;
  1328. }
  1329. }
  1330. char buf[8192];
  1331. f.read(buf, sizeof(buf));
  1332. auto n = static_cast<size_t>(f.gcount());
  1333. if (n > 0) { return sink.write(buf, n); }
  1334. sink.done(); // EOF
  1335. return true;
  1336. };
  1337. return fdp;
  1338. }
  1339. inline std::pair<size_t, ContentProvider>
  1340. make_file_body(const std::string &filepath) {
  1341. size_t size = 0;
  1342. {
  1343. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  1344. if (!f) { return {0, ContentProvider{}}; }
  1345. size = static_cast<size_t>(f.tellg());
  1346. }
  1347. ContentProvider provider = [filepath](size_t offset, size_t length,
  1348. DataSink &sink) -> bool {
  1349. std::ifstream f(filepath, std::ios::binary);
  1350. if (!f) { return false; }
  1351. f.seekg(static_cast<std::streamoff>(offset));
  1352. if (!f.good()) { return false; }
  1353. char buf[8192];
  1354. while (length > 0) {
  1355. auto to_read = (std::min)(sizeof(buf), length);
  1356. f.read(buf, static_cast<std::streamsize>(to_read));
  1357. auto n = static_cast<size_t>(f.gcount());
  1358. // The file is shorter than the size make_file_body() measured, which the
  1359. // caller has already committed to as Content-Length. The body cannot be
  1360. // completed, so fail as every other error here does.
  1361. if (n == 0) { return false; }
  1362. if (!sink.write(buf, n)) { return false; }
  1363. length -= n;
  1364. }
  1365. return true;
  1366. };
  1367. return {size, std::move(provider)};
  1368. }
  1369. using ContentReceiverWithProgress = std::function<bool(
  1370. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1371. using ContentReceiver =
  1372. std::function<bool(const char *data, size_t data_length)>;
  1373. using FormDataHeader = std::function<bool(const FormData &file)>;
  1374. class ContentReader {
  1375. public:
  1376. using Reader = std::function<bool(ContentReceiver receiver)>;
  1377. using FormDataReader =
  1378. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1379. ContentReader(Reader reader, FormDataReader multipart_reader)
  1380. : reader_(std::move(reader)),
  1381. formdata_reader_(std::move(multipart_reader)) {}
  1382. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1383. return formdata_reader_(std::move(header), std::move(receiver));
  1384. }
  1385. bool operator()(ContentReceiver receiver) const {
  1386. return reader_(std::move(receiver));
  1387. }
  1388. Reader reader_;
  1389. FormDataReader formdata_reader_;
  1390. };
  1391. using Range = std::pair<ssize_t, ssize_t>;
  1392. using Ranges = std::vector<Range>;
  1393. #ifdef CPPHTTPLIB_SSL_ENABLED
  1394. // TLS abstraction layer - public type definitions and API
  1395. namespace tls {
  1396. // Opaque handles (defined as void* for abstraction)
  1397. using ctx_t = void *;
  1398. using session_t = void *;
  1399. using const_session_t = const void *; // For read-only session access
  1400. using cert_t = void *;
  1401. using ca_store_t = void *;
  1402. // TLS versions
  1403. enum class Version {
  1404. TLS1_2 = 0x0303,
  1405. TLS1_3 = 0x0304,
  1406. };
  1407. // Subject Alternative Names (SAN) entry types
  1408. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1409. // SAN entry structure
  1410. struct SanEntry {
  1411. SanType type;
  1412. std::string value;
  1413. };
  1414. // Verification context for certificate verification callback
  1415. struct VerifyContext {
  1416. session_t session; // TLS session handle
  1417. cert_t cert; // Current certificate being verified
  1418. int depth; // Certificate chain depth (0 = leaf)
  1419. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1420. long error_code; // Backend-specific error code (0 = no error)
  1421. const char *error_string; // Human-readable error description
  1422. // Certificate introspection methods
  1423. std::string subject_cn() const;
  1424. std::string issuer_name() const;
  1425. bool check_hostname(const char *hostname) const;
  1426. std::vector<SanEntry> sans() const;
  1427. bool validity(time_t &not_before, time_t &not_after) const;
  1428. std::string serial() const;
  1429. };
  1430. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1431. // TlsError codes for TLS operations (backend-independent)
  1432. enum class ErrorCode : int {
  1433. Success = 0,
  1434. WantRead, // Non-blocking: need to wait for read
  1435. WantWrite, // Non-blocking: need to wait for write
  1436. PeerClosed, // Peer closed the connection
  1437. Fatal, // Unrecoverable error
  1438. SyscallError, // System call error (check sys_errno)
  1439. CertVerifyFailed, // Certificate verification failed
  1440. HostnameMismatch, // Hostname verification failed
  1441. };
  1442. // TLS error information
  1443. struct TlsError {
  1444. ErrorCode code = ErrorCode::Fatal;
  1445. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1446. int sys_errno = 0; // errno when SyscallError
  1447. // Convert verification error code to human-readable string
  1448. static std::string verify_error_to_string(long error_code);
  1449. };
  1450. // RAII wrapper for peer certificate
  1451. class PeerCert {
  1452. public:
  1453. PeerCert();
  1454. PeerCert(PeerCert &&other) noexcept;
  1455. PeerCert &operator=(PeerCert &&other) noexcept;
  1456. ~PeerCert();
  1457. PeerCert(const PeerCert &) = delete;
  1458. PeerCert &operator=(const PeerCert &) = delete;
  1459. explicit operator bool() const;
  1460. std::string subject_cn() const;
  1461. std::string issuer_name() const;
  1462. bool check_hostname(const char *hostname) const;
  1463. std::vector<SanEntry> sans() const;
  1464. bool validity(time_t &not_before, time_t &not_after) const;
  1465. std::string serial() const;
  1466. private:
  1467. explicit PeerCert(cert_t cert);
  1468. cert_t cert_ = nullptr;
  1469. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1470. };
  1471. // Callback for TLS context setup (used by SSLServer constructor)
  1472. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1473. } // namespace tls
  1474. #endif
  1475. struct Request {
  1476. std::string method;
  1477. std::string path;
  1478. std::string matched_route;
  1479. Params params;
  1480. Headers headers;
  1481. Headers trailers;
  1482. std::string body;
  1483. std::string remote_addr;
  1484. int remote_port = -1;
  1485. std::string local_addr;
  1486. int local_port = -1;
  1487. // for server
  1488. std::string version;
  1489. std::string target;
  1490. MultipartFormData form;
  1491. Ranges ranges;
  1492. Match matches;
  1493. std::unordered_map<std::string, std::string> path_params;
  1494. std::function<bool()> is_connection_closed = []() { return true; };
  1495. // for client
  1496. std::vector<std::string> accept_content_types;
  1497. ResponseHandler response_handler;
  1498. ContentReceiverWithProgress content_receiver;
  1499. DownloadProgress download_progress;
  1500. UploadProgress upload_progress;
  1501. bool has_header(const std::string &key) const;
  1502. std::string get_header_value(const std::string &key, const char *def = "",
  1503. size_t id = 0) const;
  1504. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1505. size_t id = 0) const;
  1506. size_t get_header_value_count(const std::string &key) const;
  1507. void set_header(const std::string &key, const std::string &val);
  1508. bool has_trailer(const std::string &key) const;
  1509. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1510. size_t get_trailer_value_count(const std::string &key) const;
  1511. bool has_param(const std::string &key) const;
  1512. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1513. std::vector<std::string> get_param_values(const std::string &key) const;
  1514. size_t get_param_value_count(const std::string &key) const;
  1515. bool is_multipart_form_data() const;
  1516. // private members...
  1517. bool body_consumed_ = false;
  1518. bool expect_100_continue_pending_ = false;
  1519. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1520. size_t content_length_ = 0;
  1521. ContentProvider content_provider_;
  1522. bool is_chunked_content_provider_ = false;
  1523. size_t authorization_count_ = 0;
  1524. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1525. (std::chrono::steady_clock::time_point::min)();
  1526. #ifdef CPPHTTPLIB_SSL_ENABLED
  1527. tls::const_session_t ssl = nullptr;
  1528. tls::PeerCert peer_cert() const;
  1529. std::string sni() const;
  1530. #endif
  1531. };
  1532. namespace detail {
  1533. // Declared up here, away from the rest of the compression helpers, because
  1534. // `Response` stores one.
  1535. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1536. } // namespace detail
  1537. struct Response {
  1538. std::string version;
  1539. int status = -1;
  1540. std::string reason;
  1541. Headers headers;
  1542. Headers trailers;
  1543. std::string body;
  1544. std::string location; // Redirect location
  1545. // User-defined context — set by pre-routing/pre-request handlers and read
  1546. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1547. UserData user_data;
  1548. bool has_header(const std::string &key) const;
  1549. std::string get_header_value(const std::string &key, const char *def = "",
  1550. size_t id = 0) const;
  1551. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1552. size_t id = 0) const;
  1553. size_t get_header_value_count(const std::string &key) const;
  1554. void set_header(const std::string &key, const std::string &val);
  1555. bool has_trailer(const std::string &key) const;
  1556. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1557. size_t get_trailer_value_count(const std::string &key) const;
  1558. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1559. void set_content(const char *s, size_t n, const std::string &content_type);
  1560. void set_content(const std::string &s, const std::string &content_type);
  1561. void set_content(std::string &&s, const std::string &content_type);
  1562. void set_content_provider(
  1563. size_t length, const std::string &content_type, ContentProvider provider,
  1564. ContentProviderResourceReleaser resource_releaser = nullptr);
  1565. void set_content_provider(
  1566. const std::string &content_type, ContentProviderWithoutLength provider,
  1567. ContentProviderResourceReleaser resource_releaser = nullptr);
  1568. void set_chunked_content_provider(
  1569. const std::string &content_type, ContentProviderWithoutLength provider,
  1570. ContentProviderResourceReleaser resource_releaser = nullptr);
  1571. void set_file_content(const std::string &path,
  1572. const std::string &content_type);
  1573. void set_file_content(const std::string &path);
  1574. Response() = default;
  1575. Response(const Response &) = default;
  1576. Response &operator=(const Response &) = default;
  1577. Response(Response &&) = default;
  1578. Response &operator=(Response &&) = default;
  1579. ~Response() {
  1580. if (content_provider_resource_releaser_) {
  1581. content_provider_resource_releaser_(content_provider_success_);
  1582. }
  1583. }
  1584. // private members...
  1585. size_t content_length_ = 0;
  1586. ContentProvider content_provider_;
  1587. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1588. bool is_chunked_content_provider_ = false;
  1589. bool is_file_content_provider_ = false;
  1590. bool content_provider_success_ = false;
  1591. std::string file_content_path_;
  1592. std::string file_content_content_type_;
  1593. // Content coding chosen for the response body, decided once so that the
  1594. // headers and the body cannot disagree: where the file is opened for a
  1595. // file-backed content provider (keeping the ETag honest), and in
  1596. // `apply_ranges()` for a chunked content provider. `EncodingType::None`
  1597. // for every other kind of response.
  1598. detail::EncodingType content_coding_ = detail::EncodingType::None;
  1599. };
  1600. enum class Error {
  1601. Success = 0,
  1602. Unknown,
  1603. Connection,
  1604. BindIPAddress,
  1605. Read,
  1606. Write,
  1607. ExceedRedirectCount,
  1608. Canceled,
  1609. SSLConnection,
  1610. SSLLoadingCerts,
  1611. SSLServerVerification,
  1612. SSLServerHostnameVerification,
  1613. UnsupportedMultipartBoundaryChars,
  1614. Compression,
  1615. ConnectionTimeout,
  1616. ProxyConnection,
  1617. ConnectionClosed,
  1618. Timeout,
  1619. ResourceExhaustion,
  1620. TooManyFormDataFiles,
  1621. ExceedMaxPayloadSize,
  1622. ExceedUriMaxLength,
  1623. ExceedMaxSocketDescriptorCount,
  1624. InvalidRequestLine,
  1625. InvalidHTTPMethod,
  1626. InvalidHTTPVersion,
  1627. InvalidHeaders,
  1628. MultipartParsing,
  1629. OpenFile,
  1630. Listen,
  1631. GetSockName,
  1632. UnsupportedAddressFamily,
  1633. HTTPParsing,
  1634. InvalidRangeHeader,
  1635. UnsupportedContentEncoding,
  1636. WebSocketHandshake,
  1637. UserCallbackException,
  1638. // For internal use only
  1639. SSLPeerCouldBeClosed_,
  1640. };
  1641. std::string to_string(Error error);
  1642. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1643. class Stream {
  1644. public:
  1645. virtual ~Stream() = default;
  1646. virtual bool is_readable() const = 0;
  1647. virtual bool wait_readable() const = 0;
  1648. virtual bool wait_writable() const = 0;
  1649. virtual bool is_peer_alive() const { return wait_writable(); }
  1650. virtual ssize_t read(char *ptr, size_t size) = 0;
  1651. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1652. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1653. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1654. virtual socket_t socket() const = 0;
  1655. virtual time_t duration() const = 0;
  1656. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1657. (void)sec;
  1658. (void)usec;
  1659. }
  1660. // Bytes already pulled off the socket and sitting in this stream's own
  1661. // buffer. Exposing them lets a line reader scan for a terminator in one
  1662. // pass instead of asking for a byte at a time. A stream that does no
  1663. // buffering of its own reports none, and readers fall back to read().
  1664. virtual const char *buffered_data(size_t &size) const {
  1665. size = 0;
  1666. return nullptr;
  1667. }
  1668. // Discards `size` bytes previously returned by buffered_data().
  1669. virtual void consume_buffered(size_t size) { (void)size; }
  1670. ssize_t write(const char *ptr);
  1671. ssize_t write(const std::string &s);
  1672. Error get_error() const { return error_; }
  1673. protected:
  1674. Error error_ = Error::Success;
  1675. };
  1676. class TaskQueue {
  1677. public:
  1678. TaskQueue() = default;
  1679. virtual ~TaskQueue() = default;
  1680. virtual bool enqueue(std::function<void()> fn) = 0;
  1681. virtual void shutdown() = 0;
  1682. virtual void on_idle() {}
  1683. };
  1684. class ThreadPool final : public TaskQueue {
  1685. public:
  1686. explicit ThreadPool(
  1687. size_t n, size_t max_n = 0, size_t mqr = 0,
  1688. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1689. ThreadPool(const ThreadPool &) = delete;
  1690. ~ThreadPool() override = default;
  1691. bool enqueue(std::function<void()> fn) override;
  1692. void shutdown() override;
  1693. private:
  1694. void worker(bool is_dynamic);
  1695. void move_to_finished(std::thread::id id);
  1696. void cleanup_finished_threads();
  1697. size_t base_thread_count_;
  1698. size_t max_thread_count_;
  1699. size_t max_queued_requests_;
  1700. time_t idle_timeout_sec_;
  1701. size_t idle_thread_count_;
  1702. bool shutdown_;
  1703. std::list<std::function<void()>> jobs_;
  1704. std::vector<std::thread> threads_; // base threads
  1705. std::list<std::thread> dynamic_threads_; // dynamic threads
  1706. std::vector<std::thread>
  1707. finished_threads_; // exited dynamic threads awaiting join
  1708. std::condition_variable cond_;
  1709. std::mutex mutex_;
  1710. };
  1711. using Logger = std::function<void(const Request &, const Response &)>;
  1712. // Forward declaration for Error type
  1713. enum class Error;
  1714. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1715. using SocketOptions = std::function<void(socket_t sock)>;
  1716. void default_socket_options(socket_t sock);
  1717. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1718. const char *status_message(int status);
  1719. std::string to_string(Error error);
  1720. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1721. std::string get_bearer_token_auth(const Request &req);
  1722. namespace detail {
  1723. class MatcherBase {
  1724. public:
  1725. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1726. virtual ~MatcherBase() = default;
  1727. const std::string &pattern() const { return pattern_; }
  1728. // Match request path and populate its matches and
  1729. virtual bool match(Request &request) const = 0;
  1730. private:
  1731. std::string pattern_;
  1732. };
  1733. /**
  1734. * Captures parameters in request path and stores them in Request::path_params
  1735. *
  1736. * Capture name is a substring of a pattern from : to /.
  1737. * The rest of the pattern is matched against the request path directly
  1738. * Parameters are captured starting from the next character after
  1739. * the end of the last matched static pattern fragment until the next /.
  1740. *
  1741. * Example pattern:
  1742. * "/path/fragments/:capture/more/fragments/:second_capture"
  1743. * Static fragments:
  1744. * "/path/fragments/", "more/fragments/"
  1745. *
  1746. * Given the following request path:
  1747. * "/path/fragments/:1/more/fragments/:2"
  1748. * the resulting capture will be
  1749. * {{"capture", "1"}, {"second_capture", "2"}}
  1750. */
  1751. class PathParamsMatcher final : public MatcherBase {
  1752. public:
  1753. PathParamsMatcher(const std::string &pattern);
  1754. bool match(Request &request) const override;
  1755. private:
  1756. // Treat segment separators as the end of path parameter capture
  1757. // Does not need to handle query parameters as they are parsed before path
  1758. // matching
  1759. static constexpr char separator = '/';
  1760. // Contains static path fragments to match against, excluding the '/' after
  1761. // path params
  1762. // Fragments are separated by path params
  1763. std::vector<std::string> static_fragments_;
  1764. // Stores the names of the path parameters to be used as keys in the
  1765. // Request::path_params map
  1766. std::vector<std::string> param_names_;
  1767. };
  1768. /**
  1769. * Performs std::regex_match on request path
  1770. * and stores the result in Request::matches
  1771. *
  1772. * Note that regex match is performed directly on the whole request.
  1773. * This means that wildcard patterns may match multiple path segments with /:
  1774. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1775. */
  1776. class RegexMatcher final : public MatcherBase {
  1777. public:
  1778. RegexMatcher(const std::string &pattern)
  1779. : MatcherBase(pattern), regex_(pattern) {}
  1780. bool match(Request &request) const override;
  1781. private:
  1782. std::regex regex_;
  1783. };
  1784. int close_socket(socket_t sock) noexcept;
  1785. bool is_accept_resource_error();
  1786. bool is_accept_transient_error();
  1787. ssize_t write_headers(Stream &strm, const Headers &headers);
  1788. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1789. time_t usec);
  1790. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1791. const std::string &boundary);
  1792. ContentProvider
  1793. make_multipart_content_provider(const UploadFormDataItems &items,
  1794. const std::string &boundary);
  1795. } // namespace detail
  1796. bool is_valid_multipart_boundary(const std::string &boundary);
  1797. // Serializer for multipart/form-data request bodies. The boundary is owned
  1798. // by the writer so that per-part framing and the final terminator always
  1799. // agree. Field names and filenames are escaped following the WHATWG HTML
  1800. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1801. // in content types.
  1802. class MultipartFormDataWriter {
  1803. public:
  1804. MultipartFormDataWriter();
  1805. // precondition: is_valid_multipart_boundary(boundary)
  1806. explicit MultipartFormDataWriter(std::string boundary);
  1807. const std::string &boundary() const;
  1808. std::string content_type() const;
  1809. // In-memory items -> whole body (known length)
  1810. std::string serialize(const UploadFormDataItems &items) const;
  1811. size_t content_length(const UploadFormDataItems &items) const;
  1812. // Per-part framing for streaming via a content provider
  1813. std::string item_begin(const UploadFormData &item) const;
  1814. static std::string item_end();
  1815. std::string finish() const;
  1816. private:
  1817. std::string boundary_;
  1818. };
  1819. class Server {
  1820. public:
  1821. using Handler = std::function<void(const Request &, Response &)>;
  1822. using ExceptionHandler =
  1823. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1824. enum class HandlerResponse {
  1825. Handled,
  1826. Unhandled,
  1827. };
  1828. using HandlerWithResponse =
  1829. std::function<HandlerResponse(const Request &, Response &)>;
  1830. using HandlerWithContentReader = std::function<void(
  1831. const Request &, Response &, const ContentReader &content_reader)>;
  1832. using Expect100ContinueHandler =
  1833. std::function<int(const Request &, Response &)>;
  1834. using StartHandler = std::function<void()>;
  1835. using WebSocketHandler =
  1836. std::function<void(const Request &, ws::WebSocket &)>;
  1837. using SubProtocolSelector =
  1838. std::function<std::string(const std::vector<std::string> &protocols)>;
  1839. Server();
  1840. virtual ~Server();
  1841. virtual bool is_valid() const;
  1842. Server &Get(const std::string &pattern, Handler handler);
  1843. Server &Post(const std::string &pattern, Handler handler);
  1844. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1845. Server &Put(const std::string &pattern, Handler handler);
  1846. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1847. Server &Patch(const std::string &pattern, Handler handler);
  1848. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1849. Server &Delete(const std::string &pattern, Handler handler);
  1850. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1851. Server &Options(const std::string &pattern, Handler handler);
  1852. // Register a handler for an HTTP method outside the built-in set (e.g. the
  1853. // WebDAV methods from RFC 4918). Registering a method here is what makes the
  1854. // server accept it; an unregistered method is still rejected with 400.
  1855. // `method` must be a valid HTTP method token and must not be one of the
  1856. // built-in methods, which have their own registration functions above. A
  1857. // rejected registration makes is_valid() return false, so listen() fails.
  1858. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1859. Handler handler);
  1860. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1861. HandlerWithContentReader handler);
  1862. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1863. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1864. SubProtocolSelector sub_protocol_selector);
  1865. bool set_base_dir(const std::string &dir,
  1866. const std::string &mount_point = std::string());
  1867. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1868. Headers headers = Headers());
  1869. bool remove_mount_point(const std::string &mount_point);
  1870. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1871. const std::string &mime);
  1872. Server &set_default_file_mimetype(const std::string &mime);
  1873. Server &set_file_request_handler(Handler handler);
  1874. template <class ErrorHandlerFunc>
  1875. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1876. return set_error_handler_core(
  1877. std::forward<ErrorHandlerFunc>(handler),
  1878. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1879. }
  1880. Server &set_exception_handler(ExceptionHandler handler);
  1881. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1882. Server &set_post_routing_handler(Handler handler);
  1883. Server &set_pre_request_handler(HandlerWithResponse handler);
  1884. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1885. Server &set_start_handler(StartHandler handler);
  1886. Server &set_logger(Logger logger);
  1887. Server &set_pre_compression_logger(Logger logger);
  1888. Server &set_error_logger(ErrorLogger error_logger);
  1889. Server &set_address_family(int family);
  1890. Server &set_tcp_nodelay(bool on);
  1891. Server &set_ipv6_v6only(bool on);
  1892. Server &set_socket_options(SocketOptions socket_options);
  1893. Server &set_default_headers(Headers headers);
  1894. Server &
  1895. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1896. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1897. Server &set_keep_alive_max_count(size_t count);
  1898. Server &set_keep_alive_timeout(time_t sec);
  1899. template <class Rep, class Period>
  1900. Server &
  1901. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1902. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1903. template <class Rep, class Period>
  1904. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1905. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1906. template <class Rep, class Period>
  1907. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1908. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1909. template <class Rep, class Period>
  1910. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1911. Server &set_payload_max_length(size_t length);
  1912. Server &set_static_file_compression(bool on);
  1913. Server &set_static_file_compression_min_length(size_t length);
  1914. Server &set_static_file_compression_max_length(size_t length);
  1915. Server &set_websocket_ping_interval(time_t sec);
  1916. template <class Rep, class Period>
  1917. Server &set_websocket_ping_interval(
  1918. const std::chrono::duration<Rep, Period> &duration);
  1919. Server &set_websocket_max_missed_pongs(int count);
  1920. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1921. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1922. bool listen_after_bind();
  1923. bool listen(const std::string &host, int port, int socket_flags = 0);
  1924. bool is_running() const;
  1925. void wait_until_ready() const;
  1926. void stop() noexcept;
  1927. void decommission();
  1928. std::function<TaskQueue *(void)> new_task_queue;
  1929. protected:
  1930. bool process_request(Stream &strm, const std::string &remote_addr,
  1931. int remote_port, const std::string &local_addr,
  1932. int local_port, bool close_connection,
  1933. bool &connection_closed,
  1934. const std::function<void(Request &)> &setup_request,
  1935. bool *websocket_upgraded = nullptr);
  1936. // Runs the per-connection serving loop and stops an exception thrown by a
  1937. // user callback from escaping the worker thread.
  1938. //
  1939. // process_request() wraps only routing() in a try/catch. Content providers,
  1940. // the post-routing, error, logging and expect-100 handlers and WebSocket
  1941. // handlers all run outside it, and the task queue calls the job without a
  1942. // catch, so an exception from any of those would terminate the process.
  1943. //
  1944. // No 500 is possible here: by the time a content provider runs, the status
  1945. // line and headers are already on the wire. Report it through the error
  1946. // logger and drop the connection, which is what the peer observes either
  1947. // way. Other connections are unaffected.
  1948. template <typename Serve> bool serve_guarded(Serve &&serve) const {
  1949. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  1950. return serve();
  1951. #else
  1952. try {
  1953. return serve();
  1954. } catch (...) {
  1955. // The error logger is a user callback too, so it must not be able to
  1956. // throw the guard back open.
  1957. try {
  1958. output_error_log(Error::UserCallbackException, nullptr);
  1959. } catch (...) {}
  1960. return false;
  1961. }
  1962. #endif
  1963. }
  1964. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1965. std::vector<std::string> trusted_proxies_;
  1966. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1967. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1968. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1969. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1970. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1971. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1972. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1973. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1974. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1975. bool static_file_compression_ = false;
  1976. size_t static_file_compression_min_length_ =
  1977. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH;
  1978. size_t static_file_compression_max_length_ =
  1979. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH;
  1980. time_t websocket_ping_interval_sec_ =
  1981. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1982. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1983. private:
  1984. using Handlers =
  1985. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1986. using HandlersForContentReader =
  1987. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1988. HandlerWithContentReader>>;
  1989. // Both handler tables for one custom method live in a single entry, so that
  1990. // routing() needs only one map lookup per request to reach either of them.
  1991. struct CustomHandlerEntry {
  1992. Handlers handlers;
  1993. HandlersForContentReader handlers_for_content_reader;
  1994. };
  1995. using CustomHandlers = std::map<std::string, CustomHandlerEntry>;
  1996. static std::unique_ptr<detail::MatcherBase>
  1997. make_matcher(const std::string &pattern);
  1998. static const std::set<std::string> &builtin_methods();
  1999. CustomHandlerEntry *custom_entry_for_registration(const std::string &method);
  2000. const CustomHandlerEntry *find_custom_entry(const std::string &method) const;
  2001. template <typename H>
  2002. Server &add_handler(
  2003. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  2004. const std::string &pattern, H handler) {
  2005. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  2006. return *this;
  2007. }
  2008. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  2009. Server &set_error_handler_core(Handler handler, std::false_type);
  2010. socket_t create_server_socket(const std::string &host, int port,
  2011. int socket_flags,
  2012. SocketOptions socket_options) const;
  2013. int bind_internal(const std::string &host, int port, int socket_flags);
  2014. bool listen_internal();
  2015. bool routing(Request &req, Response &res, Stream &strm);
  2016. bool handle_file_request(Request &req, Response &res);
  2017. bool check_if_not_modified(const Request &req, Response &res,
  2018. const std::string &etag, time_t mtime) const;
  2019. bool check_if_range(Request &req, const std::string &etag,
  2020. time_t mtime) const;
  2021. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  2022. Stream &strm);
  2023. bool dispatch_request_for_content_reader(
  2024. Request &req, Response &res, ContentReader content_reader,
  2025. const HandlersForContentReader &handlers) const;
  2026. bool parse_request_line(const char *s, Request &req) const;
  2027. detail::EncodingType static_file_encoding(const Request &req,
  2028. const Response &res,
  2029. const std::string &content_type,
  2030. size_t length) const;
  2031. bool apply_static_file_compression(const Request &req, Response &res) const;
  2032. void apply_ranges(const Request &req, Response &res,
  2033. std::string &content_type, std::string &boundary) const;
  2034. bool write_response(Stream &strm, bool close_connection, Request &req,
  2035. Response &res);
  2036. bool write_response_with_content(Stream &strm, bool close_connection,
  2037. const Request &req, Response &res);
  2038. bool write_response_core(Stream &strm, bool close_connection,
  2039. const Request &req, Response &res,
  2040. bool need_apply_ranges);
  2041. bool write_content_with_provider(Stream &strm, const Request &req,
  2042. Response &res, const std::string &boundary,
  2043. const std::string &content_type);
  2044. bool read_content(Stream &strm, Request &req, Response &res);
  2045. bool read_content_with_content_receiver(Stream &strm, Request &req,
  2046. Response &res,
  2047. ContentReceiver receiver,
  2048. FormDataHeader multipart_header,
  2049. ContentReceiver multipart_receiver);
  2050. bool read_content_core(Stream &strm, Request &req, Response &res,
  2051. ContentReceiver receiver,
  2052. FormDataHeader multipart_header,
  2053. ContentReceiver multipart_receiver) const;
  2054. virtual bool process_and_close_socket(socket_t sock);
  2055. void output_log(const Request &req, const Response &res) const;
  2056. void output_pre_compression_log(const Request &req,
  2057. const Response &res) const;
  2058. void output_error_log(const Error &err, const Request *req) const;
  2059. std::atomic<bool> is_running_{false};
  2060. std::atomic<bool> is_decommissioned{false};
  2061. // Set when CustomRoute() refuses a registration. Written before listen(),
  2062. // read by is_valid() on the same thread, so it needs no synchronization.
  2063. bool has_invalid_registration_ = false;
  2064. struct MountPointEntry {
  2065. std::string mount_point;
  2066. std::string base_dir;
  2067. std::string resolved_base_dir;
  2068. Headers headers;
  2069. };
  2070. std::vector<MountPointEntry> base_dirs_;
  2071. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  2072. std::string default_file_mimetype_ = "application/octet-stream";
  2073. Handler file_request_handler_;
  2074. Handlers get_handlers_;
  2075. Handlers post_handlers_;
  2076. HandlersForContentReader post_handlers_for_content_reader_;
  2077. Handlers put_handlers_;
  2078. HandlersForContentReader put_handlers_for_content_reader_;
  2079. Handlers patch_handlers_;
  2080. HandlersForContentReader patch_handlers_for_content_reader_;
  2081. Handlers delete_handlers_;
  2082. HandlersForContentReader delete_handlers_for_content_reader_;
  2083. Handlers options_handlers_;
  2084. CustomHandlers custom_handlers_;
  2085. struct WebSocketHandlerEntry {
  2086. std::unique_ptr<detail::MatcherBase> matcher;
  2087. WebSocketHandler handler;
  2088. SubProtocolSelector sub_protocol_selector;
  2089. };
  2090. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  2091. WebSocketHandlers websocket_handlers_;
  2092. HandlerWithResponse error_handler_;
  2093. ExceptionHandler exception_handler_;
  2094. HandlerWithResponse pre_routing_handler_;
  2095. Handler post_routing_handler_;
  2096. HandlerWithResponse pre_request_handler_;
  2097. Expect100ContinueHandler expect_100_continue_handler_;
  2098. StartHandler start_handler_;
  2099. mutable std::mutex logger_mutex_;
  2100. Logger logger_;
  2101. Logger pre_compression_logger_;
  2102. ErrorLogger error_logger_;
  2103. int address_family_ = AF_UNSPEC;
  2104. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2105. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2106. SocketOptions socket_options_ = default_socket_options;
  2107. Headers default_headers_;
  2108. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2109. detail::write_headers;
  2110. };
  2111. class Result {
  2112. public:
  2113. Result() = default;
  2114. Result(std::unique_ptr<Response> &&res, Error err,
  2115. Headers &&request_headers = Headers{})
  2116. : res_(std::move(res)), err_(err),
  2117. request_headers_(std::move(request_headers)) {}
  2118. // Response
  2119. operator bool() const { return res_ != nullptr; }
  2120. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  2121. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  2122. const Response &value() const { return *res_; }
  2123. Response &value() { return *res_; }
  2124. const Response &operator*() const { return *res_; }
  2125. Response &operator*() { return *res_; }
  2126. const Response *operator->() const { return res_.get(); }
  2127. Response *operator->() { return res_.get(); }
  2128. // Error
  2129. Error error() const { return err_; }
  2130. // Request Headers
  2131. bool has_request_header(const std::string &key) const;
  2132. std::string get_request_header_value(const std::string &key,
  2133. const char *def = "",
  2134. size_t id = 0) const;
  2135. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  2136. size_t id = 0) const;
  2137. size_t get_request_header_value_count(const std::string &key) const;
  2138. private:
  2139. std::unique_ptr<Response> res_;
  2140. Error err_ = Error::Unknown;
  2141. Headers request_headers_;
  2142. #ifdef CPPHTTPLIB_SSL_ENABLED
  2143. public:
  2144. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2145. int ssl_error)
  2146. : res_(std::move(res)), err_(err),
  2147. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  2148. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2149. int ssl_error, uint64_t ssl_backend_error)
  2150. : res_(std::move(res)), err_(err),
  2151. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  2152. ssl_backend_error_(ssl_backend_error) {}
  2153. int ssl_error() const { return ssl_error_; }
  2154. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  2155. private:
  2156. int ssl_error_ = 0;
  2157. uint64_t ssl_backend_error_ = 0;
  2158. #endif
  2159. };
  2160. struct ClientConnection {
  2161. socket_t sock = INVALID_SOCKET;
  2162. bool is_open() const { return sock != INVALID_SOCKET; }
  2163. ClientConnection() = default;
  2164. ~ClientConnection();
  2165. ClientConnection(const ClientConnection &) = delete;
  2166. ClientConnection &operator=(const ClientConnection &) = delete;
  2167. ClientConnection(ClientConnection &&other) noexcept
  2168. : sock(other.sock)
  2169. #ifdef CPPHTTPLIB_SSL_ENABLED
  2170. ,
  2171. session(other.session)
  2172. #endif
  2173. {
  2174. other.sock = INVALID_SOCKET;
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. other.session = nullptr;
  2177. #endif
  2178. }
  2179. ClientConnection &operator=(ClientConnection &&other) noexcept {
  2180. if (this != &other) {
  2181. sock = other.sock;
  2182. other.sock = INVALID_SOCKET;
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. session = other.session;
  2185. other.session = nullptr;
  2186. #endif
  2187. }
  2188. return *this;
  2189. }
  2190. #ifdef CPPHTTPLIB_SSL_ENABLED
  2191. tls::session_t session = nullptr;
  2192. #endif
  2193. };
  2194. namespace detail {
  2195. struct ChunkedDecoder;
  2196. struct BodyReader {
  2197. Stream *stream = nullptr;
  2198. bool has_content_length = false;
  2199. size_t content_length = 0;
  2200. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2201. size_t bytes_read = 0;
  2202. bool chunked = false;
  2203. bool eof = false;
  2204. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  2205. Error last_error = Error::Success;
  2206. ssize_t read(char *buf, size_t len);
  2207. bool has_error() const { return last_error != Error::Success; }
  2208. };
  2209. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  2210. size_t len) {
  2211. (void)stream;
  2212. return br.read(buf, len);
  2213. }
  2214. class decompressor;
  2215. enum class NoProxyKind {
  2216. Wildcard, // "*"
  2217. HostnameSuffix, // "example.com" or ".example.com"
  2218. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  2219. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  2220. };
  2221. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  2222. // Lets one CIDR matcher cover both families.
  2223. using IPBytes = std::array<uint8_t, 16>;
  2224. struct NoProxyEntry {
  2225. NoProxyKind kind = NoProxyKind::Wildcard;
  2226. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  2227. IPBytes net{};
  2228. int prefix_bits = 0;
  2229. };
  2230. struct NormalizedTarget {
  2231. std::string hostname; // lowercase; brackets and trailing dot removed
  2232. bool is_ipv4 = false;
  2233. bool is_ipv6 = false;
  2234. IPBytes ip{};
  2235. };
  2236. } // namespace detail
  2237. class ClientImpl {
  2238. public:
  2239. explicit ClientImpl(const std::string &host);
  2240. explicit ClientImpl(const std::string &host, int port);
  2241. explicit ClientImpl(const std::string &host, int port,
  2242. const std::string &client_cert_path,
  2243. const std::string &client_key_path);
  2244. virtual ~ClientImpl();
  2245. virtual bool is_valid() const;
  2246. struct StreamHandle {
  2247. std::unique_ptr<Response> response;
  2248. Error error = Error::Success;
  2249. StreamHandle() = default;
  2250. StreamHandle(const StreamHandle &) = delete;
  2251. StreamHandle &operator=(const StreamHandle &) = delete;
  2252. StreamHandle(StreamHandle &&) = default;
  2253. StreamHandle &operator=(StreamHandle &&) = default;
  2254. ~StreamHandle() = default;
  2255. bool is_valid() const {
  2256. return response != nullptr && error == Error::Success;
  2257. }
  2258. ssize_t read(char *buf, size_t len);
  2259. void parse_trailers_if_needed();
  2260. Error get_read_error() const { return body_reader_.last_error; }
  2261. bool has_read_error() const { return body_reader_.has_error(); }
  2262. bool trailers_parsed_ = false;
  2263. private:
  2264. friend class ClientImpl;
  2265. ssize_t read_with_decompression(char *buf, size_t len);
  2266. std::unique_ptr<ClientConnection> connection_;
  2267. std::unique_ptr<Stream> socket_stream_;
  2268. Stream *stream_ = nullptr;
  2269. detail::BodyReader body_reader_;
  2270. std::unique_ptr<detail::decompressor> decompressor_;
  2271. std::string decompress_buffer_;
  2272. size_t decompress_offset_ = 0;
  2273. size_t decompressed_bytes_read_ = 0;
  2274. };
  2275. // clang-format off
  2276. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2277. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2278. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2279. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2280. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2281. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2282. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2283. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2284. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2285. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2286. Result Head(const std::string &path);
  2287. Result Head(const std::string &path, const Headers &headers);
  2288. Result Post(const std::string &path);
  2289. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2290. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2291. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2292. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2293. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2294. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2295. Result Post(const std::string &path, const Params &params);
  2296. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2297. Result Post(const std::string &path, const Headers &headers);
  2298. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2299. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2300. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2301. 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);
  2302. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2303. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2304. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2305. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2306. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2307. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2308. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2309. Result Put(const std::string &path);
  2310. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2311. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2312. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2313. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2314. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2315. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2316. Result Put(const std::string &path, const Params &params);
  2317. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2318. Result Put(const std::string &path, const Headers &headers);
  2319. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2320. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2321. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2322. 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);
  2323. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2324. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2325. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2326. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2327. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2328. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2329. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2330. Result Patch(const std::string &path);
  2331. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2332. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2333. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2334. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2335. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2336. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2337. Result Patch(const std::string &path, const Params &params);
  2338. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2339. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  2340. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2341. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2342. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2343. 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);
  2344. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2345. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2346. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2347. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2348. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2349. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2350. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2351. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2352. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2353. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2354. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2355. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2356. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2357. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2358. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2359. Result Options(const std::string &path);
  2360. Result Options(const std::string &path, const Headers &headers);
  2361. // clang-format on
  2362. // Streaming API: Open a stream for reading response body incrementally
  2363. // Socket ownership is transferred to StreamHandle for true streaming
  2364. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2365. StreamHandle open_stream(const std::string &method, const std::string &path,
  2366. const Params &params = {},
  2367. const Headers &headers = {},
  2368. const std::string &body = {},
  2369. const std::string &content_type = {});
  2370. bool send(Request &req, Response &res, Error &error);
  2371. Result send(const Request &req);
  2372. void stop();
  2373. std::string host() const;
  2374. int port() const;
  2375. size_t is_socket_open() const;
  2376. socket_t socket() const;
  2377. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2378. void set_default_headers(Headers headers);
  2379. void
  2380. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2381. void set_address_family(int family);
  2382. void set_tcp_nodelay(bool on);
  2383. void set_ipv6_v6only(bool on);
  2384. void set_socket_options(SocketOptions socket_options);
  2385. void set_connection_timeout(time_t sec, time_t usec = 0);
  2386. template <class Rep, class Period>
  2387. void
  2388. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2389. void set_read_timeout(time_t sec, time_t usec = 0);
  2390. template <class Rep, class Period>
  2391. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2392. void set_write_timeout(time_t sec, time_t usec = 0);
  2393. template <class Rep, class Period>
  2394. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2395. void set_max_timeout(time_t msec);
  2396. template <class Rep, class Period>
  2397. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2398. void set_basic_auth(const std::string &username, const std::string &password);
  2399. void set_bearer_token_auth(const std::string &token);
  2400. void set_keep_alive(bool on);
  2401. void set_follow_location(bool on);
  2402. void set_path_encode(bool on);
  2403. void set_compress(bool on);
  2404. void set_decompress(bool on);
  2405. void set_payload_max_length(size_t length);
  2406. void set_interface(const std::string &intf);
  2407. void set_proxy(const std::string &host, int port);
  2408. void set_proxy_basic_auth(const std::string &username,
  2409. const std::string &password);
  2410. void set_proxy_bearer_token_auth(const std::string &token);
  2411. void set_no_proxy(const std::vector<std::string> &patterns);
  2412. void set_logger(Logger logger);
  2413. void set_error_logger(ErrorLogger error_logger);
  2414. protected:
  2415. struct Socket {
  2416. socket_t sock = INVALID_SOCKET;
  2417. // For Mbed TLS compatibility: start_time for request timeout tracking
  2418. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2419. bool is_open() const { return sock != INVALID_SOCKET; }
  2420. #ifdef CPPHTTPLIB_SSL_ENABLED
  2421. tls::session_t ssl = nullptr;
  2422. #endif
  2423. };
  2424. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  2425. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  2426. virtual bool setup_proxy_connection(
  2427. Socket &socket,
  2428. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2429. Response &res, bool &success, Error &error);
  2430. bool is_proxy_enabled_for_host(const std::string &host) const;
  2431. // All of:
  2432. // shutdown_ssl
  2433. // shutdown_socket
  2434. // close_socket
  2435. // disconnect
  2436. // should ONLY be called when socket_mutex_ is locked, and only when
  2437. // no other thread is using the socket.
  2438. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  2439. void shutdown_socket(Socket &socket) const;
  2440. void close_socket(Socket &socket);
  2441. void disconnect(bool gracefully);
  2442. bool process_request(Stream &strm, Request &req, Response &res,
  2443. bool close_connection, Error &error);
  2444. bool write_content_with_provider(Stream &strm, const Request &req,
  2445. Error &error) const;
  2446. void copy_settings(const ClientImpl &rhs);
  2447. void output_log(const Request &req, const Response &res) const;
  2448. void output_error_log(const Error &err, const Request *req) const;
  2449. // Socket endpoint information
  2450. const std::string host_;
  2451. const int port_;
  2452. // Current open socket
  2453. Socket socket_;
  2454. mutable std::mutex socket_mutex_;
  2455. std::recursive_mutex request_mutex_;
  2456. // These are all protected under socket_mutex
  2457. size_t socket_requests_in_flight_ = 0;
  2458. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2459. bool socket_should_be_closed_when_request_is_done_ = false;
  2460. // Hostname to connection target map. The value is an IP literal or another
  2461. // hostname; only the connection target changes, never the identity.
  2462. std::map<std::string, std::string> addr_map_;
  2463. // Default headers
  2464. Headers default_headers_;
  2465. // Header writer
  2466. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2467. detail::write_headers;
  2468. // Settings
  2469. std::string client_cert_path_;
  2470. std::string client_key_path_;
  2471. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2472. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2473. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2474. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2475. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2476. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2477. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2478. std::string basic_auth_username_;
  2479. std::string basic_auth_password_;
  2480. std::string bearer_token_auth_token_;
  2481. bool keep_alive_ = false;
  2482. bool follow_location_ = false;
  2483. bool path_encode_ = true;
  2484. int address_family_ = AF_UNSPEC;
  2485. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2486. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2487. SocketOptions socket_options_ = nullptr;
  2488. bool compress_ = false;
  2489. bool decompress_ = true;
  2490. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2491. bool has_payload_max_length_ = false;
  2492. std::string interface_;
  2493. std::string proxy_host_;
  2494. int proxy_port_ = -1;
  2495. std::string proxy_basic_auth_username_;
  2496. std::string proxy_basic_auth_password_;
  2497. std::string proxy_bearer_token_auth_token_;
  2498. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2499. mutable detail::NormalizedTarget host_normalized_;
  2500. mutable bool host_normalized_valid_ = false;
  2501. mutable std::mutex logger_mutex_;
  2502. Logger logger_;
  2503. ErrorLogger error_logger_;
  2504. private:
  2505. bool send_(Request &req, Response &res, Error &error);
  2506. Result send_(Request &&req);
  2507. socket_t create_client_socket(Error &error) const;
  2508. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2509. bool skip_100_continue = true) const;
  2510. bool write_request(Stream &strm, Request &req, bool close_connection,
  2511. Error &error, bool skip_body, bool &rejected_locally);
  2512. bool write_request_body(Stream &strm, Request &req, Error &error);
  2513. void prepare_default_headers(Request &r, bool for_stream,
  2514. const std::string &ct);
  2515. bool redirect(Request &req, Response &res, Error &error);
  2516. bool create_redirect_client(const std::string &scheme,
  2517. const std::string &host, int port, Request &req,
  2518. Response &res, const std::string &path,
  2519. const std::string &location, Error &error);
  2520. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2521. bool handle_request(Stream &strm, Request &req, Response &res,
  2522. bool close_connection, Error &error);
  2523. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2524. Request &req, const char *body, size_t content_length,
  2525. ContentProvider content_provider,
  2526. ContentProviderWithoutLength content_provider_without_length,
  2527. const std::string &content_type, ContentReceiver content_receiver,
  2528. Error &error);
  2529. Result send_with_content_provider_and_receiver(
  2530. const std::string &method, const std::string &path,
  2531. const Headers &headers, const char *body, size_t content_length,
  2532. ContentProvider content_provider,
  2533. ContentProviderWithoutLength content_provider_without_length,
  2534. const std::string &content_type, ContentReceiver content_receiver,
  2535. UploadProgress progress);
  2536. ContentProviderWithoutLength get_multipart_content_provider(
  2537. const std::string &boundary, const UploadFormDataItems &items,
  2538. const FormDataProviderItems &provider_items) const;
  2539. virtual bool
  2540. process_socket(const Socket &socket,
  2541. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2542. std::function<bool(Stream &strm)> callback);
  2543. virtual bool is_ssl() const;
  2544. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2545. #ifdef CPPHTTPLIB_SSL_ENABLED
  2546. public:
  2547. void set_digest_auth(const std::string &username,
  2548. const std::string &password);
  2549. void set_proxy_digest_auth(const std::string &username,
  2550. const std::string &password);
  2551. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2552. const std::string &ca_cert_dir_path = std::string());
  2553. void enable_server_certificate_verification(bool enabled);
  2554. void enable_server_hostname_verification(bool enabled);
  2555. void enable_system_ca(bool enabled);
  2556. protected:
  2557. std::string digest_auth_username_;
  2558. std::string digest_auth_password_;
  2559. std::string proxy_digest_auth_username_;
  2560. std::string proxy_digest_auth_password_;
  2561. std::string ca_cert_file_path_;
  2562. std::string ca_cert_dir_path_;
  2563. bool server_certificate_verification_ = true;
  2564. bool server_hostname_verification_ = true;
  2565. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2566. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2567. int last_ssl_error_ = 0;
  2568. uint64_t last_backend_error_ = 0;
  2569. #endif
  2570. };
  2571. class Client {
  2572. public:
  2573. // Universal interface
  2574. explicit Client(const std::string &scheme_host_port);
  2575. explicit Client(const std::string &scheme_host_port,
  2576. const std::string &client_cert_path,
  2577. const std::string &client_key_path);
  2578. // HTTP only interface
  2579. explicit Client(const std::string &host, int port);
  2580. explicit Client(const std::string &host, int port,
  2581. const std::string &client_cert_path,
  2582. const std::string &client_key_path);
  2583. Client(Client &&) = default;
  2584. Client &operator=(Client &&) = default;
  2585. ~Client();
  2586. bool is_valid() const;
  2587. // clang-format off
  2588. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2589. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2590. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2591. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2592. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2593. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2594. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2595. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2596. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2597. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2598. Result Head(const std::string &path);
  2599. Result Head(const std::string &path, const Headers &headers);
  2600. Result Post(const std::string &path);
  2601. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2602. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2603. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2604. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2605. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2606. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2607. Result Post(const std::string &path, const Params &params);
  2608. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2609. Result Post(const std::string &path, const Headers &headers);
  2610. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2611. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2612. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2613. 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);
  2614. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2615. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2616. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2617. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2618. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2619. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2620. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2621. Result Put(const std::string &path);
  2622. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2623. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2624. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2625. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2626. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2627. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2628. Result Put(const std::string &path, const Params &params);
  2629. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2630. Result Put(const std::string &path, const Headers &headers);
  2631. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2632. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2633. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2634. 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);
  2635. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2636. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2637. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2638. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2639. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2640. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2641. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2642. Result Patch(const std::string &path);
  2643. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2644. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2645. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2646. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2647. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2648. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2649. Result Patch(const std::string &path, const Params &params);
  2650. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2651. Result Patch(const std::string &path, const Headers &headers);
  2652. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2653. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2654. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2655. 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);
  2656. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2657. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2658. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2659. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2660. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2661. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2662. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2663. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2664. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2665. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2666. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2667. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2668. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2669. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2670. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2671. Result Options(const std::string &path);
  2672. Result Options(const std::string &path, const Headers &headers);
  2673. // clang-format on
  2674. // Streaming API: Open a stream for reading response body incrementally
  2675. // Socket ownership is transferred to StreamHandle for true streaming
  2676. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2677. ClientImpl::StreamHandle open_stream(const std::string &method,
  2678. const std::string &path,
  2679. const Params &params = {},
  2680. const Headers &headers = {},
  2681. const std::string &body = {},
  2682. const std::string &content_type = {});
  2683. bool send(Request &req, Response &res, Error &error);
  2684. Result send(const Request &req);
  2685. void stop();
  2686. std::string host() const;
  2687. int port() const;
  2688. size_t is_socket_open() const;
  2689. socket_t socket() const;
  2690. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2691. void set_default_headers(Headers headers);
  2692. void
  2693. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2694. void set_address_family(int family);
  2695. void set_tcp_nodelay(bool on);
  2696. void set_socket_options(SocketOptions socket_options);
  2697. void set_connection_timeout(time_t sec, time_t usec = 0);
  2698. template <class Rep, class Period>
  2699. void
  2700. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2701. void set_read_timeout(time_t sec, time_t usec = 0);
  2702. template <class Rep, class Period>
  2703. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2704. void set_write_timeout(time_t sec, time_t usec = 0);
  2705. template <class Rep, class Period>
  2706. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2707. void set_max_timeout(time_t msec);
  2708. template <class Rep, class Period>
  2709. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2710. void set_basic_auth(const std::string &username, const std::string &password);
  2711. void set_bearer_token_auth(const std::string &token);
  2712. void set_keep_alive(bool on);
  2713. void set_follow_location(bool on);
  2714. void set_path_encode(bool on);
  2715. void set_compress(bool on);
  2716. void set_decompress(bool on);
  2717. void set_payload_max_length(size_t length);
  2718. void set_interface(const std::string &intf);
  2719. void set_proxy(const std::string &host, int port);
  2720. void set_proxy_basic_auth(const std::string &username,
  2721. const std::string &password);
  2722. void set_proxy_bearer_token_auth(const std::string &token);
  2723. void set_no_proxy(const std::vector<std::string> &patterns);
  2724. void set_logger(Logger logger);
  2725. void set_error_logger(ErrorLogger error_logger);
  2726. private:
  2727. std::unique_ptr<ClientImpl> cli_;
  2728. #ifdef CPPHTTPLIB_SSL_ENABLED
  2729. public:
  2730. void set_digest_auth(const std::string &username,
  2731. const std::string &password);
  2732. void set_proxy_digest_auth(const std::string &username,
  2733. const std::string &password);
  2734. void enable_server_certificate_verification(bool enabled);
  2735. void enable_server_hostname_verification(bool enabled);
  2736. void enable_system_ca(bool enabled);
  2737. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2738. const std::string &ca_cert_dir_path = std::string());
  2739. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2740. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2741. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2742. void set_session_verifier(
  2743. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2744. tls::ctx_t tls_context() const;
  2745. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2746. void enable_windows_certificate_verification(bool enabled);
  2747. #endif
  2748. private:
  2749. bool is_ssl_ = false;
  2750. #endif
  2751. };
  2752. #ifdef CPPHTTPLIB_SSL_ENABLED
  2753. class SSLServer : public Server {
  2754. public:
  2755. SSLServer(const char *cert_path, const char *private_key_path,
  2756. const char *client_ca_cert_file_path = nullptr,
  2757. const char *client_ca_cert_dir_path = nullptr,
  2758. const char *private_key_password = nullptr);
  2759. struct PemMemory {
  2760. const char *cert_pem;
  2761. size_t cert_pem_len;
  2762. const char *key_pem;
  2763. size_t key_pem_len;
  2764. const char *client_ca_pem;
  2765. size_t client_ca_pem_len;
  2766. const char *private_key_password;
  2767. };
  2768. explicit SSLServer(const PemMemory &pem);
  2769. // The callback receives the ctx_t handle which can be cast to the
  2770. // appropriate backend type (SSL_CTX* for OpenSSL,
  2771. // tls::impl::MbedTlsContext* for Mbed TLS)
  2772. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2773. ~SSLServer() override;
  2774. bool is_valid() const override;
  2775. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2776. const char *client_ca_pem = nullptr,
  2777. const char *password = nullptr);
  2778. tls::ctx_t tls_context() const { return ctx_; }
  2779. int ssl_last_error() const { return last_ssl_error_; }
  2780. private:
  2781. bool process_and_close_socket(socket_t sock) override;
  2782. tls::ctx_t ctx_ = nullptr;
  2783. std::mutex ctx_mutex_;
  2784. int last_ssl_error_ = 0;
  2785. };
  2786. class SSLClient final : public ClientImpl {
  2787. public:
  2788. explicit SSLClient(const std::string &host);
  2789. explicit SSLClient(const std::string &host, int port);
  2790. explicit SSLClient(const std::string &host, int port,
  2791. const std::string &client_cert_path,
  2792. const std::string &client_key_path,
  2793. const std::string &private_key_password = std::string());
  2794. struct PemMemory {
  2795. const char *cert_pem;
  2796. size_t cert_pem_len;
  2797. const char *key_pem;
  2798. size_t key_pem_len;
  2799. const char *private_key_password;
  2800. };
  2801. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2802. ~SSLClient() override;
  2803. bool is_valid() const override;
  2804. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2805. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2806. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2807. // Post-handshake session verifier (backend-independent)
  2808. void set_session_verifier(
  2809. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2810. tls::ctx_t tls_context() const { return ctx_; }
  2811. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2812. void enable_windows_certificate_verification(bool enabled);
  2813. #endif
  2814. private:
  2815. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2816. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2817. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2818. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2819. bool
  2820. process_socket(const Socket &socket,
  2821. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2822. std::function<bool(Stream &strm)> callback) override;
  2823. bool is_ssl() const override;
  2824. bool setup_proxy_connection(
  2825. Socket &socket,
  2826. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2827. Response &res, bool &success, Error &error) override;
  2828. bool connect_with_proxy(
  2829. Socket &sock,
  2830. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2831. Response &res, bool &success, Error &error);
  2832. bool initialize_ssl(Socket &socket, Error &error);
  2833. void init_ctx();
  2834. void reset_ctx_on_error();
  2835. bool load_certs();
  2836. tls::ctx_t ctx_ = nullptr;
  2837. std::mutex ctx_mutex_;
  2838. std::once_flag initialize_cert_;
  2839. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2840. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2841. // Used to keep custom CA configuration exclusive with system CA loading.
  2842. bool ca_cert_store_set_ = false;
  2843. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2844. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2845. bool enable_windows_cert_verification_ = true;
  2846. // Like ca_cert_store_set_, tracks what ctx_ cannot report back: whether
  2847. // set_server_certificate_verifier() installed a verifier.
  2848. bool server_certificate_verifier_set_ = false;
  2849. #endif
  2850. friend class ClientImpl;
  2851. };
  2852. #endif // CPPHTTPLIB_SSL_ENABLED
  2853. namespace detail {
  2854. template <typename T, typename U>
  2855. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2856. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2857. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2858. duration - std::chrono::seconds(sec))
  2859. .count();
  2860. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2861. }
  2862. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2863. return N - 1;
  2864. }
  2865. inline bool is_numeric(const std::string &str) {
  2866. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2867. }
  2868. // std::ranges::next(first, n, last) for C++11
  2869. template <typename It> inline It bounded_next(It first, size_t n, It last) {
  2870. for (; n > 0 && first != last; --n) {
  2871. ++first;
  2872. }
  2873. return first;
  2874. }
  2875. inline size_t get_header_value_u64(const Headers &headers,
  2876. const std::string &key, size_t def,
  2877. size_t id, bool &is_invalid_value) {
  2878. is_invalid_value = false;
  2879. auto rng = headers.equal_range(key);
  2880. auto it = bounded_next(rng.first, id, rng.second);
  2881. if (it != rng.second) {
  2882. if (is_numeric(it->second)) {
  2883. // Parse at size_t width so an out-of-range Content-Length is reported
  2884. // rather than silently saturated/truncated (a value above 2^32 would
  2885. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  2886. // and return SIZE_MAX so the existing oversized-value guards reject it.
  2887. size_t val = 0;
  2888. const auto &s = it->second;
  2889. auto r = from_chars(s.data(), s.data() + s.size(), val);
  2890. if (r.ec == std::errc::result_out_of_range) {
  2891. is_invalid_value = true;
  2892. return (std::numeric_limits<size_t>::max)();
  2893. }
  2894. return val;
  2895. } else {
  2896. is_invalid_value = true;
  2897. }
  2898. }
  2899. return def;
  2900. }
  2901. inline size_t get_header_value_u64(const Headers &headers,
  2902. const std::string &key, size_t def,
  2903. size_t id) {
  2904. auto dummy = false;
  2905. return get_header_value_u64(headers, key, def, id, dummy);
  2906. }
  2907. } // namespace detail
  2908. template <class Rep, class Period>
  2909. inline Server &
  2910. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2911. detail::duration_to_sec_and_usec(
  2912. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2913. return *this;
  2914. }
  2915. template <class Rep, class Period>
  2916. inline Server &
  2917. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2918. detail::duration_to_sec_and_usec(
  2919. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2920. return *this;
  2921. }
  2922. template <class Rep, class Period>
  2923. inline Server &
  2924. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2925. detail::duration_to_sec_and_usec(
  2926. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2927. return *this;
  2928. }
  2929. template <class Rep, class Period>
  2930. inline void ClientImpl::set_connection_timeout(
  2931. const std::chrono::duration<Rep, Period> &duration) {
  2932. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2933. set_connection_timeout(sec, usec);
  2934. });
  2935. }
  2936. template <class Rep, class Period>
  2937. inline void ClientImpl::set_read_timeout(
  2938. const std::chrono::duration<Rep, Period> &duration) {
  2939. detail::duration_to_sec_and_usec(
  2940. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2941. }
  2942. template <class Rep, class Period>
  2943. inline void ClientImpl::set_write_timeout(
  2944. const std::chrono::duration<Rep, Period> &duration) {
  2945. detail::duration_to_sec_and_usec(
  2946. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2947. }
  2948. template <class Rep, class Period>
  2949. inline void ClientImpl::set_max_timeout(
  2950. const std::chrono::duration<Rep, Period> &duration) {
  2951. auto msec =
  2952. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2953. set_max_timeout(msec);
  2954. }
  2955. template <class Rep, class Period>
  2956. inline void Client::set_connection_timeout(
  2957. const std::chrono::duration<Rep, Period> &duration) {
  2958. cli_->set_connection_timeout(duration);
  2959. }
  2960. template <class Rep, class Period>
  2961. inline void
  2962. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2963. cli_->set_read_timeout(duration);
  2964. }
  2965. template <class Rep, class Period>
  2966. inline void
  2967. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2968. cli_->set_write_timeout(duration);
  2969. }
  2970. inline void Client::set_max_timeout(time_t msec) {
  2971. cli_->set_max_timeout(msec);
  2972. }
  2973. template <class Rep, class Period>
  2974. inline void
  2975. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2976. cli_->set_max_timeout(duration);
  2977. }
  2978. /*
  2979. * Forward declarations and types that will be part of the .h file if split into
  2980. * .h + .cc.
  2981. */
  2982. std::string hosted_at(const std::string &hostname);
  2983. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2984. // JavaScript-style URL encoding/decoding functions
  2985. std::string encode_uri_component(const std::string &value);
  2986. std::string encode_uri(const std::string &value);
  2987. std::string decode_uri_component(const std::string &value);
  2988. std::string decode_uri(const std::string &value);
  2989. // RFC 3986 compliant URL component encoding/decoding functions
  2990. std::string encode_path_component(const std::string &component);
  2991. std::string decode_path_component(const std::string &component);
  2992. std::string encode_query_component(const std::string &component,
  2993. bool space_as_plus = true);
  2994. std::string decode_query_component(const std::string &component,
  2995. bool plus_as_space = true);
  2996. std::string sanitize_filename(const std::string &filename);
  2997. std::string append_query_params(const std::string &path, const Params &params);
  2998. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2999. std::pair<std::string, std::string>
  3000. make_basic_authentication_header(const std::string &username,
  3001. const std::string &password,
  3002. bool is_proxy = false);
  3003. namespace detail {
  3004. #if defined(_WIN32)
  3005. inline std::wstring u8string_to_wstring(const char *s) {
  3006. if (!s) { return std::wstring(); }
  3007. auto len = static_cast<int>(strlen(s));
  3008. if (!len) { return std::wstring(); }
  3009. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  3010. if (!wlen) { return std::wstring(); }
  3011. std::wstring ws;
  3012. ws.resize(wlen);
  3013. wlen = ::MultiByteToWideChar(
  3014. CP_UTF8, 0, s, len,
  3015. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  3016. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  3017. return ws;
  3018. }
  3019. #endif
  3020. struct FileStat {
  3021. FileStat(const std::string &path);
  3022. bool is_file() const;
  3023. bool is_dir() const;
  3024. time_t mtime() const;
  3025. size_t size() const;
  3026. private:
  3027. #if defined(_WIN32)
  3028. struct _stat st_;
  3029. #else
  3030. struct stat st_;
  3031. #endif
  3032. int ret_ = -1;
  3033. };
  3034. std::string make_host_and_port_string(const std::string &host, int port,
  3035. bool is_ssl);
  3036. template <typename T>
  3037. bool check_and_write_headers(Stream &strm, Headers &headers, T header_writer,
  3038. Error &error);
  3039. std::string trim_copy(const std::string &s);
  3040. void divide(
  3041. const char *data, std::size_t size, char d,
  3042. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3043. fn);
  3044. void divide(
  3045. const std::string &str, char d,
  3046. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3047. fn);
  3048. void split(const char *b, const char *e, char d,
  3049. std::function<void(const char *, const char *)> fn);
  3050. void split(const char *b, const char *e, char d, size_t m,
  3051. std::function<void(const char *, const char *)> fn);
  3052. bool split_find(const char *b, const char *e, char d,
  3053. std::function<bool(const char *, const char *)> fn);
  3054. bool has_header_token(const Headers &headers, const std::string &key,
  3055. const std::string &token);
  3056. std::string websocket_accept_key(const std::string &client_key);
  3057. bool is_websocket_upgrade(const Request &req);
  3058. bool process_client_socket(
  3059. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3060. time_t write_timeout_sec, time_t write_timeout_usec,
  3061. time_t max_timeout_msec,
  3062. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3063. std::function<bool(Stream &)> callback);
  3064. socket_t create_client_socket(const std::string &host, const std::string &ip,
  3065. int port, int address_family, bool tcp_nodelay,
  3066. bool ipv6_v6only, SocketOptions socket_options,
  3067. time_t connection_timeout_sec,
  3068. time_t connection_timeout_usec,
  3069. time_t read_timeout_sec, time_t read_timeout_usec,
  3070. time_t write_timeout_sec,
  3071. time_t write_timeout_usec,
  3072. const std::string &intf, Error &error);
  3073. const char *get_header_value(const Headers &headers, const std::string &key,
  3074. const char *def, size_t id);
  3075. std::string get_combined_header_value(const Headers &headers,
  3076. const std::string &key);
  3077. std::string params_to_query_str(const Params &params);
  3078. void parse_query_text(const char *data, std::size_t size, Params &params);
  3079. void parse_query_text(const std::string &s, Params &params);
  3080. bool parse_multipart_boundary(const std::string &content_type,
  3081. std::string &boundary);
  3082. bool parse_range_header(const std::string &s, Ranges &ranges);
  3083. bool parse_accept_header(const std::string &s,
  3084. std::vector<std::string> &content_types);
  3085. void parse_disposition_params(const std::string &s, Params &params);
  3086. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  3087. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  3088. EncodingType encoding_type(const Request &req, const std::string &content_type);
  3089. EncodingType encoding_type(const Request &req, const Response &res,
  3090. const std::string &content_type);
  3091. EncodingType encoding_type(const Request &req, const Response &res);
  3092. class BufferStream final : public Stream {
  3093. public:
  3094. BufferStream() = default;
  3095. ~BufferStream() override = default;
  3096. bool is_readable() const override;
  3097. bool wait_readable() const override;
  3098. bool wait_writable() const override;
  3099. ssize_t read(char *ptr, size_t size) override;
  3100. ssize_t write(const char *ptr, size_t size) override;
  3101. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3102. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3103. socket_t socket() const override;
  3104. time_t duration() const override;
  3105. const std::string &get_buffer() const;
  3106. private:
  3107. std::string buffer;
  3108. size_t position = 0;
  3109. };
  3110. class compressor {
  3111. public:
  3112. virtual ~compressor() = default;
  3113. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3114. virtual bool compress(const char *data, size_t data_length, bool last,
  3115. Callback callback) = 0;
  3116. };
  3117. class decompressor {
  3118. public:
  3119. virtual ~decompressor() = default;
  3120. virtual bool is_valid() const = 0;
  3121. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3122. virtual bool decompress(const char *data, size_t data_length,
  3123. Callback callback) = 0;
  3124. };
  3125. class nocompressor final : public compressor {
  3126. public:
  3127. ~nocompressor() override = default;
  3128. bool compress(const char *data, size_t data_length, bool /*last*/,
  3129. Callback callback) override;
  3130. };
  3131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3132. class gzip_compressor final : public compressor {
  3133. public:
  3134. gzip_compressor();
  3135. ~gzip_compressor() override;
  3136. bool compress(const char *data, size_t data_length, bool last,
  3137. Callback callback) override;
  3138. private:
  3139. bool is_valid_ = false;
  3140. z_stream strm_;
  3141. };
  3142. class gzip_decompressor final : public decompressor {
  3143. public:
  3144. gzip_decompressor();
  3145. ~gzip_decompressor() override;
  3146. bool is_valid() const override;
  3147. bool decompress(const char *data, size_t data_length,
  3148. Callback callback) override;
  3149. private:
  3150. bool is_valid_ = false;
  3151. z_stream strm_;
  3152. };
  3153. #endif
  3154. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3155. class brotli_compressor final : public compressor {
  3156. public:
  3157. brotli_compressor();
  3158. ~brotli_compressor();
  3159. bool compress(const char *data, size_t data_length, bool last,
  3160. Callback callback) override;
  3161. private:
  3162. BrotliEncoderState *state_ = nullptr;
  3163. };
  3164. class brotli_decompressor final : public decompressor {
  3165. public:
  3166. brotli_decompressor();
  3167. ~brotli_decompressor();
  3168. bool is_valid() const override;
  3169. bool decompress(const char *data, size_t data_length,
  3170. Callback callback) override;
  3171. private:
  3172. BrotliDecoderResult decoder_r;
  3173. BrotliDecoderState *decoder_s = nullptr;
  3174. };
  3175. #endif
  3176. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3177. class zstd_compressor : public compressor {
  3178. public:
  3179. zstd_compressor();
  3180. ~zstd_compressor();
  3181. bool compress(const char *data, size_t data_length, bool last,
  3182. Callback callback) override;
  3183. private:
  3184. ZSTD_CCtx *ctx_ = nullptr;
  3185. };
  3186. class zstd_decompressor : public decompressor {
  3187. public:
  3188. zstd_decompressor();
  3189. ~zstd_decompressor();
  3190. bool is_valid() const override;
  3191. bool decompress(const char *data, size_t data_length,
  3192. Callback callback) override;
  3193. private:
  3194. ZSTD_DCtx *ctx_ = nullptr;
  3195. };
  3196. #endif
  3197. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  3198. // to store data. The call can set memory on stack for performance.
  3199. class stream_line_reader {
  3200. public:
  3201. stream_line_reader(Stream &strm, char *fixed_buffer,
  3202. size_t fixed_buffer_size);
  3203. const char *ptr() const;
  3204. size_t size() const;
  3205. bool end_with_crlf() const;
  3206. bool getline();
  3207. private:
  3208. void append(char c);
  3209. void append(const char *data, size_t size);
  3210. Stream &strm_;
  3211. char *fixed_buffer_;
  3212. const size_t fixed_buffer_size_;
  3213. size_t fixed_buffer_used_size_ = 0;
  3214. std::string growable_buffer_;
  3215. };
  3216. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3217. const Headers &src_headers);
  3218. struct ChunkedDecoder {
  3219. Stream &strm;
  3220. size_t chunk_remaining = 0;
  3221. bool finished = false;
  3222. char line_buf[64];
  3223. size_t last_chunk_total = 0;
  3224. size_t last_chunk_offset = 0;
  3225. explicit ChunkedDecoder(Stream &s);
  3226. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  3227. size_t &out_chunk_total);
  3228. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  3229. };
  3230. class mmap {
  3231. public:
  3232. mmap(const char *path);
  3233. ~mmap();
  3234. bool open(const char *path);
  3235. void close();
  3236. bool is_open() const;
  3237. size_t size() const;
  3238. const char *data() const;
  3239. private:
  3240. #if defined(_WIN32)
  3241. HANDLE hFile_ = NULL;
  3242. HANDLE hMapping_ = NULL;
  3243. #else
  3244. int fd_ = -1;
  3245. #endif
  3246. size_t size_ = 0;
  3247. void *addr_ = nullptr;
  3248. bool is_open_empty_file = false;
  3249. };
  3250. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  3251. namespace fields {
  3252. bool is_token_char(char c);
  3253. bool is_token(const std::string &s);
  3254. bool is_field_name(const std::string &s);
  3255. bool is_vchar(char c);
  3256. bool is_obs_text(char c);
  3257. bool is_field_vchar(char c);
  3258. bool is_field_content(const std::string &s);
  3259. bool is_field_value(const std::string &s);
  3260. bool is_field_valid(const std::string &name, const std::string &value);
  3261. bool is_request_target(const std::string &s);
  3262. bool is_host(const std::string &s);
  3263. } // namespace fields
  3264. } // namespace detail
  3265. /*
  3266. * TLS Abstraction Layer Declarations
  3267. */
  3268. #ifdef CPPHTTPLIB_SSL_ENABLED
  3269. // TLS abstraction layer - backend-specific type declarations
  3270. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  3271. namespace tls {
  3272. namespace impl {
  3273. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  3274. // cert/key). This struct is accessible via tls::impl for use in SSL context
  3275. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  3276. struct MbedTlsContext {
  3277. mbedtls_ssl_config conf;
  3278. #ifndef CPPHTTPLIB_MBEDTLS_V4
  3279. // Mbed TLS 4.x uses PSA Crypto's internal RNG; no explicit entropy/DRBG.
  3280. mbedtls_entropy_context entropy;
  3281. mbedtls_ctr_drbg_context ctr_drbg;
  3282. #endif
  3283. mbedtls_x509_crt ca_chain;
  3284. mbedtls_x509_crt own_cert;
  3285. mbedtls_pk_context own_key;
  3286. bool is_server = false;
  3287. bool verify_client = false;
  3288. bool has_verify_callback = false;
  3289. MbedTlsContext();
  3290. ~MbedTlsContext();
  3291. MbedTlsContext(const MbedTlsContext &) = delete;
  3292. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  3293. };
  3294. } // namespace impl
  3295. } // namespace tls
  3296. #endif
  3297. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  3298. namespace tls {
  3299. namespace impl {
  3300. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  3301. // This struct is accessible via tls::impl for use in SSL context
  3302. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  3303. struct WolfSSLContext {
  3304. WOLFSSL_CTX *ctx = nullptr;
  3305. bool is_server = false;
  3306. bool verify_client = false;
  3307. bool has_verify_callback = false;
  3308. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  3309. WolfSSLContext();
  3310. ~WolfSSLContext();
  3311. WolfSSLContext(const WolfSSLContext &) = delete;
  3312. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  3313. };
  3314. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  3315. struct WolfSSLCAStore {
  3316. std::string pem_data;
  3317. };
  3318. } // namespace impl
  3319. } // namespace tls
  3320. #endif
  3321. #endif // CPPHTTPLIB_SSL_ENABLED
  3322. namespace stream {
  3323. class Result {
  3324. public:
  3325. Result();
  3326. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  3327. Result(Result &&other) noexcept;
  3328. Result &operator=(Result &&other) noexcept;
  3329. Result(const Result &) = delete;
  3330. Result &operator=(const Result &) = delete;
  3331. // Response info
  3332. bool is_valid() const;
  3333. explicit operator bool() const;
  3334. int status() const;
  3335. const Headers &headers() const;
  3336. std::string get_header_value(const std::string &key,
  3337. const char *def = "") const;
  3338. bool has_header(const std::string &key) const;
  3339. Error error() const;
  3340. Error read_error() const;
  3341. bool has_read_error() const;
  3342. // Stream reading
  3343. bool next();
  3344. const char *data() const;
  3345. size_t size() const;
  3346. std::string read_all();
  3347. private:
  3348. ClientImpl::StreamHandle handle_;
  3349. std::string buffer_;
  3350. size_t current_size_ = 0;
  3351. size_t chunk_size_;
  3352. bool finished_ = false;
  3353. };
  3354. // GET
  3355. template <typename ClientType>
  3356. inline Result Get(ClientType &cli, const std::string &path,
  3357. size_t chunk_size = 8192) {
  3358. return Result{cli.open_stream("GET", path), chunk_size};
  3359. }
  3360. template <typename ClientType>
  3361. inline Result Get(ClientType &cli, const std::string &path,
  3362. const Headers &headers, size_t chunk_size = 8192) {
  3363. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  3364. }
  3365. template <typename ClientType>
  3366. inline Result Get(ClientType &cli, const std::string &path,
  3367. const Params &params, size_t chunk_size = 8192) {
  3368. return Result{cli.open_stream("GET", path, params), chunk_size};
  3369. }
  3370. template <typename ClientType>
  3371. inline Result Get(ClientType &cli, const std::string &path,
  3372. const Params &params, const Headers &headers,
  3373. size_t chunk_size = 8192) {
  3374. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  3375. }
  3376. // POST
  3377. template <typename ClientType>
  3378. inline Result Post(ClientType &cli, const std::string &path,
  3379. const std::string &body, const std::string &content_type,
  3380. size_t chunk_size = 8192) {
  3381. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  3382. chunk_size};
  3383. }
  3384. template <typename ClientType>
  3385. inline Result Post(ClientType &cli, const std::string &path,
  3386. const Headers &headers, const std::string &body,
  3387. const std::string &content_type, size_t chunk_size = 8192) {
  3388. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  3389. chunk_size};
  3390. }
  3391. template <typename ClientType>
  3392. inline Result Post(ClientType &cli, const std::string &path,
  3393. const Params &params, const std::string &body,
  3394. const std::string &content_type, size_t chunk_size = 8192) {
  3395. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  3396. chunk_size};
  3397. }
  3398. template <typename ClientType>
  3399. inline Result Post(ClientType &cli, const std::string &path,
  3400. const Params &params, const Headers &headers,
  3401. const std::string &body, const std::string &content_type,
  3402. size_t chunk_size = 8192) {
  3403. return Result{
  3404. cli.open_stream("POST", path, params, headers, body, content_type),
  3405. chunk_size};
  3406. }
  3407. // PUT
  3408. template <typename ClientType>
  3409. inline Result Put(ClientType &cli, const std::string &path,
  3410. const std::string &body, const std::string &content_type,
  3411. size_t chunk_size = 8192) {
  3412. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  3413. chunk_size};
  3414. }
  3415. template <typename ClientType>
  3416. inline Result Put(ClientType &cli, const std::string &path,
  3417. const Headers &headers, const std::string &body,
  3418. const std::string &content_type, size_t chunk_size = 8192) {
  3419. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  3420. chunk_size};
  3421. }
  3422. template <typename ClientType>
  3423. inline Result Put(ClientType &cli, const std::string &path,
  3424. const Params &params, const std::string &body,
  3425. const std::string &content_type, size_t chunk_size = 8192) {
  3426. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  3427. chunk_size};
  3428. }
  3429. template <typename ClientType>
  3430. inline Result Put(ClientType &cli, const std::string &path,
  3431. const Params &params, const Headers &headers,
  3432. const std::string &body, const std::string &content_type,
  3433. size_t chunk_size = 8192) {
  3434. return Result{
  3435. cli.open_stream("PUT", path, params, headers, body, content_type),
  3436. chunk_size};
  3437. }
  3438. // PATCH
  3439. template <typename ClientType>
  3440. inline Result Patch(ClientType &cli, const std::string &path,
  3441. const std::string &body, const std::string &content_type,
  3442. size_t chunk_size = 8192) {
  3443. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  3444. chunk_size};
  3445. }
  3446. template <typename ClientType>
  3447. inline Result Patch(ClientType &cli, const std::string &path,
  3448. const Headers &headers, const std::string &body,
  3449. const std::string &content_type, size_t chunk_size = 8192) {
  3450. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  3451. chunk_size};
  3452. }
  3453. template <typename ClientType>
  3454. inline Result Patch(ClientType &cli, const std::string &path,
  3455. const Params &params, const std::string &body,
  3456. const std::string &content_type, size_t chunk_size = 8192) {
  3457. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  3458. chunk_size};
  3459. }
  3460. template <typename ClientType>
  3461. inline Result Patch(ClientType &cli, const std::string &path,
  3462. const Params &params, const Headers &headers,
  3463. const std::string &body, const std::string &content_type,
  3464. size_t chunk_size = 8192) {
  3465. return Result{
  3466. cli.open_stream("PATCH", path, params, headers, body, content_type),
  3467. chunk_size};
  3468. }
  3469. // DELETE
  3470. template <typename ClientType>
  3471. inline Result Delete(ClientType &cli, const std::string &path,
  3472. size_t chunk_size = 8192) {
  3473. return Result{cli.open_stream("DELETE", path), chunk_size};
  3474. }
  3475. template <typename ClientType>
  3476. inline Result Delete(ClientType &cli, const std::string &path,
  3477. const Headers &headers, size_t chunk_size = 8192) {
  3478. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  3479. }
  3480. template <typename ClientType>
  3481. inline Result Delete(ClientType &cli, const std::string &path,
  3482. const std::string &body, const std::string &content_type,
  3483. size_t chunk_size = 8192) {
  3484. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3485. chunk_size};
  3486. }
  3487. template <typename ClientType>
  3488. inline Result Delete(ClientType &cli, const std::string &path,
  3489. const Headers &headers, const std::string &body,
  3490. const std::string &content_type,
  3491. size_t chunk_size = 8192) {
  3492. return Result{
  3493. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3494. chunk_size};
  3495. }
  3496. template <typename ClientType>
  3497. inline Result Delete(ClientType &cli, const std::string &path,
  3498. const Params &params, size_t chunk_size = 8192) {
  3499. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3500. }
  3501. template <typename ClientType>
  3502. inline Result Delete(ClientType &cli, const std::string &path,
  3503. const Params &params, const Headers &headers,
  3504. size_t chunk_size = 8192) {
  3505. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3506. }
  3507. template <typename ClientType>
  3508. inline Result Delete(ClientType &cli, const std::string &path,
  3509. const Params &params, const std::string &body,
  3510. const std::string &content_type,
  3511. size_t chunk_size = 8192) {
  3512. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3513. chunk_size};
  3514. }
  3515. template <typename ClientType>
  3516. inline Result Delete(ClientType &cli, const std::string &path,
  3517. const Params &params, const Headers &headers,
  3518. const std::string &body, const std::string &content_type,
  3519. size_t chunk_size = 8192) {
  3520. return Result{
  3521. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3522. chunk_size};
  3523. }
  3524. // HEAD
  3525. template <typename ClientType>
  3526. inline Result Head(ClientType &cli, const std::string &path,
  3527. size_t chunk_size = 8192) {
  3528. return Result{cli.open_stream("HEAD", path), chunk_size};
  3529. }
  3530. template <typename ClientType>
  3531. inline Result Head(ClientType &cli, const std::string &path,
  3532. const Headers &headers, size_t chunk_size = 8192) {
  3533. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3534. }
  3535. template <typename ClientType>
  3536. inline Result Head(ClientType &cli, const std::string &path,
  3537. const Params &params, size_t chunk_size = 8192) {
  3538. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3539. }
  3540. template <typename ClientType>
  3541. inline Result Head(ClientType &cli, const std::string &path,
  3542. const Params &params, const Headers &headers,
  3543. size_t chunk_size = 8192) {
  3544. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3545. }
  3546. // OPTIONS
  3547. template <typename ClientType>
  3548. inline Result Options(ClientType &cli, const std::string &path,
  3549. size_t chunk_size = 8192) {
  3550. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3551. }
  3552. template <typename ClientType>
  3553. inline Result Options(ClientType &cli, const std::string &path,
  3554. const Headers &headers, size_t chunk_size = 8192) {
  3555. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3556. }
  3557. template <typename ClientType>
  3558. inline Result Options(ClientType &cli, const std::string &path,
  3559. const Params &params, size_t chunk_size = 8192) {
  3560. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3561. }
  3562. template <typename ClientType>
  3563. inline Result Options(ClientType &cli, const std::string &path,
  3564. const Params &params, const Headers &headers,
  3565. size_t chunk_size = 8192) {
  3566. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3567. }
  3568. } // namespace stream
  3569. namespace sse {
  3570. struct SSEMessage {
  3571. std::string event; // Event type (default: "message")
  3572. std::string data; // Event payload
  3573. std::string id; // Event ID for Last-Event-ID header
  3574. SSEMessage();
  3575. void clear();
  3576. };
  3577. class SSEClient {
  3578. public:
  3579. using MessageHandler = std::function<void(const SSEMessage &)>;
  3580. using ErrorHandler = std::function<void(Error)>;
  3581. using OpenHandler = std::function<void()>;
  3582. SSEClient(Client &client, const std::string &path);
  3583. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3584. ~SSEClient();
  3585. SSEClient(const SSEClient &) = delete;
  3586. SSEClient &operator=(const SSEClient &) = delete;
  3587. // Event handlers
  3588. SSEClient &on_message(MessageHandler handler);
  3589. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3590. SSEClient &on_open(OpenHandler handler);
  3591. SSEClient &on_error(ErrorHandler handler);
  3592. SSEClient &set_reconnect_interval(int ms);
  3593. SSEClient &set_max_reconnect_attempts(int n);
  3594. // Update headers (thread-safe)
  3595. SSEClient &set_headers(const Headers &headers);
  3596. // State accessors
  3597. bool is_connected() const;
  3598. const std::string &last_event_id() const;
  3599. // Blocking start - runs event loop with auto-reconnect
  3600. void start();
  3601. // Non-blocking start - runs in background thread
  3602. void start_async();
  3603. // Stop the client (thread-safe)
  3604. void stop();
  3605. private:
  3606. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms,
  3607. bool &has_data, bool &has_id);
  3608. void run_event_loop();
  3609. void dispatch_event(const SSEMessage &msg);
  3610. bool should_reconnect(int count) const;
  3611. void wait_for_reconnect();
  3612. // Client and path
  3613. Client &client_;
  3614. std::string path_;
  3615. Headers headers_;
  3616. mutable std::mutex headers_mutex_;
  3617. // Callbacks
  3618. MessageHandler on_message_;
  3619. std::map<std::string, MessageHandler> event_handlers_;
  3620. OpenHandler on_open_;
  3621. ErrorHandler on_error_;
  3622. // Configuration
  3623. int reconnect_interval_ms_ = 3000;
  3624. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3625. // State
  3626. std::atomic<bool> running_{false};
  3627. std::atomic<bool> connected_{false};
  3628. std::string last_event_id_;
  3629. // Async support
  3630. std::thread async_thread_;
  3631. };
  3632. } // namespace sse
  3633. namespace ws {
  3634. class WebSocketClient;
  3635. enum class Opcode : uint8_t {
  3636. Continuation = 0x0,
  3637. Text = 0x1,
  3638. Binary = 0x2,
  3639. Close = 0x8,
  3640. Ping = 0x9,
  3641. Pong = 0xA,
  3642. };
  3643. enum class CloseStatus : uint16_t {
  3644. Normal = 1000,
  3645. GoingAway = 1001,
  3646. ProtocolError = 1002,
  3647. UnsupportedData = 1003,
  3648. NoStatus = 1005,
  3649. Abnormal = 1006,
  3650. InvalidPayload = 1007,
  3651. PolicyViolation = 1008,
  3652. MessageTooBig = 1009,
  3653. MandatoryExtension = 1010,
  3654. InternalError = 1011,
  3655. };
  3656. // Timeout is returned only when a read timeout was set and it elapsed before
  3657. // any byte of a frame arrived: nothing was consumed and the connection is
  3658. // still open, so the caller can send on it and read again. `msg` is left
  3659. // untouched, so a `while (ws.read(msg))` loop must not treat it as a message.
  3660. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2, Timeout = 3 };
  3661. // Result of WebSocketClient::connect(). Truthy only when the WebSocket
  3662. // upgrade handshake fully succeeded. On failure error() identifies the
  3663. // failing layer; status()/headers() expose the server's upgrade response
  3664. // when one was received (status() is -1 otherwise).
  3665. class Result {
  3666. public:
  3667. Result() = default;
  3668. Result(Error err, int status, Headers &&headers)
  3669. : err_(err), status_(status), headers_(std::move(headers)) {}
  3670. explicit operator bool() const { return err_ == Error::Success; }
  3671. Error error() const { return err_; }
  3672. // Upgrade response info
  3673. int status() const { return status_; }
  3674. const Headers &headers() const { return headers_; }
  3675. std::string get_header_value(const std::string &key,
  3676. const char *def = "") const {
  3677. return detail::get_header_value(headers_, key, def, 0);
  3678. }
  3679. bool has_header(const std::string &key) const {
  3680. return headers_.find(key) != headers_.end();
  3681. }
  3682. #ifdef CPPHTTPLIB_SSL_ENABLED
  3683. Result(Error err, int status, Headers &&headers, int ssl_error,
  3684. uint64_t ssl_backend_error)
  3685. : err_(err), status_(status), headers_(std::move(headers)),
  3686. ssl_error_(ssl_error), ssl_backend_error_(ssl_backend_error) {}
  3687. int ssl_error() const { return ssl_error_; }
  3688. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  3689. #endif
  3690. private:
  3691. Error err_ = Error::Unknown; // a default-constructed Result is falsy
  3692. int status_ = -1;
  3693. Headers headers_;
  3694. #ifdef CPPHTTPLIB_SSL_ENABLED
  3695. int ssl_error_ = 0;
  3696. uint64_t ssl_backend_error_ = 0;
  3697. #endif
  3698. };
  3699. class WebSocket {
  3700. public:
  3701. WebSocket(const WebSocket &) = delete;
  3702. WebSocket &operator=(const WebSocket &) = delete;
  3703. ~WebSocket();
  3704. ReadResult read(std::string &msg);
  3705. bool send(const std::string &data);
  3706. bool send(const char *data, size_t len);
  3707. void close(CloseStatus status = CloseStatus::Normal,
  3708. const std::string &reason = "");
  3709. const Request &request() const;
  3710. bool is_open() const;
  3711. // Bound how long read() waits before returning Timeout. 0 waits forever.
  3712. // A server handler owns its connection's timeout this way; a client sets it
  3713. // through WebSocketClient. Safe to call while another thread is in read().
  3714. //
  3715. // Only a timeout set here is reported as Timeout. The compile-time default
  3716. // (CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND) is a backstop rather
  3717. // than a request for control, so when it elapses read() returns Fail and
  3718. // closes the connection, and `while (ws.read(msg))` ends as it always has.
  3719. void set_read_timeout(time_t sec, time_t usec = 0);
  3720. template <class Rep, class Period>
  3721. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  3722. private:
  3723. friend class httplib::Server;
  3724. friend class httplib::ws::WebSocketClient;
  3725. WebSocket(
  3726. Stream &strm, const Request &req, bool is_server,
  3727. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3728. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3729. : strm_(strm), req_(req), is_server_(is_server),
  3730. ping_interval_sec_(ping_interval_sec),
  3731. max_missed_pongs_(max_missed_pongs) {
  3732. start_heartbeat();
  3733. }
  3734. WebSocket(
  3735. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3736. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3737. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3738. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3739. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3740. max_missed_pongs_(max_missed_pongs) {
  3741. start_heartbeat();
  3742. }
  3743. void start_heartbeat();
  3744. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3745. Stream &strm_;
  3746. std::unique_ptr<Stream> owned_strm_;
  3747. Request req_;
  3748. bool is_server_;
  3749. time_t ping_interval_sec_;
  3750. int max_missed_pongs_;
  3751. int unacked_pings_ = 0;
  3752. std::atomic<bool> closed_{false};
  3753. // Set once the caller has bounded read() through set_read_timeout(). Until
  3754. // then the timeout in effect is the compile-time default, and elapsing it
  3755. // is a failure that closes the connection, not a Timeout.
  3756. std::atomic<bool> read_timeout_set_{false};
  3757. std::mutex write_mutex_;
  3758. // Owned by whichever thread is parsing frames off strm_. Only one thread
  3759. // may do so: read_websocket_frame() reads a payload until it has the whole
  3760. // declared length, so a second parser stealing bytes silently corrupts the
  3761. // message the first one is assembling.
  3762. std::mutex read_mutex_;
  3763. std::thread ping_thread_;
  3764. std::mutex ping_mutex_;
  3765. std::condition_variable ping_cv_;
  3766. };
  3767. class WebSocketClient {
  3768. public:
  3769. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3770. const Headers &headers = {});
  3771. ~WebSocketClient();
  3772. WebSocketClient(const WebSocketClient &) = delete;
  3773. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3774. bool is_valid() const;
  3775. Result connect();
  3776. ReadResult read(std::string &msg);
  3777. bool send(const std::string &data);
  3778. bool send(const char *data, size_t len);
  3779. void close(CloseStatus status = CloseStatus::Normal,
  3780. const std::string &reason = "");
  3781. bool is_open() const;
  3782. const std::string &subprotocol() const;
  3783. void set_read_timeout(time_t sec, time_t usec = 0);
  3784. template <class Rep, class Period>
  3785. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  3786. void set_write_timeout(time_t sec, time_t usec = 0);
  3787. template <class Rep, class Period>
  3788. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  3789. void set_websocket_ping_interval(time_t sec);
  3790. void set_websocket_max_missed_pongs(int count);
  3791. void set_tcp_nodelay(bool on);
  3792. void set_address_family(int family);
  3793. void set_ipv6_v6only(bool on);
  3794. void set_socket_options(SocketOptions socket_options);
  3795. void set_connection_timeout(time_t sec, time_t usec = 0);
  3796. template <class Rep, class Period>
  3797. void
  3798. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  3799. void set_interface(const std::string &intf);
  3800. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3801. #ifdef CPPHTTPLIB_SSL_ENABLED
  3802. struct PemMemory {
  3803. const char *cert_pem;
  3804. size_t cert_pem_len;
  3805. const char *key_pem;
  3806. size_t key_pem_len;
  3807. const char *private_key_password;
  3808. };
  3809. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3810. const PemMemory &pem, const Headers &headers = {});
  3811. void set_ca_cert_path(const std::string &ca_cert_file_path,
  3812. const std::string &ca_cert_dir_path = std::string());
  3813. void set_ca_cert_store(tls::ca_store_t store);
  3814. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3815. void enable_server_certificate_verification(bool enabled);
  3816. void enable_server_hostname_verification(bool enabled);
  3817. void enable_system_ca(bool enabled);
  3818. #endif
  3819. private:
  3820. void shutdown_and_close();
  3821. bool create_stream(std::unique_ptr<Stream> &strm, Error &error,
  3822. int &ssl_error, uint64_t &ssl_backend_error);
  3823. void prepare_default_headers(Request &req);
  3824. std::string host_;
  3825. int port_;
  3826. std::string path_;
  3827. Headers headers_;
  3828. std::string subprotocol_;
  3829. bool is_valid_ = false;
  3830. socket_t sock_ = INVALID_SOCKET;
  3831. std::unique_ptr<WebSocket> ws_;
  3832. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND;
  3833. time_t read_timeout_usec_ = 0;
  3834. bool read_timeout_set_ = false; // see WebSocket::read_timeout_set_
  3835. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3836. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3837. time_t websocket_ping_interval_sec_ =
  3838. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3839. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3840. int address_family_ = AF_UNSPEC;
  3841. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3842. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3843. SocketOptions socket_options_ = nullptr;
  3844. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3845. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3846. std::string interface_;
  3847. // Hostname to connection target map. The value is an IP literal or another
  3848. // hostname; only the connection target changes, never the identity.
  3849. std::map<std::string, std::string> addr_map_;
  3850. #ifdef CPPHTTPLIB_SSL_ENABLED
  3851. bool is_ssl_ = false;
  3852. tls::ctx_t tls_ctx_ = nullptr;
  3853. tls::session_t tls_session_ = nullptr;
  3854. std::string ca_cert_file_path_;
  3855. std::string ca_cert_dir_path_;
  3856. bool custom_ca_loaded_ = false;
  3857. bool certs_loaded_ = false;
  3858. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3859. bool server_certificate_verification_ = true;
  3860. bool server_hostname_verification_ = true;
  3861. #endif
  3862. };
  3863. template <class Rep, class Period>
  3864. inline void WebSocket::set_read_timeout(
  3865. const std::chrono::duration<Rep, Period> &duration) {
  3866. detail::duration_to_sec_and_usec(
  3867. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3868. }
  3869. template <class Rep, class Period>
  3870. inline void WebSocketClient::set_read_timeout(
  3871. const std::chrono::duration<Rep, Period> &duration) {
  3872. detail::duration_to_sec_and_usec(
  3873. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3874. }
  3875. template <class Rep, class Period>
  3876. inline void WebSocketClient::set_write_timeout(
  3877. const std::chrono::duration<Rep, Period> &duration) {
  3878. detail::duration_to_sec_and_usec(
  3879. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3880. }
  3881. template <class Rep, class Period>
  3882. inline void WebSocketClient::set_connection_timeout(
  3883. const std::chrono::duration<Rep, Period> &duration) {
  3884. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  3885. set_connection_timeout(sec, usec);
  3886. });
  3887. }
  3888. namespace impl {
  3889. bool is_valid_utf8(const std::string &s);
  3890. // Three states, because a failure that consumed bytes and one that consumed
  3891. // none are not the same thing: the first has left the stream in the middle of
  3892. // a frame and the connection cannot be reused, the second can just be retried.
  3893. enum class FrameRead { Ok, Fail, Timeout };
  3894. FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  3895. std::string &payload, bool &fin,
  3896. bool expect_masked, size_t max_len);
  3897. } // namespace impl
  3898. } // namespace ws
  3899. // ----------------------------------------------------------------------------
  3900. /*
  3901. * Implementation that will be part of the .cc file if split into .h + .cc.
  3902. */
  3903. namespace stream {
  3904. // stream::Result implementations
  3905. inline Result::Result() : chunk_size_(8192) {}
  3906. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3907. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3908. inline Result::Result(Result &&other) noexcept
  3909. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3910. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3911. finished_(other.finished_) {
  3912. other.current_size_ = 0;
  3913. other.finished_ = true;
  3914. }
  3915. inline Result &Result::operator=(Result &&other) noexcept {
  3916. if (this != &other) {
  3917. handle_ = std::move(other.handle_);
  3918. buffer_ = std::move(other.buffer_);
  3919. current_size_ = other.current_size_;
  3920. chunk_size_ = other.chunk_size_;
  3921. finished_ = other.finished_;
  3922. other.current_size_ = 0;
  3923. other.finished_ = true;
  3924. }
  3925. return *this;
  3926. }
  3927. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3928. inline Result::operator bool() const { return is_valid(); }
  3929. inline int Result::status() const {
  3930. return handle_.response ? handle_.response->status : -1;
  3931. }
  3932. inline const Headers &Result::headers() const {
  3933. static const Headers empty_headers;
  3934. return handle_.response ? handle_.response->headers : empty_headers;
  3935. }
  3936. inline std::string Result::get_header_value(const std::string &key,
  3937. const char *def) const {
  3938. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3939. }
  3940. inline bool Result::has_header(const std::string &key) const {
  3941. return handle_.response ? handle_.response->has_header(key) : false;
  3942. }
  3943. inline Error Result::error() const { return handle_.error; }
  3944. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3945. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3946. inline bool Result::next() {
  3947. if (!handle_.is_valid() || finished_) { return false; }
  3948. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3949. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3950. if (n > 0) {
  3951. current_size_ = static_cast<size_t>(n);
  3952. return true;
  3953. }
  3954. current_size_ = 0;
  3955. finished_ = true;
  3956. return false;
  3957. }
  3958. inline const char *Result::data() const { return buffer_.data(); }
  3959. inline size_t Result::size() const { return current_size_; }
  3960. inline std::string Result::read_all() {
  3961. std::string result;
  3962. while (next()) {
  3963. result.append(data(), size());
  3964. }
  3965. return result;
  3966. }
  3967. } // namespace stream
  3968. namespace sse {
  3969. // SSEMessage implementations
  3970. inline SSEMessage::SSEMessage() : event("message") {}
  3971. inline void SSEMessage::clear() {
  3972. event = "message";
  3973. data.clear();
  3974. id.clear();
  3975. }
  3976. // SSEClient implementations
  3977. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3978. : client_(client), path_(path) {}
  3979. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3980. const Headers &headers)
  3981. : client_(client), path_(path), headers_(headers) {}
  3982. inline SSEClient::~SSEClient() { stop(); }
  3983. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3984. on_message_ = std::move(handler);
  3985. return *this;
  3986. }
  3987. inline SSEClient &SSEClient::on_event(const std::string &type,
  3988. MessageHandler handler) {
  3989. event_handlers_[type] = std::move(handler);
  3990. return *this;
  3991. }
  3992. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3993. on_open_ = std::move(handler);
  3994. return *this;
  3995. }
  3996. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3997. on_error_ = std::move(handler);
  3998. return *this;
  3999. }
  4000. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  4001. reconnect_interval_ms_ = ms;
  4002. return *this;
  4003. }
  4004. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  4005. max_reconnect_attempts_ = n;
  4006. return *this;
  4007. }
  4008. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  4009. std::lock_guard<std::mutex> lock(headers_mutex_);
  4010. headers_ = headers;
  4011. return *this;
  4012. }
  4013. inline bool SSEClient::is_connected() const { return connected_.load(); }
  4014. inline const std::string &SSEClient::last_event_id() const {
  4015. return last_event_id_;
  4016. }
  4017. inline void SSEClient::start() {
  4018. running_.store(true);
  4019. run_event_loop();
  4020. }
  4021. inline void SSEClient::start_async() {
  4022. running_.store(true);
  4023. async_thread_ = std::thread([this]() { run_event_loop(); });
  4024. }
  4025. inline void SSEClient::stop() {
  4026. running_.store(false);
  4027. client_.stop(); // Cancel any pending operations
  4028. if (async_thread_.joinable()) { async_thread_.join(); }
  4029. }
  4030. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  4031. int &retry_ms, bool &has_data,
  4032. bool &has_id) {
  4033. // Blank line signals end of event
  4034. if (line.empty()) { return true; }
  4035. // Lines starting with ':' are comments (ignored)
  4036. if (line[0] == ':') { return false; }
  4037. // Find the colon separator
  4038. auto colon_pos = line.find(':');
  4039. auto field = line.substr(0, colon_pos);
  4040. std::string value;
  4041. // Value starts after colon, skip optional single space
  4042. if (colon_pos != std::string::npos && colon_pos + 1 < line.size()) {
  4043. auto value_start = colon_pos + 1;
  4044. if (line[value_start] == ' ') { value_start++; }
  4045. value = line.substr(value_start);
  4046. }
  4047. // Handle known fields
  4048. if (field == "event") {
  4049. msg.event = value;
  4050. } else if (field == "data") {
  4051. // Multiple data lines are concatenated with newlines
  4052. if (has_data) { msg.data += "\n"; }
  4053. msg.data += value;
  4054. has_data = true;
  4055. } else if (field == "id") {
  4056. // An id that cannot be sent back as Last-Event-ID is ignored. Empty id is
  4057. // valid (clears the last event ID)
  4058. if (detail::fields::is_field_value(value)) {
  4059. msg.id = value;
  4060. has_id = true;
  4061. }
  4062. } else if (field == "retry") {
  4063. // Parse retry interval in milliseconds
  4064. // Per the SSE spec, a value that is not all ASCII digits is ignored.
  4065. if (detail::is_numeric(value)) {
  4066. int v = 0;
  4067. auto res =
  4068. detail::from_chars(value.data(), value.data() + value.size(), v);
  4069. if (res.ec == std::errc{}) { retry_ms = v; }
  4070. }
  4071. }
  4072. // Unknown fields are ignored per SSE spec
  4073. return false;
  4074. }
  4075. inline void SSEClient::run_event_loop() {
  4076. auto reconnect_count = 0;
  4077. while (running_.load()) {
  4078. // Build headers, including Last-Event-ID if we have one
  4079. Headers request_headers;
  4080. {
  4081. std::lock_guard<std::mutex> lock(headers_mutex_);
  4082. request_headers = headers_;
  4083. }
  4084. if (!last_event_id_.empty()) {
  4085. request_headers.emplace("Last-Event-ID", last_event_id_);
  4086. }
  4087. // Open streaming connection
  4088. auto result = stream::Get(client_, path_, request_headers);
  4089. // Connection error handling
  4090. if (!result) {
  4091. connected_.store(false);
  4092. if (on_error_) { on_error_(result.error()); }
  4093. if (!should_reconnect(reconnect_count)) { break; }
  4094. wait_for_reconnect();
  4095. reconnect_count++;
  4096. continue;
  4097. }
  4098. if (result.status() != StatusCode::OK_200) {
  4099. connected_.store(false);
  4100. if (on_error_) { on_error_(Error::Connection); }
  4101. // For certain errors, don't reconnect.
  4102. // Note: 401 is intentionally absent so that handlers can refresh
  4103. // credentials via set_headers() and let the client reconnect.
  4104. if (result.status() == StatusCode::NoContent_204 ||
  4105. result.status() == StatusCode::NotFound_404 ||
  4106. result.status() == StatusCode::Forbidden_403) {
  4107. break;
  4108. }
  4109. if (!should_reconnect(reconnect_count)) { break; }
  4110. wait_for_reconnect();
  4111. reconnect_count++;
  4112. continue;
  4113. }
  4114. // Connection successful
  4115. connected_.store(true);
  4116. reconnect_count = 0;
  4117. if (on_open_) { on_open_(); }
  4118. // Event receiving loop
  4119. std::string buffer;
  4120. SSEMessage current_msg;
  4121. auto has_data = false;
  4122. auto has_id = false;
  4123. auto first_line = true;
  4124. auto after_cr = false;
  4125. while (running_.load() && result.next()) {
  4126. // What is left in the buffer has no line ending
  4127. auto search_pos = buffer.size();
  4128. buffer.append(result.data(), result.size());
  4129. // Process complete lines in the buffer. A line ends with \r\n, \n or \r
  4130. // per the SSE spec
  4131. size_t line_start = 0;
  4132. size_t eol_pos;
  4133. while ((eol_pos = buffer.find_first_of("\r\n", search_pos)) !=
  4134. std::string::npos) {
  4135. auto line = buffer.substr(line_start, eol_pos - line_start);
  4136. line_start = eol_pos + 1;
  4137. search_pos = line_start;
  4138. // The \n of a \r\n may arrive in a later chunk than its \r
  4139. auto is_lf_of_crlf =
  4140. after_cr && line.empty() && buffer[eol_pos] == '\n';
  4141. after_cr = buffer[eol_pos] == '\r';
  4142. if (is_lf_of_crlf) { continue; }
  4143. // A UTF-8 BOM at the start of the stream is ignored per the SSE spec
  4144. if (first_line) {
  4145. first_line = false;
  4146. if (line.compare(0, 3, "\xEF\xBB\xBF") == 0) { line.erase(0, 3); }
  4147. }
  4148. // Parse the line and check if event is complete
  4149. auto event_complete = parse_sse_line(
  4150. line, current_msg, reconnect_interval_ms_, has_data, has_id);
  4151. if (event_complete) {
  4152. // Update last_event_id for reconnection, even for an event that
  4153. // has no data. An empty id clears it.
  4154. if (has_id) { last_event_id_ = current_msg.id; }
  4155. // An event without a data field is not dispatched
  4156. if (has_data) { dispatch_event(current_msg); }
  4157. // Reset the message for the next event either way
  4158. current_msg.clear();
  4159. has_data = false;
  4160. has_id = false;
  4161. }
  4162. }
  4163. // Keep unprocessed data in buffer
  4164. buffer.erase(0, line_start);
  4165. }
  4166. // Connection ended
  4167. connected_.store(false);
  4168. if (!running_.load()) { break; }
  4169. // Check for read errors
  4170. if (result.has_read_error()) {
  4171. if (on_error_) { on_error_(result.read_error()); }
  4172. }
  4173. if (!should_reconnect(reconnect_count)) { break; }
  4174. wait_for_reconnect();
  4175. reconnect_count++;
  4176. }
  4177. connected_.store(false);
  4178. }
  4179. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  4180. // Check for specific event type handler first
  4181. auto it = event_handlers_.find(msg.event);
  4182. if (it != event_handlers_.end()) {
  4183. it->second(msg);
  4184. return;
  4185. }
  4186. // Fall back to generic message handler
  4187. if (on_message_) { on_message_(msg); }
  4188. }
  4189. inline bool SSEClient::should_reconnect(int count) const {
  4190. if (!running_.load()) { return false; }
  4191. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  4192. return count < max_reconnect_attempts_;
  4193. }
  4194. inline void SSEClient::wait_for_reconnect() {
  4195. // Use small increments to check running_ flag frequently.
  4196. // Always wait at least one increment, so that a zero interval (e.g.
  4197. // "retry: 0" from the server) cannot cause a busy reconnect loop.
  4198. const auto step_ms = 100;
  4199. auto interval_ms = (std::max)(reconnect_interval_ms_, step_ms);
  4200. auto waited = 0;
  4201. while (running_.load() && waited < interval_ms) {
  4202. std::this_thread::sleep_for(std::chrono::milliseconds(step_ms));
  4203. waited += step_ms;
  4204. }
  4205. }
  4206. } // namespace sse
  4207. #ifdef CPPHTTPLIB_SSL_ENABLED
  4208. /*
  4209. * TLS abstraction layer - internal function declarations
  4210. * These are implementation details and not part of the public API.
  4211. */
  4212. namespace tls {
  4213. // Client context
  4214. ctx_t create_client_context();
  4215. void free_context(ctx_t ctx);
  4216. bool set_min_version(ctx_t ctx, Version version);
  4217. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  4218. bool load_ca_file(ctx_t ctx, const char *file_path);
  4219. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  4220. bool load_system_certs(ctx_t ctx);
  4221. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4222. const char *password);
  4223. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  4224. const char *key_path, const char *password);
  4225. // Server context
  4226. ctx_t create_server_context();
  4227. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4228. const char *password);
  4229. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  4230. const char *key_path, const char *password);
  4231. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  4232. void set_verify_client(ctx_t ctx, bool require);
  4233. // Session management
  4234. session_t create_session(ctx_t ctx, socket_t sock);
  4235. void free_session(session_t session);
  4236. bool set_sni(session_t session, const char *hostname, bool verify_hostname);
  4237. // Handshake (non-blocking capable)
  4238. TlsError connect(session_t session);
  4239. TlsError accept(session_t session);
  4240. // Handshake with timeout (blocking until timeout)
  4241. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4242. time_t timeout_usec, TlsError *err);
  4243. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4244. time_t timeout_usec, TlsError *err);
  4245. // I/O (non-blocking capable)
  4246. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  4247. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  4248. int pending(const_session_t session);
  4249. void shutdown(session_t session, bool graceful);
  4250. // Connection state
  4251. bool is_peer_closed(session_t session, socket_t sock);
  4252. // Certificate verification
  4253. cert_t get_peer_cert(const_session_t session);
  4254. // The certificates the peer sent, leaf first. Free each with free_cert(), and
  4255. // do not use them after free_session(), as with get_peer_cert().
  4256. size_t get_peer_certs(const_session_t session, std::vector<cert_t> &certs);
  4257. void free_cert(cert_t cert);
  4258. bool verify_hostname(cert_t cert, const char *hostname);
  4259. uint64_t hostname_mismatch_code();
  4260. long get_verify_result(const_session_t session);
  4261. // Certificate introspection
  4262. std::string get_cert_subject_cn(cert_t cert);
  4263. std::string get_cert_issuer_name(cert_t cert);
  4264. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  4265. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  4266. std::string get_cert_serial(cert_t cert);
  4267. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  4268. const char *get_sni(const_session_t session);
  4269. // CA store management
  4270. ca_store_t create_ca_store(const char *pem, size_t len);
  4271. void free_ca_store(ca_store_t store);
  4272. bool set_ca_store(ctx_t ctx, ca_store_t store);
  4273. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  4274. std::vector<std::string> get_ca_names(ctx_t ctx);
  4275. // Dynamic certificate update (for servers)
  4276. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  4277. const char *password);
  4278. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  4279. // Certificate verification callback
  4280. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  4281. long get_verify_error(const_session_t session);
  4282. std::string verify_error_string(long error_code);
  4283. // TlsError information
  4284. uint64_t peek_error();
  4285. uint64_t get_error();
  4286. std::string error_string(uint64_t code);
  4287. } // namespace tls
  4288. #endif // CPPHTTPLIB_SSL_ENABLED
  4289. /*
  4290. * Group 1: detail namespace - Non-SSL utilities
  4291. */
  4292. namespace detail {
  4293. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  4294. const void *optval, socklen_t optlen) {
  4295. return setsockopt(sock, level, optname,
  4296. #ifdef _WIN32
  4297. reinterpret_cast<const char *>(optval),
  4298. #else
  4299. optval,
  4300. #endif
  4301. optlen) == 0;
  4302. }
  4303. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  4304. time_t sec, time_t usec) {
  4305. #ifdef _WIN32
  4306. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  4307. #else
  4308. timeval timeout;
  4309. timeout.tv_sec = static_cast<long>(sec);
  4310. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  4311. #endif
  4312. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  4313. }
  4314. inline bool is_hex(char c, int &v) {
  4315. if (is_ascii_digit(c)) {
  4316. v = c - '0';
  4317. return true;
  4318. } else if ('A' <= c && c <= 'F') {
  4319. v = c - 'A' + 10;
  4320. return true;
  4321. } else if ('a' <= c && c <= 'f') {
  4322. v = c - 'a' + 10;
  4323. return true;
  4324. }
  4325. return false;
  4326. }
  4327. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  4328. int &val) {
  4329. if (i >= s.size()) { return false; }
  4330. val = 0;
  4331. for (; cnt; i++, cnt--) {
  4332. if (!s[i]) { return false; }
  4333. auto v = 0;
  4334. if (is_hex(s[i], v)) {
  4335. val = val * 16 + v;
  4336. } else {
  4337. return false;
  4338. }
  4339. }
  4340. return true;
  4341. }
  4342. inline std::string from_i_to_hex(size_t n) {
  4343. static const auto charset = "0123456789abcdef";
  4344. std::string ret;
  4345. do {
  4346. ret = charset[n & 15] + ret;
  4347. n >>= 4;
  4348. } while (n > 0);
  4349. return ret;
  4350. }
  4351. inline std::string compute_etag(const FileStat &fs,
  4352. const std::string &suffix = std::string()) {
  4353. if (!fs.is_file()) { return std::string(); }
  4354. // If mtime cannot be determined (negative value indicates an error
  4355. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  4356. // value like 0 could collide with a real file that legitimately has
  4357. // mtime == 0 (epoch) and lead to misleading validators.
  4358. auto mtime_raw = fs.mtime();
  4359. if (mtime_raw < 0) { return std::string(); }
  4360. auto mtime = static_cast<size_t>(mtime_raw);
  4361. auto size = fs.size();
  4362. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  4363. from_i_to_hex(size) + suffix + "\"";
  4364. }
  4365. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  4366. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  4367. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  4368. inline std::string file_mtime_to_http_date(time_t mtime) {
  4369. if (mtime < 0) { return std::string(); }
  4370. struct tm tm_buf;
  4371. #ifdef _WIN32
  4372. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  4373. #else
  4374. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  4375. #endif
  4376. char buf[64];
  4377. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  4378. return std::string();
  4379. }
  4380. return std::string(buf);
  4381. }
  4382. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  4383. inline time_t parse_http_date(const std::string &date_str) {
  4384. struct tm tm_buf;
  4385. // Create a classic locale object once for all parsing attempts
  4386. const std::locale classic_locale = std::locale::classic();
  4387. // Try to parse using std::get_time (C++11, cross-platform)
  4388. auto try_parse = [&](const char *fmt) -> bool {
  4389. std::istringstream ss(date_str);
  4390. ss.imbue(classic_locale);
  4391. memset(&tm_buf, 0, sizeof(tm_buf));
  4392. ss >> std::get_time(&tm_buf, fmt);
  4393. return !ss.fail();
  4394. };
  4395. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  4396. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  4397. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  4398. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  4399. // asctime format: "Sun Nov 6 08:49:37 1994"
  4400. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  4401. return static_cast<time_t>(-1);
  4402. }
  4403. }
  4404. }
  4405. #ifdef _WIN32
  4406. return _mkgmtime(&tm_buf);
  4407. #elif defined _AIX
  4408. return mktime(&tm_buf);
  4409. #else
  4410. return timegm(&tm_buf);
  4411. #endif
  4412. }
  4413. inline bool is_weak_etag(const std::string &s) {
  4414. // Check if the string is a weak ETag (starts with 'W/"')
  4415. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  4416. }
  4417. inline bool is_strong_etag(const std::string &s) {
  4418. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  4419. // chars)
  4420. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  4421. }
  4422. inline size_t to_utf8(int code, char *buff) {
  4423. if (code < 0x0080) {
  4424. buff[0] = static_cast<char>(code & 0x7F);
  4425. return 1;
  4426. } else if (code < 0x0800) {
  4427. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  4428. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  4429. return 2;
  4430. } else if (code < 0xD800) {
  4431. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4432. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4433. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4434. return 3;
  4435. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  4436. return 0;
  4437. } else if (code < 0x10000) {
  4438. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4439. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4440. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4441. return 3;
  4442. } else if (code < 0x110000) {
  4443. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  4444. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  4445. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4446. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  4447. return 4;
  4448. }
  4449. // NOTREACHED
  4450. return 0;
  4451. }
  4452. } // namespace detail
  4453. namespace ws {
  4454. namespace impl {
  4455. inline bool is_valid_utf8(const std::string &s) {
  4456. size_t i = 0;
  4457. auto n = s.size();
  4458. while (i < n) {
  4459. auto c = static_cast<unsigned char>(s[i]);
  4460. size_t len;
  4461. uint32_t cp;
  4462. if (c < 0x80) {
  4463. i++;
  4464. continue;
  4465. } else if ((c & 0xE0) == 0xC0) {
  4466. len = 2;
  4467. cp = c & 0x1F;
  4468. } else if ((c & 0xF0) == 0xE0) {
  4469. len = 3;
  4470. cp = c & 0x0F;
  4471. } else if ((c & 0xF8) == 0xF0) {
  4472. len = 4;
  4473. cp = c & 0x07;
  4474. } else {
  4475. return false;
  4476. }
  4477. if (i + len > n) { return false; }
  4478. for (size_t j = 1; j < len; j++) {
  4479. auto b = static_cast<unsigned char>(s[i + j]);
  4480. if ((b & 0xC0) != 0x80) { return false; }
  4481. cp = (cp << 6) | (b & 0x3F);
  4482. }
  4483. // Overlong encoding check
  4484. if (len == 2 && cp < 0x80) { return false; }
  4485. if (len == 3 && cp < 0x800) { return false; }
  4486. if (len == 4 && cp < 0x10000) { return false; }
  4487. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  4488. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  4489. if (cp > 0x10FFFF) { return false; }
  4490. i += len;
  4491. }
  4492. return true;
  4493. }
  4494. } // namespace impl
  4495. } // namespace ws
  4496. namespace detail {
  4497. // NOTE: This code came up with the following stackoverflow post:
  4498. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  4499. inline std::string base64_encode(const std::string &in) {
  4500. static const auto lookup =
  4501. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4502. std::string out;
  4503. out.reserve(in.size());
  4504. // Unsigned: the accumulator is never masked, so with a signed int the
  4505. // `val << 8` below overflows once enough bytes are folded in (undefined
  4506. // behaviour before C++20). Only the low bits are ever emitted, so the
  4507. // wrap-around of an unsigned accumulator does not affect the output.
  4508. uint32_t val = 0;
  4509. auto valb = -6;
  4510. for (auto c : in) {
  4511. val = (val << 8) + static_cast<uint8_t>(c);
  4512. valb += 8;
  4513. while (valb >= 0) {
  4514. out.push_back(lookup[(val >> valb) & 0x3F]);
  4515. valb -= 6;
  4516. }
  4517. }
  4518. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  4519. while (out.size() % 4) {
  4520. out.push_back('=');
  4521. }
  4522. return out;
  4523. }
  4524. inline std::string sha1(const std::string &input) {
  4525. // RFC 3174 SHA-1 implementation
  4526. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  4527. return (x << n) | (x >> (32 - n));
  4528. };
  4529. uint32_t h0 = 0x67452301;
  4530. uint32_t h1 = 0xEFCDAB89;
  4531. uint32_t h2 = 0x98BADCFE;
  4532. uint32_t h3 = 0x10325476;
  4533. uint32_t h4 = 0xC3D2E1F0;
  4534. // Pre-processing: adding padding bits
  4535. std::string msg = input;
  4536. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  4537. msg.push_back(static_cast<char>(0x80u));
  4538. while (msg.size() % 64 != 56) {
  4539. msg.push_back(0);
  4540. }
  4541. // Append original length in bits as 64-bit big-endian
  4542. for (int i = 56; i >= 0; i -= 8) {
  4543. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  4544. }
  4545. // Process each 512-bit chunk
  4546. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  4547. uint32_t w[80];
  4548. for (size_t i = 0; i < 16; i++) {
  4549. w[i] =
  4550. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  4551. << 24) |
  4552. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  4553. << 16) |
  4554. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  4555. << 8) |
  4556. (static_cast<uint32_t>(
  4557. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  4558. }
  4559. for (int i = 16; i < 80; i++) {
  4560. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  4561. }
  4562. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  4563. for (int i = 0; i < 80; i++) {
  4564. uint32_t f, k;
  4565. if (i < 20) {
  4566. f = (b & c) | ((~b) & d);
  4567. k = 0x5A827999;
  4568. } else if (i < 40) {
  4569. f = b ^ c ^ d;
  4570. k = 0x6ED9EBA1;
  4571. } else if (i < 60) {
  4572. f = (b & c) | (b & d) | (c & d);
  4573. k = 0x8F1BBCDC;
  4574. } else {
  4575. f = b ^ c ^ d;
  4576. k = 0xCA62C1D6;
  4577. }
  4578. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  4579. e = d;
  4580. d = c;
  4581. c = left_rotate(b, 30);
  4582. b = a;
  4583. a = temp;
  4584. }
  4585. h0 += a;
  4586. h1 += b;
  4587. h2 += c;
  4588. h3 += d;
  4589. h4 += e;
  4590. }
  4591. // Produce the final hash as a 20-byte binary string
  4592. std::string hash(20, '\0');
  4593. for (size_t i = 0; i < 4; i++) {
  4594. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  4595. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  4596. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  4597. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  4598. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  4599. }
  4600. return hash;
  4601. }
  4602. inline std::string websocket_accept_key(const std::string &client_key) {
  4603. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  4604. return base64_encode(sha1(client_key + magic));
  4605. }
  4606. inline bool is_websocket_upgrade(const Request &req) {
  4607. if (req.method != "GET") { return false; }
  4608. // Check Upgrade: websocket. RFC 9110 7.8 defines Upgrade as a comma-separated
  4609. // list of protocols and asks recipients to match each name
  4610. // case-insensitively, so look for the token rather than compare the whole
  4611. // field value.
  4612. if (!has_header_token(req.headers, "Upgrade", "websocket")) { return false; }
  4613. // Check Connection: Upgrade
  4614. if (!has_header_token(req.headers, "Connection", "upgrade")) { return false; }
  4615. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  4616. // RFC 6455 Section 4.2.1
  4617. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  4618. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  4619. return false;
  4620. }
  4621. static const std::string b64chars =
  4622. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4623. for (size_t i = 0; i < 22; i++) {
  4624. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  4625. }
  4626. // Check Sec-WebSocket-Version: 13
  4627. auto version = req.get_header_value("Sec-WebSocket-Version");
  4628. if (version != "13") { return false; }
  4629. return true;
  4630. }
  4631. // RFC 6455 Section 5.3: the masking key must be unpredictable
  4632. inline void fill_random_bytes(unsigned char *out, size_t n) {
  4633. thread_local std::random_device rd;
  4634. size_t filled = 0;
  4635. while (filled < n) {
  4636. auto v = rd();
  4637. for (size_t b = 0; b < sizeof(v) && filled < n; ++b, ++filled) {
  4638. out[filled] = static_cast<unsigned char>((v >> (b * 8)) & 0xFFu);
  4639. }
  4640. }
  4641. }
  4642. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  4643. const char *data, size_t len, bool fin,
  4644. bool mask) {
  4645. // First byte: FIN + opcode
  4646. uint8_t header[2];
  4647. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  4648. (static_cast<uint8_t>(opcode) & 0x0F));
  4649. // Second byte: MASK + payload length
  4650. if (len < 126) {
  4651. header[1] = static_cast<uint8_t>(len);
  4652. if (mask) { header[1] |= 0x80; }
  4653. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4654. } else if (len <= 0xFFFF) {
  4655. header[1] = 126;
  4656. if (mask) { header[1] |= 0x80; }
  4657. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4658. uint8_t ext[2];
  4659. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4660. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4661. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4662. } else {
  4663. header[1] = 127;
  4664. if (mask) { header[1] |= 0x80; }
  4665. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4666. uint8_t ext[8];
  4667. for (int i = 7; i >= 0; i--) {
  4668. ext[7 - i] =
  4669. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4670. }
  4671. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4672. }
  4673. if (mask) {
  4674. // Generate random mask key
  4675. uint8_t mask_key[4];
  4676. fill_random_bytes(mask_key, sizeof(mask_key));
  4677. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4678. // Write masked payload in chunks
  4679. const size_t chunk_size = 4096;
  4680. std::vector<char> buf((std::min)(len, chunk_size));
  4681. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4682. size_t n = (std::min)(chunk_size, len - offset);
  4683. for (size_t i = 0; i < n; i++) {
  4684. buf[i] =
  4685. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4686. }
  4687. if (strm.write(buf.data(), n) < 0) { return false; }
  4688. }
  4689. } else {
  4690. if (len > 0) {
  4691. if (strm.write(data, len) < 0) { return false; }
  4692. }
  4693. }
  4694. return true;
  4695. }
  4696. } // namespace detail
  4697. namespace ws {
  4698. namespace impl {
  4699. // Read exactly `size` bytes. Stream::read may return less than asked for -- it
  4700. // hands back whatever its buffer already holds -- so every multi-byte field has
  4701. // to loop. Reading a 2-byte header with a single read() fails whenever the
  4702. // header straddles the read buffer's boundary.
  4703. //
  4704. // Timeout is reported only when nothing at all was consumed. Once a byte has
  4705. // been taken the stream sits mid-field and cannot be resumed, so a timeout
  4706. // there is a failure like any other. (When read() fails it always records why,
  4707. // so the error belongs to this call and not to an earlier one.)
  4708. inline FrameRead read_exact(Stream &strm, void *buf, size_t size) {
  4709. auto p = static_cast<char *>(buf);
  4710. size_t total = 0;
  4711. while (total < size) {
  4712. auto n = strm.read(p + total, size - total);
  4713. if (n <= 0) {
  4714. auto timed_out = total == 0 && strm.get_error() == Error::Timeout;
  4715. return timed_out ? FrameRead::Timeout : FrameRead::Fail;
  4716. }
  4717. total += static_cast<size_t>(n);
  4718. }
  4719. return FrameRead::Ok;
  4720. }
  4721. inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  4722. std::string &payload, bool &fin,
  4723. bool expect_masked, size_t max_len) {
  4724. // Read first 2 bytes. This is the only read that may report a timeout: it
  4725. // sits on a frame boundary, where nothing has been consumed yet.
  4726. uint8_t header[2];
  4727. FrameRead first = read_exact(strm, header, 2);
  4728. if (first != FrameRead::Ok) { return first; }
  4729. fin = (header[0] & 0x80) != 0;
  4730. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4731. if (header[0] & 0x70) { return FrameRead::Fail; }
  4732. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4733. bool masked = (header[1] & 0x80) != 0;
  4734. uint64_t payload_len = header[1] & 0x7F;
  4735. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4736. // MUST have a payload length of 125 bytes or less
  4737. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4738. if (is_control) {
  4739. if (!fin) { return FrameRead::Fail; }
  4740. if (payload_len > 125) { return FrameRead::Fail; }
  4741. }
  4742. if (masked != expect_masked) { return FrameRead::Fail; }
  4743. // Extended payload length
  4744. if (payload_len == 126) {
  4745. uint8_t ext[2];
  4746. if (read_exact(strm, ext, 2) != FrameRead::Ok) { return FrameRead::Fail; }
  4747. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4748. } else if (payload_len == 127) {
  4749. uint8_t ext[8];
  4750. if (read_exact(strm, ext, 8) != FrameRead::Ok) { return FrameRead::Fail; }
  4751. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4752. if (ext[0] & 0x80) { return FrameRead::Fail; }
  4753. payload_len = 0;
  4754. for (int i = 0; i < 8; i++) {
  4755. payload_len = (payload_len << 8) | ext[i];
  4756. }
  4757. }
  4758. if (payload_len > max_len) { return FrameRead::Fail; }
  4759. // Read mask key if present
  4760. uint8_t mask_key[4] = {0};
  4761. if (masked) {
  4762. if (read_exact(strm, mask_key, 4) != FrameRead::Ok) {
  4763. return FrameRead::Fail;
  4764. }
  4765. }
  4766. // Read payload
  4767. payload.resize(static_cast<size_t>(payload_len));
  4768. if (payload_len > 0 &&
  4769. read_exact(strm, &payload[0], static_cast<size_t>(payload_len)) !=
  4770. FrameRead::Ok) {
  4771. return FrameRead::Fail;
  4772. }
  4773. // Unmask if needed
  4774. if (masked) {
  4775. for (size_t i = 0; i < payload.size(); i++) {
  4776. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4777. }
  4778. }
  4779. return FrameRead::Ok;
  4780. }
  4781. } // namespace impl
  4782. } // namespace ws
  4783. namespace detail {
  4784. inline bool is_valid_path(const std::string &path) {
  4785. size_t level = 0;
  4786. size_t i = 0;
  4787. // Skip slash
  4788. while (i < path.size() && path[i] == '/') {
  4789. i++;
  4790. }
  4791. while (i < path.size()) {
  4792. // Read component
  4793. auto beg = i;
  4794. while (i < path.size() && path[i] != '/') {
  4795. if (path[i] == '\0') {
  4796. return false;
  4797. } else if (path[i] == '\\') {
  4798. return false;
  4799. }
  4800. i++;
  4801. }
  4802. auto len = i - beg;
  4803. assert(len > 0);
  4804. if (!path.compare(beg, len, ".")) {
  4805. ;
  4806. } else if (!path.compare(beg, len, "..")) {
  4807. if (level == 0) { return false; }
  4808. level--;
  4809. } else {
  4810. level++;
  4811. }
  4812. // Skip slash
  4813. while (i < path.size() && path[i] == '/') {
  4814. i++;
  4815. }
  4816. }
  4817. return true;
  4818. }
  4819. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4820. #if defined(_WIN32)
  4821. char buf[_MAX_PATH];
  4822. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4823. resolved = buf;
  4824. #elif defined(PATH_MAX)
  4825. char buf[PATH_MAX];
  4826. if (realpath(path, buf) == nullptr) { return false; }
  4827. resolved = buf;
  4828. #else
  4829. auto buf = realpath(path, nullptr);
  4830. auto guard = scope_exit([&]() { std::free(buf); });
  4831. if (buf == nullptr) { return false; }
  4832. resolved = buf;
  4833. #endif
  4834. return true;
  4835. }
  4836. inline bool is_path_within_base(const std::string &resolved_path,
  4837. const std::string &resolved_base) {
  4838. #if defined(_WIN32)
  4839. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4840. resolved_base.size()) == 0;
  4841. #else
  4842. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4843. resolved_base.size()) == 0;
  4844. #endif
  4845. }
  4846. inline FileStat::FileStat(const std::string &path) {
  4847. #if defined(_WIN32)
  4848. auto wpath = u8string_to_wstring(path.c_str());
  4849. ret_ = _wstat(wpath.c_str(), &st_);
  4850. #else
  4851. ret_ = stat(path.c_str(), &st_);
  4852. #endif
  4853. }
  4854. inline bool FileStat::is_file() const {
  4855. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4856. }
  4857. inline bool FileStat::is_dir() const {
  4858. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4859. }
  4860. inline time_t FileStat::mtime() const {
  4861. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4862. : static_cast<time_t>(-1);
  4863. }
  4864. inline size_t FileStat::size() const {
  4865. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4866. }
  4867. inline std::string encode_path(const std::string &s) {
  4868. std::string result;
  4869. result.reserve(s.size());
  4870. for (size_t i = 0; s[i]; i++) {
  4871. switch (s[i]) {
  4872. case ' ': result += "%20"; break;
  4873. case '+': result += "%2B"; break;
  4874. case '\'': result += "%27"; break;
  4875. case ',': result += "%2C"; break;
  4876. // case ':': result += "%3A"; break; // ok? probably...
  4877. case ';': result += "%3B"; break;
  4878. default:
  4879. auto c = static_cast<uint8_t>(s[i]);
  4880. // Control characters (incl. CR/LF) and non-ASCII bytes are not allowed
  4881. // in a request-target as-is.
  4882. if (c < 0x20 || c == 0x7f || c >= 0x80) {
  4883. result += '%';
  4884. char hex[4];
  4885. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4886. assert(len == 2);
  4887. result.append(hex, static_cast<size_t>(len));
  4888. } else {
  4889. result += s[i];
  4890. }
  4891. break;
  4892. }
  4893. }
  4894. return result;
  4895. }
  4896. inline std::string file_extension(const std::string &path) {
  4897. std::smatch m;
  4898. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4899. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4900. return std::string();
  4901. }
  4902. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4903. template <typename T>
  4904. inline bool parse_header(const char *beg, const char *end, T fn);
  4905. template <typename T>
  4906. inline bool parse_header(const char *beg, const char *end, T fn) {
  4907. // Skip trailing spaces and tabs.
  4908. while (beg < end && is_space_or_tab(end[-1])) {
  4909. end--;
  4910. }
  4911. auto p = beg;
  4912. while (p < end && *p != ':') {
  4913. p++;
  4914. }
  4915. auto name = std::string(beg, p);
  4916. if (!detail::fields::is_field_name(name)) { return false; }
  4917. if (p == end) { return false; }
  4918. auto key_end = p;
  4919. if (*p++ != ':') { return false; }
  4920. while (p < end && is_space_or_tab(*p)) {
  4921. p++;
  4922. }
  4923. if (p <= end) {
  4924. auto key_len = key_end - beg;
  4925. if (!key_len) { return false; }
  4926. auto key = std::string(beg, key_end);
  4927. auto val = std::string(p, end);
  4928. if (!detail::fields::is_field_value(val)) { return false; }
  4929. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4930. // percent-decoded by the recipient. Applications that need to interpret a
  4931. // value as a URI component should call httplib::decode_uri_component()
  4932. // (or decode_path_component()) explicitly.
  4933. fn(key, val);
  4934. return true;
  4935. }
  4936. return false;
  4937. }
  4938. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4939. const Headers &src_headers) {
  4940. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4941. // transfer coding is complete when a chunk with a chunk-size of zero is
  4942. // received, possibly followed by a trailer section, and finally terminated by
  4943. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4944. //
  4945. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4946. // doesn't care for the existence of the final CRLF. In other words, it seems
  4947. // to be ok whether the final CRLF exists or not in the chunked data.
  4948. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4949. //
  4950. // According to the reference code in RFC 9112, cpp-httplib now allows
  4951. // chunked transfer coding data without the final CRLF.
  4952. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4953. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4954. "transfer-encoding",
  4955. "content-length",
  4956. "host",
  4957. "authorization",
  4958. "www-authenticate",
  4959. "proxy-authenticate",
  4960. "proxy-authorization",
  4961. "cookie",
  4962. "set-cookie",
  4963. "cache-control",
  4964. "expect",
  4965. "max-forwards",
  4966. "pragma",
  4967. "range",
  4968. "te",
  4969. "age",
  4970. "expires",
  4971. "date",
  4972. "location",
  4973. "retry-after",
  4974. "vary",
  4975. "warning",
  4976. "content-encoding",
  4977. "content-type",
  4978. "content-range",
  4979. "trailer"};
  4980. case_ignore::unordered_set<std::string> declared_trailers;
  4981. auto trailer_header = get_combined_header_value(src_headers, "Trailer");
  4982. if (!trailer_header.empty()) {
  4983. // split() trims each token and skips empty ones, so the name arrives ready
  4984. // to look up.
  4985. split(trailer_header.data(), trailer_header.data() + trailer_header.size(),
  4986. ',', [&](const char *b, const char *e) {
  4987. // A legitimate message declares only a handful of trailers. Cap the
  4988. // set so a peer cannot grow it without bound: an oversized set only
  4989. // arises from an attempt to force many colliding names into
  4990. // quadratic lookups (case_ignore::hash is unkeyed).
  4991. if (declared_trailers.size() >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  4992. return;
  4993. }
  4994. std::string key(b, e);
  4995. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4996. declared_trailers.insert(key);
  4997. }
  4998. });
  4999. }
  5000. size_t trailer_header_count = 0;
  5001. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  5002. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5003. // Count every received trailer field, not only the declared ones stored in
  5004. // dest, so undeclared fields cannot keep this loop running past the limit.
  5005. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5006. constexpr auto line_terminator_len = 2;
  5007. auto line_beg = line_reader.ptr();
  5008. auto line_end =
  5009. line_reader.ptr() + line_reader.size() - line_terminator_len;
  5010. if (!parse_header(line_beg, line_end,
  5011. [&](const std::string &key, const std::string &val) {
  5012. if (declared_trailers.find(key) !=
  5013. declared_trailers.end()) {
  5014. dest.emplace(key, val);
  5015. }
  5016. })) {
  5017. return false;
  5018. }
  5019. trailer_header_count++;
  5020. if (!line_reader.getline()) { return false; }
  5021. }
  5022. return true;
  5023. }
  5024. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  5025. size_t right) {
  5026. while (b + left < e && is_space_or_tab(b[left])) {
  5027. left++;
  5028. }
  5029. while (right > 0 && is_space_or_tab(b[right - 1])) {
  5030. right--;
  5031. }
  5032. return std::make_pair(left, right);
  5033. }
  5034. inline std::string trim_copy(const std::string &s) {
  5035. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  5036. return s.substr(r.first, r.second - r.first);
  5037. }
  5038. inline std::string trim_double_quotes_copy(const std::string &s) {
  5039. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  5040. return s.substr(1, s.size() - 2);
  5041. }
  5042. return s;
  5043. }
  5044. inline void
  5045. divide(const char *data, std::size_t size, char d,
  5046. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  5047. fn) {
  5048. const auto it = std::find(data, data + size, d);
  5049. const auto found = static_cast<std::size_t>(it != data + size);
  5050. const auto lhs_data = data;
  5051. const auto lhs_size = static_cast<std::size_t>(it - data);
  5052. const auto rhs_data = it + found;
  5053. const auto rhs_size = size - lhs_size - found;
  5054. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  5055. }
  5056. inline void
  5057. divide(const std::string &str, char d,
  5058. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  5059. fn) {
  5060. divide(str.data(), str.size(), d, std::move(fn));
  5061. }
  5062. inline void split(const char *b, const char *e, char d,
  5063. std::function<void(const char *, const char *)> fn) {
  5064. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  5065. }
  5066. inline void split(const char *b, const char *e, char d, size_t m,
  5067. std::function<void(const char *, const char *)> fn) {
  5068. size_t i = 0;
  5069. size_t beg = 0;
  5070. size_t count = 1;
  5071. while (e ? (b + i < e) : (b[i] != '\0')) {
  5072. if (b[i] == d && count < m) {
  5073. auto r = trim(b, e, beg, i);
  5074. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5075. beg = i + 1;
  5076. count++;
  5077. }
  5078. i++;
  5079. }
  5080. if (i) {
  5081. auto r = trim(b, e, beg, i);
  5082. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5083. }
  5084. }
  5085. // Same contract as split(), except that a delimiter inside a quoted-string is
  5086. // not a delimiter. RFC 9110 Section 5.6.6 lets a parameter value be a
  5087. // quoted-string, and ';' and '=' are legal characters inside one.
  5088. inline void split_unquoted(const char *b, const char *e, char d, size_t m,
  5089. std::function<void(const char *, const char *)> fn) {
  5090. size_t i = 0;
  5091. size_t beg = 0;
  5092. size_t count = 1;
  5093. auto in_quotes = false;
  5094. while (e ? (b + i < e) : (b[i] != '\0')) {
  5095. if (b[i] == '"') {
  5096. in_quotes = !in_quotes;
  5097. } else if (b[i] == d && !in_quotes && count < m) {
  5098. auto r = trim(b, e, beg, i);
  5099. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5100. beg = i + 1;
  5101. count++;
  5102. }
  5103. i++;
  5104. }
  5105. if (i) {
  5106. auto r = trim(b, e, beg, i);
  5107. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5108. }
  5109. }
  5110. inline void split_unquoted(const char *b, const char *e, char d,
  5111. std::function<void(const char *, const char *)> fn) {
  5112. return split_unquoted(b, e, d, (std::numeric_limits<size_t>::max)(),
  5113. std::move(fn));
  5114. }
  5115. // Divide a header parameter at its first '='. RFC 9110 Section 5.6.6 makes the
  5116. // key a token, so the first '=' is the separator even when the value is a
  5117. // quoted-string carrying more of them.
  5118. inline void divide_param_pair(const char *b, const char *e, std::string &key,
  5119. std::string &val) {
  5120. divide(
  5121. b, static_cast<std::size_t>(e - b), '=',
  5122. [&](const char *kb, std::size_t klen, const char *vb, std::size_t vlen) {
  5123. const auto kr = trim(kb, kb + klen, 0, klen);
  5124. key.assign(kb + kr.first, kb + kr.second);
  5125. const auto vr = trim(vb, vb + vlen, 0, vlen);
  5126. val.assign(vb + vr.first, vb + vr.second);
  5127. });
  5128. }
  5129. inline bool split_find(const char *b, const char *e, char d, size_t m,
  5130. std::function<bool(const char *, const char *)> fn) {
  5131. size_t i = 0;
  5132. size_t beg = 0;
  5133. size_t count = 1;
  5134. while (e ? (b + i < e) : (b[i] != '\0')) {
  5135. if (b[i] == d && count < m) {
  5136. auto r = trim(b, e, beg, i);
  5137. if (r.first < r.second) {
  5138. auto found = fn(&b[r.first], &b[r.second]);
  5139. if (found) { return true; }
  5140. }
  5141. beg = i + 1;
  5142. count++;
  5143. }
  5144. i++;
  5145. }
  5146. if (i) {
  5147. auto r = trim(b, e, beg, i);
  5148. if (r.first < r.second) {
  5149. auto found = fn(&b[r.first], &b[r.second]);
  5150. if (found) { return true; }
  5151. }
  5152. }
  5153. return false;
  5154. }
  5155. inline bool split_find(const char *b, const char *e, char d,
  5156. std::function<bool(const char *, const char *)> fn) {
  5157. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  5158. std::move(fn));
  5159. }
  5160. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  5161. size_t fixed_buffer_size)
  5162. : strm_(strm), fixed_buffer_(fixed_buffer),
  5163. fixed_buffer_size_(fixed_buffer_size) {}
  5164. inline const char *stream_line_reader::ptr() const {
  5165. if (growable_buffer_.empty()) {
  5166. return fixed_buffer_;
  5167. } else {
  5168. return growable_buffer_.data();
  5169. }
  5170. }
  5171. inline size_t stream_line_reader::size() const {
  5172. if (growable_buffer_.empty()) {
  5173. return fixed_buffer_used_size_;
  5174. } else {
  5175. return growable_buffer_.size();
  5176. }
  5177. }
  5178. inline bool stream_line_reader::end_with_crlf() const {
  5179. auto end = ptr() + size();
  5180. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  5181. }
  5182. inline bool stream_line_reader::getline() {
  5183. fixed_buffer_used_size_ = 0;
  5184. growable_buffer_.clear();
  5185. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5186. char prev_byte = 0;
  5187. #endif
  5188. for (size_t i = 0;; i++) {
  5189. // Fast path: whatever the stream has already buffered can be scanned for
  5190. // the terminator in one pass. Asking for a byte at a time costs a virtual
  5191. // call, a bounds check and a one-byte copy per character of the request.
  5192. size_t buffered_size = 0;
  5193. if (auto buffered = strm_.buffered_data(buffered_size)) {
  5194. auto take = buffered_size;
  5195. auto terminated = false;
  5196. for (size_t at = 0; at < buffered_size;) {
  5197. auto nl = static_cast<const char *>(
  5198. memchr(buffered + at, '\n', buffered_size - at));
  5199. if (!nl) { break; }
  5200. auto pos = static_cast<size_t>(nl - buffered);
  5201. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5202. take = pos + 1;
  5203. terminated = true;
  5204. break;
  5205. #else
  5206. // A bare LF does not end the line; keep looking for CRLF. The CR may
  5207. // be the last byte of an earlier chunk, hence prev_byte.
  5208. if ((pos > 0 ? buffered[pos - 1] : prev_byte) == '\r') {
  5209. take = pos + 1;
  5210. terminated = true;
  5211. break;
  5212. }
  5213. at = pos + 1;
  5214. #endif
  5215. }
  5216. if (size() + take > CPPHTTPLIB_MAX_LINE_LENGTH) { return false; }
  5217. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5218. prev_byte = buffered[take - 1];
  5219. #endif
  5220. append(buffered, take);
  5221. strm_.consume_buffered(take);
  5222. i += take;
  5223. if (terminated) { return true; }
  5224. continue;
  5225. }
  5226. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  5227. // Treat exceptionally long lines as an error to
  5228. // prevent infinite loops/memory exhaustion
  5229. return false;
  5230. }
  5231. char byte;
  5232. auto n = strm_.read(&byte, 1);
  5233. if (n < 0) {
  5234. return false;
  5235. } else if (n == 0) {
  5236. if (i == 0) {
  5237. return false;
  5238. } else {
  5239. break;
  5240. }
  5241. }
  5242. append(byte);
  5243. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5244. if (byte == '\n') { break; }
  5245. #else
  5246. if (prev_byte == '\r' && byte == '\n') { break; }
  5247. prev_byte = byte;
  5248. #endif
  5249. }
  5250. return true;
  5251. }
  5252. inline void stream_line_reader::append(char c) { append(&c, 1); }
  5253. inline void stream_line_reader::append(const char *data, size_t size) {
  5254. // Once the line has outgrown the fixed buffer everything must keep going to
  5255. // the growable one, even if a later chunk would have fit. Without the
  5256. // emptiness check a short append after a long one would land in the fixed
  5257. // buffer, which ptr() and size() no longer look at, and be lost.
  5258. if (growable_buffer_.empty() &&
  5259. fixed_buffer_used_size_ + size < fixed_buffer_size_) {
  5260. memcpy(fixed_buffer_ + fixed_buffer_used_size_, data, size);
  5261. fixed_buffer_used_size_ += size;
  5262. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  5263. } else {
  5264. // Unlike the per-character overload, this can be the very first append of
  5265. // the line, so the fixed buffer may hold nothing and carry no terminator
  5266. // yet. assign() takes an explicit length and does not need one.
  5267. if (growable_buffer_.empty()) {
  5268. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  5269. }
  5270. growable_buffer_.append(data, size);
  5271. }
  5272. }
  5273. inline mmap::mmap(const char *path) { open(path); }
  5274. inline mmap::~mmap() { close(); }
  5275. inline bool mmap::open(const char *path) {
  5276. close();
  5277. #if defined(_WIN32)
  5278. auto wpath = u8string_to_wstring(path);
  5279. if (wpath.empty()) { return false; }
  5280. hFile_ =
  5281. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  5282. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  5283. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  5284. LARGE_INTEGER size{};
  5285. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  5286. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  5287. // See:
  5288. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  5289. if (static_cast<ULONGLONG>(size.QuadPart) >
  5290. (std::numeric_limits<decltype(size_)>::max)()) {
  5291. // `size_t` might be 32-bits, on 32-bits Windows.
  5292. return false;
  5293. }
  5294. size_ = static_cast<size_t>(size.QuadPart);
  5295. hMapping_ =
  5296. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  5297. // Special treatment for an empty file...
  5298. if (hMapping_ == NULL && size_ == 0) {
  5299. close();
  5300. is_open_empty_file = true;
  5301. return true;
  5302. }
  5303. if (hMapping_ == NULL) {
  5304. close();
  5305. return false;
  5306. }
  5307. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  5308. if (addr_ == nullptr) {
  5309. close();
  5310. return false;
  5311. }
  5312. #else
  5313. fd_ = ::open(path, O_RDONLY);
  5314. if (fd_ == -1) { return false; }
  5315. struct stat sb;
  5316. if (fstat(fd_, &sb) == -1) {
  5317. close();
  5318. return false;
  5319. }
  5320. size_ = static_cast<size_t>(sb.st_size);
  5321. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  5322. // Special treatment for an empty file...
  5323. if (addr_ == MAP_FAILED && size_ == 0) {
  5324. close();
  5325. is_open_empty_file = true;
  5326. return false;
  5327. }
  5328. if (addr_ == MAP_FAILED) {
  5329. // Clear the sentinel before `close()`, since `is_open()` only checks
  5330. // `addr_` against nullptr and `munmap()` must not be called with it.
  5331. addr_ = nullptr;
  5332. close();
  5333. return false;
  5334. }
  5335. #endif
  5336. return true;
  5337. }
  5338. inline bool mmap::is_open() const {
  5339. return is_open_empty_file ? true : addr_ != nullptr;
  5340. }
  5341. inline size_t mmap::size() const { return size_; }
  5342. inline const char *mmap::data() const {
  5343. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  5344. }
  5345. inline void mmap::close() {
  5346. #if defined(_WIN32)
  5347. if (addr_) {
  5348. ::UnmapViewOfFile(addr_);
  5349. addr_ = nullptr;
  5350. }
  5351. if (hMapping_) {
  5352. ::CloseHandle(hMapping_);
  5353. hMapping_ = NULL;
  5354. }
  5355. if (hFile_ != INVALID_HANDLE_VALUE) {
  5356. ::CloseHandle(hFile_);
  5357. hFile_ = INVALID_HANDLE_VALUE;
  5358. }
  5359. is_open_empty_file = false;
  5360. #else
  5361. if (addr_ != nullptr) {
  5362. munmap(addr_, size_);
  5363. addr_ = nullptr;
  5364. }
  5365. if (fd_ != -1) {
  5366. ::close(fd_);
  5367. fd_ = -1;
  5368. }
  5369. #endif
  5370. size_ = 0;
  5371. }
  5372. inline int close_socket(socket_t sock) noexcept {
  5373. #ifdef _WIN32
  5374. return closesocket(sock);
  5375. #else
  5376. return close(sock);
  5377. #endif
  5378. }
  5379. template <typename T> inline ssize_t handle_EINTR(T fn) {
  5380. ssize_t res = 0;
  5381. while (true) {
  5382. res = fn();
  5383. if (res < 0 && errno == EINTR) {
  5384. std::this_thread::sleep_for(std::chrono::microseconds{1});
  5385. continue;
  5386. }
  5387. break;
  5388. }
  5389. return res;
  5390. }
  5391. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  5392. return handle_EINTR([&]() {
  5393. return recv(sock,
  5394. #ifdef _WIN32
  5395. static_cast<char *>(ptr), static_cast<int>(size),
  5396. #else
  5397. ptr, size,
  5398. #endif
  5399. flags);
  5400. });
  5401. }
  5402. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  5403. int flags) {
  5404. return handle_EINTR([&]() {
  5405. return send(sock,
  5406. #ifdef _WIN32
  5407. static_cast<const char *>(ptr), static_cast<int>(size),
  5408. #else
  5409. ptr, size,
  5410. #endif
  5411. flags);
  5412. });
  5413. }
  5414. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  5415. #ifdef _WIN32
  5416. return ::WSAPoll(fds, nfds, timeout);
  5417. #else
  5418. return ::poll(fds, nfds, timeout);
  5419. #endif
  5420. }
  5421. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  5422. time_t usec) {
  5423. struct pollfd pfd;
  5424. pfd.fd = sock;
  5425. pfd.events = events;
  5426. pfd.revents = 0;
  5427. // A negative timeout waits forever, poll's own convention. 0 keeps meaning
  5428. // "return immediately", which callers here rely on to probe a socket.
  5429. auto timeout = sec < 0 ? -1 : static_cast<int>(sec * 1000 + usec / 1000);
  5430. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  5431. }
  5432. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  5433. return select_impl(sock, POLLIN, sec, usec);
  5434. }
  5435. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  5436. return select_impl(sock, POLLOUT, sec, usec);
  5437. }
  5438. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  5439. time_t usec) {
  5440. struct pollfd pfd_read;
  5441. pfd_read.fd = sock;
  5442. pfd_read.events = POLLIN | POLLOUT;
  5443. pfd_read.revents = 0;
  5444. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  5445. auto poll_res =
  5446. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  5447. if (poll_res == 0) { return Error::ConnectionTimeout; }
  5448. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  5449. auto error = 0;
  5450. socklen_t len = sizeof(error);
  5451. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  5452. reinterpret_cast<char *>(&error), &len);
  5453. auto successful = res >= 0 && !error;
  5454. return successful ? Error::Success : Error::Connection;
  5455. }
  5456. return Error::Connection;
  5457. }
  5458. inline bool is_socket_alive(socket_t sock) {
  5459. const auto val = detail::select_read(sock, 0, 0);
  5460. if (val == 0) {
  5461. return true;
  5462. } else if (val < 0 && errno == EBADF) {
  5463. return false;
  5464. }
  5465. char buf[1];
  5466. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  5467. }
  5468. class SocketStream final : public Stream {
  5469. public:
  5470. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5471. time_t write_timeout_sec, time_t write_timeout_usec,
  5472. time_t max_timeout_msec = 0,
  5473. std::chrono::time_point<std::chrono::steady_clock> start_time =
  5474. (std::chrono::steady_clock::time_point::min)());
  5475. ~SocketStream() override;
  5476. bool is_readable() const override;
  5477. bool wait_readable() const override;
  5478. bool wait_writable() const override;
  5479. bool is_peer_alive() const override;
  5480. ssize_t read(char *ptr, size_t size) override;
  5481. ssize_t write(const char *ptr, size_t size) override;
  5482. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  5483. void get_local_ip_and_port(std::string &ip, int &port) const override;
  5484. socket_t socket() const override;
  5485. time_t duration() const override;
  5486. void set_read_timeout(time_t sec, time_t usec = 0) override;
  5487. const char *buffered_data(size_t &size) const override;
  5488. void consume_buffered(size_t size) override;
  5489. // The caller has just seen this socket become readable. Lets the next read
  5490. // skip its own readiness wait, which would otherwise ask the kernel a
  5491. // question that was answered a moment ago. Consumed by that read.
  5492. void set_readable_hint() { readable_hint_ = true; }
  5493. private:
  5494. bool ensure_readable();
  5495. socket_t sock_;
  5496. // Atomic because ws::WebSocket::set_read_timeout() reaches this from another
  5497. // thread while a read is in flight -- that is the point of it, for a caller
  5498. // holding one connection and wanting control back to send on it.
  5499. std::atomic<time_t> read_timeout_sec_;
  5500. std::atomic<time_t> read_timeout_usec_;
  5501. time_t write_timeout_sec_;
  5502. time_t write_timeout_usec_;
  5503. time_t max_timeout_msec_;
  5504. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  5505. std::vector<char> read_buff_;
  5506. size_t read_buff_off_ = 0;
  5507. size_t read_buff_content_size_ = 0;
  5508. bool readable_hint_ = false;
  5509. static const size_t read_buff_size_ = 1024l * 4;
  5510. };
  5511. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5512. time_t keep_alive_timeout_sec) {
  5513. using namespace std::chrono;
  5514. const auto interval_usec =
  5515. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  5516. // Avoid expensive `steady_clock::now()` call for the first time
  5517. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  5518. const auto start = steady_clock::now() - microseconds{interval_usec};
  5519. const auto timeout = seconds{keep_alive_timeout_sec};
  5520. while (true) {
  5521. if (svr_sock == INVALID_SOCKET) {
  5522. break; // Server socket is closed
  5523. }
  5524. auto val = select_read(sock, 0, interval_usec);
  5525. if (val < 0) {
  5526. break; // Ssocket error
  5527. } else if (val == 0) {
  5528. if (steady_clock::now() - start > timeout) {
  5529. break; // Timeout
  5530. }
  5531. } else {
  5532. return true; // Ready for read
  5533. }
  5534. }
  5535. return false;
  5536. }
  5537. // `has_buffered_request` reports whether the connection's stream already holds
  5538. // bytes of the next request. A client may pipeline its requests (RFC 9112
  5539. // 9.3.2), so reading one request can pull the start of the next one into the
  5540. // stream's buffer; that request must be served without waiting for the socket
  5541. // to become readable again, since its bytes are no longer on the socket.
  5542. // `callback` is told whether keep_alive() has just seen the socket go readable.
  5543. template <typename P, typename T>
  5544. inline bool process_server_socket_core(const std::atomic<socket_t> &svr_sock,
  5545. socket_t sock,
  5546. size_t keep_alive_max_count,
  5547. time_t keep_alive_timeout_sec,
  5548. P has_buffered_request, T callback) {
  5549. assert(keep_alive_max_count > 0);
  5550. auto ret = false;
  5551. auto count = keep_alive_max_count;
  5552. while (count > 0) {
  5553. auto socket_readable = false;
  5554. if (!has_buffered_request()) {
  5555. if (!keep_alive(svr_sock, sock, keep_alive_timeout_sec)) { break; }
  5556. socket_readable = true;
  5557. }
  5558. auto close_connection = count == 1;
  5559. auto connection_closed = false;
  5560. ret = callback(socket_readable, close_connection, connection_closed);
  5561. if (!ret || connection_closed) { break; }
  5562. count--;
  5563. }
  5564. return ret;
  5565. }
  5566. template <typename T>
  5567. inline bool
  5568. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5569. size_t keep_alive_max_count,
  5570. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  5571. time_t read_timeout_usec, time_t write_timeout_sec,
  5572. time_t write_timeout_usec, T callback) {
  5573. // One stream per connection: its read buffer can already hold the start of
  5574. // the next, pipelined request.
  5575. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5576. write_timeout_sec, write_timeout_usec);
  5577. return process_server_socket_core(
  5578. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  5579. [&]() { return strm.is_readable(); },
  5580. [&](bool socket_readable, bool close_connection,
  5581. bool &connection_closed) {
  5582. if (socket_readable) { strm.set_readable_hint(); }
  5583. return callback(strm, close_connection, connection_closed);
  5584. });
  5585. }
  5586. inline bool process_client_socket(
  5587. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5588. time_t write_timeout_sec, time_t write_timeout_usec,
  5589. time_t max_timeout_msec,
  5590. std::chrono::time_point<std::chrono::steady_clock> start_time,
  5591. std::function<bool(Stream &)> callback) {
  5592. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5593. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  5594. start_time);
  5595. return callback(strm);
  5596. }
  5597. inline int shutdown_socket(socket_t sock) noexcept {
  5598. #ifdef _WIN32
  5599. return shutdown(sock, SD_BOTH);
  5600. #else
  5601. return shutdown(sock, SHUT_RDWR);
  5602. #endif
  5603. }
  5604. // Half-closes the write side and drains any in-flight/queued bytes before
  5605. // the final shutdown+close. Closing with unread data in the receive queue
  5606. // (or bytes arriving after the receive side is closed) makes the stack send
  5607. // an abortive RST instead of a graceful FIN, which can make the peer see the
  5608. // response as a failed read even though it was fully written.
  5609. inline void drain_and_close_socket(socket_t sock) noexcept {
  5610. #ifdef _WIN32
  5611. shutdown(sock, SD_SEND);
  5612. #else
  5613. shutdown(sock, SHUT_WR);
  5614. #endif
  5615. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5616. size_t total = 0;
  5617. const auto deadline = std::chrono::steady_clock::now() +
  5618. std::chrono::milliseconds(100); // bound #1
  5619. while (total < size_t(1024u * 1024u)) { // bound #2
  5620. const auto remaining =
  5621. std::chrono::duration_cast<std::chrono::microseconds>(
  5622. deadline - std::chrono::steady_clock::now())
  5623. .count();
  5624. if (remaining <= 0) { break; }
  5625. if (select_read(sock, 0, static_cast<time_t>(remaining)) <= 0) { break; }
  5626. const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  5627. if (n <= 0) { break; }
  5628. total += static_cast<size_t>(n);
  5629. }
  5630. shutdown_socket(sock);
  5631. close_socket(sock);
  5632. }
  5633. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  5634. if (s.size() > 1 && s[0] == '\0') {
  5635. auto ret = s;
  5636. ret[0] = '@';
  5637. return ret;
  5638. }
  5639. return s;
  5640. }
  5641. inline std::string
  5642. unescape_abstract_namespace_unix_domain(const std::string &s) {
  5643. if (s.size() > 1 && s[0] == '@') {
  5644. auto ret = s;
  5645. ret[0] = '\0';
  5646. return ret;
  5647. }
  5648. return s;
  5649. }
  5650. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  5651. const struct addrinfo *hints,
  5652. struct addrinfo **res, time_t timeout_sec) {
  5653. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  5654. if (timeout_sec <= 0) {
  5655. // No timeout specified, use standard getaddrinfo
  5656. return getaddrinfo(node, service, hints, res);
  5657. }
  5658. #ifdef _WIN32
  5659. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  5660. OVERLAPPED overlapped = {};
  5661. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  5662. if (!event) { return EAI_FAIL; }
  5663. overlapped.hEvent = event;
  5664. PADDRINFOEXW result_addrinfo = nullptr;
  5665. HANDLE cancel_handle = nullptr;
  5666. ADDRINFOEXW hints_ex = {};
  5667. if (hints) {
  5668. hints_ex.ai_flags = hints->ai_flags;
  5669. hints_ex.ai_family = hints->ai_family;
  5670. hints_ex.ai_socktype = hints->ai_socktype;
  5671. hints_ex.ai_protocol = hints->ai_protocol;
  5672. }
  5673. auto wnode = u8string_to_wstring(node);
  5674. auto wservice = u8string_to_wstring(service);
  5675. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  5676. hints ? &hints_ex : nullptr, &result_addrinfo,
  5677. nullptr, &overlapped, nullptr, &cancel_handle);
  5678. if (ret == WSA_IO_PENDING) {
  5679. auto wait_result =
  5680. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  5681. if (wait_result == WAIT_TIMEOUT) {
  5682. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  5683. ::CloseHandle(event);
  5684. return EAI_AGAIN;
  5685. }
  5686. DWORD bytes_returned;
  5687. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  5688. &bytes_returned, FALSE)) {
  5689. ::CloseHandle(event);
  5690. return ::WSAGetLastError();
  5691. }
  5692. }
  5693. ::CloseHandle(event);
  5694. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  5695. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  5696. return 0;
  5697. }
  5698. return ret;
  5699. #elif TARGET_OS_MAC && defined(__clang__)
  5700. if (!node) { return EAI_NONAME; }
  5701. // macOS implementation using CFHost API for asynchronous DNS resolution
  5702. CFStringRef hostname_ref = CFStringCreateWithCString(
  5703. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  5704. if (!hostname_ref) { return EAI_MEMORY; }
  5705. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  5706. CFRelease(hostname_ref);
  5707. if (!host_ref) { return EAI_MEMORY; }
  5708. // Set up context for callback
  5709. struct CFHostContext {
  5710. bool completed = false;
  5711. bool success = false;
  5712. CFArrayRef addresses = nullptr;
  5713. std::mutex mutex;
  5714. std::condition_variable cv;
  5715. } context;
  5716. CFHostClientContext client_context;
  5717. memset(&client_context, 0, sizeof(client_context));
  5718. client_context.info = &context;
  5719. // Set callback
  5720. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  5721. const CFStreamError *error, void *info) {
  5722. auto ctx = static_cast<CFHostContext *>(info);
  5723. std::lock_guard<std::mutex> lock(ctx->mutex);
  5724. if (error && error->error != 0) {
  5725. ctx->success = false;
  5726. } else {
  5727. Boolean hasBeenResolved;
  5728. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  5729. if (ctx->addresses && hasBeenResolved) {
  5730. CFRetain(ctx->addresses);
  5731. ctx->success = true;
  5732. } else {
  5733. ctx->success = false;
  5734. }
  5735. }
  5736. ctx->completed = true;
  5737. ctx->cv.notify_one();
  5738. };
  5739. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  5740. CFRelease(host_ref);
  5741. return EAI_SYSTEM;
  5742. }
  5743. // Schedule on run loop
  5744. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  5745. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5746. // Start resolution
  5747. CFStreamError stream_error;
  5748. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  5749. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5750. CFRelease(host_ref);
  5751. return EAI_FAIL;
  5752. }
  5753. // Wait for completion with timeout
  5754. auto timeout_time =
  5755. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  5756. bool timed_out = false;
  5757. {
  5758. std::unique_lock<std::mutex> lock(context.mutex);
  5759. while (!context.completed) {
  5760. auto now = std::chrono::steady_clock::now();
  5761. if (now >= timeout_time) {
  5762. timed_out = true;
  5763. break;
  5764. }
  5765. // Run the runloop for a short time
  5766. lock.unlock();
  5767. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  5768. lock.lock();
  5769. }
  5770. }
  5771. // Clean up
  5772. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5773. CFHostSetClient(host_ref, nullptr, nullptr);
  5774. if (timed_out || !context.completed) {
  5775. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  5776. CFRelease(host_ref);
  5777. return EAI_AGAIN;
  5778. }
  5779. if (!context.success || !context.addresses) {
  5780. CFRelease(host_ref);
  5781. return EAI_NODATA;
  5782. }
  5783. // Convert CFArray to addrinfo
  5784. CFIndex count = CFArrayGetCount(context.addresses);
  5785. if (count == 0) {
  5786. CFRelease(context.addresses);
  5787. CFRelease(host_ref);
  5788. return EAI_NODATA;
  5789. }
  5790. struct addrinfo *result_addrinfo = nullptr;
  5791. struct addrinfo **current = &result_addrinfo;
  5792. for (CFIndex i = 0; i < count; i++) {
  5793. CFDataRef addr_data =
  5794. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  5795. if (!addr_data) continue;
  5796. const struct sockaddr *sockaddr_ptr =
  5797. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  5798. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  5799. // Allocate addrinfo structure
  5800. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  5801. if (!*current) {
  5802. freeaddrinfo(result_addrinfo);
  5803. CFRelease(context.addresses);
  5804. CFRelease(host_ref);
  5805. return EAI_MEMORY;
  5806. }
  5807. memset(*current, 0, sizeof(struct addrinfo));
  5808. // Set up addrinfo fields
  5809. (*current)->ai_family = sockaddr_ptr->sa_family;
  5810. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  5811. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  5812. (*current)->ai_addrlen = sockaddr_len;
  5813. // Copy sockaddr
  5814. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  5815. if (!(*current)->ai_addr) {
  5816. freeaddrinfo(result_addrinfo);
  5817. CFRelease(context.addresses);
  5818. CFRelease(host_ref);
  5819. return EAI_MEMORY;
  5820. }
  5821. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  5822. // Set port if service is specified
  5823. if (service && *service) {
  5824. int port = 0;
  5825. if (parse_port(service, strlen(service), port)) {
  5826. if (sockaddr_ptr->sa_family == AF_INET) {
  5827. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5828. ->sin_port = htons(static_cast<uint16_t>(port));
  5829. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5830. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5831. ->sin6_port = htons(static_cast<uint16_t>(port));
  5832. }
  5833. }
  5834. }
  5835. current = &((*current)->ai_next);
  5836. }
  5837. CFRelease(context.addresses);
  5838. CFRelease(host_ref);
  5839. *res = result_addrinfo;
  5840. return 0;
  5841. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5842. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5843. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5844. // the resolver worker still references the stack-local gaicb. The cancel
  5845. // path therefore waits (gai_suspend with no timeout) for the worker to
  5846. // actually finish before letting the stack frame go. The trade-off is that
  5847. // a wedged DNS server can hold this thread for the system resolver timeout
  5848. // (~30s by default) past the caller's connection timeout.
  5849. struct gaicb request{};
  5850. struct gaicb *requests[1] = {&request};
  5851. struct sigevent sevp{};
  5852. struct timespec timeout{timeout_sec, 0};
  5853. request.ar_name = node;
  5854. request.ar_service = service;
  5855. request.ar_request = hints;
  5856. sevp.sigev_notify = SIGEV_NONE;
  5857. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5858. if (rc != 0) { return rc; }
  5859. auto cleanup = scope_exit([&] {
  5860. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5861. });
  5862. int wait_result = gai_suspend(requests, 1, &timeout);
  5863. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5864. int gai_result = gai_error(&request);
  5865. if (gai_result == 0) {
  5866. *res = request.ar_result;
  5867. request.ar_result = nullptr;
  5868. return 0;
  5869. }
  5870. return gai_result;
  5871. }
  5872. gai_cancel(&request);
  5873. while (gai_error(&request) == EAI_INPROGRESS) {
  5874. gai_suspend(requests, 1, nullptr);
  5875. }
  5876. return wait_result;
  5877. #else
  5878. // Fallback implementation using thread-based timeout for other Unix systems.
  5879. struct GetAddrInfoState {
  5880. ~GetAddrInfoState() {
  5881. if (info) { freeaddrinfo(info); }
  5882. }
  5883. std::mutex mutex;
  5884. std::condition_variable result_cv;
  5885. bool completed = false;
  5886. int result = EAI_SYSTEM;
  5887. std::string node;
  5888. std::string service;
  5889. struct addrinfo hints;
  5890. struct addrinfo *info = nullptr;
  5891. };
  5892. // Allocate on the heap, so the resolver thread can keep using the data.
  5893. auto state = std::make_shared<GetAddrInfoState>();
  5894. if (node) { state->node = node; }
  5895. state->service = service;
  5896. state->hints = *hints;
  5897. std::thread resolve_thread([state]() {
  5898. auto thread_result =
  5899. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5900. &state->info);
  5901. std::lock_guard<std::mutex> lock(state->mutex);
  5902. state->result = thread_result;
  5903. state->completed = true;
  5904. state->result_cv.notify_one();
  5905. });
  5906. // Wait for completion or timeout
  5907. std::unique_lock<std::mutex> lock(state->mutex);
  5908. auto finished =
  5909. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5910. [&] { return state->completed; });
  5911. if (finished) {
  5912. // Operation completed within timeout
  5913. resolve_thread.join();
  5914. *res = state->info;
  5915. state->info = nullptr; // Pass ownership to caller
  5916. return state->result;
  5917. } else {
  5918. // Timeout occurred
  5919. resolve_thread.detach(); // Let the thread finish in background
  5920. return EAI_AGAIN; // Return timeout error
  5921. }
  5922. #endif
  5923. #else
  5924. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5925. return getaddrinfo(node, service, hints, res);
  5926. #endif
  5927. }
  5928. template <typename BindOrConnect>
  5929. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5930. int address_family, int socket_flags, bool tcp_nodelay,
  5931. bool ipv6_v6only, SocketOptions socket_options,
  5932. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5933. // Get address info
  5934. const char *node = nullptr;
  5935. struct addrinfo hints;
  5936. struct addrinfo *result;
  5937. memset(&hints, 0, sizeof(struct addrinfo));
  5938. hints.ai_socktype = SOCK_STREAM;
  5939. hints.ai_protocol = IPPROTO_IP;
  5940. if (!ip.empty()) {
  5941. node = ip.c_str();
  5942. // Ask getaddrinfo to convert IP in c-string to address
  5943. hints.ai_family = AF_UNSPEC;
  5944. hints.ai_flags = AI_NUMERICHOST;
  5945. } else {
  5946. if (!host.empty()) { node = host.c_str(); }
  5947. hints.ai_family = address_family;
  5948. hints.ai_flags = socket_flags;
  5949. }
  5950. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5951. if (hints.ai_family == AF_UNIX) {
  5952. const auto addrlen = host.length();
  5953. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5954. #ifdef SOCK_CLOEXEC
  5955. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5956. hints.ai_protocol);
  5957. #else
  5958. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5959. #endif
  5960. if (sock != INVALID_SOCKET) {
  5961. sockaddr_un addr{};
  5962. addr.sun_family = AF_UNIX;
  5963. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5964. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5965. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5966. hints.ai_addrlen = static_cast<socklen_t>(
  5967. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5968. #ifndef SOCK_CLOEXEC
  5969. #ifndef _WIN32
  5970. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5971. #endif
  5972. #endif
  5973. if (socket_options) { socket_options(sock); }
  5974. #ifdef _WIN32
  5975. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5976. // remove the option.
  5977. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5978. #endif
  5979. bool dummy;
  5980. if (!bind_or_connect(sock, hints, dummy)) {
  5981. close_socket(sock);
  5982. sock = INVALID_SOCKET;
  5983. }
  5984. }
  5985. return sock;
  5986. }
  5987. #endif
  5988. auto service = std::to_string(port);
  5989. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5990. timeout_sec)) {
  5991. #if defined __linux__ && !defined __ANDROID__
  5992. res_init();
  5993. #endif
  5994. return INVALID_SOCKET;
  5995. }
  5996. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5997. for (auto rp = result; rp; rp = rp->ai_next) {
  5998. // Create a socket
  5999. #ifdef _WIN32
  6000. auto sock =
  6001. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  6002. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  6003. /**
  6004. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  6005. * and above the socket creation fails on older Windows Systems.
  6006. *
  6007. * Let's try to create a socket the old way in this case.
  6008. *
  6009. * Reference:
  6010. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  6011. *
  6012. * WSA_FLAG_NO_HANDLE_INHERIT:
  6013. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  6014. * SP1, and later
  6015. *
  6016. */
  6017. if (sock == INVALID_SOCKET) {
  6018. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  6019. }
  6020. #else
  6021. #ifdef SOCK_CLOEXEC
  6022. auto sock =
  6023. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  6024. #else
  6025. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  6026. #endif
  6027. #endif
  6028. if (sock == INVALID_SOCKET) { continue; }
  6029. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  6030. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  6031. close_socket(sock);
  6032. continue;
  6033. }
  6034. #endif
  6035. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  6036. if (rp->ai_family == AF_INET6) {
  6037. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  6038. }
  6039. if (socket_options) { socket_options(sock); }
  6040. // bind or connect
  6041. auto quit = false;
  6042. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  6043. close_socket(sock);
  6044. if (quit) { break; }
  6045. }
  6046. return INVALID_SOCKET;
  6047. }
  6048. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  6049. #ifdef _WIN32
  6050. auto flags = nonblocking ? 1UL : 0UL;
  6051. ioctlsocket(sock, FIONBIO, &flags);
  6052. #else
  6053. auto flags = fcntl(sock, F_GETFL, 0);
  6054. fcntl(sock, F_SETFL,
  6055. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  6056. #endif
  6057. }
  6058. inline bool is_connection_error() {
  6059. #ifdef _WIN32
  6060. return WSAGetLastError() != WSAEWOULDBLOCK;
  6061. #else
  6062. return errno != EINPROGRESS;
  6063. #endif
  6064. }
  6065. // accept() failed because the process or the network stack is temporarily out
  6066. // of resources. The listening socket is still usable, so back off briefly and
  6067. // try again.
  6068. inline bool is_accept_resource_error() {
  6069. #ifdef _WIN32
  6070. auto err = WSAGetLastError();
  6071. return err == WSAEMFILE || err == WSAENOBUFS;
  6072. #else
  6073. auto err = errno;
  6074. return err == EMFILE || err == ENFILE || err == ENOBUFS || err == ENOMEM;
  6075. #endif
  6076. }
  6077. // accept() failed for a reason that says nothing about the listening socket:
  6078. // the pending connection went away before it could be accepted, or the call
  6079. // was interrupted. Retry immediately. WSAAccept()'s own documentation omits
  6080. // WSAECONNRESET, but the accept() it wraps reports an aborted pending
  6081. // connection that way.
  6082. inline bool is_accept_transient_error() {
  6083. #ifdef _WIN32
  6084. auto err = WSAGetLastError();
  6085. return err == WSAEINTR || err == WSAEWOULDBLOCK || err == WSAECONNRESET ||
  6086. err == WSAECONNABORTED;
  6087. #else
  6088. auto err = errno;
  6089. return err == EINTR || err == EAGAIN || err == EWOULDBLOCK ||
  6090. err == ECONNABORTED;
  6091. #endif
  6092. }
  6093. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  6094. struct addrinfo hints;
  6095. struct addrinfo *result;
  6096. memset(&hints, 0, sizeof(struct addrinfo));
  6097. hints.ai_family = AF_UNSPEC;
  6098. hints.ai_socktype = SOCK_STREAM;
  6099. hints.ai_protocol = 0;
  6100. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  6101. return false;
  6102. }
  6103. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6104. auto ret = false;
  6105. for (auto rp = result; rp; rp = rp->ai_next) {
  6106. const auto &ai = *rp;
  6107. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6108. ret = true;
  6109. break;
  6110. }
  6111. }
  6112. return ret;
  6113. }
  6114. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  6115. #define USE_IF2IP
  6116. #endif
  6117. #ifdef USE_IF2IP
  6118. inline std::string if2ip(int address_family, const std::string &ifn) {
  6119. struct ifaddrs *ifap;
  6120. getifaddrs(&ifap);
  6121. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  6122. std::string addr_candidate;
  6123. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  6124. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  6125. (AF_UNSPEC == address_family ||
  6126. ifa->ifa_addr->sa_family == address_family)) {
  6127. if (ifa->ifa_addr->sa_family == AF_INET) {
  6128. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  6129. char buf[INET_ADDRSTRLEN];
  6130. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  6131. return std::string(buf, INET_ADDRSTRLEN);
  6132. }
  6133. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  6134. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  6135. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  6136. char buf[INET6_ADDRSTRLEN] = {};
  6137. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  6138. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  6139. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  6140. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  6141. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  6142. } else {
  6143. return std::string(buf, INET6_ADDRSTRLEN);
  6144. }
  6145. }
  6146. }
  6147. }
  6148. }
  6149. }
  6150. return addr_candidate;
  6151. }
  6152. #endif
  6153. inline socket_t create_client_socket(
  6154. const std::string &host, const std::string &ip, int port,
  6155. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  6156. SocketOptions socket_options, time_t connection_timeout_sec,
  6157. time_t connection_timeout_usec, time_t read_timeout_sec,
  6158. time_t read_timeout_usec, time_t write_timeout_sec,
  6159. time_t write_timeout_usec, const std::string &intf, Error &error) {
  6160. auto sock = create_socket(
  6161. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  6162. std::move(socket_options),
  6163. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  6164. if (!intf.empty()) {
  6165. #ifdef USE_IF2IP
  6166. auto ip_from_if = if2ip(address_family, intf);
  6167. if (ip_from_if.empty()) { ip_from_if = intf; }
  6168. if (!bind_ip_address(sock2, ip_from_if)) {
  6169. error = Error::BindIPAddress;
  6170. return false;
  6171. }
  6172. #endif
  6173. }
  6174. set_nonblocking(sock2, true);
  6175. auto ret =
  6176. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  6177. if (ret < 0) {
  6178. if (is_connection_error()) {
  6179. error = Error::Connection;
  6180. return false;
  6181. }
  6182. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  6183. connection_timeout_usec);
  6184. if (error != Error::Success) {
  6185. if (error == Error::ConnectionTimeout) { quit = true; }
  6186. return false;
  6187. }
  6188. }
  6189. set_nonblocking(sock2, false);
  6190. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  6191. read_timeout_usec);
  6192. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  6193. write_timeout_usec);
  6194. error = Error::Success;
  6195. return true;
  6196. },
  6197. connection_timeout_sec); // Pass DNS timeout
  6198. if (sock != INVALID_SOCKET) {
  6199. error = Error::Success;
  6200. } else {
  6201. if (error == Error::Success) { error = Error::Connection; }
  6202. }
  6203. return sock;
  6204. }
  6205. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  6206. socklen_t addr_len, std::string &ip, int &port) {
  6207. if (addr.ss_family == AF_INET) {
  6208. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  6209. } else if (addr.ss_family == AF_INET6) {
  6210. port =
  6211. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  6212. } else {
  6213. return false;
  6214. }
  6215. std::array<char, NI_MAXHOST> ipstr{};
  6216. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  6217. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  6218. 0, NI_NUMERICHOST)) {
  6219. return false;
  6220. }
  6221. ip = ipstr.data();
  6222. return true;
  6223. }
  6224. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  6225. struct sockaddr_storage addr;
  6226. socklen_t addr_len = sizeof(addr);
  6227. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  6228. &addr_len)) {
  6229. get_ip_and_port(addr, addr_len, ip, port);
  6230. }
  6231. }
  6232. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  6233. struct sockaddr_storage addr;
  6234. socklen_t addr_len = sizeof(addr);
  6235. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  6236. &addr_len)) {
  6237. #ifndef _WIN32
  6238. if (addr.ss_family == AF_UNIX) {
  6239. #if defined(__linux__)
  6240. struct ucred ucred;
  6241. socklen_t len = sizeof(ucred);
  6242. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  6243. port = ucred.pid;
  6244. }
  6245. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  6246. pid_t pid;
  6247. socklen_t len = sizeof(pid);
  6248. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  6249. port = pid;
  6250. }
  6251. #endif
  6252. return;
  6253. }
  6254. #endif
  6255. get_ip_and_port(addr, addr_len, ip, port);
  6256. }
  6257. }
  6258. // Recursive form retained so operator""_t below can compute hashes for
  6259. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  6260. // call from runtime paths with arbitrary-length inputs — use str2tag()
  6261. // instead, which is iterative and stack-safe.
  6262. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  6263. unsigned int h) {
  6264. return (l == 0)
  6265. ? h
  6266. : str2tag_core(
  6267. s + 1, l - 1,
  6268. // Unsets the 6 high bits of h, therefore no overflow happens
  6269. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  6270. h * 33) ^
  6271. static_cast<unsigned char>(*s));
  6272. }
  6273. inline unsigned int str2tag(const std::string &s) {
  6274. // Iterative form of str2tag_core: the recursive constexpr version is kept
  6275. // for compile-time UDL evaluation of short string literals, but at runtime
  6276. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  6277. // would blow the stack with one frame per character.
  6278. unsigned int h = 0;
  6279. for (auto c : s) {
  6280. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  6281. static_cast<unsigned char>(c);
  6282. }
  6283. return h;
  6284. }
  6285. namespace udl {
  6286. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  6287. return str2tag_core(s, l, 0);
  6288. }
  6289. } // namespace udl
  6290. inline std::string
  6291. find_content_type(const std::string &path,
  6292. const std::map<std::string, std::string> &user_data,
  6293. const std::string &default_content_type) {
  6294. auto ext = file_extension(path);
  6295. auto it = user_data.find(ext);
  6296. if (it != user_data.end()) { return it->second; }
  6297. using udl::operator""_t;
  6298. switch (str2tag(ext)) {
  6299. default: return default_content_type;
  6300. case "css"_t: return "text/css";
  6301. case "csv"_t: return "text/csv";
  6302. case "htm"_t:
  6303. case "html"_t: return "text/html";
  6304. case "js"_t:
  6305. case "mjs"_t: return "text/javascript";
  6306. case "txt"_t: return "text/plain";
  6307. case "vtt"_t: return "text/vtt";
  6308. case "apng"_t: return "image/apng";
  6309. case "avif"_t: return "image/avif";
  6310. case "bmp"_t: return "image/bmp";
  6311. case "gif"_t: return "image/gif";
  6312. case "png"_t: return "image/png";
  6313. case "svg"_t: return "image/svg+xml";
  6314. case "webp"_t: return "image/webp";
  6315. case "ico"_t: return "image/x-icon";
  6316. case "tif"_t: return "image/tiff";
  6317. case "tiff"_t: return "image/tiff";
  6318. case "jpg"_t:
  6319. case "jpeg"_t: return "image/jpeg";
  6320. case "mp4"_t: return "video/mp4";
  6321. case "mpeg"_t: return "video/mpeg";
  6322. case "webm"_t: return "video/webm";
  6323. case "mp3"_t: return "audio/mp3";
  6324. case "mpga"_t: return "audio/mpeg";
  6325. case "weba"_t: return "audio/webm";
  6326. case "wav"_t: return "audio/wave";
  6327. case "otf"_t: return "font/otf";
  6328. case "ttf"_t: return "font/ttf";
  6329. case "woff"_t: return "font/woff";
  6330. case "woff2"_t: return "font/woff2";
  6331. case "7z"_t: return "application/x-7z-compressed";
  6332. case "atom"_t: return "application/atom+xml";
  6333. case "pdf"_t: return "application/pdf";
  6334. case "json"_t: return "application/json";
  6335. case "rss"_t: return "application/rss+xml";
  6336. case "tar"_t: return "application/x-tar";
  6337. case "xht"_t:
  6338. case "xhtml"_t: return "application/xhtml+xml";
  6339. case "xslt"_t: return "application/xslt+xml";
  6340. case "xml"_t: return "application/xml";
  6341. case "gz"_t: return "application/gzip";
  6342. case "zip"_t: return "application/zip";
  6343. case "wasm"_t: return "application/wasm";
  6344. }
  6345. }
  6346. inline std::string
  6347. extract_media_type(const std::string &content_type,
  6348. std::map<std::string, std::string> *params = nullptr) {
  6349. // Extract type/subtype from Content-Type value (RFC 2045)
  6350. // e.g. "application/json; charset=utf-8" -> "application/json"
  6351. auto media_type = content_type;
  6352. auto semicolon_pos = media_type.find(';');
  6353. if (semicolon_pos != std::string::npos) {
  6354. auto param_str = media_type.substr(semicolon_pos + 1);
  6355. media_type = media_type.substr(0, semicolon_pos);
  6356. if (params) {
  6357. // Parse parameters: key=value pairs separated by ';'
  6358. split_unquoted(param_str.data(), param_str.data() + param_str.size(), ';',
  6359. [&](const char *b, const char *e) {
  6360. std::string key;
  6361. std::string val;
  6362. divide_param_pair(b, e, key, val);
  6363. if (!key.empty()) {
  6364. params->emplace(trim_copy(key),
  6365. trim_double_quotes_copy(val));
  6366. }
  6367. });
  6368. }
  6369. }
  6370. // Trim whitespace from media type
  6371. return trim_copy(media_type);
  6372. }
  6373. inline bool can_compress_content_type(const std::string &content_type) {
  6374. using udl::operator""_t;
  6375. auto mime_type = extract_media_type(content_type);
  6376. auto tag = str2tag(mime_type);
  6377. switch (tag) {
  6378. case "image/svg+xml"_t:
  6379. case "application/javascript"_t:
  6380. case "application/x-javascript"_t:
  6381. case "application/json"_t:
  6382. case "application/ld+json"_t:
  6383. case "application/xml"_t:
  6384. case "application/xhtml+xml"_t:
  6385. case "application/rss+xml"_t:
  6386. case "application/atom+xml"_t:
  6387. case "application/xslt+xml"_t:
  6388. case "application/protobuf"_t: return true;
  6389. case "text/event-stream"_t: return false;
  6390. default: return !mime_type.rfind("text/", 0);
  6391. }
  6392. }
  6393. inline bool parse_quality(const char *b, const char *e, std::string &token,
  6394. double &quality) {
  6395. quality = 1.0;
  6396. token.clear();
  6397. // Split on first ';': left = token name, right = parameters
  6398. const char *params_b = nullptr;
  6399. std::size_t params_len = 0;
  6400. divide(
  6401. b, static_cast<std::size_t>(e - b), ';',
  6402. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  6403. auto r = trim(lb, lb + llen, 0, llen);
  6404. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  6405. params_b = rb;
  6406. params_len = rlen;
  6407. });
  6408. if (token.empty()) { return false; }
  6409. if (params_len == 0) { return true; }
  6410. // Scan parameters for q= (stops on first match)
  6411. bool invalid = false;
  6412. split_find(params_b, params_b + params_len, ';',
  6413. (std::numeric_limits<size_t>::max)(),
  6414. [&](const char *pb, const char *pe) -> bool {
  6415. // Match exactly "q=" or "Q=" (not "query=" etc.)
  6416. auto len = static_cast<size_t>(pe - pb);
  6417. if (len < 2) { return false; }
  6418. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  6419. return false;
  6420. }
  6421. // Trim the value portion
  6422. auto r = trim(pb, pe, 2, len);
  6423. if (r.first >= r.second) {
  6424. invalid = true;
  6425. return true;
  6426. }
  6427. double v = 0.0;
  6428. auto res = from_chars(pb + r.first, pb + r.second, v);
  6429. if (res.ec != std::errc{} || res.ptr != pb + r.second ||
  6430. v < 0.0 || v > 1.0) {
  6431. invalid = true;
  6432. return true;
  6433. }
  6434. quality = v;
  6435. return true;
  6436. });
  6437. return !invalid;
  6438. }
  6439. inline EncodingType encoding_type(const Request &req,
  6440. const std::string &content_type) {
  6441. if (!can_compress_content_type(content_type)) { return EncodingType::None; }
  6442. auto s = get_combined_header_value(req.headers, "Accept-Encoding");
  6443. if (s.empty()) { return EncodingType::None; }
  6444. // Single-pass: iterate tokens and track the best supported encoding.
  6445. // Server preference breaks ties (br > gzip > zstd).
  6446. EncodingType best = EncodingType::None;
  6447. double best_q = 0.0; // q=0 means "not acceptable"
  6448. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  6449. auto priority = [](EncodingType t) -> int {
  6450. switch (t) {
  6451. case EncodingType::Brotli: return 0;
  6452. case EncodingType::Gzip: return 1;
  6453. case EncodingType::Zstd: return 2;
  6454. default: return 3;
  6455. }
  6456. };
  6457. std::string name;
  6458. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6459. double quality = 1.0;
  6460. if (!parse_quality(b, e, name, quality)) { return; }
  6461. if (quality <= 0.0) { return; }
  6462. EncodingType type = EncodingType::None;
  6463. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6464. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  6465. #endif
  6466. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6467. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  6468. type = EncodingType::Gzip;
  6469. }
  6470. #endif
  6471. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6472. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  6473. type = EncodingType::Zstd;
  6474. }
  6475. #endif
  6476. if (type == EncodingType::None) { return; }
  6477. // Higher q-value wins; for equal q, server preference breaks ties
  6478. if (quality > best_q ||
  6479. (quality == best_q && priority(type) < priority(best))) {
  6480. best_q = quality;
  6481. best = type;
  6482. }
  6483. });
  6484. return best;
  6485. }
  6486. // `content_type` is taken separately because a file-backed response has not
  6487. // been given one yet when its coding has to be decided.
  6488. inline EncodingType encoding_type(const Request &req, const Response &res,
  6489. const std::string &content_type) {
  6490. // The response already names a content coding of its own: a handler serving
  6491. // a body it encoded itself (pre-compressed static assets, say), or a mount
  6492. // point whose headers name the coding its files are stored in. Applying one
  6493. // on top of that would double-encode the body and append a second
  6494. // `Content-Encoding` field line.
  6495. if (res.has_header("Content-Encoding")) { return EncodingType::None; }
  6496. return encoding_type(req, content_type);
  6497. }
  6498. inline EncodingType encoding_type(const Request &req, const Response &res) {
  6499. return encoding_type(req, res, res.get_header_value("Content-Type"));
  6500. }
  6501. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  6502. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6503. if (type == EncodingType::Gzip) {
  6504. return detail::make_unique<gzip_compressor>();
  6505. }
  6506. #endif
  6507. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6508. if (type == EncodingType::Brotli) {
  6509. return detail::make_unique<brotli_compressor>();
  6510. }
  6511. #endif
  6512. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6513. if (type == EncodingType::Zstd) {
  6514. return detail::make_unique<zstd_compressor>();
  6515. }
  6516. #endif
  6517. (void)type;
  6518. return nullptr;
  6519. }
  6520. inline const char *encoding_name(EncodingType type) {
  6521. switch (type) {
  6522. case EncodingType::Gzip: return "gzip";
  6523. case EncodingType::Brotli: return "br";
  6524. case EncodingType::Zstd: return "zstd";
  6525. default: return "";
  6526. }
  6527. }
  6528. inline bool nocompressor::compress(const char *data, size_t data_length,
  6529. bool /*last*/, Callback callback) {
  6530. if (!data_length) { return true; }
  6531. return callback(data, data_length);
  6532. }
  6533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6534. inline gzip_compressor::gzip_compressor() {
  6535. std::memset(&strm_, 0, sizeof(strm_));
  6536. strm_.zalloc = Z_NULL;
  6537. strm_.zfree = Z_NULL;
  6538. strm_.opaque = Z_NULL;
  6539. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  6540. Z_DEFAULT_STRATEGY) == Z_OK;
  6541. }
  6542. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  6543. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  6544. bool last, Callback callback) {
  6545. assert(is_valid_);
  6546. do {
  6547. constexpr size_t max_avail_in =
  6548. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6549. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6550. (std::min)(data_length, max_avail_in));
  6551. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6552. data_length -= strm_.avail_in;
  6553. data += strm_.avail_in;
  6554. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  6555. auto ret = Z_OK;
  6556. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6557. do {
  6558. strm_.avail_out = static_cast<uInt>(buff.size());
  6559. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6560. ret = deflate(&strm_, flush);
  6561. if (ret == Z_STREAM_ERROR) { return false; }
  6562. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6563. return false;
  6564. }
  6565. } while (strm_.avail_out == 0);
  6566. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  6567. (flush == Z_NO_FLUSH && ret == Z_OK));
  6568. assert(strm_.avail_in == 0);
  6569. } while (data_length > 0);
  6570. return true;
  6571. }
  6572. inline gzip_decompressor::gzip_decompressor() {
  6573. std::memset(&strm_, 0, sizeof(strm_));
  6574. strm_.zalloc = Z_NULL;
  6575. strm_.zfree = Z_NULL;
  6576. strm_.opaque = Z_NULL;
  6577. // 15 is the value of wbits, which should be at the maximum possible value
  6578. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  6579. // that the stream type should be automatically detected either gzip or
  6580. // deflate.
  6581. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  6582. }
  6583. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  6584. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  6585. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  6586. Callback callback) {
  6587. assert(is_valid_);
  6588. auto ret = Z_OK;
  6589. do {
  6590. constexpr size_t max_avail_in =
  6591. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6592. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6593. (std::min)(data_length, max_avail_in));
  6594. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6595. data_length -= strm_.avail_in;
  6596. data += strm_.avail_in;
  6597. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6598. while (strm_.avail_in > 0 && ret == Z_OK) {
  6599. strm_.avail_out = static_cast<uInt>(buff.size());
  6600. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6601. ret = inflate(&strm_, Z_NO_FLUSH);
  6602. assert(ret != Z_STREAM_ERROR);
  6603. switch (ret) {
  6604. case Z_NEED_DICT:
  6605. case Z_DATA_ERROR:
  6606. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  6607. }
  6608. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6609. return false;
  6610. }
  6611. }
  6612. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  6613. } while (data_length > 0);
  6614. return true;
  6615. }
  6616. #endif
  6617. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6618. inline brotli_compressor::brotli_compressor() {
  6619. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  6620. }
  6621. inline brotli_compressor::~brotli_compressor() {
  6622. BrotliEncoderDestroyInstance(state_);
  6623. }
  6624. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  6625. bool last, Callback callback) {
  6626. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6627. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  6628. auto available_in = data_length;
  6629. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6630. for (;;) {
  6631. if (last) {
  6632. if (BrotliEncoderIsFinished(state_)) { break; }
  6633. } else {
  6634. if (!available_in) { break; }
  6635. }
  6636. auto available_out = buff.size();
  6637. auto next_out = buff.data();
  6638. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  6639. &available_out, &next_out, nullptr)) {
  6640. return false;
  6641. }
  6642. auto output_bytes = buff.size() - available_out;
  6643. if (output_bytes) {
  6644. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  6645. }
  6646. }
  6647. return true;
  6648. }
  6649. inline brotli_decompressor::brotli_decompressor() {
  6650. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  6651. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  6652. : BROTLI_DECODER_RESULT_ERROR;
  6653. }
  6654. inline brotli_decompressor::~brotli_decompressor() {
  6655. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  6656. }
  6657. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  6658. inline bool brotli_decompressor::decompress(const char *data,
  6659. size_t data_length,
  6660. Callback callback) {
  6661. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6662. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  6663. return 0;
  6664. }
  6665. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6666. size_t avail_in = data_length;
  6667. size_t total_out;
  6668. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  6669. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6670. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  6671. char *next_out = buff.data();
  6672. size_t avail_out = buff.size();
  6673. decoder_r = BrotliDecoderDecompressStream(
  6674. decoder_s, &avail_in, &next_in, &avail_out,
  6675. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  6676. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  6677. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  6678. }
  6679. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6680. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  6681. }
  6682. #endif
  6683. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6684. inline zstd_compressor::zstd_compressor() {
  6685. ctx_ = ZSTD_createCCtx();
  6686. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  6687. }
  6688. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  6689. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  6690. bool last, Callback callback) {
  6691. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6692. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  6693. ZSTD_inBuffer input = {data, data_length, 0};
  6694. bool finished;
  6695. do {
  6696. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6697. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  6698. if (ZSTD_isError(remaining)) { return false; }
  6699. if (!callback(buff.data(), output.pos)) { return false; }
  6700. finished = last ? (remaining == 0) : (input.pos == input.size);
  6701. } while (!finished);
  6702. return true;
  6703. }
  6704. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  6705. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  6706. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  6707. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  6708. Callback callback) {
  6709. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6710. ZSTD_inBuffer input = {data, data_length, 0};
  6711. while (input.pos < input.size) {
  6712. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6713. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  6714. if (ZSTD_isError(remaining)) { return false; }
  6715. if (!callback(buff.data(), output.pos)) { return false; }
  6716. }
  6717. return true;
  6718. }
  6719. #endif
  6720. // Content codings are case-insensitive (RFC 9110 8.4.1). Matching them
  6721. // case-sensitively would make a response labeled e.g. "GZIP" look like an
  6722. // unknown coding, and its payload would be handed back still compressed.
  6723. inline bool is_zlib_encoding(const std::string &encoding) {
  6724. return case_ignore::equal(encoding, "gzip") ||
  6725. case_ignore::equal(encoding, "deflate");
  6726. }
  6727. inline bool is_brotli_encoding(const std::string &encoding) {
  6728. return case_ignore::equal(encoding, "br");
  6729. }
  6730. inline bool is_zstd_encoding(const std::string &encoding) {
  6731. return case_ignore::equal(encoding, "zstd");
  6732. }
  6733. // Returns true if the content coding is one cpp-httplib is able to decompress
  6734. // when the corresponding support is compiled in.
  6735. inline bool is_known_content_encoding(const std::string &encoding) {
  6736. return is_zlib_encoding(encoding) || is_brotli_encoding(encoding) ||
  6737. is_zstd_encoding(encoding);
  6738. }
  6739. inline std::unique_ptr<decompressor>
  6740. create_decompressor(const std::string &encoding) {
  6741. std::unique_ptr<decompressor> decompressor;
  6742. if (is_zlib_encoding(encoding)) {
  6743. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6744. decompressor = detail::make_unique<gzip_decompressor>();
  6745. #endif
  6746. } else if (is_brotli_encoding(encoding)) {
  6747. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6748. decompressor = detail::make_unique<brotli_decompressor>();
  6749. #endif
  6750. } else if (is_zstd_encoding(encoding)) {
  6751. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6752. decompressor = detail::make_unique<zstd_decompressor>();
  6753. #endif
  6754. }
  6755. return decompressor;
  6756. }
  6757. // Returns the best available compressor and its Content-Encoding name.
  6758. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  6759. inline std::pair<std::unique_ptr<compressor>, const char *>
  6760. create_compressor() {
  6761. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6762. return {detail::make_unique<brotli_compressor>(), "br"};
  6763. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6764. return {detail::make_unique<gzip_compressor>(), "gzip"};
  6765. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6766. return {detail::make_unique<zstd_compressor>(), "zstd"};
  6767. #else
  6768. return {nullptr, nullptr};
  6769. #endif
  6770. }
  6771. inline bool is_prohibited_header_name(const std::string &name) {
  6772. using udl::operator""_t;
  6773. switch (str2tag(name)) {
  6774. case "REMOTE_ADDR"_t:
  6775. case "REMOTE_PORT"_t:
  6776. case "LOCAL_ADDR"_t:
  6777. case "LOCAL_PORT"_t: return true;
  6778. default: return false;
  6779. }
  6780. }
  6781. inline bool has_header(const Headers &headers, const std::string &key) {
  6782. if (is_prohibited_header_name(key)) { return false; }
  6783. return headers.find(key) != headers.end();
  6784. }
  6785. inline const char *get_header_value(const Headers &headers,
  6786. const std::string &key, const char *def,
  6787. size_t id) {
  6788. if (is_prohibited_header_name(key)) {
  6789. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6790. std::string msg = "Prohibited header name '" + key + "' is specified.";
  6791. throw std::invalid_argument(msg);
  6792. #else
  6793. return "";
  6794. #endif
  6795. }
  6796. auto rng = headers.equal_range(key);
  6797. auto it = bounded_next(rng.first, id, rng.second);
  6798. if (it != rng.second) { return it->second.c_str(); }
  6799. return def;
  6800. }
  6801. inline size_t get_header_value_count(const Headers &headers,
  6802. const std::string &key) {
  6803. return headers.count(key);
  6804. }
  6805. // RFC 9110 Section 5.2 and 5.3: a field that is defined as a comma-separated
  6806. // list may be sent as several field lines, and the combined field value is
  6807. // those values joined by commas in the order they were received. Callers that
  6808. // parse such a list must work on the combined value; reading only the first
  6809. // occurrence silently drops whatever the later field lines carry.
  6810. inline std::string get_combined_header_value(const Headers &headers,
  6811. const std::string &key) {
  6812. std::string combined;
  6813. auto rng = headers.equal_range(key);
  6814. for (auto it = rng.first; it != rng.second; ++it) {
  6815. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  6816. // elements, so an empty field line must not contribute a bare comma to the
  6817. // combined value.
  6818. if (it->second.empty()) { continue; }
  6819. if (!combined.empty()) { combined += ", "; }
  6820. combined += it->second;
  6821. }
  6822. return combined;
  6823. }
  6824. inline bool has_header_token(const Headers &headers, const std::string &key,
  6825. const std::string &token) {
  6826. // RFC 9110 7.6.1: a comma-separated token list field such as Connection may
  6827. // carry several tokens, and RFC 9110 5.3 lets that list be split across
  6828. // several lines. Match complete tokens rather than searching the raw value,
  6829. // so that a value such as "notupgrade" is not read as the token "upgrade".
  6830. auto rng = headers.equal_range(key);
  6831. for (auto it = rng.first; it != rng.second; ++it) {
  6832. const auto &value = it->second;
  6833. if (split_find(value.data(), value.data() + value.size(), ',',
  6834. [&](const char *b, const char *e) {
  6835. return case_ignore::equal(std::string(b, e), token);
  6836. })) {
  6837. return true;
  6838. }
  6839. }
  6840. return false;
  6841. }
  6842. template <typename Map>
  6843. inline typename Map::mapped_type
  6844. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  6845. auto rng = m.equal_range(key);
  6846. auto it = bounded_next(rng.first, id, rng.second);
  6847. if (it != rng.second) { return it->second; }
  6848. return typename Map::mapped_type();
  6849. }
  6850. inline void set_header(Headers &headers, const std::string &key,
  6851. const std::string &val) {
  6852. if (fields::is_field_valid(key, val)) { headers.emplace(key, val); }
  6853. }
  6854. inline bool read_headers(Stream &strm, Headers &headers) {
  6855. const auto bufsiz = 2048;
  6856. char buf[bufsiz];
  6857. stream_line_reader line_reader(strm, buf, bufsiz);
  6858. size_t header_count = 0;
  6859. for (;;) {
  6860. if (!line_reader.getline()) { return false; }
  6861. // Check if the line ends with CRLF.
  6862. auto line_terminator_len = 2;
  6863. if (line_reader.end_with_crlf()) {
  6864. // Blank line indicates end of headers.
  6865. if (line_reader.size() == 2) { break; }
  6866. } else {
  6867. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6868. // Blank line indicates end of headers.
  6869. if (line_reader.size() == 1) { break; }
  6870. line_terminator_len = 1;
  6871. #else
  6872. continue; // Skip invalid line.
  6873. #endif
  6874. }
  6875. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6876. // Check header count limit
  6877. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  6878. // Exclude line terminator
  6879. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  6880. if (!parse_header(line_reader.ptr(), end,
  6881. [&](const std::string &key, const std::string &val) {
  6882. headers.emplace(key, val);
  6883. })) {
  6884. return false;
  6885. }
  6886. header_count++;
  6887. }
  6888. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  6889. // headers that have different values to prevent request smuggling.
  6890. auto cl_range = headers.equal_range("Content-Length");
  6891. if (cl_range.first != cl_range.second) {
  6892. const auto &first_val = cl_range.first->second;
  6893. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  6894. if (it->second != first_val) { return false; }
  6895. }
  6896. }
  6897. return true;
  6898. }
  6899. inline bool parse_status_line(const char *line, std::string &version,
  6900. int &status, std::string &reason) {
  6901. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6902. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  6903. #else
  6904. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  6905. #endif
  6906. std::cmatch m;
  6907. if (!std::regex_match(line, m, re)) { return false; }
  6908. version = std::string(m[1]);
  6909. status = std::stoi(std::string(m[2]));
  6910. reason = std::string(m[3]);
  6911. return true;
  6912. }
  6913. // Everything WebSocketClient::connect() reports about the upgrade exchange.
  6914. // status stays -1 until a status line is parsed, mirroring stream::Result.
  6915. struct WebSocketUpgradeResponse {
  6916. Error error = Error::Success;
  6917. int status = -1;
  6918. Headers headers;
  6919. std::string selected_subprotocol;
  6920. };
  6921. inline bool
  6922. read_websocket_upgrade_response(Stream &strm,
  6923. const std::string &expected_accept,
  6924. const std::string &offered_subprotocols,
  6925. WebSocketUpgradeResponse &upgrade) {
  6926. // Read status line
  6927. const auto bufsiz = 2048;
  6928. char buf[bufsiz];
  6929. stream_line_reader line_reader(strm, buf, bufsiz);
  6930. if (!line_reader.getline()) {
  6931. upgrade.error = Error::Read;
  6932. return false;
  6933. }
  6934. std::string version;
  6935. std::string reason;
  6936. if (!parse_status_line(line_reader.ptr(), version, upgrade.status, reason)) {
  6937. upgrade.error = Error::WebSocketHandshake;
  6938. return false;
  6939. }
  6940. // Read the headers even for a rejection so the caller can see why the
  6941. // server refused the upgrade. A non-101 response may carry a body; it is
  6942. // deliberately left unread since the caller closes the socket right away.
  6943. if (!read_headers(strm, upgrade.headers)) {
  6944. upgrade.error = Error::Read;
  6945. return false;
  6946. }
  6947. const auto &headers = upgrade.headers;
  6948. if (upgrade.status != StatusCode::SwitchingProtocol_101) {
  6949. upgrade.error = Error::WebSocketHandshake;
  6950. return false;
  6951. }
  6952. // Verify Upgrade: websocket (a comma-separated list, matched per token)
  6953. if (!has_header_token(headers, "Upgrade", "websocket")) {
  6954. upgrade.error = Error::WebSocketHandshake;
  6955. return false;
  6956. }
  6957. // Verify Connection: Upgrade
  6958. if (!has_header_token(headers, "Connection", "upgrade")) {
  6959. upgrade.error = Error::WebSocketHandshake;
  6960. return false;
  6961. }
  6962. // Verify Sec-WebSocket-Accept header value
  6963. auto it = headers.find("Sec-WebSocket-Accept");
  6964. if (it == headers.end() || it->second != expected_accept) {
  6965. upgrade.error = Error::WebSocketHandshake;
  6966. return false;
  6967. }
  6968. // Extract negotiated subprotocol
  6969. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6970. if (proto_it != headers.end()) {
  6971. upgrade.selected_subprotocol = proto_it->second;
  6972. }
  6973. // Verify the subprotocol is one the client offered (RFC 6455 4.1)
  6974. if (!upgrade.selected_subprotocol.empty()) {
  6975. auto was_offered = false;
  6976. split(offered_subprotocols.data(),
  6977. offered_subprotocols.data() + offered_subprotocols.size(), ',',
  6978. [&](const char *b, const char *e) {
  6979. if (std::string(b, e) == upgrade.selected_subprotocol) {
  6980. was_offered = true;
  6981. }
  6982. });
  6983. if (!was_offered) {
  6984. upgrade.error = Error::WebSocketHandshake;
  6985. return false;
  6986. }
  6987. }
  6988. return true;
  6989. }
  6990. enum class ReadContentResult {
  6991. Success, // Successfully read the content
  6992. PayloadTooLarge, // The content exceeds the specified payload limit
  6993. Error // An error occurred while reading the content
  6994. };
  6995. inline ReadContentResult read_content_with_length(
  6996. Stream &strm, size_t len, DownloadProgress progress,
  6997. ContentReceiverWithProgress out,
  6998. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6999. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7000. detail::BodyReader br;
  7001. br.stream = &strm;
  7002. br.has_content_length = true;
  7003. br.content_length = len;
  7004. br.payload_max_length = payload_max_length;
  7005. br.chunked = false;
  7006. br.bytes_read = 0;
  7007. br.last_error = Error::Success;
  7008. size_t r = 0;
  7009. while (r < len) {
  7010. auto read_len = static_cast<size_t>(len - r);
  7011. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  7012. auto n = detail::read_body_content(&strm, br, buf, to_read);
  7013. if (n <= 0) {
  7014. // Check if it was a payload size error
  7015. if (br.last_error == Error::ExceedMaxPayloadSize) {
  7016. return ReadContentResult::PayloadTooLarge;
  7017. }
  7018. return ReadContentResult::Error;
  7019. }
  7020. if (!out(buf, static_cast<size_t>(n), r, len)) {
  7021. return ReadContentResult::Error;
  7022. }
  7023. r += static_cast<size_t>(n);
  7024. if (progress) {
  7025. if (!progress(r, len)) { return ReadContentResult::Error; }
  7026. }
  7027. }
  7028. return ReadContentResult::Success;
  7029. }
  7030. inline ReadContentResult
  7031. read_content_without_length(Stream &strm, size_t payload_max_length,
  7032. ContentReceiverWithProgress out) {
  7033. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7034. size_t r = 0;
  7035. for (;;) {
  7036. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  7037. if (n == 0) { return ReadContentResult::Success; }
  7038. if (n < 0) { return ReadContentResult::Error; }
  7039. // Check if adding this data would exceed the payload limit
  7040. if (payload_max_length > 0 &&
  7041. (r > payload_max_length ||
  7042. payload_max_length - r < static_cast<size_t>(n))) {
  7043. return ReadContentResult::PayloadTooLarge;
  7044. }
  7045. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  7046. return ReadContentResult::Error;
  7047. }
  7048. r += static_cast<size_t>(n);
  7049. }
  7050. return ReadContentResult::Success;
  7051. }
  7052. template <typename T>
  7053. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  7054. size_t payload_max_length,
  7055. ContentReceiverWithProgress out) {
  7056. detail::ChunkedDecoder dec(strm);
  7057. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  7058. size_t total_len = 0;
  7059. for (;;) {
  7060. size_t chunk_offset = 0;
  7061. size_t chunk_total = 0;
  7062. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  7063. if (n < 0) { return ReadContentResult::Error; }
  7064. if (n == 0) {
  7065. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  7066. return ReadContentResult::Error;
  7067. }
  7068. return ReadContentResult::Success;
  7069. }
  7070. if (payload_max_length > 0 &&
  7071. (total_len > payload_max_length ||
  7072. payload_max_length - total_len < static_cast<size_t>(n))) {
  7073. return ReadContentResult::PayloadTooLarge;
  7074. }
  7075. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  7076. return ReadContentResult::Error;
  7077. }
  7078. total_len += static_cast<size_t>(n);
  7079. }
  7080. }
  7081. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  7082. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  7083. // is the final transfer coding. A single field value may list several
  7084. // codings ("gzip, chunked"), and RFC 9110 5.3 lets that list be split across
  7085. // several Transfer-Encoding lines, which combine into one comma-separated
  7086. // list in the order the lines were received. Headers preserves that order,
  7087. // so the final coding is the last token of the last line. Match it
  7088. // case-insensitively rather than comparing the whole value against
  7089. // "chunked".
  7090. //
  7091. // Security: reading a chunked message as unframed leaves its body in the
  7092. // socket, where a keep-alive connection parses it as a smuggled request.
  7093. // Server::process_request() answers 400 and closes when the final coding is
  7094. // not chunked, so a request whose framing cannot be determined never
  7095. // reaches the "no body" path.
  7096. auto rng = headers.equal_range("Transfer-Encoding");
  7097. if (rng.first == rng.second) { return false; }
  7098. // Cleared per line, so a trailing line carrying no coding at all leaves the
  7099. // combined list ending in nothing rather than inheriting the line before it.
  7100. std::string last_coding;
  7101. for (auto it = rng.first; it != rng.second; ++it) {
  7102. const auto &value = it->second;
  7103. last_coding.clear();
  7104. split(value.data(), value.data() + value.size(), ',',
  7105. [&](const char *b, const char *e) { last_coding.assign(b, e); });
  7106. }
  7107. return case_ignore::equal(last_coding, "chunked");
  7108. }
  7109. inline bool has_conflicting_content_length(const Headers &headers) {
  7110. // RFC 9112 §6.3: a message carrying both Transfer-Encoding and a non-zero
  7111. // Content-Length is framed ambiguously. The body readers here delimit it by
  7112. // the transfer coding and drop Content-Length, while an intermediary may do
  7113. // the reverse, so the two disagree on where the body ends and a reused
  7114. // connection is desynchronised (request/response smuggling). Content-Length:
  7115. // 0 is tolerated for compatibility with existing peers.
  7116. return has_header(headers, "Transfer-Encoding") &&
  7117. get_header_value_u64(headers, "Content-Length", 0, 0) > 0;
  7118. }
  7119. template <typename T, typename U>
  7120. bool prepare_content_receiver(T &x, int &status,
  7121. ContentReceiverWithProgress receiver,
  7122. bool decompress, size_t payload_max_length,
  7123. bool &exceed_payload_max_length, U callback) {
  7124. if (decompress) {
  7125. auto encoding = get_combined_header_value(x.headers, "Content-Encoding");
  7126. std::unique_ptr<decompressor> decompressor;
  7127. if (!encoding.empty()) {
  7128. // A coding we know about but were not built with is an error. An
  7129. // unrecognized coding (including "identity") is left alone and the
  7130. // payload is passed through as-is, since some servers misuse the header,
  7131. // e.g. by sending a character set such as "Content-Encoding: UTF-8".
  7132. decompressor = detail::create_decompressor(encoding);
  7133. if (!decompressor && detail::is_known_content_encoding(encoding)) {
  7134. status = StatusCode::UnsupportedMediaType_415;
  7135. return false;
  7136. }
  7137. }
  7138. if (decompressor) {
  7139. if (decompressor->is_valid()) {
  7140. size_t decompressed_size = 0;
  7141. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  7142. size_t off, size_t len) {
  7143. return decompressor->decompress(
  7144. buf, n, [&](const char *buf2, size_t n2) {
  7145. // Guard against zip-bomb: check
  7146. // decompressed size against limit.
  7147. if (payload_max_length > 0 &&
  7148. (decompressed_size >= payload_max_length ||
  7149. n2 > payload_max_length - decompressed_size)) {
  7150. exceed_payload_max_length = true;
  7151. return false;
  7152. }
  7153. decompressed_size += n2;
  7154. return receiver(buf2, n2, off, len);
  7155. });
  7156. };
  7157. return callback(std::move(out));
  7158. } else {
  7159. status = StatusCode::InternalServerError_500;
  7160. return false;
  7161. }
  7162. }
  7163. }
  7164. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  7165. size_t len) {
  7166. return receiver(buf, n, off, len);
  7167. };
  7168. return callback(std::move(out));
  7169. }
  7170. template <typename T>
  7171. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  7172. DownloadProgress progress,
  7173. ContentReceiverWithProgress receiver, bool decompress) {
  7174. bool exceed_payload_max_length = false;
  7175. return prepare_content_receiver(
  7176. x, status, std::move(receiver), decompress, payload_max_length,
  7177. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  7178. auto ret = true;
  7179. // Note: exceed_payload_max_length may also be set by the decompressor
  7180. // wrapper in prepare_content_receiver when the decompressed payload
  7181. // size exceeds the limit.
  7182. if (is_chunked_transfer_encoding(x.headers)) {
  7183. auto result = read_content_chunked(strm, x, payload_max_length, out);
  7184. if (result == ReadContentResult::Success) {
  7185. ret = true;
  7186. } else if (result == ReadContentResult::PayloadTooLarge) {
  7187. exceed_payload_max_length = true;
  7188. ret = false;
  7189. } else {
  7190. ret = false;
  7191. }
  7192. } else if (!has_header(x.headers, "Content-Length")) {
  7193. auto result =
  7194. read_content_without_length(strm, payload_max_length, out);
  7195. if (result == ReadContentResult::Success) {
  7196. ret = true;
  7197. } else if (result == ReadContentResult::PayloadTooLarge) {
  7198. exceed_payload_max_length = true;
  7199. ret = false;
  7200. } else {
  7201. ret = false;
  7202. }
  7203. } else {
  7204. auto is_invalid_value = false;
  7205. auto len = get_header_value_u64(x.headers, "Content-Length",
  7206. (std::numeric_limits<size_t>::max)(),
  7207. 0, is_invalid_value);
  7208. if (is_invalid_value) {
  7209. ret = false;
  7210. } else if (len > 0) {
  7211. auto result = read_content_with_length(
  7212. strm, len, std::move(progress), out, payload_max_length);
  7213. ret = (result == ReadContentResult::Success);
  7214. if (result == ReadContentResult::PayloadTooLarge) {
  7215. exceed_payload_max_length = true;
  7216. }
  7217. }
  7218. }
  7219. if (!ret) {
  7220. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  7221. : StatusCode::BadRequest_400;
  7222. }
  7223. return ret;
  7224. });
  7225. }
  7226. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  7227. const std::string &path) {
  7228. // Neither the method nor the request target may carry CR/LF, SP or other
  7229. // control octets; otherwise a value smuggled into either splits the request
  7230. // line and injects headers or a whole request.
  7231. if (!fields::is_token(method)) { return -1; }
  7232. if (!fields::is_request_target(path)) { return -1; }
  7233. std::string s = method;
  7234. s += ' ';
  7235. s += path;
  7236. s += " HTTP/1.1\r\n";
  7237. return strm.write(s.data(), s.size());
  7238. }
  7239. inline ssize_t write_response_line(Stream &strm, int status) {
  7240. std::string s = "HTTP/1.1 ";
  7241. s += std::to_string(status);
  7242. s += ' ';
  7243. s += httplib::status_message(status);
  7244. s += "\r\n";
  7245. return strm.write(s.data(), s.size());
  7246. }
  7247. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  7248. ssize_t write_len = 0;
  7249. for (const auto &x : headers) {
  7250. // Skip fields with invalid names or values to prevent response splitting
  7251. // via CR/LF injection, matching set_header(). The client validates request
  7252. // headers up front in check_and_write_headers, but the server passes
  7253. // res.headers straight to this writer, and res.headers is a public field
  7254. // an application can populate directly with request-derived values.
  7255. if (!fields::is_field_valid(x.first, x.second)) { continue; }
  7256. std::string s;
  7257. s = x.first;
  7258. s += ": ";
  7259. s += x.second;
  7260. s += "\r\n";
  7261. auto len = strm.write(s.data(), s.size());
  7262. if (len < 0) { return len; }
  7263. write_len += len;
  7264. }
  7265. auto len = strm.write("\r\n");
  7266. if (len < 0) { return len; }
  7267. write_len += len;
  7268. return write_len;
  7269. }
  7270. inline bool write_data(Stream &strm, const char *d, size_t l) {
  7271. size_t offset = 0;
  7272. while (offset < l) {
  7273. auto length = strm.write(d + offset, l - offset);
  7274. if (length < 0) { return false; }
  7275. offset += static_cast<size_t>(length);
  7276. }
  7277. return true;
  7278. }
  7279. template <typename T>
  7280. inline bool write_content_with_progress(Stream &strm,
  7281. const ContentProvider &content_provider,
  7282. size_t offset, size_t length,
  7283. T is_shutting_down,
  7284. const UploadProgress &upload_progress,
  7285. Error &error) {
  7286. size_t end_offset = offset + length;
  7287. size_t start_offset = offset;
  7288. auto ok = true;
  7289. auto finished = false;
  7290. DataSink data_sink;
  7291. data_sink.write = [&](const char *d, size_t l) -> bool {
  7292. if (ok) {
  7293. if (write_data(strm, d, l)) {
  7294. offset += l;
  7295. if (upload_progress && length > 0) {
  7296. size_t current_written = offset - start_offset;
  7297. if (!upload_progress(current_written, length)) {
  7298. ok = false;
  7299. return false;
  7300. }
  7301. }
  7302. } else {
  7303. ok = false;
  7304. }
  7305. }
  7306. return ok;
  7307. };
  7308. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7309. // The body is framed by `length`, so a provider that reports itself done
  7310. // early has truncated it. Record that and let the short-body check below
  7311. // fail the write, rather than calling the provider again forever.
  7312. data_sink.done = [&]() { finished = true; };
  7313. while (offset < end_offset && !finished && !is_shutting_down()) {
  7314. auto last_offset = offset;
  7315. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7316. error = Error::Write;
  7317. return false;
  7318. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  7319. error = Error::Canceled;
  7320. return false;
  7321. } else if (!ok) {
  7322. error = Error::Write;
  7323. return false;
  7324. }
  7325. // A provider that reports success without writing anything and without
  7326. // reporting itself done gets handed the same offset and length again on
  7327. // the next pass, so it would spin here for as long as the peer stays
  7328. // connected. Treat making no progress as a short body, like done() early.
  7329. if (!finished && offset == last_offset) {
  7330. error = Error::Write;
  7331. return false;
  7332. }
  7333. }
  7334. if (offset < end_offset) { // done() called early, or is_shutting_down()
  7335. error = Error::Write;
  7336. return false;
  7337. }
  7338. error = Error::Success;
  7339. return true;
  7340. }
  7341. template <typename T>
  7342. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  7343. size_t offset, size_t length, T is_shutting_down,
  7344. Error &error) {
  7345. return write_content_with_progress<T>(strm, content_provider, offset, length,
  7346. is_shutting_down, nullptr, error);
  7347. }
  7348. template <typename T>
  7349. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  7350. size_t offset, size_t length,
  7351. const T &is_shutting_down) {
  7352. auto error = Error::Success;
  7353. return write_content(strm, content_provider, offset, length, is_shutting_down,
  7354. error);
  7355. }
  7356. template <typename T>
  7357. inline bool
  7358. write_content_without_length(Stream &strm,
  7359. const ContentProvider &content_provider,
  7360. const T &is_shutting_down) {
  7361. size_t offset = 0;
  7362. auto data_available = true;
  7363. auto ok = true;
  7364. DataSink data_sink;
  7365. data_sink.write = [&](const char *d, size_t l) -> bool {
  7366. if (ok) {
  7367. offset += l;
  7368. if (!write_data(strm, d, l)) { ok = false; }
  7369. }
  7370. return ok;
  7371. };
  7372. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7373. data_sink.done = [&](void) { data_available = false; };
  7374. while (data_available && !is_shutting_down()) {
  7375. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7376. return false;
  7377. } else if (!content_provider(offset, 0, data_sink)) {
  7378. return false;
  7379. } else if (!ok) {
  7380. return false;
  7381. }
  7382. }
  7383. return !data_available; // true only if done() was called, false if shutting
  7384. // down
  7385. }
  7386. // Runs a known-length content provider to completion and compresses what it
  7387. // writes into `out`. Nothing is buffered in identity form: a provider backed
  7388. // by an mmap hands the compressor a pointer straight into the mapping.
  7389. inline bool compress_content_provider(const ContentProvider &content_provider,
  7390. size_t length, compressor &cmp,
  7391. std::string &out) {
  7392. size_t offset = 0;
  7393. auto ok = true;
  7394. auto finished = false;
  7395. DataSink data_sink;
  7396. auto append = [&](const char *data, size_t data_len) {
  7397. out.append(data, data_len);
  7398. return true;
  7399. };
  7400. data_sink.write = [&](const char *d, size_t l) -> bool {
  7401. if (!ok) { return false; }
  7402. offset += l;
  7403. if (l > 0 && !cmp.compress(d, l, false, append)) { ok = false; }
  7404. return ok;
  7405. };
  7406. // The body is framed by `length`, so a provider that reports itself done
  7407. // early has truncated it; the short-body check below turns that into a
  7408. // failure rather than calling the provider again forever.
  7409. data_sink.done = [&]() { finished = true; };
  7410. while (offset < length && !finished) {
  7411. auto prev_offset = offset;
  7412. if (!content_provider(offset, length - offset, data_sink) || !ok) {
  7413. return false;
  7414. }
  7415. // No Stream to block on here, so a provider that keeps returning true
  7416. // without writing would spin. Treat a pass that made no progress as a
  7417. // failure.
  7418. if (offset == prev_offset) { return false; }
  7419. }
  7420. if (offset != length) { return false; }
  7421. return cmp.compress(nullptr, 0, true, append);
  7422. }
  7423. // Serves `m` as the response body. `set_content_provider()` clears the coding
  7424. // and the file flag, so recording them has to come after; keeping all of it
  7425. // here means a third file-serving path cannot get that order wrong.
  7426. inline void set_file_content_provider(Response &res,
  7427. const std::shared_ptr<mmap> &m,
  7428. const std::string &content_type,
  7429. EncodingType encoding) {
  7430. res.set_content_provider(
  7431. m->size(), content_type,
  7432. [m](size_t offset, size_t length, DataSink &sink) -> bool {
  7433. sink.write(m->data() + offset, length);
  7434. return true;
  7435. });
  7436. res.is_file_content_provider_ = true;
  7437. res.content_coding_ = encoding;
  7438. }
  7439. template <typename T, typename U>
  7440. inline bool
  7441. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  7442. const T &is_shutting_down, U &compressor, Error &error) {
  7443. size_t offset = 0;
  7444. auto data_available = true;
  7445. auto ok = true;
  7446. DataSink data_sink;
  7447. data_sink.write = [&](const char *d, size_t l) -> bool {
  7448. // Only done()/done_with_trailer() end a chunked body. A pass with nothing
  7449. // to hand over is ordinary (an empty buffer popped off a queue), and a
  7450. // zero-length chunk is the terminator, so it must not be emitted here.
  7451. if (ok && l > 0) {
  7452. offset += l;
  7453. std::string payload;
  7454. if (compressor.compress(d, l, false,
  7455. [&](const char *data, size_t data_len) {
  7456. payload.append(data, data_len);
  7457. return true;
  7458. })) {
  7459. if (!payload.empty()) {
  7460. // Emit chunked response header and footer for each chunk
  7461. auto chunk =
  7462. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7463. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  7464. }
  7465. } else {
  7466. ok = false;
  7467. }
  7468. }
  7469. return ok;
  7470. };
  7471. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7472. auto done_with_trailer = [&](const Headers *trailer) {
  7473. if (!ok) { return; }
  7474. data_available = false;
  7475. std::string payload;
  7476. if (!compressor.compress(nullptr, 0, true,
  7477. [&](const char *data, size_t data_len) {
  7478. payload.append(data, data_len);
  7479. return true;
  7480. })) {
  7481. ok = false;
  7482. return;
  7483. }
  7484. if (!payload.empty()) {
  7485. // Emit chunked response header and footer for each chunk
  7486. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7487. if (!write_data(strm, chunk.data(), chunk.size())) {
  7488. ok = false;
  7489. return;
  7490. }
  7491. }
  7492. constexpr const char done_marker[] = "0\r\n";
  7493. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  7494. // Trailer
  7495. if (trailer) {
  7496. for (const auto &kv : *trailer) {
  7497. // Skip fields with invalid names or values to prevent response
  7498. // splitting via CR/LF injection, matching set_header().
  7499. if (!fields::is_field_valid(kv.first, kv.second)) { continue; }
  7500. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  7501. if (!write_data(strm, field_line.data(), field_line.size())) {
  7502. ok = false;
  7503. }
  7504. }
  7505. }
  7506. constexpr const char crlf[] = "\r\n";
  7507. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  7508. };
  7509. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  7510. data_sink.done_with_trailer = [&](const Headers &trailer) {
  7511. done_with_trailer(&trailer);
  7512. };
  7513. while (data_available && !is_shutting_down()) {
  7514. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7515. error = Error::Write;
  7516. return false;
  7517. } else if (!content_provider(offset, 0, data_sink)) {
  7518. error = Error::Canceled;
  7519. return false;
  7520. } else if (!ok) {
  7521. error = Error::Write;
  7522. return false;
  7523. }
  7524. }
  7525. if (data_available) { // exited due to is_shutting_down(), not done()
  7526. error = Error::Write;
  7527. return false;
  7528. }
  7529. error = Error::Success;
  7530. return true;
  7531. }
  7532. template <typename T, typename U>
  7533. inline bool write_content_chunked(Stream &strm,
  7534. const ContentProvider &content_provider,
  7535. const T &is_shutting_down, U &compressor) {
  7536. auto error = Error::Success;
  7537. return write_content_chunked(strm, content_provider, is_shutting_down,
  7538. compressor, error);
  7539. }
  7540. template <typename T>
  7541. inline bool redirect(T &cli, Request &req, Response &res,
  7542. const std::string &path, const std::string &location,
  7543. Error &error) {
  7544. Request new_req = req;
  7545. new_req.path = path;
  7546. new_req.redirect_count_ -= 1;
  7547. if (res.status == StatusCode::SeeOther_303 &&
  7548. (req.method != "GET" && req.method != "HEAD")) {
  7549. new_req.method = "GET";
  7550. new_req.body.clear();
  7551. new_req.headers.clear();
  7552. new_req.content_length_ = 0;
  7553. new_req.content_provider_ = nullptr;
  7554. new_req.is_chunked_content_provider_ = false;
  7555. }
  7556. Response new_res;
  7557. auto ret = cli.send(new_req, new_res, error);
  7558. if (ret) {
  7559. req = std::move(new_req);
  7560. res = std::move(new_res);
  7561. if (res.location.empty()) { res.location = location; }
  7562. }
  7563. return ret;
  7564. }
  7565. inline std::string params_to_query_str(const Params &params) {
  7566. std::string query;
  7567. for (auto it = params.begin(); it != params.end(); ++it) {
  7568. if (it != params.begin()) { query += '&'; }
  7569. query += encode_query_component(it->first);
  7570. query += '=';
  7571. query += encode_query_component(it->second);
  7572. }
  7573. return query;
  7574. }
  7575. // Splits one "key=value" span of a query string at its first '='. A span with
  7576. // no '=' at all lands entirely in key, leaving val empty, which is how a bare
  7577. // "?flag" keeps its name.
  7578. inline void divide_query_pair(const char *b, const char *e, std::string &key,
  7579. std::string &val) {
  7580. divide(b, static_cast<std::size_t>(e - b), '=',
  7581. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  7582. std::size_t rhs_size) {
  7583. key.assign(lhs_data, lhs_size);
  7584. val.assign(rhs_data, rhs_size);
  7585. });
  7586. }
  7587. inline void parse_query_text(const char *data, std::size_t size,
  7588. Params &params) {
  7589. std::set<std::string> cache;
  7590. split(data, data + size, '&', [&](const char *b, const char *e) {
  7591. std::string kv(b, e);
  7592. if (cache.find(kv) != cache.end()) { return; }
  7593. cache.insert(std::move(kv));
  7594. std::string key;
  7595. std::string val;
  7596. divide_query_pair(b, e, key, val);
  7597. if (!key.empty()) {
  7598. params.emplace(decode_query_component(key), decode_query_component(val));
  7599. }
  7600. });
  7601. }
  7602. inline void parse_query_text(const std::string &s, Params &params) {
  7603. parse_query_text(s.data(), s.size(), params);
  7604. }
  7605. // Normalize a query string by decoding and re-encoding each key/value pair
  7606. // while preserving the original parameter order. This avoids double-encoding
  7607. // and ensures consistent encoding. It works on the raw string rather than
  7608. // parsing into Params and re-serializing, because that round trip cannot
  7609. // reproduce the input: params_to_query_str() always emits '=', so a bare
  7610. // "flag" would come back as "flag=", and parse_query_text() drops exactly
  7611. // duplicated pairs.
  7612. inline std::string normalize_query_string(const std::string &query) {
  7613. std::string result;
  7614. split(query.data(), query.data() + query.size(), '&',
  7615. [&](const char *b, const char *e) {
  7616. std::string key;
  7617. std::string val;
  7618. divide_query_pair(b, e, key, val);
  7619. if (!key.empty()) {
  7620. auto dec_key = decode_query_component(key);
  7621. auto dec_val = decode_query_component(val);
  7622. if (!result.empty()) { result += '&'; }
  7623. result += encode_query_component(dec_key);
  7624. if (!val.empty() || std::find(b, e, '=') != e) {
  7625. result += '=';
  7626. result += encode_query_component(dec_val);
  7627. }
  7628. }
  7629. });
  7630. return result;
  7631. }
  7632. // Build the request target that goes on the wire from a caller-supplied path.
  7633. // Shared by the buffered send path and the streaming API so that both put the
  7634. // same bytes in the request line for the same input.
  7635. inline std::string encode_request_target(const std::string &target,
  7636. bool path_encode) {
  7637. // `substr(0, npos)` yields the whole string, which is what the no-query
  7638. // case needs.
  7639. auto query_pos = target.find('?');
  7640. auto path_part = target.substr(0, query_pos);
  7641. std::string query_part;
  7642. if (query_pos != std::string::npos) {
  7643. query_part = target.substr(query_pos + 1);
  7644. }
  7645. auto result = path_encode ? encode_path(path_part) : std::move(path_part);
  7646. if (!query_part.empty()) {
  7647. // When path encoding is disabled the caller has supplied an already-encoded
  7648. // target and expects the exact bytes to be sent on the wire, so skip
  7649. // normalization for the query too. Normalizing would decode-then-re-encode
  7650. // it and corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  7651. // which a strict RFC 3986 server decodes back as `+`, not a space).
  7652. if (path_encode) {
  7653. auto normalized = normalize_query_string(query_part);
  7654. if (!normalized.empty()) {
  7655. result += '?';
  7656. result += normalized;
  7657. }
  7658. } else {
  7659. result += '?';
  7660. result += query_part;
  7661. }
  7662. }
  7663. return result;
  7664. }
  7665. inline bool parse_multipart_boundary(const std::string &content_type,
  7666. std::string &boundary) {
  7667. std::map<std::string, std::string> params;
  7668. extract_media_type(content_type, &params);
  7669. auto it = params.find("boundary");
  7670. if (it == params.end()) { return false; }
  7671. boundary = it->second;
  7672. // RFC 2046 5.1.1 caps a boundary at 70 characters. The parser scans the body
  7673. // for "--" + boundary, so a body crafted to repeat that delimiter's leading
  7674. // bytes costs a nearly full comparison at nearly every position: the
  7675. // boundary's length multiplies the worst-case cost of scanning a body.
  7676. return !boundary.empty() && boundary.size() <= 70;
  7677. }
  7678. inline void parse_disposition_params(const std::string &s, Params &params) {
  7679. std::set<std::string> cache;
  7680. split_unquoted(s.data(), s.data() + s.size(), ';',
  7681. [&](const char *b, const char *e) {
  7682. std::string kv(b, e);
  7683. if (cache.find(kv) != cache.end()) { return; }
  7684. cache.insert(kv);
  7685. std::string key;
  7686. std::string val;
  7687. divide_param_pair(b, e, key, val);
  7688. if (!key.empty()) {
  7689. params.emplace(trim_double_quotes_copy(key),
  7690. trim_double_quotes_copy(val));
  7691. }
  7692. });
  7693. }
  7694. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7695. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  7696. #else
  7697. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  7698. #endif
  7699. auto is_valid = [](const std::string &str) {
  7700. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  7701. };
  7702. if (s.size() > 7 && case_ignore::equal(s.substr(0, 6), "bytes=")) {
  7703. const auto pos = static_cast<size_t>(6);
  7704. const auto len = static_cast<size_t>(s.size() - 6);
  7705. auto all_valid_ranges = true;
  7706. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  7707. if (!all_valid_ranges) { return; }
  7708. const auto it = std::find(b, e, '-');
  7709. if (it == e) {
  7710. all_valid_ranges = false;
  7711. return;
  7712. }
  7713. const auto lhs = std::string(b, it);
  7714. const auto rhs = std::string(it + 1, e);
  7715. if (!is_valid(lhs) || !is_valid(rhs)) {
  7716. all_valid_ranges = false;
  7717. return;
  7718. }
  7719. ssize_t first = -1;
  7720. if (!lhs.empty()) {
  7721. // Reject an overflowing first-byte-pos; treating it as absent (-1)
  7722. // would turn the range into a suffix range.
  7723. auto res =
  7724. detail::from_chars(lhs.data(), lhs.data() + lhs.size(), first);
  7725. if (res.ec != std::errc{}) {
  7726. all_valid_ranges = false;
  7727. return;
  7728. }
  7729. }
  7730. ssize_t last = -1;
  7731. if (!rhs.empty()) {
  7732. // An overflowing last-byte-pos is past any content length, so keeping
  7733. // -1 ("remainder", RFC 9110 14.1.2) is correct here.
  7734. ssize_t v;
  7735. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  7736. if (res.ec == std::errc{}) { last = v; }
  7737. }
  7738. if ((first == -1 && last == -1) ||
  7739. (first != -1 && last != -1 && first > last)) {
  7740. all_valid_ranges = false;
  7741. return;
  7742. }
  7743. ranges.emplace_back(first, last);
  7744. });
  7745. return all_valid_ranges && !ranges.empty();
  7746. }
  7747. return false;
  7748. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7749. }
  7750. #else
  7751. } catch (...) { return false; }
  7752. #endif
  7753. // Removes each quoted-string, honoring a quoted-pair (RFC 9110 Section 5.6.4)
  7754. inline std::string remove_quoted_strings(const std::string &s) {
  7755. std::string out;
  7756. auto in_quotes = false;
  7757. for (size_t i = 0; i < s.size(); i++) {
  7758. if (s[i] == '"') {
  7759. in_quotes = !in_quotes;
  7760. } else if (!in_quotes) {
  7761. out += s[i];
  7762. } else if (s[i] == '\\') {
  7763. i++;
  7764. }
  7765. }
  7766. return out;
  7767. }
  7768. inline bool parse_accept_header(const std::string &s,
  7769. std::vector<std::string> &content_types) {
  7770. // Parameter values are not used here, so a quoted-string is dropped rather
  7771. // than parsed: a ',' or ';' inside one must not be read as a delimiter.
  7772. if (s.find('"') != std::string::npos) {
  7773. return parse_accept_header(remove_quoted_strings(s), content_types);
  7774. }
  7775. content_types.clear();
  7776. // Empty string is considered valid (no preference)
  7777. if (s.empty()) { return true; }
  7778. struct AcceptEntry {
  7779. std::string media_type;
  7780. double quality;
  7781. int order;
  7782. };
  7783. std::vector<AcceptEntry> entries;
  7784. int order = 0;
  7785. bool has_invalid_entry = false;
  7786. // Split by comma and parse each entry. RFC 9110 Section 5.6.1.2: a recipient
  7787. // has to parse and ignore empty list elements, so a leading, trailing or
  7788. // doubled comma must not turn a legal Accept value into 400 Bad Request.
  7789. // split() skips them, and the header length limit bounds how many a sender
  7790. // can send, so ignoring all of them cannot be used as a denial-of-service
  7791. // vector.
  7792. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  7793. std::string entry(b, e);
  7794. entry = trim_copy(entry);
  7795. AcceptEntry accept_entry;
  7796. accept_entry.order = order++;
  7797. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  7798. accept_entry.media_type, accept_entry.quality)) {
  7799. has_invalid_entry = true;
  7800. return;
  7801. }
  7802. // Remove additional parameters from media type
  7803. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  7804. // Basic validation of media type format
  7805. if (accept_entry.media_type.empty()) {
  7806. has_invalid_entry = true;
  7807. return;
  7808. }
  7809. // Check for basic media type format (should contain '/' or be '*')
  7810. if (accept_entry.media_type != "*" &&
  7811. accept_entry.media_type.find('/') == std::string::npos) {
  7812. has_invalid_entry = true;
  7813. return;
  7814. }
  7815. entries.push_back(std::move(accept_entry));
  7816. });
  7817. // Return false if any invalid entry was found
  7818. if (has_invalid_entry) { return false; }
  7819. // Sort by quality (descending), then by original order (ascending)
  7820. std::sort(entries.begin(), entries.end(),
  7821. [](const AcceptEntry &a, const AcceptEntry &b) {
  7822. if (a.quality != b.quality) {
  7823. return a.quality > b.quality; // Higher quality first
  7824. }
  7825. return a.order < b.order; // Earlier order first for same quality
  7826. });
  7827. // Extract sorted media types
  7828. content_types.reserve(entries.size());
  7829. for (auto &entry : entries) {
  7830. content_types.push_back(std::move(entry.media_type));
  7831. }
  7832. return true;
  7833. }
  7834. class FormDataParser {
  7835. public:
  7836. FormDataParser() = default;
  7837. void set_boundary(std::string &&boundary) {
  7838. boundary_ = std::move(boundary);
  7839. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  7840. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  7841. }
  7842. bool is_valid() const { return is_valid_; }
  7843. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  7844. const ContentReceiver &content_callback) {
  7845. // Once the close delimiter has been seen the rest of the body is epilogue
  7846. // to be discarded (RFC 2046). Drop it without buffering so a large epilogue
  7847. // spread across reads is not copied in only to be erased right away.
  7848. if (state_ == 5) { return true; }
  7849. buf_append(buf, n);
  7850. while (buf_size() > 0) {
  7851. switch (state_) {
  7852. case 0: { // Initial boundary
  7853. auto pos = buf_find(dash_boundary_crlf_);
  7854. if (pos == buf_size()) {
  7855. // Not found yet: keep only a possible partial boundary at the tail so
  7856. // that a body which never contains the boundary cannot grow the
  7857. // buffer (and get rescanned from the start) without bound.
  7858. auto keep = dash_boundary_crlf_.size() - 1;
  7859. if (buf_size() > keep) { buf_erase(buf_size() - keep); }
  7860. return true;
  7861. }
  7862. buf_erase(pos + dash_boundary_crlf_.size());
  7863. state_ = 1;
  7864. break;
  7865. }
  7866. case 1: { // New entry
  7867. clear_file_info();
  7868. state_ = 2;
  7869. break;
  7870. }
  7871. case 2: { // Headers
  7872. auto pos = buf_find(crlf_);
  7873. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  7874. while (pos < buf_size()) {
  7875. // Empty line
  7876. if (pos == 0) {
  7877. if (!header_callback(file_)) {
  7878. is_valid_ = false;
  7879. return false;
  7880. }
  7881. buf_erase(crlf_.size());
  7882. state_ = 3;
  7883. break;
  7884. }
  7885. // Check header count limit
  7886. if (header_count_ >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  7887. is_valid_ = false;
  7888. return false;
  7889. }
  7890. header_count_++;
  7891. const auto header = buf_head(pos);
  7892. if (!parse_header(header.data(), header.data() + header.size(),
  7893. [&](const std::string &, const std::string &) {})) {
  7894. is_valid_ = false;
  7895. return false;
  7896. }
  7897. // Parse and emplace space trimmed headers into a map
  7898. if (!parse_header(
  7899. header.data(), header.data() + header.size(),
  7900. [&](const std::string &key, const std::string &val) {
  7901. file_.headers.emplace(key, val);
  7902. })) {
  7903. is_valid_ = false;
  7904. return false;
  7905. }
  7906. constexpr const char header_content_type[] = "Content-Type:";
  7907. if (start_with_case_ignore(header, header_content_type)) {
  7908. file_.content_type =
  7909. trim_copy(header.substr(str_len(header_content_type)));
  7910. } else {
  7911. std::string disposition_params;
  7912. if (parse_content_disposition(header, disposition_params)) {
  7913. Params params;
  7914. parse_disposition_params(disposition_params, params);
  7915. auto it = params.find("name");
  7916. if (it != params.end()) {
  7917. file_.name = it->second;
  7918. } else {
  7919. is_valid_ = false;
  7920. return false;
  7921. }
  7922. it = params.find("filename");
  7923. if (it != params.end()) { file_.filename = it->second; }
  7924. it = params.find("filename*");
  7925. if (it != params.end()) {
  7926. // RFC 5987: only UTF-8 encoding is allowed
  7927. const auto &val = it->second;
  7928. constexpr const char utf8_prefix[] = "UTF-8''";
  7929. constexpr size_t prefix_len = str_len(utf8_prefix);
  7930. if (val.size() > prefix_len &&
  7931. start_with_case_ignore(val, utf8_prefix)) {
  7932. file_.filename = decode_path_component(
  7933. val.substr(prefix_len)); // override...
  7934. } else {
  7935. is_valid_ = false;
  7936. return false;
  7937. }
  7938. }
  7939. }
  7940. }
  7941. buf_erase(pos + crlf_.size());
  7942. pos = buf_find(crlf_);
  7943. }
  7944. if (state_ != 3) { return true; }
  7945. break;
  7946. }
  7947. case 3: { // Body
  7948. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  7949. auto pos = buf_find(crlf_dash_boundary_);
  7950. if (pos < buf_size()) {
  7951. if (!content_callback(buf_data(), pos)) {
  7952. is_valid_ = false;
  7953. return false;
  7954. }
  7955. buf_erase(pos + crlf_dash_boundary_.size());
  7956. state_ = 4;
  7957. } else {
  7958. auto len = buf_size() - crlf_dash_boundary_.size();
  7959. if (len > 0) {
  7960. if (!content_callback(buf_data(), len)) {
  7961. is_valid_ = false;
  7962. return false;
  7963. }
  7964. buf_erase(len);
  7965. }
  7966. return true;
  7967. }
  7968. break;
  7969. }
  7970. case 4: { // Boundary
  7971. if (crlf_.size() > buf_size()) { return true; }
  7972. if (buf_start_with(crlf_)) {
  7973. buf_erase(crlf_.size());
  7974. state_ = 1;
  7975. } else if (buf_start_with(dash_)) {
  7976. buf_erase(dash_.size());
  7977. is_valid_ = true;
  7978. state_ = 5;
  7979. } else {
  7980. // Only CRLF (another part follows) and "--" (close-delimiter) are
  7981. // accepted after a boundary; RFC 2046 allows transport-padding in
  7982. // between, but this parser has never supported it. Either way the
  7983. // body is already destined to be rejected, so fail now instead of
  7984. // buffering the rest of it. Both are two bytes, so the check above
  7985. // already guarantees enough buffered data to decide.
  7986. is_valid_ = false;
  7987. return false;
  7988. }
  7989. break;
  7990. }
  7991. case 5: { // Epilogue
  7992. buf_erase(buf_size());
  7993. break;
  7994. }
  7995. }
  7996. }
  7997. return true;
  7998. }
  7999. private:
  8000. void clear_file_info() {
  8001. file_.name.clear();
  8002. file_.filename.clear();
  8003. file_.content_type.clear();
  8004. file_.headers.clear();
  8005. header_count_ = 0;
  8006. }
  8007. bool start_with_case_ignore(const std::string &a, const char *b,
  8008. size_t offset = 0) const {
  8009. const auto b_len = strlen(b);
  8010. if (a.size() < offset + b_len) { return false; }
  8011. for (size_t i = 0; i < b_len; i++) {
  8012. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  8013. return false;
  8014. }
  8015. }
  8016. return true;
  8017. }
  8018. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  8019. // Returns true if header matches, with the params portion in `params_out`.
  8020. bool parse_content_disposition(const std::string &header,
  8021. std::string &params_out) const {
  8022. constexpr const char prefix[] = "Content-Disposition:";
  8023. constexpr size_t prefix_len = str_len(prefix);
  8024. if (!start_with_case_ignore(header, prefix)) { return false; }
  8025. // Skip whitespace after "Content-Disposition:"
  8026. auto pos = prefix_len;
  8027. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  8028. pos++;
  8029. }
  8030. // Match "form-data;" (case-insensitive)
  8031. constexpr const char form_data[] = "form-data;";
  8032. constexpr size_t form_data_len = str_len(form_data);
  8033. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  8034. pos += form_data_len;
  8035. // Skip whitespace after "form-data;"
  8036. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  8037. pos++;
  8038. }
  8039. params_out = header.substr(pos);
  8040. return true;
  8041. }
  8042. const std::string dash_ = "--";
  8043. const std::string crlf_ = "\r\n";
  8044. std::string boundary_;
  8045. std::string dash_boundary_crlf_;
  8046. std::string crlf_dash_boundary_;
  8047. size_t state_ = 0;
  8048. bool is_valid_ = false;
  8049. FormData file_;
  8050. size_t header_count_ = 0;
  8051. // Buffer
  8052. bool start_with(const std::string &a, size_t spos, size_t epos,
  8053. const std::string &b) const {
  8054. if (epos - spos < b.size()) { return false; }
  8055. for (size_t i = 0; i < b.size(); i++) {
  8056. if (a[i + spos] != b[i]) { return false; }
  8057. }
  8058. return true;
  8059. }
  8060. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  8061. const char *buf_data() const { return &buf_[buf_spos_]; }
  8062. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  8063. bool buf_start_with(const std::string &s) const {
  8064. return start_with(buf_, buf_spos_, buf_epos_, s);
  8065. }
  8066. size_t buf_find(const std::string &s) const {
  8067. auto c = s.front();
  8068. size_t off = buf_spos_;
  8069. while (off < buf_epos_) {
  8070. auto pos = off;
  8071. while (true) {
  8072. if (pos == buf_epos_) { return buf_size(); }
  8073. if (buf_[pos] == c) { break; }
  8074. pos++;
  8075. }
  8076. auto remaining_size = buf_epos_ - pos;
  8077. if (s.size() > remaining_size) { return buf_size(); }
  8078. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  8079. off = pos + 1;
  8080. }
  8081. return buf_size();
  8082. }
  8083. void buf_append(const char *data, size_t n) {
  8084. auto remaining_size = buf_size();
  8085. if (remaining_size > 0 && buf_spos_ > 0) {
  8086. for (size_t i = 0; i < remaining_size; i++) {
  8087. buf_[i] = buf_[buf_spos_ + i];
  8088. }
  8089. }
  8090. buf_spos_ = 0;
  8091. buf_epos_ = remaining_size;
  8092. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  8093. for (size_t i = 0; i < n; i++) {
  8094. buf_[buf_epos_ + i] = data[i];
  8095. }
  8096. buf_epos_ += n;
  8097. }
  8098. void buf_erase(size_t size) { buf_spos_ += size; }
  8099. std::string buf_;
  8100. size_t buf_spos_ = 0;
  8101. size_t buf_epos_ = 0;
  8102. };
  8103. inline std::string random_string(size_t length) {
  8104. constexpr const char data[] =
  8105. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  8106. thread_local auto engine([]() {
  8107. // std::random_device might actually be deterministic on some
  8108. // platforms, but due to lack of support in the c++ standard library,
  8109. // doing better requires either some ugly hacks or breaking portability.
  8110. std::random_device seed_gen;
  8111. // Request 128 bits of entropy for initialization
  8112. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  8113. return std::mt19937(seed_sequence);
  8114. }());
  8115. std::string result;
  8116. for (size_t i = 0; i < length; i++) {
  8117. result += data[engine() % (sizeof(data) - 1)];
  8118. }
  8119. return result;
  8120. }
  8121. inline std::string make_multipart_data_boundary() {
  8122. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  8123. }
  8124. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  8125. auto valid = true;
  8126. for (size_t i = 0; i < boundary.size(); i++) {
  8127. auto c = boundary[i];
  8128. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  8129. valid = false;
  8130. break;
  8131. }
  8132. }
  8133. return valid;
  8134. }
  8135. // Escape a multipart field name/filename following the WHATWG HTML standard
  8136. // ("escape a multipart form-data name"), which is what browsers send:
  8137. // '"' -> %22, CR -> %0D, LF -> %0A
  8138. // With escape_quote = false, only CR and LF are escaped; this is for header
  8139. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  8140. inline std::string escape_multipart_field(const std::string &s,
  8141. bool escape_quote = true) {
  8142. std::string result;
  8143. result.reserve(s.size());
  8144. for (auto c : s) {
  8145. switch (c) {
  8146. case '"':
  8147. if (escape_quote) {
  8148. result += "%22";
  8149. } else {
  8150. result += c;
  8151. }
  8152. break;
  8153. case '\r': result += "%0D"; break;
  8154. case '\n': result += "%0A"; break;
  8155. default: result += c; break;
  8156. }
  8157. }
  8158. return result;
  8159. }
  8160. template <typename T>
  8161. inline std::string
  8162. serialize_multipart_formdata_item_begin(const T &item,
  8163. const std::string &boundary) {
  8164. std::string body = "--" + boundary + "\r\n";
  8165. body += "Content-Disposition: form-data; name=\"" +
  8166. escape_multipart_field(item.name) + "\"";
  8167. if (!item.filename.empty()) {
  8168. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  8169. }
  8170. body += "\r\n";
  8171. if (!item.content_type.empty()) {
  8172. body +=
  8173. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  8174. "\r\n";
  8175. }
  8176. body += "\r\n";
  8177. return body;
  8178. }
  8179. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  8180. inline std::string
  8181. serialize_multipart_formdata_finish(const std::string &boundary) {
  8182. return "--" + boundary + "--\r\n";
  8183. }
  8184. inline std::string
  8185. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  8186. return "multipart/form-data; boundary=" + boundary;
  8187. }
  8188. inline std::string
  8189. serialize_multipart_formdata(const UploadFormDataItems &items,
  8190. const std::string &boundary, bool finish = true) {
  8191. std::string body;
  8192. for (const auto &item : items) {
  8193. body += serialize_multipart_formdata_item_begin(item, boundary);
  8194. body += item.content + serialize_multipart_formdata_item_end();
  8195. }
  8196. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  8197. return body;
  8198. }
  8199. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  8200. const std::string &boundary) {
  8201. size_t total = 0;
  8202. for (const auto &item : items) {
  8203. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  8204. total += item.content.size();
  8205. total += serialize_multipart_formdata_item_end().size();
  8206. }
  8207. total += serialize_multipart_formdata_finish(boundary).size();
  8208. return total;
  8209. }
  8210. struct MultipartSegment {
  8211. const char *data;
  8212. size_t size;
  8213. };
  8214. // NOTE: items must outlive the returned ContentProvider
  8215. // (safe for synchronous use inside Post/Put/Patch)
  8216. inline ContentProvider
  8217. make_multipart_content_provider(const UploadFormDataItems &items,
  8218. const std::string &boundary) {
  8219. // Own the per-item header strings and the finish string
  8220. std::vector<std::string> owned;
  8221. owned.reserve(items.size() + 1);
  8222. for (const auto &item : items)
  8223. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  8224. owned.push_back(serialize_multipart_formdata_finish(boundary));
  8225. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  8226. std::vector<MultipartSegment> segs;
  8227. segs.reserve(items.size() * 3 + 1);
  8228. static const char crlf[] = "\r\n";
  8229. for (size_t i = 0; i < items.size(); i++) {
  8230. segs.push_back({owned[i].data(), owned[i].size()});
  8231. segs.push_back({items[i].content.data(), items[i].content.size()});
  8232. segs.push_back({crlf, 2});
  8233. }
  8234. segs.push_back({owned.back().data(), owned.back().size()});
  8235. struct MultipartState {
  8236. std::vector<std::string> owned;
  8237. std::vector<MultipartSegment> segs;
  8238. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  8239. };
  8240. auto state = std::make_shared<MultipartState>();
  8241. state->owned = std::move(owned);
  8242. // `segs` holds raw pointers into owned strings; std::string move preserves
  8243. // the data pointer, so these pointers remain valid after the move above.
  8244. state->segs = std::move(segs);
  8245. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  8246. // Buffer multiple small segments into fewer, larger writes to avoid
  8247. // excessive TCP packets when there are many form data items (#2410)
  8248. auto &buf = state->buf;
  8249. auto buf_size = buf.size();
  8250. size_t buf_len = 0;
  8251. size_t remaining = length;
  8252. // Find the first segment containing 'offset'
  8253. size_t pos = 0;
  8254. size_t seg_idx = 0;
  8255. for (; seg_idx < state->segs.size(); seg_idx++) {
  8256. const auto &seg = state->segs[seg_idx];
  8257. if (seg.size > 0 && offset - pos < seg.size) { break; }
  8258. pos += seg.size;
  8259. }
  8260. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  8261. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  8262. const auto &seg = state->segs[seg_idx];
  8263. size_t available = seg.size - seg_offset;
  8264. size_t to_copy = (std::min)(available, remaining);
  8265. const char *src = seg.data + seg_offset;
  8266. seg_offset = 0; // only the first segment has a non-zero offset
  8267. while (to_copy > 0) {
  8268. size_t space = buf_size - buf_len;
  8269. size_t chunk = (std::min)(to_copy, space);
  8270. std::memcpy(buf.data() + buf_len, src, chunk);
  8271. buf_len += chunk;
  8272. src += chunk;
  8273. to_copy -= chunk;
  8274. remaining -= chunk;
  8275. if (buf_len == buf_size) {
  8276. if (!sink.write(buf.data(), buf_len)) { return false; }
  8277. buf_len = 0;
  8278. }
  8279. }
  8280. }
  8281. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  8282. return true;
  8283. };
  8284. }
  8285. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  8286. if (ranges.size() <= 1) return;
  8287. // Sort ranges by start position
  8288. std::sort(ranges.begin(), ranges.end(),
  8289. [](const Range &a, const Range &b) { return a.first < b.first; });
  8290. Ranges coalesced;
  8291. coalesced.reserve(ranges.size());
  8292. for (auto &r : ranges) {
  8293. auto first_pos = r.first;
  8294. auto last_pos = r.second;
  8295. // Handle special cases like in range_error
  8296. if (first_pos == -1 && last_pos == -1) {
  8297. first_pos = 0;
  8298. last_pos = static_cast<ssize_t>(content_length);
  8299. }
  8300. if (first_pos == -1) {
  8301. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  8302. last_pos = static_cast<ssize_t>(content_length) - 1;
  8303. }
  8304. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  8305. last_pos = static_cast<ssize_t>(content_length) - 1;
  8306. }
  8307. // Skip invalid ranges
  8308. if (!(0 <= first_pos && first_pos <= last_pos &&
  8309. last_pos < static_cast<ssize_t>(content_length))) {
  8310. continue;
  8311. }
  8312. // Coalesce with previous range if overlapping or adjacent (but not
  8313. // identical)
  8314. if (!coalesced.empty()) {
  8315. auto &prev = coalesced.back();
  8316. // Check if current range overlaps or is adjacent to previous range
  8317. // but don't coalesce identical ranges (allow duplicates)
  8318. if (first_pos <= prev.second + 1 &&
  8319. !(first_pos == prev.first && last_pos == prev.second)) {
  8320. // Extend the previous range
  8321. prev.second = (std::max)(prev.second, last_pos);
  8322. continue;
  8323. }
  8324. }
  8325. // Add new range
  8326. coalesced.emplace_back(first_pos, last_pos);
  8327. }
  8328. ranges = std::move(coalesced);
  8329. }
  8330. inline bool range_error(Request &req, Response &res) {
  8331. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  8332. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  8333. req.ranges.clear();
  8334. if (res.status == StatusCode::PartialContent_206) {
  8335. res.status = StatusCode::OK_200;
  8336. }
  8337. return false;
  8338. }
  8339. ssize_t content_len = static_cast<ssize_t>(
  8340. res.content_length_ ? res.content_length_ : res.body.size());
  8341. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  8342. size_t overwrapping_count = 0;
  8343. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  8344. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  8345. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  8346. // Too many ranges
  8347. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  8348. for (auto &r : req.ranges) {
  8349. auto &first_pos = r.first;
  8350. auto &last_pos = r.second;
  8351. if (first_pos == -1 && last_pos == -1) {
  8352. first_pos = 0;
  8353. last_pos = content_len;
  8354. }
  8355. // RFC 9110 14.1.2: a suffix-length longer than the representation
  8356. // selects the entire representation.
  8357. if (first_pos == -1) {
  8358. first_pos = (std::max)(static_cast<ssize_t>(0), content_len - last_pos);
  8359. last_pos = content_len - 1;
  8360. }
  8361. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  8362. // A client can limit the number of bytes requested without knowing the
  8363. // size of the selected representation. If the last-pos value is absent,
  8364. // or if the value is greater than or equal to the current length of the
  8365. // representation data, the byte range is interpreted as the remainder of
  8366. // the representation (i.e., the server replaces the value of last-pos
  8367. // with a value that is one less than the current length of the selected
  8368. // representation).
  8369. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  8370. if (last_pos == -1 || last_pos >= content_len) {
  8371. last_pos = content_len - 1;
  8372. }
  8373. // Range must be within content length
  8374. if (!(0 <= first_pos && first_pos <= last_pos &&
  8375. last_pos <= content_len - 1)) {
  8376. return true;
  8377. }
  8378. // Request must not have more than two overlapping ranges
  8379. for (const auto &processed_range : processed_ranges) {
  8380. if (!(last_pos < processed_range.first ||
  8381. first_pos > processed_range.second)) {
  8382. overwrapping_count++;
  8383. if (overwrapping_count > 2) { return true; }
  8384. break; // Only count once per range
  8385. }
  8386. }
  8387. processed_ranges.emplace_back(first_pos, last_pos);
  8388. }
  8389. // After validation, coalesce overlapping ranges as per RFC 9110
  8390. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  8391. }
  8392. return false;
  8393. }
  8394. inline std::pair<size_t, size_t>
  8395. get_range_offset_and_length(Range r, size_t content_length) {
  8396. assert(r.first != -1 && r.second != -1);
  8397. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  8398. assert(r.first <= r.second &&
  8399. r.second < static_cast<ssize_t>(content_length));
  8400. (void)(content_length);
  8401. return std::make_pair(static_cast<size_t>(r.first),
  8402. static_cast<size_t>(r.second - r.first) + 1);
  8403. }
  8404. inline std::string make_content_range_header_field(
  8405. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  8406. auto st = offset_and_length.first;
  8407. auto ed = st + offset_and_length.second - 1;
  8408. std::string field = "bytes ";
  8409. field += std::to_string(st);
  8410. field += '-';
  8411. field += std::to_string(ed);
  8412. field += '/';
  8413. field += std::to_string(content_length);
  8414. return field;
  8415. }
  8416. template <typename SToken, typename CToken, typename Content>
  8417. bool process_multipart_ranges_data(const Request &req,
  8418. const std::string &boundary,
  8419. const std::string &content_type,
  8420. size_t content_length, SToken stoken,
  8421. CToken ctoken, Content content) {
  8422. for (size_t i = 0; i < req.ranges.size(); i++) {
  8423. ctoken("--");
  8424. stoken(boundary);
  8425. ctoken("\r\n");
  8426. if (!content_type.empty()) {
  8427. ctoken("Content-Type: ");
  8428. stoken(content_type);
  8429. ctoken("\r\n");
  8430. }
  8431. auto offset_and_length =
  8432. get_range_offset_and_length(req.ranges[i], content_length);
  8433. ctoken("Content-Range: ");
  8434. stoken(make_content_range_header_field(offset_and_length, content_length));
  8435. ctoken("\r\n");
  8436. ctoken("\r\n");
  8437. if (!content(offset_and_length.first, offset_and_length.second)) {
  8438. return false;
  8439. }
  8440. ctoken("\r\n");
  8441. }
  8442. ctoken("--");
  8443. stoken(boundary);
  8444. ctoken("--");
  8445. return true;
  8446. }
  8447. inline void make_multipart_ranges_data(const Request &req, Response &res,
  8448. const std::string &boundary,
  8449. const std::string &content_type,
  8450. size_t content_length,
  8451. std::string &data) {
  8452. process_multipart_ranges_data(
  8453. req, boundary, content_type, content_length,
  8454. [&](const std::string &token) { data += token; },
  8455. [&](const std::string &token) { data += token; },
  8456. [&](size_t offset, size_t length) {
  8457. assert(offset + length <= content_length);
  8458. data += res.body.substr(offset, length);
  8459. return true;
  8460. });
  8461. }
  8462. inline size_t get_multipart_ranges_data_length(const Request &req,
  8463. const std::string &boundary,
  8464. const std::string &content_type,
  8465. size_t content_length) {
  8466. size_t data_length = 0;
  8467. process_multipart_ranges_data(
  8468. req, boundary, content_type, content_length,
  8469. [&](const std::string &token) { data_length += token.size(); },
  8470. [&](const std::string &token) { data_length += token.size(); },
  8471. [&](size_t /*offset*/, size_t length) {
  8472. data_length += length;
  8473. return true;
  8474. });
  8475. return data_length;
  8476. }
  8477. template <typename T>
  8478. inline bool
  8479. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  8480. const std::string &boundary,
  8481. const std::string &content_type,
  8482. size_t content_length, const T &is_shutting_down) {
  8483. return process_multipart_ranges_data(
  8484. req, boundary, content_type, content_length,
  8485. [&](const std::string &token) { strm.write(token); },
  8486. [&](const std::string &token) { strm.write(token); },
  8487. [&](size_t offset, size_t length) {
  8488. return write_content(strm, res.content_provider_, offset, length,
  8489. is_shutting_down);
  8490. });
  8491. }
  8492. inline bool has_framed_body(const Request &req) {
  8493. return is_chunked_transfer_encoding(req.headers) ||
  8494. req.get_header_value_u64("Content-Length") > 0;
  8495. }
  8496. inline bool is_connection_persistent(const Request &req) {
  8497. if (has_header_token(req.headers, "Connection", "close")) { return false; }
  8498. if (req.version == "HTTP/1.0" &&
  8499. !has_header_token(req.headers, "Connection", "keep-alive")) {
  8500. return false;
  8501. }
  8502. return true;
  8503. }
  8504. inline bool expect_content(const Request &req) {
  8505. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  8506. req.method == "DELETE") {
  8507. return true;
  8508. }
  8509. return has_framed_body(req);
  8510. }
  8511. #ifdef _WIN32
  8512. class WSInit {
  8513. public:
  8514. WSInit() {
  8515. WSADATA wsaData;
  8516. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  8517. }
  8518. ~WSInit() {
  8519. if (is_valid_) WSACleanup();
  8520. }
  8521. bool is_valid_ = false;
  8522. };
  8523. static WSInit wsinit_;
  8524. #endif
  8525. // RFC 9110 Section 11.6.1 defines a challenge list as
  8526. // WWW-Authenticate = #challenge
  8527. // challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
  8528. // auth-param = token BWS "=" BWS ( token / quoted-string )
  8529. // so a server may offer several schemes, each with its own comma-separated
  8530. // auth-param list, in either order and either as separate field lines or
  8531. // packed into one. Splitting on every comma would break apart a challenge's
  8532. // own param list; splitting only on the first space would miss a Digest
  8533. // challenge that isn't first. Split on commas that aren't inside a
  8534. // quoted-string instead, then track which scheme each resulting segment
  8535. // belongs to: a segment whose text before "=" contains whitespace (or that
  8536. // has no "=" at all) starts a new challenge named by its leading token.
  8537. inline std::vector<std::string> split_challenge_segments(const std::string &s) {
  8538. std::vector<std::string> segments;
  8539. size_t start = 0;
  8540. auto in_quotes = false;
  8541. for (size_t i = 0; i < s.size(); i++) {
  8542. auto c = s[i];
  8543. if (in_quotes) {
  8544. if (c == '\\' && i + 1 < s.size()) {
  8545. i++;
  8546. } else if (c == '"') {
  8547. in_quotes = false;
  8548. }
  8549. } else if (c == '"') {
  8550. in_quotes = true;
  8551. } else if (c == ',') {
  8552. segments.push_back(s.substr(start, i - start));
  8553. start = i + 1;
  8554. }
  8555. }
  8556. segments.push_back(s.substr(start));
  8557. return segments;
  8558. }
  8559. inline std::string unescape_quoted_pairs(const std::string &s) {
  8560. std::string out;
  8561. out.reserve(s.size());
  8562. for (size_t i = 0; i < s.size(); i++) {
  8563. if (s[i] == '\\' && i + 1 < s.size()) {
  8564. out += s[++i];
  8565. } else {
  8566. out += s[i];
  8567. }
  8568. }
  8569. return out;
  8570. }
  8571. // Inverse of unescape_quoted_pairs: prepares a value to sit inside a
  8572. // quoted-string. RFC 9110 §5.6.4 requires a literal '\' or '"' to be sent as a
  8573. // quoted-pair, so the recipient recovers the original value.
  8574. inline std::string escape_quoted_pairs(const std::string &s) {
  8575. std::string out;
  8576. out.reserve(s.size());
  8577. for (auto c : s) {
  8578. if (c == '\\' || c == '"') { out += '\\'; }
  8579. out += c;
  8580. }
  8581. return out;
  8582. }
  8583. inline bool parse_www_authenticate(const Response &res,
  8584. std::map<std::string, std::string> &auth,
  8585. bool is_proxy) {
  8586. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  8587. auto combined = get_combined_header_value(res.headers, auth_key);
  8588. if (combined.empty()) { return false; }
  8589. auto found_digest = false;
  8590. auto in_digest_challenge = false;
  8591. for (const auto &raw_segment : split_challenge_segments(combined)) {
  8592. auto segment = trim_copy(raw_segment);
  8593. if (segment.empty()) { continue; }
  8594. auto eq_pos = segment.find('=');
  8595. // BWS is allowed on both sides of "=", so the text naming the key (or,
  8596. // for the first segment of a challenge, "<scheme> <key>") must be
  8597. // trimmed before its boundaries are inspected.
  8598. auto key_part = trim_copy(
  8599. eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
  8600. auto space_pos = key_part.find_last_of(" \t");
  8601. if (space_pos != std::string::npos || eq_pos == std::string::npos) {
  8602. // "<scheme>[ <key>]" starts a new challenge.
  8603. auto scheme_end =
  8604. space_pos == std::string::npos ? key_part.size() : space_pos;
  8605. // RFC 7616 Section 3.7: a server may offer more than one Digest
  8606. // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
  8607. // from one challenge is never paired with another's algorithm.
  8608. in_digest_challenge =
  8609. !found_digest &&
  8610. case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
  8611. if (in_digest_challenge) { found_digest = true; }
  8612. if (space_pos == std::string::npos) {
  8613. // Bare scheme (or a token68), no auth-param on this segment.
  8614. continue;
  8615. }
  8616. key_part = key_part.substr(space_pos + 1);
  8617. }
  8618. if (!in_digest_challenge) { continue; }
  8619. auto val = trim_copy(segment.substr(eq_pos + 1));
  8620. auto unquoted = trim_double_quotes_copy(val);
  8621. if (unquoted.size() != val.size()) {
  8622. unquoted = unescape_quoted_pairs(unquoted);
  8623. }
  8624. auth[std::move(key_part)] = std::move(unquoted);
  8625. }
  8626. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
  8627. // make_digest_authentication_header() dereferences both unconditionally, so
  8628. // a challenge missing either can't produce a usable Authorization header.
  8629. // Treat it the same as no Digest challenge at all.
  8630. return found_digest && auth.find("realm") != auth.end() &&
  8631. auth.find("nonce") != auth.end();
  8632. }
  8633. class ContentProviderAdapter {
  8634. public:
  8635. explicit ContentProviderAdapter(
  8636. ContentProviderWithoutLength &&content_provider)
  8637. : content_provider_(std::move(content_provider)) {}
  8638. bool operator()(size_t offset, size_t, DataSink &sink) {
  8639. return content_provider_(offset, sink);
  8640. }
  8641. private:
  8642. ContentProviderWithoutLength content_provider_;
  8643. };
  8644. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  8645. namespace fields {
  8646. inline bool is_token_char(char c) {
  8647. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  8648. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  8649. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  8650. }
  8651. inline bool is_token(const std::string &s) {
  8652. if (s.empty()) { return false; }
  8653. for (auto c : s) {
  8654. if (!is_token_char(c)) { return false; }
  8655. }
  8656. return true;
  8657. }
  8658. inline bool is_field_name(const std::string &s) { return is_token(s); }
  8659. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  8660. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  8661. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  8662. inline bool is_field_content(const std::string &s) {
  8663. if (s.empty()) { return true; }
  8664. if (s.size() == 1) {
  8665. return is_field_vchar(s[0]);
  8666. } else if (s.size() == 2) {
  8667. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  8668. } else {
  8669. size_t i = 0;
  8670. if (!is_field_vchar(s[i])) { return false; }
  8671. i++;
  8672. while (i < s.size() - 1) {
  8673. auto c = s[i++];
  8674. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  8675. } else {
  8676. return false;
  8677. }
  8678. }
  8679. return is_field_vchar(s[i]);
  8680. }
  8681. }
  8682. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  8683. inline bool is_field_valid(const std::string &name, const std::string &value) {
  8684. return is_field_name(name) && is_field_value(value);
  8685. }
  8686. // RFC 9112 §2.2/§3.2: the request-target has no SP, HTAB or other control
  8687. // characters (incl. bare CR). obs-text (raw UTF-8) is allowed.
  8688. inline bool is_request_target(const std::string &s) {
  8689. return std::all_of(s.begin(), s.end(), is_field_vchar);
  8690. }
  8691. // RFC 9110 §7.2: the bytes of uri-host [ ":" port ], i.e. unreserved,
  8692. // sub-delims, "%", ":" and the IP-literal brackets. An empty value is valid.
  8693. inline bool is_host(const std::string &s) {
  8694. return std::all_of(s.begin(), s.end(), [](char c) {
  8695. return is_ascii_alnum(c) || c == '-' || c == '.' || c == '_' || c == '~' ||
  8696. c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8697. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8698. c == '=' || c == '%' || c == ':' || c == '[' || c == ']';
  8699. });
  8700. }
  8701. } // namespace fields
  8702. inline bool perform_websocket_handshake(Stream &strm, Request &req,
  8703. WebSocketUpgradeResponse &upgrade) {
  8704. // Generate a random 16-byte Sec-WebSocket-Key (RFC 6455 Section 4.1)
  8705. std::string key_bytes(16, '\0');
  8706. fill_random_bytes(reinterpret_cast<unsigned char *>(&key_bytes[0]),
  8707. key_bytes.size());
  8708. auto client_key = base64_encode(key_bytes);
  8709. req.headers.erase("Upgrade");
  8710. req.headers.erase("Connection");
  8711. req.headers.erase("Sec-WebSocket-Key");
  8712. req.headers.erase("Sec-WebSocket-Version");
  8713. req.headers.emplace("Upgrade", "websocket");
  8714. req.headers.emplace("Connection", "Upgrade");
  8715. req.headers.emplace("Sec-WebSocket-Key", client_key);
  8716. req.headers.emplace("Sec-WebSocket-Version", "13");
  8717. // Build the request in memory first, like ClientImpl::write_request does.
  8718. // Writing straight to the socket would leak a request line onto the wire
  8719. // before check_and_write_headers gets a chance to reject an invalid header,
  8720. // and would emit one small write per header.
  8721. BufferStream bstrm;
  8722. if (write_request_line(bstrm, req.method, req.path) < 0) {
  8723. upgrade.error = Error::Write;
  8724. return false;
  8725. }
  8726. auto error = Error::Success;
  8727. if (!check_and_write_headers(bstrm, req.headers, write_headers, error)) {
  8728. upgrade.error = error;
  8729. return false;
  8730. }
  8731. const auto &data = bstrm.get_buffer();
  8732. if (!write_data(strm, data.data(), data.size())) {
  8733. upgrade.error = Error::Write;
  8734. return false;
  8735. }
  8736. // Verify 101 response and Sec-WebSocket-Accept header
  8737. auto expected_accept = websocket_accept_key(client_key);
  8738. auto offered_subprotocols =
  8739. get_combined_header_value(req.headers, "Sec-WebSocket-Protocol");
  8740. return read_websocket_upgrade_response(strm, expected_accept,
  8741. offered_subprotocols, upgrade);
  8742. }
  8743. inline bool is_ip_address(const std::string &host) {
  8744. struct in_addr addr4;
  8745. struct in6_addr addr6;
  8746. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  8747. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  8748. }
  8749. // Resolve where a client should connect for `host`, honoring a user-supplied
  8750. // hostname-to-address map. `host` itself is never rewritten, so it keeps
  8751. // supplying the Host header and SNI; only the connection target changes.
  8752. //
  8753. // A mapped IP literal goes to `ip`, which keeps create_socket's AI_NUMERICHOST
  8754. // path. Anything else goes to `connect_host`, which create_socket resolves as
  8755. // a name, or uses as the socket path when the address family is AF_UNIX. An
  8756. // absent or empty mapping leaves `host` as the connection target; without the
  8757. // empty check the value would reach getaddrinfo as a null node and silently
  8758. // resolve to loopback.
  8759. inline void apply_addr_map(const std::map<std::string, std::string> &addr_map,
  8760. const std::string &host, std::string &connect_host,
  8761. std::string &ip) {
  8762. connect_host = host;
  8763. ip.clear();
  8764. auto it = addr_map.find(host);
  8765. if (it == addr_map.end() || it->second.empty()) { return; }
  8766. if (is_ip_address(it->second)) {
  8767. ip = it->second;
  8768. } else {
  8769. connect_host = it->second;
  8770. }
  8771. }
  8772. } // namespace detail
  8773. /*
  8774. * Group 2: detail namespace - SSL common utilities
  8775. */
  8776. #ifdef CPPHTTPLIB_SSL_ENABLED
  8777. namespace detail {
  8778. class SSLSocketStream final : public Stream {
  8779. public:
  8780. SSLSocketStream(
  8781. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8782. time_t read_timeout_usec, time_t write_timeout_sec,
  8783. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  8784. std::chrono::time_point<std::chrono::steady_clock> start_time =
  8785. (std::chrono::steady_clock::time_point::min)());
  8786. ~SSLSocketStream() override;
  8787. bool is_readable() const override;
  8788. bool wait_readable() const override;
  8789. bool wait_writable() const override;
  8790. bool is_peer_alive() const override;
  8791. ssize_t read(char *ptr, size_t size) override;
  8792. ssize_t write(const char *ptr, size_t size) override;
  8793. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8794. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8795. socket_t socket() const override;
  8796. time_t duration() const override;
  8797. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8798. // See SocketStream::set_readable_hint().
  8799. void set_readable_hint() { readable_hint_ = true; }
  8800. private:
  8801. bool ensure_readable();
  8802. socket_t sock_;
  8803. tls::session_t session_;
  8804. time_t read_timeout_sec_;
  8805. time_t read_timeout_usec_;
  8806. time_t write_timeout_sec_;
  8807. time_t write_timeout_usec_;
  8808. time_t max_timeout_msec_;
  8809. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8810. bool readable_hint_ = false;
  8811. };
  8812. // A TLS stream for WebSocket connections, where the receive path and the
  8813. // send path (application send() plus the heartbeat ping thread) run on
  8814. // different threads. A single TLS session must never be entered
  8815. // concurrently, so every call into the session is serialized by one mutex.
  8816. //
  8817. // Unlike SSLSocketStream, the socket is kept non-blocking for the stream's
  8818. // whole lifetime and each read()/write() performs a single non-blocking TLS
  8819. // call under the lock, then waits for readiness with select() outside the
  8820. // lock. The lock is therefore held only for CPU-bound work, so a reader
  8821. // blocked waiting for data never stalls a concurrent sender.
  8822. //
  8823. // This stream is used only for wss:// connections. Plain ws:// and ordinary
  8824. // HTTP/HTTPS keep using SocketStream/SSLSocketStream unchanged.
  8825. class WebSocketSSLStream final : public Stream {
  8826. public:
  8827. WebSocketSSLStream(socket_t sock, tls::session_t session,
  8828. time_t read_timeout_sec, time_t read_timeout_usec,
  8829. time_t write_timeout_sec, time_t write_timeout_usec);
  8830. ~WebSocketSSLStream() override;
  8831. bool is_readable() const override;
  8832. bool wait_readable() const override;
  8833. bool wait_writable() const override;
  8834. ssize_t read(char *ptr, size_t size) override;
  8835. ssize_t write(const char *ptr, size_t size) override;
  8836. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8837. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8838. socket_t socket() const override;
  8839. time_t duration() const override;
  8840. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8841. private:
  8842. mutable std::mutex session_mutex_;
  8843. socket_t sock_;
  8844. tls::session_t session_;
  8845. // WebSocket::close() shortens the read timeout from the closing thread
  8846. // while the receive thread is inside wait_readable(), so these two are read
  8847. // and written concurrently. The write timeouts are never mutated.
  8848. std::atomic<time_t> read_timeout_sec_;
  8849. std::atomic<time_t> read_timeout_usec_;
  8850. time_t write_timeout_sec_;
  8851. time_t write_timeout_usec_;
  8852. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8853. };
  8854. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8855. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  8856. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  8857. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  8858. unsigned int hash_length = 0;
  8859. unsigned char hash[EVP_MAX_MD_SIZE];
  8860. EVP_DigestInit_ex(context.get(), algo, nullptr);
  8861. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  8862. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  8863. std::stringstream ss;
  8864. for (auto i = 0u; i < hash_length; ++i) {
  8865. ss << std::hex << std::setw(2) << std::setfill('0')
  8866. << static_cast<unsigned int>(hash[i]);
  8867. }
  8868. return ss.str();
  8869. }
  8870. inline std::string MD5(const std::string &s) {
  8871. return message_digest(s, EVP_md5());
  8872. }
  8873. inline std::string SHA_256(const std::string &s) {
  8874. return message_digest(s, EVP_sha256());
  8875. }
  8876. inline std::string SHA_512(const std::string &s) {
  8877. return message_digest(s, EVP_sha512());
  8878. }
  8879. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  8880. namespace {
  8881. template <size_t N>
  8882. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8883. std::stringstream ss;
  8884. for (size_t i = 0; i < N; ++i) {
  8885. ss << std::hex << std::setw(2) << std::setfill('0')
  8886. << static_cast<unsigned int>(hash[i]);
  8887. }
  8888. return ss.str();
  8889. }
  8890. } // namespace
  8891. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8892. // Mbed TLS 4.x provides hashing (and TLS RNG) via PSA Crypto, which must be
  8893. // initialized once. PSA state is process-global; do not free it.
  8894. inline bool ensure_mbedtls_psa_crypto() {
  8895. static std::once_flag once;
  8896. static bool ok = false;
  8897. std::call_once(once, []() { ok = (psa_crypto_init() == PSA_SUCCESS); });
  8898. return ok;
  8899. }
  8900. inline bool psa_hash(psa_algorithm_t alg, const std::string &s,
  8901. unsigned char *out, size_t out_size) {
  8902. if (!ensure_mbedtls_psa_crypto()) { return false; }
  8903. size_t olen = 0;
  8904. return psa_hash_compute(alg, reinterpret_cast<const uint8_t *>(s.data()),
  8905. s.size(), out, out_size, &olen) == PSA_SUCCESS &&
  8906. olen == out_size;
  8907. }
  8908. #endif
  8909. inline std::string MD5(const std::string &s) {
  8910. unsigned char hash[16];
  8911. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8912. if (!psa_hash(PSA_ALG_MD5, s, hash, sizeof(hash))) { return {}; }
  8913. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8914. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8915. hash);
  8916. #else
  8917. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8918. hash);
  8919. #endif
  8920. return hash_to_hex(hash);
  8921. }
  8922. inline std::string SHA_256(const std::string &s) {
  8923. unsigned char hash[32];
  8924. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8925. if (!psa_hash(PSA_ALG_SHA_256, s, hash, sizeof(hash))) { return {}; }
  8926. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8927. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8928. hash, 0);
  8929. #else
  8930. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8931. s.size(), hash, 0);
  8932. #endif
  8933. return hash_to_hex(hash);
  8934. }
  8935. inline std::string SHA_512(const std::string &s) {
  8936. unsigned char hash[64];
  8937. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8938. if (!psa_hash(PSA_ALG_SHA_512, s, hash, sizeof(hash))) { return {}; }
  8939. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8940. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8941. hash, 0);
  8942. #else
  8943. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8944. s.size(), hash, 0);
  8945. #endif
  8946. return hash_to_hex(hash);
  8947. }
  8948. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  8949. namespace {
  8950. template <size_t N>
  8951. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8952. std::stringstream ss;
  8953. for (size_t i = 0; i < N; ++i) {
  8954. ss << std::hex << std::setw(2) << std::setfill('0')
  8955. << static_cast<unsigned int>(hash[i]);
  8956. }
  8957. return ss.str();
  8958. }
  8959. } // namespace
  8960. inline std::string MD5(const std::string &s) {
  8961. unsigned char hash[WC_MD5_DIGEST_SIZE];
  8962. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8963. static_cast<word32>(s.size()), hash);
  8964. return hash_to_hex(hash);
  8965. }
  8966. inline std::string SHA_256(const std::string &s) {
  8967. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  8968. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8969. static_cast<word32>(s.size()), hash);
  8970. return hash_to_hex(hash);
  8971. }
  8972. inline std::string SHA_512(const std::string &s) {
  8973. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  8974. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8975. static_cast<word32>(s.size()), hash);
  8976. return hash_to_hex(hash);
  8977. }
  8978. #endif
  8979. template <typename T>
  8980. inline bool process_server_socket_ssl(
  8981. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  8982. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8983. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8984. time_t write_timeout_usec, T callback) {
  8985. // See process_server_socket(). The TLS library keeps already decrypted bytes
  8986. // of a pipelined request, which keep_alive() cannot see on the socket.
  8987. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  8988. write_timeout_sec, write_timeout_usec);
  8989. return process_server_socket_core(
  8990. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8991. [&]() { return strm.is_readable(); },
  8992. [&](bool socket_readable, bool close_connection,
  8993. bool &connection_closed) {
  8994. if (socket_readable) { strm.set_readable_hint(); }
  8995. return callback(strm, close_connection, connection_closed);
  8996. });
  8997. }
  8998. template <typename T>
  8999. inline bool process_client_socket_ssl(
  9000. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  9001. time_t read_timeout_usec, time_t write_timeout_sec,
  9002. time_t write_timeout_usec, time_t max_timeout_msec,
  9003. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  9004. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  9005. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  9006. start_time);
  9007. return callback(strm);
  9008. }
  9009. inline std::pair<std::string, std::string> make_digest_authentication_header(
  9010. const Request &req, const std::map<std::string, std::string> &auth,
  9011. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  9012. const std::string &password, bool is_proxy = false) {
  9013. std::string nc;
  9014. {
  9015. std::stringstream ss;
  9016. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  9017. nc = ss.str();
  9018. }
  9019. std::string qop;
  9020. if (auth.find("qop") != auth.end()) {
  9021. qop = auth.at("qop");
  9022. if (qop.find("auth-int") != std::string::npos) {
  9023. qop = "auth-int";
  9024. } else if (qop.find("auth") != std::string::npos) {
  9025. qop = "auth";
  9026. } else {
  9027. qop.clear();
  9028. }
  9029. }
  9030. std::string algo = "MD5";
  9031. if (auth.find("algorithm") != auth.end()) {
  9032. // algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
  9033. // not a token would otherwise be emitted verbatim and could carry commas
  9034. // or quotes that inject further auth-params into the header below.
  9035. const auto &a = auth.at("algorithm");
  9036. if (fields::is_token(a)) { algo = a; }
  9037. }
  9038. std::string response;
  9039. {
  9040. auto H = algo == "SHA-256" ? detail::SHA_256
  9041. : algo == "SHA-512" ? detail::SHA_512
  9042. : detail::MD5;
  9043. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  9044. auto A2 = req.method + ":" + req.path;
  9045. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  9046. if (qop.empty()) {
  9047. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  9048. } else {
  9049. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  9050. ":" + qop + ":" + H(A2));
  9051. }
  9052. }
  9053. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  9054. // Every value placed inside a quoted-string is escaped so a '"' in it cannot
  9055. // close the string early. realm, nonce and opaque come straight from the
  9056. // server's challenge (parse_www_authenticate() already de-escaped them), so
  9057. // without this a crafted challenge injects extra auth-params into the header.
  9058. auto field =
  9059. "Digest username=\"" + detail::escape_quoted_pairs(username) +
  9060. "\", realm=\"" + detail::escape_quoted_pairs(auth.at("realm")) +
  9061. "\", nonce=\"" + detail::escape_quoted_pairs(auth.at("nonce")) +
  9062. "\", uri=\"" + detail::escape_quoted_pairs(req.path) +
  9063. "\", algorithm=" + algo +
  9064. (qop.empty() ? ", response=\""
  9065. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce +
  9066. "\", response=\"") +
  9067. response + "\"" +
  9068. (opaque.empty()
  9069. ? ""
  9070. : ", opaque=\"" + detail::escape_quoted_pairs(opaque) + "\"");
  9071. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9072. return std::make_pair(key, field);
  9073. }
  9074. inline bool match_hostname(const std::string &pattern,
  9075. const std::string &hostname) {
  9076. // Exact match (case-insensitive)
  9077. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  9078. // Split both pattern and hostname into components by '.'
  9079. std::vector<std::string> pattern_components;
  9080. if (!pattern.empty()) {
  9081. split(pattern.data(), pattern.data() + pattern.size(), '.',
  9082. [&](const char *b, const char *e) {
  9083. pattern_components.emplace_back(b, e);
  9084. });
  9085. }
  9086. std::vector<std::string> host_components;
  9087. if (!hostname.empty()) {
  9088. split(hostname.data(), hostname.data() + hostname.size(), '.',
  9089. [&](const char *b, const char *e) {
  9090. host_components.emplace_back(b, e);
  9091. });
  9092. }
  9093. // Component count must match
  9094. if (host_components.size() != pattern_components.size()) { return false; }
  9095. // Compare each component with wildcard support
  9096. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  9097. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  9098. // Only the leftmost label may carry a wildcard (RFC 6125 6.4.3)
  9099. auto itr = pattern_components.begin();
  9100. for (const auto &h : host_components) {
  9101. auto &p = *itr;
  9102. auto is_leftmost = itr == pattern_components.begin();
  9103. if (!detail::case_ignore::equal(p, h) && !(is_leftmost && p == "*")) {
  9104. bool partial_match = false;
  9105. if (is_leftmost && !p.empty() && p[p.size() - 1] == '*') {
  9106. const auto prefix_length = p.size() - 1;
  9107. if (prefix_length == 0) {
  9108. partial_match = true;
  9109. } else if (h.size() >= prefix_length) {
  9110. partial_match =
  9111. std::equal(p.begin(),
  9112. p.begin() + static_cast<std::string::difference_type>(
  9113. prefix_length),
  9114. h.begin(), [](const char ca, const char cb) {
  9115. return detail::case_ignore::to_lower(ca) ==
  9116. detail::case_ignore::to_lower(cb);
  9117. });
  9118. }
  9119. }
  9120. if (!partial_match) { return false; }
  9121. }
  9122. ++itr;
  9123. }
  9124. return true;
  9125. }
  9126. #ifdef _WIN32
  9127. // Verify certificate using Windows CertGetCertificateChain API.
  9128. // This provides real-time certificate validation with Windows Update
  9129. // integration, independent of the TLS backend.
  9130. inline bool verify_cert_with_windows_schannel(
  9131. const std::vector<unsigned char> &der_cert, const std::string &hostname,
  9132. bool verify_hostname, uint64_t &out_error, tls::const_session_t session) {
  9133. if (der_cert.empty()) { return false; }
  9134. out_error = 0;
  9135. // Create Windows certificate context from DER data
  9136. auto cert_context = CertCreateCertificateContext(
  9137. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  9138. static_cast<DWORD>(der_cert.size()));
  9139. if (!cert_context) {
  9140. out_error = GetLastError();
  9141. return false;
  9142. }
  9143. auto cert_guard =
  9144. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  9145. // Give CryptoAPI the certificates the server sent. Without them it follows
  9146. // the leaf's AIA URL, which may lead to an issuer under an untrusted root.
  9147. std::vector<tls::cert_t> peer_certs;
  9148. tls::get_peer_certs(session, peer_certs);
  9149. auto store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, nullptr);
  9150. auto store_guard = scope_exit([&] {
  9151. for (auto cert : peer_certs) {
  9152. tls::free_cert(cert);
  9153. }
  9154. if (store) { CertCloseStore(store, 0); }
  9155. });
  9156. for (auto cert : peer_certs) {
  9157. std::vector<unsigned char> der;
  9158. if (store && tls::get_cert_der(cert, der)) {
  9159. CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING, der.data(),
  9160. static_cast<DWORD>(der.size()),
  9161. CERT_STORE_ADD_USE_EXISTING, nullptr);
  9162. }
  9163. }
  9164. // Setup chain parameters
  9165. CERT_CHAIN_PARA chain_para = {};
  9166. chain_para.cbSize = sizeof(chain_para);
  9167. // Require the server authentication usage along the chain, which also
  9168. // rejects roots that Windows trusts only for other purposes.
  9169. LPSTR server_auth = const_cast<LPSTR>(szOID_PKIX_KP_SERVER_AUTH);
  9170. chain_para.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
  9171. chain_para.RequestedUsage.Usage.cUsageIdentifier = 1;
  9172. chain_para.RequestedUsage.Usage.rgpszUsageIdentifier = &server_auth;
  9173. // Build certificate chain with revocation checking
  9174. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  9175. auto chain_result = CertGetCertificateChain(
  9176. nullptr, cert_context, nullptr, store, &chain_para,
  9177. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  9178. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  9179. nullptr, &chain_context);
  9180. if (!chain_result || !chain_context) {
  9181. out_error = GetLastError();
  9182. return false;
  9183. }
  9184. auto chain_guard =
  9185. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  9186. // Verify SSL policy
  9187. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  9188. extra_policy_para.cbSize = sizeof(extra_policy_para);
  9189. #ifdef AUTHTYPE_SERVER
  9190. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  9191. #endif
  9192. std::wstring whost;
  9193. if (verify_hostname) {
  9194. whost = u8string_to_wstring(hostname.c_str());
  9195. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  9196. }
  9197. CERT_CHAIN_POLICY_PARA policy_para = {};
  9198. policy_para.cbSize = sizeof(policy_para);
  9199. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  9200. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  9201. #else
  9202. policy_para.dwFlags = 0;
  9203. #endif
  9204. policy_para.pvExtraPolicyPara = &extra_policy_para;
  9205. CERT_CHAIN_POLICY_STATUS policy_status = {};
  9206. policy_status.cbSize = sizeof(policy_status);
  9207. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  9208. &policy_para, &policy_status)) {
  9209. out_error = GetLastError();
  9210. return false;
  9211. }
  9212. if (policy_status.dwError != 0) {
  9213. out_error = policy_status.dwError;
  9214. return false;
  9215. }
  9216. return true;
  9217. }
  9218. #endif // _WIN32
  9219. // Loads CA file/dir configuration and applies the system CA policy to a
  9220. // client TLS context. PEM data and native stores are applied to the context
  9221. // directly at set time; has_custom_store reflects them for the Auto policy
  9222. // decision.
  9223. inline bool load_client_ca_config(tls::ctx_t ctx,
  9224. const std::string &ca_cert_file_path,
  9225. const std::string &ca_cert_dir_path,
  9226. bool has_custom_store, SystemCAMode mode,
  9227. uint64_t &backend_error) {
  9228. auto ret = true;
  9229. if (!ca_cert_file_path.empty()) {
  9230. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  9231. backend_error = tls::get_error();
  9232. ret = false;
  9233. }
  9234. } else if (!ca_cert_dir_path.empty()) {
  9235. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  9236. backend_error = tls::get_error();
  9237. ret = false;
  9238. }
  9239. }
  9240. auto has_custom_ca = !ca_cert_file_path.empty() ||
  9241. !ca_cert_dir_path.empty() || has_custom_store;
  9242. if (mode == SystemCAMode::Enabled ||
  9243. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  9244. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  9245. }
  9246. return ret;
  9247. }
  9248. // The parts of session setup that only SSLClient needs, plus the handful
  9249. // WebSocketClient also exposes; everything else takes the defaults, which is
  9250. // what keeps the two clients on one implementation.
  9251. struct ClientTlsSessionOptions {
  9252. // Both SSLClient and WebSocketClient expose this independently of
  9253. // certificate verification.
  9254. bool server_hostname_verification = true;
  9255. std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
  9256. // When non-null, guards session creation against concurrent use of the
  9257. // context. A WebSocketClient is not safe to use from several threads to
  9258. // begin with, so it passes nothing.
  9259. std::mutex *ctx_mutex = nullptr;
  9260. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  9261. // The caller decides whether Schannel has anything to say about this
  9262. // connection; see SSLClient::initialize_ssl().
  9263. bool windows_cert_verification = false;
  9264. // A server certificate verifier works on the backend's chain verification,
  9265. // so the backend keeps deciding and Schannel only adds its own check.
  9266. bool server_certificate_verifier_set = false;
  9267. #endif
  9268. };
  9269. // Filled in on failure for callers that report error details.
  9270. struct ClientTlsSessionError {
  9271. Error error = Error::Success;
  9272. int ssl_error = 0;
  9273. uint64_t backend_error = 0;
  9274. };
  9275. // Establishes a client TLS session on an already connected socket. On failure
  9276. // the session is left for the caller to free: SSLClient frees it right away,
  9277. // WebSocketClient keeps it in a member that shutdown_and_close() cleans up.
  9278. inline bool setup_client_tls_session(
  9279. const std::string &host, tls::ctx_t ctx, tls::session_t &session,
  9280. socket_t sock, bool server_certificate_verification, time_t timeout_sec,
  9281. time_t timeout_usec, ClientTlsSessionError *out_error = nullptr,
  9282. const ClientTlsSessionOptions &options = ClientTlsSessionOptions()) {
  9283. using namespace tls;
  9284. auto fail = [&](Error error, int ssl_error, uint64_t backend_error) {
  9285. if (out_error) {
  9286. out_error->error = error;
  9287. out_error->ssl_error = ssl_error;
  9288. out_error->backend_error = backend_error;
  9289. }
  9290. return false;
  9291. };
  9292. if (!ctx) {
  9293. session = nullptr;
  9294. return fail(Error::SSLConnection, 0, 0);
  9295. }
  9296. // With Windows verification on and no server certificate verifier set,
  9297. // Schannel is the only chain verifier. The backend's trust store is a
  9298. // snapshot of the Windows stores that lacks the roots Windows fetches on
  9299. // demand, so the backend's verdict is not used.
  9300. auto windows_verifies_chain = false;
  9301. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  9302. windows_verifies_chain = options.windows_cert_verification &&
  9303. !options.server_certificate_verifier_set;
  9304. #endif
  9305. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  9306. // Mbed TLS and wolfSSL need the verification mode set explicitly; OpenSSL
  9307. // uses SSL_VERIFY_NONE and does all verification post-handshake. Unless
  9308. // Schannel verifies the chain instead, chain verification happens during
  9309. // the handshake even for IP hosts; the certificate identity is verified
  9310. // post-handshake via verify_hostname().
  9311. set_verify_client(ctx,
  9312. server_certificate_verification && !windows_verifies_chain);
  9313. #endif
  9314. {
  9315. std::unique_lock<std::mutex> guard;
  9316. if (options.ctx_mutex) {
  9317. guard = std::unique_lock<std::mutex>(*options.ctx_mutex);
  9318. }
  9319. session = create_session(ctx, sock);
  9320. }
  9321. if (!session) { return fail(Error::SSLConnection, 0, get_error()); }
  9322. // RFC 6066: SNI must not be set for IP addresses; skip it for IP hosts, so
  9323. // their identity is checked post-handshake below instead. On Mbed TLS and
  9324. // wolfSSL, set_sni also drives handshake-time hostname verification, so
  9325. // options.server_hostname_verification is threaded through here.
  9326. if (!is_ip_address(host)) {
  9327. if (!set_sni(session, host.c_str(), options.server_hostname_verification)) {
  9328. return fail(Error::SSLConnection, 0, get_error());
  9329. }
  9330. }
  9331. TlsError tls_err;
  9332. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec,
  9333. &tls_err)) {
  9334. auto error = Error::SSLConnection;
  9335. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  9336. error = Error::SSLServerVerification;
  9337. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  9338. error = Error::SSLServerHostnameVerification;
  9339. }
  9340. return fail(error, static_cast<int>(tls_err.code), tls_err.backend_code);
  9341. }
  9342. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  9343. if (options.session_verifier) {
  9344. verification_status = options.session_verifier(session);
  9345. }
  9346. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  9347. return fail(Error::SSLServerVerification, 0, get_error());
  9348. }
  9349. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  9350. server_certificate_verification) {
  9351. if (!windows_verifies_chain) {
  9352. auto verify_result = get_verify_result(session);
  9353. if (verify_result != 0) {
  9354. return fail(Error::SSLServerVerification, 0,
  9355. static_cast<uint64_t>(verify_result));
  9356. }
  9357. }
  9358. auto server_cert = get_peer_cert(session);
  9359. if (!server_cert) {
  9360. return fail(Error::SSLServerVerification, 0, get_error());
  9361. }
  9362. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  9363. // Identity check against the peer certificate, post-handshake for all
  9364. // backends. For IP hosts this is the only identity verification, since no
  9365. // hostname is bound during the handshake.
  9366. if (options.server_hostname_verification) {
  9367. if (!verify_hostname(server_cert, host.c_str())) {
  9368. return fail(Error::SSLServerHostnameVerification, 0,
  9369. hostname_mismatch_code());
  9370. }
  9371. }
  9372. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  9373. // Windows Schannel verification, which lets Windows fetch missing roots
  9374. // and intermediates on demand. It must not be skipped: unless a server
  9375. // certificate verifier is set, it is the only chain check.
  9376. if (options.windows_cert_verification) {
  9377. std::vector<unsigned char> der;
  9378. uint64_t wincrypt_error = 0;
  9379. if (!get_cert_der(server_cert, der) ||
  9380. !verify_cert_with_windows_schannel(
  9381. der, host, options.server_hostname_verification, wincrypt_error,
  9382. session)) {
  9383. return fail(Error::SSLServerVerification, 0, wincrypt_error);
  9384. }
  9385. }
  9386. #endif
  9387. }
  9388. return true;
  9389. }
  9390. } // namespace detail
  9391. #endif // CPPHTTPLIB_SSL_ENABLED
  9392. /*
  9393. * Group 3: httplib namespace - Non-SSL public API implementations
  9394. */
  9395. inline void default_socket_options(socket_t sock) {
  9396. set_socket_opt(sock, SOL_SOCKET,
  9397. #ifdef SO_REUSEPORT
  9398. SO_REUSEPORT,
  9399. #else
  9400. SO_REUSEADDR,
  9401. #endif
  9402. 1);
  9403. }
  9404. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  9405. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  9406. sizeof(optval));
  9407. }
  9408. inline std::string get_bearer_token_auth(const Request &req) {
  9409. // The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
  9410. // than the prefix carries no token.
  9411. constexpr const char bearer_prefix[] = "Bearer ";
  9412. constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
  9413. auto value = req.get_header_value("Authorization");
  9414. if (value.size() >= bearer_prefix_len &&
  9415. detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
  9416. bearer_prefix)) {
  9417. return value.substr(bearer_prefix_len);
  9418. }
  9419. return "";
  9420. }
  9421. inline const char *status_message(int status) {
  9422. switch (status) {
  9423. case StatusCode::Continue_100: return "Continue";
  9424. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  9425. case StatusCode::Processing_102: return "Processing";
  9426. case StatusCode::EarlyHints_103: return "Early Hints";
  9427. case StatusCode::OK_200: return "OK";
  9428. case StatusCode::Created_201: return "Created";
  9429. case StatusCode::Accepted_202: return "Accepted";
  9430. case StatusCode::NonAuthoritativeInformation_203:
  9431. return "Non-Authoritative Information";
  9432. case StatusCode::NoContent_204: return "No Content";
  9433. case StatusCode::ResetContent_205: return "Reset Content";
  9434. case StatusCode::PartialContent_206: return "Partial Content";
  9435. case StatusCode::MultiStatus_207: return "Multi-Status";
  9436. case StatusCode::AlreadyReported_208: return "Already Reported";
  9437. case StatusCode::IMUsed_226: return "IM Used";
  9438. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  9439. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  9440. case StatusCode::Found_302: return "Found";
  9441. case StatusCode::SeeOther_303: return "See Other";
  9442. case StatusCode::NotModified_304: return "Not Modified";
  9443. case StatusCode::UseProxy_305: return "Use Proxy";
  9444. case StatusCode::unused_306: return "unused";
  9445. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  9446. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  9447. case StatusCode::BadRequest_400: return "Bad Request";
  9448. case StatusCode::Unauthorized_401: return "Unauthorized";
  9449. case StatusCode::PaymentRequired_402: return "Payment Required";
  9450. case StatusCode::Forbidden_403: return "Forbidden";
  9451. case StatusCode::NotFound_404: return "Not Found";
  9452. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  9453. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  9454. case StatusCode::ProxyAuthenticationRequired_407:
  9455. return "Proxy Authentication Required";
  9456. case StatusCode::RequestTimeout_408: return "Request Timeout";
  9457. case StatusCode::Conflict_409: return "Conflict";
  9458. case StatusCode::Gone_410: return "Gone";
  9459. case StatusCode::LengthRequired_411: return "Length Required";
  9460. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  9461. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  9462. case StatusCode::UriTooLong_414: return "URI Too Long";
  9463. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  9464. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  9465. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  9466. case StatusCode::ImATeapot_418: return "I'm a teapot";
  9467. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  9468. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  9469. case StatusCode::Locked_423: return "Locked";
  9470. case StatusCode::FailedDependency_424: return "Failed Dependency";
  9471. case StatusCode::TooEarly_425: return "Too Early";
  9472. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  9473. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  9474. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  9475. case StatusCode::RequestHeaderFieldsTooLarge_431:
  9476. return "Request Header Fields Too Large";
  9477. case StatusCode::UnavailableForLegalReasons_451:
  9478. return "Unavailable For Legal Reasons";
  9479. case StatusCode::NotImplemented_501: return "Not Implemented";
  9480. case StatusCode::BadGateway_502: return "Bad Gateway";
  9481. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  9482. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  9483. case StatusCode::HttpVersionNotSupported_505:
  9484. return "HTTP Version Not Supported";
  9485. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  9486. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  9487. case StatusCode::LoopDetected_508: return "Loop Detected";
  9488. case StatusCode::NotExtended_510: return "Not Extended";
  9489. case StatusCode::NetworkAuthenticationRequired_511:
  9490. return "Network Authentication Required";
  9491. default:
  9492. case StatusCode::InternalServerError_500: return "Internal Server Error";
  9493. }
  9494. }
  9495. inline std::string to_string(const Error error) {
  9496. switch (error) {
  9497. case Error::Success: return "Success (no error)";
  9498. case Error::Unknown: return "Unknown";
  9499. case Error::Connection: return "Could not establish connection";
  9500. case Error::BindIPAddress: return "Failed to bind IP address";
  9501. case Error::Read: return "Failed to read connection";
  9502. case Error::Write: return "Failed to write connection";
  9503. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  9504. case Error::Canceled: return "Connection handling canceled";
  9505. case Error::SSLConnection: return "SSL connection failed";
  9506. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  9507. case Error::SSLServerVerification: return "SSL server verification failed";
  9508. case Error::SSLServerHostnameVerification:
  9509. return "SSL server hostname verification failed";
  9510. case Error::UnsupportedMultipartBoundaryChars:
  9511. return "Unsupported HTTP multipart boundary characters";
  9512. case Error::Compression: return "Compression failed";
  9513. case Error::ConnectionTimeout: return "Connection timed out";
  9514. case Error::ProxyConnection: return "Proxy connection failed";
  9515. case Error::ConnectionClosed: return "Connection closed by server";
  9516. case Error::Timeout: return "Read timeout";
  9517. case Error::ResourceExhaustion: return "Resource exhaustion";
  9518. case Error::TooManyFormDataFiles: return "Too many form data files";
  9519. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  9520. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  9521. case Error::ExceedMaxSocketDescriptorCount:
  9522. return "Exceeded maximum socket descriptor count";
  9523. case Error::InvalidRequestLine: return "Invalid request line";
  9524. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  9525. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  9526. case Error::InvalidHeaders: return "Invalid headers";
  9527. case Error::MultipartParsing: return "Multipart parsing failed";
  9528. case Error::OpenFile: return "Failed to open file";
  9529. case Error::Listen: return "Failed to listen on socket";
  9530. case Error::GetSockName: return "Failed to get socket name";
  9531. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  9532. case Error::HTTPParsing: return "HTTP parsing failed";
  9533. case Error::InvalidRangeHeader: return "Invalid Range header";
  9534. case Error::UnsupportedContentEncoding: return "Unsupported Content-Encoding";
  9535. case Error::WebSocketHandshake: return "WebSocket handshake failed";
  9536. case Error::UserCallbackException: return "User callback threw an exception";
  9537. default: break;
  9538. }
  9539. return "Invalid";
  9540. }
  9541. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  9542. os << to_string(obj);
  9543. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  9544. return os;
  9545. }
  9546. inline std::string hosted_at(const std::string &hostname) {
  9547. std::vector<std::string> addrs;
  9548. hosted_at(hostname, addrs);
  9549. if (addrs.empty()) { return std::string(); }
  9550. return addrs[0];
  9551. }
  9552. inline void hosted_at(const std::string &hostname,
  9553. std::vector<std::string> &addrs) {
  9554. struct addrinfo hints;
  9555. struct addrinfo *result;
  9556. memset(&hints, 0, sizeof(struct addrinfo));
  9557. hints.ai_family = AF_UNSPEC;
  9558. hints.ai_socktype = SOCK_STREAM;
  9559. hints.ai_protocol = 0;
  9560. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  9561. &result, 0)) {
  9562. #if defined __linux__ && !defined __ANDROID__
  9563. res_init();
  9564. #endif
  9565. return;
  9566. }
  9567. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  9568. for (auto rp = result; rp; rp = rp->ai_next) {
  9569. const auto &addr =
  9570. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  9571. std::string ip;
  9572. auto dummy = -1;
  9573. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  9574. dummy)) {
  9575. addrs.emplace_back(std::move(ip));
  9576. }
  9577. }
  9578. }
  9579. inline std::string encode_uri_component(const std::string &value) {
  9580. std::ostringstream escaped;
  9581. escaped.fill('0');
  9582. escaped << std::hex;
  9583. for (auto c : value) {
  9584. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9585. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  9586. escaped << c;
  9587. } else {
  9588. escaped << std::uppercase;
  9589. escaped << '%' << std::setw(2)
  9590. << static_cast<int>(static_cast<unsigned char>(c));
  9591. escaped << std::nouppercase;
  9592. }
  9593. }
  9594. return escaped.str();
  9595. }
  9596. inline std::string encode_uri(const std::string &value) {
  9597. std::ostringstream escaped;
  9598. escaped.fill('0');
  9599. escaped << std::hex;
  9600. for (auto c : value) {
  9601. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9602. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  9603. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  9604. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  9605. escaped << c;
  9606. } else {
  9607. escaped << std::uppercase;
  9608. escaped << '%' << std::setw(2)
  9609. << static_cast<int>(static_cast<unsigned char>(c));
  9610. escaped << std::nouppercase;
  9611. }
  9612. }
  9613. return escaped.str();
  9614. }
  9615. inline std::string decode_uri_component(const std::string &value) {
  9616. std::string result;
  9617. for (size_t i = 0; i < value.size(); i++) {
  9618. if (value[i] == '%' && i + 2 < value.size()) {
  9619. auto val = 0;
  9620. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9621. result += static_cast<char>(val);
  9622. i += 2;
  9623. } else {
  9624. result += value[i];
  9625. }
  9626. } else {
  9627. result += value[i];
  9628. }
  9629. }
  9630. return result;
  9631. }
  9632. inline std::string decode_uri(const std::string &value) {
  9633. std::string result;
  9634. for (size_t i = 0; i < value.size(); i++) {
  9635. if (value[i] == '%' && i + 2 < value.size()) {
  9636. auto val = 0;
  9637. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9638. auto c = static_cast<char>(val);
  9639. // Keep escapes of the reserved characters that encode_uri leaves
  9640. // literal, so decode_uri is the inverse of encode_uri and an escaped
  9641. // delimiter is not promoted into a real one (as with JS decodeURI).
  9642. if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  9643. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' ||
  9644. c == '#') {
  9645. result += value[i];
  9646. result += value[i + 1];
  9647. result += value[i + 2];
  9648. } else {
  9649. result += c;
  9650. }
  9651. i += 2;
  9652. } else {
  9653. result += value[i];
  9654. }
  9655. } else {
  9656. result += value[i];
  9657. }
  9658. }
  9659. return result;
  9660. }
  9661. inline std::string encode_path_component(const std::string &component) {
  9662. std::string result;
  9663. result.reserve(component.size() * 3);
  9664. for (size_t i = 0; i < component.size(); i++) {
  9665. auto c = static_cast<unsigned char>(component[i]);
  9666. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  9667. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9668. c == '_' || c == '~') {
  9669. result += static_cast<char>(c);
  9670. }
  9671. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  9672. // "," / ";" / "="
  9673. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  9674. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  9675. c == '=') {
  9676. result += static_cast<char>(c);
  9677. }
  9678. // Colon is allowed in path segments except first segment
  9679. else if (c == ':') {
  9680. result += static_cast<char>(c);
  9681. }
  9682. // @ is allowed in path
  9683. else if (c == '@') {
  9684. result += static_cast<char>(c);
  9685. } else {
  9686. result += '%';
  9687. char hex[3];
  9688. snprintf(hex, sizeof(hex), "%02X", c);
  9689. result.append(hex, 2);
  9690. }
  9691. }
  9692. return result;
  9693. }
  9694. inline std::string decode_path_component(const std::string &component) {
  9695. std::string result;
  9696. result.reserve(component.size());
  9697. for (size_t i = 0; i < component.size(); i++) {
  9698. if (component[i] == '%' && i + 1 < component.size()) {
  9699. if (component[i + 1] == 'u') {
  9700. // Unicode %uXXXX encoding
  9701. auto val = 0;
  9702. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  9703. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  9704. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  9705. char buff[4];
  9706. size_t len = detail::to_utf8(val, buff);
  9707. if (len > 0) { result.append(buff, len); }
  9708. i += 5; // 'u0000'
  9709. } else {
  9710. result += component[i];
  9711. }
  9712. } else {
  9713. // Standard %XX encoding
  9714. auto val = 0;
  9715. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9716. // 2 digits hex codes
  9717. result += static_cast<char>(val);
  9718. i += 2; // 'XX'
  9719. } else {
  9720. result += component[i];
  9721. }
  9722. }
  9723. } else {
  9724. result += component[i];
  9725. }
  9726. }
  9727. return result;
  9728. }
  9729. inline std::string encode_query_component(const std::string &component,
  9730. bool space_as_plus) {
  9731. std::string result;
  9732. result.reserve(component.size() * 3);
  9733. for (size_t i = 0; i < component.size(); i++) {
  9734. auto c = static_cast<unsigned char>(component[i]);
  9735. // Unreserved characters per RFC 3986
  9736. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9737. c == '_' || c == '~') {
  9738. result += static_cast<char>(c);
  9739. }
  9740. // Space handling
  9741. else if (c == ' ') {
  9742. if (space_as_plus) {
  9743. result += '+';
  9744. } else {
  9745. result += "%20";
  9746. }
  9747. }
  9748. // Plus sign handling
  9749. else if (c == '+') {
  9750. if (space_as_plus) {
  9751. result += "%2B";
  9752. } else {
  9753. result += static_cast<char>(c);
  9754. }
  9755. }
  9756. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  9757. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  9758. c == '*' || c == ',' || c == ';') {
  9759. result += static_cast<char>(c);
  9760. }
  9761. // Colon and @ are allowed in query
  9762. else if (c == ':' || c == '@') {
  9763. result += static_cast<char>(c);
  9764. }
  9765. // Forward slash is allowed in query values
  9766. else if (c == '/') {
  9767. result += static_cast<char>(c);
  9768. }
  9769. // Question mark is allowed in query values (after first ?)
  9770. else if (c == '?') {
  9771. result += static_cast<char>(c);
  9772. } else {
  9773. result += '%';
  9774. char hex[3];
  9775. snprintf(hex, sizeof(hex), "%02X", c);
  9776. result.append(hex, 2);
  9777. }
  9778. }
  9779. return result;
  9780. }
  9781. inline std::string decode_query_component(const std::string &component,
  9782. bool plus_as_space) {
  9783. std::string result;
  9784. result.reserve(component.size());
  9785. for (size_t i = 0; i < component.size(); i++) {
  9786. if (component[i] == '%' && i + 2 < component.size()) {
  9787. auto val = 0;
  9788. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9789. result += static_cast<char>(val);
  9790. i += 2;
  9791. } else {
  9792. result += component[i];
  9793. }
  9794. } else if (component[i] == '+' && plus_as_space) {
  9795. result += ' '; // + becomes space in form-urlencoded
  9796. } else {
  9797. result += component[i];
  9798. }
  9799. }
  9800. return result;
  9801. }
  9802. inline std::string sanitize_filename(const std::string &filename) {
  9803. // Extract basename: find the last path separator (/ or \)
  9804. auto pos = filename.find_last_of("/\\");
  9805. auto result =
  9806. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  9807. // Strip null bytes
  9808. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  9809. // Trim whitespace
  9810. {
  9811. auto start = result.find_first_not_of(" \t");
  9812. auto end = result.find_last_not_of(" \t");
  9813. result = (start == std::string::npos)
  9814. ? ""
  9815. : result.substr(start, end - start + 1);
  9816. }
  9817. // Reject . and ..
  9818. if (result == "." || result == "..") { return ""; }
  9819. return result;
  9820. }
  9821. inline std::string append_query_params(const std::string &path,
  9822. const Params &params) {
  9823. std::string path_with_query = path;
  9824. thread_local const std::regex re("[^?]+\\?.*");
  9825. auto delm = std::regex_match(path, re) ? '&' : '?';
  9826. path_with_query += delm + detail::params_to_query_str(params);
  9827. return path_with_query;
  9828. }
  9829. // Header utilities
  9830. inline std::pair<std::string, std::string>
  9831. make_range_header(const Ranges &ranges) {
  9832. std::string field = "bytes=";
  9833. auto i = 0;
  9834. for (const auto &r : ranges) {
  9835. if (i != 0) { field += ", "; }
  9836. if (r.first != -1) { field += std::to_string(r.first); }
  9837. field += '-';
  9838. if (r.second != -1) { field += std::to_string(r.second); }
  9839. i++;
  9840. }
  9841. return std::make_pair("Range", std::move(field));
  9842. }
  9843. inline std::pair<std::string, std::string>
  9844. make_basic_authentication_header(const std::string &username,
  9845. const std::string &password, bool is_proxy) {
  9846. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  9847. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9848. return std::make_pair(key, std::move(field));
  9849. }
  9850. inline std::pair<std::string, std::string>
  9851. make_bearer_token_authentication_header(const std::string &token,
  9852. bool is_proxy = false) {
  9853. auto field = "Bearer " + token;
  9854. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9855. return std::make_pair(key, std::move(field));
  9856. }
  9857. // Request implementation
  9858. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  9859. size_t id) const {
  9860. return detail::get_header_value_u64(headers, key, def, id);
  9861. }
  9862. inline bool Request::has_header(const std::string &key) const {
  9863. return detail::has_header(headers, key);
  9864. }
  9865. inline std::string Request::get_header_value(const std::string &key,
  9866. const char *def, size_t id) const {
  9867. return detail::get_header_value(headers, key, def, id);
  9868. }
  9869. inline size_t Request::get_header_value_count(const std::string &key) const {
  9870. return detail::get_header_value_count(headers, key);
  9871. }
  9872. inline void Request::set_header(const std::string &key,
  9873. const std::string &val) {
  9874. detail::set_header(headers, key, val);
  9875. }
  9876. inline bool Request::has_trailer(const std::string &key) const {
  9877. return trailers.find(key) != trailers.end();
  9878. }
  9879. inline std::string Request::get_trailer_value(const std::string &key,
  9880. size_t id) const {
  9881. return detail::get_multimap_value(trailers, key, id);
  9882. }
  9883. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  9884. return trailers.count(key);
  9885. }
  9886. inline bool Request::has_param(const std::string &key) const {
  9887. return params.find(key) != params.end();
  9888. }
  9889. inline std::string Request::get_param_value(const std::string &key,
  9890. size_t id) const {
  9891. return detail::get_multimap_value(params, key, id);
  9892. }
  9893. inline std::vector<std::string>
  9894. Request::get_param_values(const std::string &key) const {
  9895. auto rng = params.equal_range(key);
  9896. std::vector<std::string> values;
  9897. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  9898. for (auto it = rng.first; it != rng.second; ++it) {
  9899. values.push_back(it->second);
  9900. }
  9901. return values;
  9902. }
  9903. inline size_t Request::get_param_value_count(const std::string &key) const {
  9904. return params.count(key);
  9905. }
  9906. inline bool Request::is_multipart_form_data() const {
  9907. const auto &content_type = get_header_value("Content-Type");
  9908. return detail::extract_media_type(content_type) == "multipart/form-data";
  9909. }
  9910. // Multipart FormData implementation
  9911. inline std::string MultipartFormData::get_field(const std::string &key,
  9912. size_t id) const {
  9913. auto rng = fields.equal_range(key);
  9914. auto it = detail::bounded_next(rng.first, id, rng.second);
  9915. if (it != rng.second) { return it->second.content; }
  9916. return std::string();
  9917. }
  9918. inline std::vector<std::string>
  9919. MultipartFormData::get_fields(const std::string &key) const {
  9920. std::vector<std::string> values;
  9921. auto rng = fields.equal_range(key);
  9922. for (auto it = rng.first; it != rng.second; it++) {
  9923. values.push_back(it->second.content);
  9924. }
  9925. return values;
  9926. }
  9927. inline bool MultipartFormData::has_field(const std::string &key) const {
  9928. return fields.find(key) != fields.end();
  9929. }
  9930. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  9931. return fields.count(key);
  9932. }
  9933. inline FormData MultipartFormData::get_file(const std::string &key,
  9934. size_t id) const {
  9935. return detail::get_multimap_value(files, key, id);
  9936. }
  9937. inline std::vector<FormData>
  9938. MultipartFormData::get_files(const std::string &key) const {
  9939. std::vector<FormData> values;
  9940. auto rng = files.equal_range(key);
  9941. for (auto it = rng.first; it != rng.second; it++) {
  9942. values.push_back(it->second);
  9943. }
  9944. return values;
  9945. }
  9946. inline bool MultipartFormData::has_file(const std::string &key) const {
  9947. return files.find(key) != files.end();
  9948. }
  9949. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  9950. return files.count(key);
  9951. }
  9952. // Multipart FormData writer implementation
  9953. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  9954. return detail::is_multipart_boundary_chars_valid(boundary);
  9955. }
  9956. inline MultipartFormDataWriter::MultipartFormDataWriter()
  9957. : boundary_(detail::make_multipart_data_boundary()) {}
  9958. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  9959. : boundary_(std::move(boundary)) {}
  9960. inline const std::string &MultipartFormDataWriter::boundary() const {
  9961. return boundary_;
  9962. }
  9963. inline std::string MultipartFormDataWriter::content_type() const {
  9964. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  9965. }
  9966. inline std::string
  9967. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  9968. return detail::serialize_multipart_formdata(items, boundary_);
  9969. }
  9970. inline size_t MultipartFormDataWriter::content_length(
  9971. const UploadFormDataItems &items) const {
  9972. return detail::get_multipart_content_length(items, boundary_);
  9973. }
  9974. inline std::string
  9975. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  9976. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  9977. }
  9978. inline std::string MultipartFormDataWriter::item_end() {
  9979. return detail::serialize_multipart_formdata_item_end();
  9980. }
  9981. inline std::string MultipartFormDataWriter::finish() const {
  9982. return detail::serialize_multipart_formdata_finish(boundary_);
  9983. }
  9984. // Response implementation
  9985. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  9986. size_t id) const {
  9987. return detail::get_header_value_u64(headers, key, def, id);
  9988. }
  9989. inline bool Response::has_header(const std::string &key) const {
  9990. return headers.find(key) != headers.end();
  9991. }
  9992. inline std::string Response::get_header_value(const std::string &key,
  9993. const char *def,
  9994. size_t id) const {
  9995. return detail::get_header_value(headers, key, def, id);
  9996. }
  9997. inline size_t Response::get_header_value_count(const std::string &key) const {
  9998. return detail::get_header_value_count(headers, key);
  9999. }
  10000. inline void Response::set_header(const std::string &key,
  10001. const std::string &val) {
  10002. detail::set_header(headers, key, val);
  10003. }
  10004. inline bool Response::has_trailer(const std::string &key) const {
  10005. return trailers.find(key) != trailers.end();
  10006. }
  10007. inline std::string Response::get_trailer_value(const std::string &key,
  10008. size_t id) const {
  10009. return detail::get_multimap_value(trailers, key, id);
  10010. }
  10011. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  10012. return trailers.count(key);
  10013. }
  10014. inline void Response::set_redirect(const std::string &url, int stat) {
  10015. if (detail::fields::is_field_value(url)) {
  10016. set_header("Location", url);
  10017. if (300 <= stat && stat < 400) {
  10018. this->status = stat;
  10019. } else {
  10020. this->status = StatusCode::Found_302;
  10021. }
  10022. }
  10023. }
  10024. inline void Response::set_content(const char *s, size_t n,
  10025. const std::string &content_type) {
  10026. body.assign(s, n);
  10027. auto rng = headers.equal_range("Content-Type");
  10028. headers.erase(rng.first, rng.second);
  10029. set_header("Content-Type", content_type);
  10030. content_coding_ = detail::EncodingType::None;
  10031. }
  10032. inline void Response::set_content(const std::string &s,
  10033. const std::string &content_type) {
  10034. set_content(s.data(), s.size(), content_type);
  10035. }
  10036. inline void Response::set_content(std::string &&s,
  10037. const std::string &content_type) {
  10038. body = std::move(s);
  10039. auto rng = headers.equal_range("Content-Type");
  10040. headers.erase(rng.first, rng.second);
  10041. set_header("Content-Type", content_type);
  10042. content_coding_ = detail::EncodingType::None;
  10043. }
  10044. inline void Response::set_content_provider(
  10045. size_t in_length, const std::string &content_type, ContentProvider provider,
  10046. ContentProviderResourceReleaser resource_releaser) {
  10047. set_header("Content-Type", content_type);
  10048. content_length_ = in_length;
  10049. if (in_length > 0) { content_provider_ = std::move(provider); }
  10050. content_provider_resource_releaser_ = std::move(resource_releaser);
  10051. is_chunked_content_provider_ = false;
  10052. is_file_content_provider_ = false;
  10053. content_coding_ = detail::EncodingType::None;
  10054. }
  10055. inline void Response::set_content_provider(
  10056. const std::string &content_type, ContentProviderWithoutLength provider,
  10057. ContentProviderResourceReleaser resource_releaser) {
  10058. set_header("Content-Type", content_type);
  10059. content_length_ = 0;
  10060. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  10061. content_provider_resource_releaser_ = std::move(resource_releaser);
  10062. is_chunked_content_provider_ = false;
  10063. is_file_content_provider_ = false;
  10064. content_coding_ = detail::EncodingType::None;
  10065. }
  10066. inline void Response::set_chunked_content_provider(
  10067. const std::string &content_type, ContentProviderWithoutLength provider,
  10068. ContentProviderResourceReleaser resource_releaser) {
  10069. set_header("Content-Type", content_type);
  10070. content_length_ = 0;
  10071. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  10072. content_provider_resource_releaser_ = std::move(resource_releaser);
  10073. is_chunked_content_provider_ = true;
  10074. is_file_content_provider_ = false;
  10075. content_coding_ = detail::EncodingType::None;
  10076. }
  10077. inline void Response::set_file_content(const std::string &path,
  10078. const std::string &content_type) {
  10079. file_content_path_ = path;
  10080. file_content_content_type_ = content_type;
  10081. }
  10082. inline void Response::set_file_content(const std::string &path) {
  10083. file_content_path_ = path;
  10084. }
  10085. // Result implementation
  10086. inline size_t Result::get_request_header_value_u64(const std::string &key,
  10087. size_t def,
  10088. size_t id) const {
  10089. return detail::get_header_value_u64(request_headers_, key, def, id);
  10090. }
  10091. inline bool Result::has_request_header(const std::string &key) const {
  10092. return request_headers_.find(key) != request_headers_.end();
  10093. }
  10094. inline std::string Result::get_request_header_value(const std::string &key,
  10095. const char *def,
  10096. size_t id) const {
  10097. return detail::get_header_value(request_headers_, key, def, id);
  10098. }
  10099. inline size_t
  10100. Result::get_request_header_value_count(const std::string &key) const {
  10101. return request_headers_.count(key);
  10102. }
  10103. // Stream implementation
  10104. inline ssize_t Stream::write(const char *ptr) {
  10105. return write(ptr, strlen(ptr));
  10106. }
  10107. inline ssize_t Stream::write(const std::string &s) {
  10108. return write(s.data(), s.size());
  10109. }
  10110. // BodyReader implementation
  10111. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  10112. if (!stream) {
  10113. last_error = Error::Connection;
  10114. return -1;
  10115. }
  10116. if (eof) { return 0; }
  10117. if (!chunked) {
  10118. // Content-Length based reading
  10119. if (has_content_length && bytes_read >= content_length) {
  10120. eof = true;
  10121. return 0;
  10122. }
  10123. auto to_read = len;
  10124. if (has_content_length) {
  10125. auto remaining = content_length - bytes_read;
  10126. to_read = (std::min)(len, remaining);
  10127. }
  10128. auto n = stream->read(buf, to_read);
  10129. if (n < 0) {
  10130. last_error = stream->get_error();
  10131. if (last_error == Error::Success) { last_error = Error::Read; }
  10132. eof = true;
  10133. return n;
  10134. }
  10135. if (n == 0) {
  10136. // Unexpected EOF before content_length
  10137. last_error = stream->get_error();
  10138. if (last_error == Error::Success) { last_error = Error::Read; }
  10139. eof = true;
  10140. return 0;
  10141. }
  10142. bytes_read += static_cast<size_t>(n);
  10143. if (has_content_length && bytes_read >= content_length) { eof = true; }
  10144. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  10145. last_error = Error::ExceedMaxPayloadSize;
  10146. eof = true;
  10147. return -1;
  10148. }
  10149. return n;
  10150. }
  10151. // Chunked transfer encoding: delegate to shared decoder instance.
  10152. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  10153. size_t chunk_offset = 0;
  10154. size_t chunk_total = 0;
  10155. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  10156. if (n < 0) {
  10157. last_error = stream->get_error();
  10158. if (last_error == Error::Success) { last_error = Error::Read; }
  10159. eof = true;
  10160. return n;
  10161. }
  10162. if (n == 0) {
  10163. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  10164. eof = true;
  10165. return 0;
  10166. }
  10167. bytes_read += static_cast<size_t>(n);
  10168. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  10169. last_error = Error::ExceedMaxPayloadSize;
  10170. eof = true;
  10171. return -1;
  10172. }
  10173. return n;
  10174. }
  10175. // ThreadPool implementation
  10176. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  10177. time_t idle_timeout_sec)
  10178. : base_thread_count_(n), max_queued_requests_(mqr),
  10179. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  10180. shutdown_(false) {
  10181. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10182. if (max_n != 0 && max_n < n) {
  10183. std::string msg = "max_threads must be >= base_threads";
  10184. throw std::invalid_argument(msg);
  10185. }
  10186. #endif
  10187. max_thread_count_ = max_n == 0 ? n : max_n;
  10188. threads_.reserve(base_thread_count_);
  10189. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10190. try {
  10191. #endif
  10192. for (size_t i = 0; i < base_thread_count_; i++) {
  10193. threads_.emplace_back(std::thread([this]() { worker(false); }));
  10194. }
  10195. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10196. } catch (...) {
  10197. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  10198. // signal the workers we already spawned to exit and join them so the
  10199. // vector destructor does not see joinable threads (which would call
  10200. // std::terminate). Then rethrow so the caller learns of the failure.
  10201. {
  10202. std::unique_lock<std::mutex> lock(mutex_);
  10203. shutdown_ = true;
  10204. }
  10205. cond_.notify_all();
  10206. for (auto &t : threads_) {
  10207. if (t.joinable()) { t.join(); }
  10208. }
  10209. throw;
  10210. }
  10211. #endif
  10212. }
  10213. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  10214. {
  10215. std::unique_lock<std::mutex> lock(mutex_);
  10216. if (shutdown_) { return false; }
  10217. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  10218. return false;
  10219. }
  10220. jobs_.push_back(std::move(fn));
  10221. // Spawn a dynamic thread if no idle threads and under max
  10222. if (idle_thread_count_ == 0 &&
  10223. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  10224. cleanup_finished_threads();
  10225. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  10226. }
  10227. }
  10228. cond_.notify_one();
  10229. return true;
  10230. }
  10231. inline void ThreadPool::shutdown() {
  10232. {
  10233. std::unique_lock<std::mutex> lock(mutex_);
  10234. shutdown_ = true;
  10235. }
  10236. cond_.notify_all();
  10237. for (auto &t : threads_) {
  10238. if (t.joinable()) { t.join(); }
  10239. }
  10240. // Move dynamic_threads_ to a local list under the lock to avoid racing
  10241. // with worker threads that call move_to_finished() concurrently.
  10242. std::list<std::thread> remaining_dynamic;
  10243. {
  10244. std::unique_lock<std::mutex> lock(mutex_);
  10245. remaining_dynamic = std::move(dynamic_threads_);
  10246. }
  10247. for (auto &t : remaining_dynamic) {
  10248. if (t.joinable()) { t.join(); }
  10249. }
  10250. std::unique_lock<std::mutex> lock(mutex_);
  10251. cleanup_finished_threads();
  10252. }
  10253. inline void ThreadPool::move_to_finished(std::thread::id id) {
  10254. // Must be called with mutex_ held
  10255. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  10256. if (it->get_id() == id) {
  10257. finished_threads_.push_back(std::move(*it));
  10258. dynamic_threads_.erase(it);
  10259. return;
  10260. }
  10261. }
  10262. }
  10263. inline void ThreadPool::cleanup_finished_threads() {
  10264. // Must be called with mutex_ held
  10265. for (auto &t : finished_threads_) {
  10266. if (t.joinable()) { t.join(); }
  10267. }
  10268. finished_threads_.clear();
  10269. }
  10270. inline void ThreadPool::worker(bool is_dynamic) {
  10271. for (;;) {
  10272. std::function<void()> fn;
  10273. {
  10274. std::unique_lock<std::mutex> lock(mutex_);
  10275. idle_thread_count_++;
  10276. if (is_dynamic) {
  10277. auto has_work =
  10278. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  10279. [&] { return !jobs_.empty() || shutdown_; });
  10280. if (!has_work) {
  10281. // Timed out with no work - exit this dynamic thread
  10282. idle_thread_count_--;
  10283. move_to_finished(std::this_thread::get_id());
  10284. break;
  10285. }
  10286. } else {
  10287. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  10288. }
  10289. idle_thread_count_--;
  10290. if (shutdown_ && jobs_.empty()) { break; }
  10291. fn = std::move(jobs_.front());
  10292. jobs_.pop_front();
  10293. }
  10294. assert(true == static_cast<bool>(fn));
  10295. fn();
  10296. }
  10297. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  10298. !defined(LIBRESSL_VERSION_NUMBER)
  10299. OPENSSL_thread_stop();
  10300. #endif
  10301. }
  10302. /*
  10303. * Group 1 (continued): detail namespace - Stream implementations
  10304. */
  10305. namespace detail {
  10306. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  10307. time_t timeout_sec, time_t timeout_usec,
  10308. time_t &actual_timeout_sec,
  10309. time_t &actual_timeout_usec) {
  10310. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  10311. auto actual_timeout_msec =
  10312. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  10313. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  10314. actual_timeout_sec = actual_timeout_msec / 1000;
  10315. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  10316. }
  10317. // Socket stream implementation
  10318. inline SocketStream::SocketStream(
  10319. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  10320. time_t write_timeout_sec, time_t write_timeout_usec,
  10321. time_t max_timeout_msec,
  10322. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10323. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  10324. read_timeout_usec_(read_timeout_usec),
  10325. write_timeout_sec_(write_timeout_sec),
  10326. write_timeout_usec_(write_timeout_usec),
  10327. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  10328. read_buff_(read_buff_size_, 0) {}
  10329. inline SocketStream::~SocketStream() = default;
  10330. inline bool SocketStream::is_readable() const {
  10331. return read_buff_off_ < read_buff_content_size_;
  10332. }
  10333. inline bool SocketStream::wait_readable() const {
  10334. if (max_timeout_msec_ <= 0) {
  10335. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10336. }
  10337. time_t read_timeout_sec;
  10338. time_t read_timeout_usec;
  10339. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10340. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10341. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10342. }
  10343. inline bool SocketStream::wait_writable() const {
  10344. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  10345. }
  10346. inline bool SocketStream::ensure_readable() {
  10347. if (readable_hint_) {
  10348. readable_hint_ = false;
  10349. return true;
  10350. }
  10351. return wait_readable();
  10352. }
  10353. inline const char *SocketStream::buffered_data(size_t &size) const {
  10354. size = read_buff_content_size_ - read_buff_off_;
  10355. return size ? read_buff_.data() + read_buff_off_ : nullptr;
  10356. }
  10357. inline void SocketStream::consume_buffered(size_t size) {
  10358. assert(size <= read_buff_content_size_ - read_buff_off_);
  10359. read_buff_off_ += size;
  10360. }
  10361. inline bool SocketStream::is_peer_alive() const {
  10362. return detail::is_socket_alive(sock_);
  10363. }
  10364. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  10365. #ifdef _WIN32
  10366. size =
  10367. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  10368. #else
  10369. size = (std::min)(size,
  10370. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  10371. #endif
  10372. if (read_buff_off_ < read_buff_content_size_) {
  10373. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  10374. if (size <= remaining_size) {
  10375. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  10376. read_buff_off_ += size;
  10377. return static_cast<ssize_t>(size);
  10378. } else {
  10379. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  10380. read_buff_off_ += remaining_size;
  10381. return static_cast<ssize_t>(remaining_size);
  10382. }
  10383. }
  10384. if (!ensure_readable()) {
  10385. error_ = Error::Timeout;
  10386. return -1;
  10387. }
  10388. read_buff_off_ = 0;
  10389. read_buff_content_size_ = 0;
  10390. if (size < read_buff_size_) {
  10391. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  10392. CPPHTTPLIB_RECV_FLAGS);
  10393. if (n <= 0) {
  10394. if (n == 0) {
  10395. error_ = Error::ConnectionClosed;
  10396. } else {
  10397. error_ = Error::Read;
  10398. }
  10399. return n;
  10400. } else if (n <= static_cast<ssize_t>(size)) {
  10401. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  10402. return n;
  10403. } else {
  10404. memcpy(ptr, read_buff_.data(), size);
  10405. read_buff_off_ = size;
  10406. read_buff_content_size_ = static_cast<size_t>(n);
  10407. return static_cast<ssize_t>(size);
  10408. }
  10409. } else {
  10410. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  10411. if (n <= 0) {
  10412. if (n == 0) {
  10413. error_ = Error::ConnectionClosed;
  10414. } else {
  10415. error_ = Error::Read;
  10416. }
  10417. }
  10418. return n;
  10419. }
  10420. }
  10421. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  10422. if (!wait_writable()) { return -1; }
  10423. #if defined(_WIN32) && !defined(_WIN64)
  10424. size =
  10425. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  10426. #endif
  10427. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  10428. }
  10429. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  10430. int &port) const {
  10431. return detail::get_remote_ip_and_port(sock_, ip, port);
  10432. }
  10433. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  10434. int &port) const {
  10435. return detail::get_local_ip_and_port(sock_, ip, port);
  10436. }
  10437. inline socket_t SocketStream::socket() const { return sock_; }
  10438. inline time_t SocketStream::duration() const {
  10439. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10440. std::chrono::steady_clock::now() - start_time_)
  10441. .count();
  10442. }
  10443. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  10444. read_timeout_sec_ = sec;
  10445. read_timeout_usec_ = usec;
  10446. }
  10447. // Buffer stream implementation
  10448. inline bool BufferStream::is_readable() const { return true; }
  10449. inline bool BufferStream::wait_readable() const { return true; }
  10450. inline bool BufferStream::wait_writable() const { return true; }
  10451. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  10452. #if defined(_MSC_VER) && _MSC_VER < 1910
  10453. auto len_read = buffer._Copy_s(ptr, size, size, position);
  10454. #else
  10455. auto len_read = buffer.copy(ptr, size, position);
  10456. #endif
  10457. position += static_cast<size_t>(len_read);
  10458. return static_cast<ssize_t>(len_read);
  10459. }
  10460. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  10461. buffer.append(ptr, size);
  10462. return static_cast<ssize_t>(size);
  10463. }
  10464. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  10465. int & /*port*/) const {}
  10466. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  10467. int & /*port*/) const {}
  10468. inline socket_t BufferStream::socket() const { return 0; }
  10469. inline time_t BufferStream::duration() const { return 0; }
  10470. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  10471. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  10472. : MatcherBase(pattern) {
  10473. constexpr const char marker[] = "/:";
  10474. // One past the last ending position of a path param substring
  10475. std::size_t last_param_end = 0;
  10476. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10477. // Needed to ensure that parameter names are unique during matcher
  10478. // construction
  10479. // If exceptions are disabled, only last duplicate path
  10480. // parameter will be set
  10481. std::unordered_set<std::string> param_name_set;
  10482. #endif
  10483. while (true) {
  10484. const auto marker_pos = pattern.find(
  10485. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  10486. if (marker_pos == std::string::npos) { break; }
  10487. static_fragments_.push_back(
  10488. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  10489. const auto param_name_start = marker_pos + str_len(marker);
  10490. auto sep_pos = pattern.find(separator, param_name_start);
  10491. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  10492. auto param_name =
  10493. pattern.substr(param_name_start, sep_pos - param_name_start);
  10494. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10495. if (param_name_set.find(param_name) != param_name_set.cend()) {
  10496. std::string msg = "Encountered path parameter '" + param_name +
  10497. "' multiple times in route pattern '" + pattern + "'.";
  10498. throw std::invalid_argument(msg);
  10499. }
  10500. #endif
  10501. param_names_.push_back(std::move(param_name));
  10502. last_param_end = sep_pos + 1;
  10503. }
  10504. if (last_param_end < pattern.length()) {
  10505. static_fragments_.push_back(pattern.substr(last_param_end));
  10506. }
  10507. }
  10508. inline bool PathParamsMatcher::match(Request &request) const {
  10509. request.matches = std::smatch();
  10510. request.path_params.clear();
  10511. // A pattern without parameters is just a literal path to compare against
  10512. if (param_names_.empty()) { return request.path == pattern(); }
  10513. request.path_params.reserve(param_names_.size());
  10514. // One past the position at which the path matched the pattern last time
  10515. std::size_t starting_pos = 0;
  10516. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  10517. const auto &fragment = static_fragments_[i];
  10518. if (starting_pos + fragment.length() > request.path.length()) {
  10519. return false;
  10520. }
  10521. // Avoid unnecessary allocation by using strncmp instead of substr +
  10522. // comparison
  10523. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  10524. fragment.length()) != 0) {
  10525. return false;
  10526. }
  10527. starting_pos += fragment.length();
  10528. // Should only happen when we have a static fragment after a param
  10529. // Example: '/users/:id/subscriptions'
  10530. // The 'subscriptions' fragment here does not have a corresponding param
  10531. if (i >= param_names_.size()) { continue; }
  10532. auto sep_pos = request.path.find(separator, starting_pos);
  10533. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  10534. const auto &param_name = param_names_[i];
  10535. request.path_params.emplace(
  10536. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  10537. // Mark everything up to '/' as matched
  10538. starting_pos = sep_pos + 1;
  10539. }
  10540. // Returns false if the path is longer than the pattern
  10541. return starting_pos >= request.path.length();
  10542. }
  10543. inline bool RegexMatcher::match(Request &request) const {
  10544. request.path_params.clear();
  10545. // See CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH: an overlong path is treated as
  10546. // a non-match rather than risking a stack overflow in std::regex_match.
  10547. if (request.path.length() > CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH) {
  10548. return false;
  10549. }
  10550. return std::regex_match(request.path, request.matches, regex_);
  10551. }
  10552. // Enclose IPv6 address in brackets if needed
  10553. inline std::string prepare_host_string(const std::string &host) {
  10554. // Enclose IPv6 address in brackets (but not if already enclosed)
  10555. if (host.find(':') == std::string::npos ||
  10556. (!host.empty() && host[0] == '[')) {
  10557. // IPv4, hostname, or already bracketed IPv6
  10558. return host;
  10559. } else {
  10560. // IPv6 address without brackets
  10561. return "[" + host + "]";
  10562. }
  10563. }
  10564. inline std::string make_host_and_port_string(const std::string &host, int port,
  10565. bool is_ssl) {
  10566. auto result = prepare_host_string(host);
  10567. // Append port if not default
  10568. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  10569. ; // do nothing
  10570. } else {
  10571. result += ":" + std::to_string(port);
  10572. }
  10573. return result;
  10574. }
  10575. // Create "host:port" string always including port number (for CONNECT method)
  10576. inline std::string
  10577. make_host_and_port_string_always_port(const std::string &host, int port) {
  10578. return prepare_host_string(host) + ":" + std::to_string(port);
  10579. }
  10580. // Value for the Host header a client sends when the caller supplied none.
  10581. // Only the value: callers decide where in their header list it goes.
  10582. inline std::string make_default_host_header_value(const std::string &host,
  10583. int port, bool is_ssl,
  10584. int address_family) {
  10585. if (address_family == AF_UNIX) { return "localhost"; }
  10586. return make_host_and_port_string(host, port, is_ssl);
  10587. }
  10588. inline void add_default_user_agent_header(Request &req) {
  10589. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10590. if (!req.has_header("User-Agent")) {
  10591. req.set_header("User-Agent",
  10592. std::string("cpp-httplib/") + CPPHTTPLIB_VERSION);
  10593. }
  10594. #else
  10595. (void)req;
  10596. #endif
  10597. }
  10598. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  10599. NormalizedTarget normalize_target(const std::string &host);
  10600. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  10601. bool host_matches_no_proxy(const NormalizedTarget &target,
  10602. const std::vector<NoProxyEntry> &entries);
  10603. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  10604. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  10605. if (prefix_bits == 0) { return true; }
  10606. int full_bytes = prefix_bits / 8;
  10607. int rem_bits = prefix_bits % 8;
  10608. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  10609. static_cast<size_t>(full_bytes)) != 0) {
  10610. return false;
  10611. }
  10612. if (rem_bits == 0) { return true; }
  10613. auto i = static_cast<size_t>(full_bytes);
  10614. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  10615. return (ip[i] & mask) == (net[i] & mask);
  10616. }
  10617. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  10618. if (token.empty()) { return false; }
  10619. if (token == "*") {
  10620. out.kind = NoProxyKind::Wildcard;
  10621. return true;
  10622. }
  10623. auto slash = token.find('/');
  10624. std::string addr_part =
  10625. (slash == std::string::npos) ? token : token.substr(0, slash);
  10626. std::string prefix_part =
  10627. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  10628. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  10629. // don't silently treat it as a /32 (or /128).
  10630. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  10631. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  10632. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  10633. // when brackets are present.
  10634. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  10635. addr_part.back() == ']';
  10636. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  10637. if (!bracketed) {
  10638. struct in_addr v4;
  10639. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  10640. int prefix = 32;
  10641. if (!prefix_part.empty() &&
  10642. !parse_int_in_range(prefix_part.data(), prefix_part.size(), 0, 32,
  10643. prefix)) {
  10644. return false;
  10645. }
  10646. out.kind = NoProxyKind::IPv4Cidr;
  10647. std::memcpy(out.net.data(), &v4, sizeof(v4));
  10648. out.prefix_bits = prefix;
  10649. return true;
  10650. }
  10651. }
  10652. struct in6_addr v6;
  10653. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  10654. int prefix = 128;
  10655. if (!prefix_part.empty() &&
  10656. !parse_int_in_range(prefix_part.data(), prefix_part.size(), 0, 128,
  10657. prefix)) {
  10658. return false;
  10659. }
  10660. out.kind = NoProxyKind::IPv6Cidr;
  10661. std::memcpy(out.net.data(), &v6, sizeof(v6));
  10662. out.prefix_bits = prefix;
  10663. return true;
  10664. }
  10665. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  10666. // the entry is malformed — don't fall through to the hostname branch.
  10667. if (bracketed) { return false; }
  10668. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  10669. if (slash != std::string::npos) { return false; }
  10670. // Port-specific entries (host:port) are not supported.
  10671. if (token.find(':') != std::string::npos) { return false; }
  10672. std::string hostname = case_ignore::to_lower(token);
  10673. while (!hostname.empty() && hostname.front() == '.') {
  10674. hostname.erase(hostname.begin());
  10675. }
  10676. while (!hostname.empty() && hostname.back() == '.') {
  10677. hostname.pop_back();
  10678. }
  10679. if (hostname.empty()) { return false; }
  10680. out.kind = NoProxyKind::HostnameSuffix;
  10681. out.hostname_pattern = std::move(hostname);
  10682. return true;
  10683. }
  10684. inline NormalizedTarget normalize_target(const std::string &host) {
  10685. NormalizedTarget t;
  10686. std::string h = host;
  10687. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  10688. h = h.substr(1, h.size() - 2);
  10689. }
  10690. // Strip a single trailing dot so "example.com." canonicalizes to
  10691. // "example.com".
  10692. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  10693. t.hostname = case_ignore::to_lower(h);
  10694. if (!t.hostname.empty()) {
  10695. struct in_addr v4;
  10696. struct in6_addr v6;
  10697. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  10698. t.is_ipv4 = true;
  10699. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  10700. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  10701. t.is_ipv6 = true;
  10702. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  10703. }
  10704. }
  10705. return t;
  10706. }
  10707. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  10708. const std::vector<NoProxyEntry> &entries) {
  10709. if (target.hostname.empty()) { return false; }
  10710. for (const auto &e : entries) {
  10711. switch (e.kind) {
  10712. case NoProxyKind::Wildcard: return true;
  10713. case NoProxyKind::IPv4Cidr:
  10714. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10715. return true;
  10716. }
  10717. break;
  10718. case NoProxyKind::IPv6Cidr:
  10719. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10720. return true;
  10721. }
  10722. break;
  10723. case NoProxyKind::HostnameSuffix:
  10724. if (target.is_ipv4 || target.is_ipv6) { break; }
  10725. if (target.hostname == e.hostname_pattern) { return true; }
  10726. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  10727. // an entry of "example.com".
  10728. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  10729. auto offset = target.hostname.size() - e.hostname_pattern.size();
  10730. if (target.hostname[offset - 1] == '.' &&
  10731. target.hostname.compare(offset, e.hostname_pattern.size(),
  10732. e.hostname_pattern) == 0) {
  10733. return true;
  10734. }
  10735. }
  10736. break;
  10737. }
  10738. }
  10739. return false;
  10740. }
  10741. template <typename T>
  10742. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  10743. T header_writer, Error &error) {
  10744. for (const auto &h : headers) {
  10745. if (!detail::fields::is_field_valid(h.first, h.second)) {
  10746. error = Error::InvalidHeaders;
  10747. return false;
  10748. }
  10749. }
  10750. if (header_writer(strm, headers) <= 0) {
  10751. error = Error::Write;
  10752. return false;
  10753. }
  10754. return true;
  10755. }
  10756. } // namespace detail
  10757. /*
  10758. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  10759. */
  10760. #ifdef CPPHTTPLIB_SSL_ENABLED
  10761. namespace detail {
  10762. // SSL socket stream implementation
  10763. inline SSLSocketStream::SSLSocketStream(
  10764. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  10765. time_t read_timeout_usec, time_t write_timeout_sec,
  10766. time_t write_timeout_usec, time_t max_timeout_msec,
  10767. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10768. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10769. read_timeout_usec_(read_timeout_usec),
  10770. write_timeout_sec_(write_timeout_sec),
  10771. write_timeout_usec_(write_timeout_usec),
  10772. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  10773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10774. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  10775. // Note: create_session() also clears this, but SSLClient currently
  10776. // uses ssl_new() which does not. Until full TLS API migration is complete,
  10777. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  10778. // SSL session was created.
  10779. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  10780. #endif
  10781. }
  10782. inline SSLSocketStream::~SSLSocketStream() = default;
  10783. inline bool SSLSocketStream::is_readable() const {
  10784. return tls::pending(session_) > 0;
  10785. }
  10786. inline bool SSLSocketStream::wait_readable() const {
  10787. if (max_timeout_msec_ <= 0) {
  10788. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10789. }
  10790. time_t read_timeout_sec;
  10791. time_t read_timeout_usec;
  10792. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10793. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10794. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10795. }
  10796. inline bool SSLSocketStream::wait_writable() const {
  10797. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  10798. !tls::is_peer_closed(session_, sock_);
  10799. }
  10800. inline bool SSLSocketStream::ensure_readable() {
  10801. if (readable_hint_) {
  10802. readable_hint_ = false;
  10803. return true;
  10804. }
  10805. return wait_readable();
  10806. }
  10807. inline bool SSLSocketStream::is_peer_alive() const {
  10808. return !tls::is_peer_closed(session_, sock_);
  10809. }
  10810. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  10811. if (tls::pending(session_) > 0) {
  10812. tls::TlsError err;
  10813. auto ret = tls::read(session_, ptr, size, err);
  10814. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10815. error_ = Error::ConnectionClosed;
  10816. }
  10817. return ret;
  10818. } else if (ensure_readable()) {
  10819. tls::TlsError err;
  10820. auto ret = tls::read(session_, ptr, size, err);
  10821. if (ret < 0) {
  10822. auto n = 1000;
  10823. #ifdef _WIN32
  10824. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  10825. (err.code == tls::ErrorCode::SyscallError &&
  10826. WSAGetLastError() == WSAETIMEDOUT))) {
  10827. #else
  10828. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  10829. #endif
  10830. if (tls::pending(session_) > 0) {
  10831. return tls::read(session_, ptr, size, err);
  10832. } else if (wait_readable()) {
  10833. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10834. ret = tls::read(session_, ptr, size, err);
  10835. if (ret >= 0) { return ret; }
  10836. } else {
  10837. break;
  10838. }
  10839. }
  10840. assert(ret < 0);
  10841. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10842. error_ = Error::ConnectionClosed;
  10843. }
  10844. return ret;
  10845. } else {
  10846. error_ = Error::Timeout;
  10847. return -1;
  10848. }
  10849. }
  10850. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  10851. if (wait_writable()) {
  10852. auto handle_size =
  10853. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10854. tls::TlsError err;
  10855. auto ret = tls::write(session_, ptr, handle_size, err);
  10856. if (ret < 0) {
  10857. auto n = 1000;
  10858. #ifdef _WIN32
  10859. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  10860. (err.code == tls::ErrorCode::SyscallError &&
  10861. WSAGetLastError() == WSAETIMEDOUT))) {
  10862. #else
  10863. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  10864. #endif
  10865. if (wait_writable()) {
  10866. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10867. ret = tls::write(session_, ptr, handle_size, err);
  10868. if (ret >= 0) { return ret; }
  10869. } else {
  10870. break;
  10871. }
  10872. }
  10873. assert(ret < 0);
  10874. }
  10875. return ret;
  10876. }
  10877. return -1;
  10878. }
  10879. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  10880. int &port) const {
  10881. detail::get_remote_ip_and_port(sock_, ip, port);
  10882. }
  10883. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  10884. int &port) const {
  10885. detail::get_local_ip_and_port(sock_, ip, port);
  10886. }
  10887. inline socket_t SSLSocketStream::socket() const { return sock_; }
  10888. inline time_t SSLSocketStream::duration() const {
  10889. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10890. std::chrono::steady_clock::now() - start_time_)
  10891. .count();
  10892. }
  10893. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  10894. read_timeout_sec_ = sec;
  10895. read_timeout_usec_ = usec;
  10896. }
  10897. inline WebSocketSSLStream::WebSocketSSLStream(socket_t sock,
  10898. tls::session_t session,
  10899. time_t read_timeout_sec,
  10900. time_t read_timeout_usec,
  10901. time_t write_timeout_sec,
  10902. time_t write_timeout_usec)
  10903. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10904. read_timeout_usec_(read_timeout_usec),
  10905. write_timeout_sec_(write_timeout_sec),
  10906. write_timeout_usec_(write_timeout_usec),
  10907. start_time_(std::chrono::steady_clock::now()) {
  10908. // The receive and send paths run on different threads, so each TLS call is
  10909. // driven in non-blocking mode and readiness is awaited with select()
  10910. // outside the session lock. Set the socket non-blocking once here; it is
  10911. // never flipped back, so no thread races on the flag.
  10912. detail::set_nonblocking(sock_, true);
  10913. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10914. SSL_clear_mode(static_cast<SSL *>(session_), SSL_MODE_AUTO_RETRY);
  10915. #endif
  10916. }
  10917. inline WebSocketSSLStream::~WebSocketSSLStream() = default;
  10918. inline bool WebSocketSSLStream::is_readable() const {
  10919. std::lock_guard<std::mutex> guard(session_mutex_);
  10920. return tls::pending(session_) > 0;
  10921. }
  10922. inline bool WebSocketSSLStream::wait_readable() const {
  10923. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10924. }
  10925. inline bool WebSocketSSLStream::wait_writable() const {
  10926. // Unlike SSLSocketStream, this deliberately does not call is_peer_closed():
  10927. // that probe toggles the socket's blocking flag, which would race with the
  10928. // concurrent reader on a permanently non-blocking socket.
  10929. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  10930. }
  10931. inline ssize_t WebSocketSSLStream::read(char *ptr, size_t size) {
  10932. tls::TlsError err;
  10933. auto n = 1000;
  10934. while (--n >= 0) {
  10935. {
  10936. std::lock_guard<std::mutex> guard(session_mutex_);
  10937. auto ret = tls::read(session_, ptr, size, err);
  10938. if (ret > 0) { return ret; }
  10939. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10940. error_ = Error::ConnectionClosed;
  10941. return ret;
  10942. }
  10943. }
  10944. // ret < 0. On a non-blocking socket a TLS read can stop needing either
  10945. // direction: the send path shares this session, so output it left pending
  10946. // has to be flushed before more input can be decrypted. Anything else is
  10947. // a hard error.
  10948. auto needs_readable = err.code == tls::ErrorCode::WantRead;
  10949. #ifdef _WIN32
  10950. // On Windows a socket timeout surfaces as a syscall error, not WantRead.
  10951. needs_readable =
  10952. needs_readable || (err.code == tls::ErrorCode::SyscallError &&
  10953. WSAGetLastError() == WSAETIMEDOUT);
  10954. #endif
  10955. if (!needs_readable && err.code != tls::ErrorCode::WantWrite) {
  10956. error_ = Error::Read;
  10957. return -1;
  10958. }
  10959. if (!(needs_readable ? wait_readable() : wait_writable())) {
  10960. error_ = Error::Timeout;
  10961. return -1;
  10962. }
  10963. }
  10964. // Out of retries. Recording a reason matters: a caller that reads get_error()
  10965. // to tell a timeout from a close would otherwise see whatever the previous
  10966. // failure left behind (error_ is never cleared on success).
  10967. error_ = Error::Read;
  10968. return -1;
  10969. }
  10970. inline ssize_t WebSocketSSLStream::write(const char *ptr, size_t size) {
  10971. auto handle_size = std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10972. tls::TlsError err;
  10973. auto n = 1000;
  10974. while (--n >= 0) {
  10975. {
  10976. std::lock_guard<std::mutex> guard(session_mutex_);
  10977. auto ret = tls::write(session_, ptr, handle_size, err);
  10978. if (ret >= 0) { return ret; }
  10979. }
  10980. // ret < 0. As in read(), either direction can be needed: a renegotiation
  10981. // or a post-handshake message must be consumed before the record goes
  10982. // out. Anything else is a hard error.
  10983. auto needs_writable = err.code == tls::ErrorCode::WantWrite;
  10984. #ifdef _WIN32
  10985. // On Windows a socket timeout surfaces as a syscall error, not WantWrite.
  10986. needs_writable =
  10987. needs_writable || (err.code == tls::ErrorCode::SyscallError &&
  10988. WSAGetLastError() == WSAETIMEDOUT);
  10989. #endif
  10990. if (!needs_writable && err.code != tls::ErrorCode::WantRead) { return -1; }
  10991. if (!(needs_writable ? wait_writable() : wait_readable())) { return -1; }
  10992. }
  10993. return -1;
  10994. }
  10995. inline void WebSocketSSLStream::get_remote_ip_and_port(std::string &ip,
  10996. int &port) const {
  10997. detail::get_remote_ip_and_port(sock_, ip, port);
  10998. }
  10999. inline void WebSocketSSLStream::get_local_ip_and_port(std::string &ip,
  11000. int &port) const {
  11001. detail::get_local_ip_and_port(sock_, ip, port);
  11002. }
  11003. inline socket_t WebSocketSSLStream::socket() const { return sock_; }
  11004. inline time_t WebSocketSSLStream::duration() const {
  11005. return std::chrono::duration_cast<std::chrono::milliseconds>(
  11006. std::chrono::steady_clock::now() - start_time_)
  11007. .count();
  11008. }
  11009. inline void WebSocketSSLStream::set_read_timeout(time_t sec, time_t usec) {
  11010. read_timeout_sec_ = sec;
  11011. read_timeout_usec_ = usec;
  11012. }
  11013. } // namespace detail
  11014. #endif // CPPHTTPLIB_SSL_ENABLED
  11015. /*
  11016. * Group 4: Server implementation
  11017. */
  11018. // HTTP server implementation
  11019. inline Server::Server()
  11020. : new_task_queue([] {
  11021. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  11022. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  11023. }) {
  11024. #ifndef _WIN32
  11025. signal(SIGPIPE, SIG_IGN);
  11026. #endif
  11027. }
  11028. inline Server::~Server() = default;
  11029. inline std::unique_ptr<detail::MatcherBase>
  11030. Server::make_matcher(const std::string &pattern) {
  11031. // Path params take precedence, so "/users/:id/(.*)" keeps being matched as
  11032. // a path params pattern
  11033. if (pattern.find("/:") != std::string::npos) {
  11034. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  11035. }
  11036. // A pattern with no regex metacharacter only has to be compared literally,
  11037. // which is what PathParamsMatcher already does when it captures no
  11038. // parameter, so std::regex is only worth building for the patterns that
  11039. // actually need it
  11040. if (pattern.find_first_of(".^$|()[]{}*+?\\") == std::string::npos) {
  11041. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  11042. }
  11043. return detail::make_unique<detail::RegexMatcher>(pattern);
  11044. }
  11045. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  11046. return add_handler(get_handlers_, pattern, std::move(handler));
  11047. }
  11048. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  11049. return add_handler(post_handlers_, pattern, std::move(handler));
  11050. }
  11051. inline Server &Server::Post(const std::string &pattern,
  11052. HandlerWithContentReader handler) {
  11053. return add_handler(post_handlers_for_content_reader_, pattern,
  11054. std::move(handler));
  11055. }
  11056. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  11057. return add_handler(put_handlers_, pattern, std::move(handler));
  11058. }
  11059. inline Server &Server::Put(const std::string &pattern,
  11060. HandlerWithContentReader handler) {
  11061. return add_handler(put_handlers_for_content_reader_, pattern,
  11062. std::move(handler));
  11063. }
  11064. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  11065. return add_handler(patch_handlers_, pattern, std::move(handler));
  11066. }
  11067. inline Server &Server::Patch(const std::string &pattern,
  11068. HandlerWithContentReader handler) {
  11069. return add_handler(patch_handlers_for_content_reader_, pattern,
  11070. std::move(handler));
  11071. }
  11072. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  11073. return add_handler(delete_handlers_, pattern, std::move(handler));
  11074. }
  11075. inline Server &Server::Delete(const std::string &pattern,
  11076. HandlerWithContentReader handler) {
  11077. return add_handler(delete_handlers_for_content_reader_, pattern,
  11078. std::move(handler));
  11079. }
  11080. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  11081. return add_handler(options_handlers_, pattern, std::move(handler));
  11082. }
  11083. inline const std::set<std::string> &Server::builtin_methods() {
  11084. thread_local const std::set<std::string> methods{
  11085. "GET", "HEAD", "POST", "PUT", "DELETE",
  11086. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  11087. return methods;
  11088. }
  11089. inline Server::CustomHandlerEntry *
  11090. Server::custom_entry_for_registration(const std::string &method) {
  11091. // Built-in methods are refused for two different reasons. GET, HEAD, POST,
  11092. // PUT, DELETE, OPTIONS and PATCH are dispatched by the if/else chain in
  11093. // routing() before the custom tables are consulted, so a route registered
  11094. // for one of them could never fire. CONNECT, TRACE and PRI have no branch
  11095. // there and would be reachable, but they carry protocol-level meaning
  11096. // (tunnel setup, request echo, the HTTP/2 connection preface) that this
  11097. // library does not route.
  11098. if (!detail::fields::is_token(method) || builtin_methods().count(method)) {
  11099. output_error_log(Error::InvalidHTTPMethod, nullptr);
  11100. has_invalid_registration_ = true;
  11101. return nullptr;
  11102. }
  11103. return &custom_handlers_[method];
  11104. }
  11105. inline Server &Server::CustomRoute(const std::string &method,
  11106. const std::string &pattern,
  11107. Handler handler) {
  11108. auto *entry = custom_entry_for_registration(method);
  11109. if (!entry) { return *this; }
  11110. return add_handler(entry->handlers, pattern, std::move(handler));
  11111. }
  11112. inline Server &Server::CustomRoute(const std::string &method,
  11113. const std::string &pattern,
  11114. HandlerWithContentReader handler) {
  11115. auto *entry = custom_entry_for_registration(method);
  11116. if (!entry) { return *this; }
  11117. return add_handler(entry->handlers_for_content_reader, pattern,
  11118. std::move(handler));
  11119. }
  11120. inline const Server::CustomHandlerEntry *
  11121. Server::find_custom_entry(const std::string &method) const {
  11122. // find() alone would be correct here. The empty() check is what keeps the
  11123. // per-request cost off servers that never call CustomRoute(), which is the
  11124. // overwhelmingly common case; keep it rather than walking into the tree.
  11125. if (custom_handlers_.empty()) { return nullptr; }
  11126. auto it = custom_handlers_.find(method);
  11127. return it == custom_handlers_.end() ? nullptr : &it->second;
  11128. }
  11129. inline Server &Server::WebSocket(const std::string &pattern,
  11130. WebSocketHandler handler) {
  11131. websocket_handlers_.push_back(
  11132. {make_matcher(pattern), std::move(handler), nullptr});
  11133. return *this;
  11134. }
  11135. inline Server &Server::WebSocket(const std::string &pattern,
  11136. WebSocketHandler handler,
  11137. SubProtocolSelector sub_protocol_selector) {
  11138. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  11139. std::move(sub_protocol_selector)});
  11140. return *this;
  11141. }
  11142. inline bool Server::set_base_dir(const std::string &dir,
  11143. const std::string &mount_point) {
  11144. return set_mount_point(mount_point, dir);
  11145. }
  11146. inline bool Server::set_mount_point(const std::string &mount_point,
  11147. const std::string &dir, Headers headers) {
  11148. detail::FileStat stat(dir);
  11149. if (stat.is_dir()) {
  11150. std::string mnt = !mount_point.empty() ? mount_point : "/";
  11151. if (!mnt.empty() && mnt[0] == '/') {
  11152. std::string resolved_base;
  11153. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  11154. #if defined(_WIN32)
  11155. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  11156. resolved_base += '\\';
  11157. }
  11158. #else
  11159. if (resolved_base.back() != '/') { resolved_base += '/'; }
  11160. #endif
  11161. }
  11162. base_dirs_.push_back(
  11163. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  11164. return true;
  11165. }
  11166. }
  11167. return false;
  11168. }
  11169. inline bool Server::remove_mount_point(const std::string &mount_point) {
  11170. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  11171. if (it->mount_point == mount_point) {
  11172. base_dirs_.erase(it);
  11173. return true;
  11174. }
  11175. }
  11176. return false;
  11177. }
  11178. inline Server &
  11179. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  11180. const std::string &mime) {
  11181. file_extension_and_mimetype_map_[ext] = mime;
  11182. return *this;
  11183. }
  11184. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  11185. default_file_mimetype_ = mime;
  11186. return *this;
  11187. }
  11188. inline Server &Server::set_file_request_handler(Handler handler) {
  11189. file_request_handler_ = std::move(handler);
  11190. return *this;
  11191. }
  11192. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  11193. std::true_type) {
  11194. error_handler_ = std::move(handler);
  11195. return *this;
  11196. }
  11197. inline Server &Server::set_error_handler_core(Handler handler,
  11198. std::false_type) {
  11199. error_handler_ = [handler](const Request &req, Response &res) {
  11200. handler(req, res);
  11201. return HandlerResponse::Handled;
  11202. };
  11203. return *this;
  11204. }
  11205. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  11206. exception_handler_ = std::move(handler);
  11207. return *this;
  11208. }
  11209. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  11210. pre_routing_handler_ = std::move(handler);
  11211. return *this;
  11212. }
  11213. inline Server &Server::set_post_routing_handler(Handler handler) {
  11214. post_routing_handler_ = std::move(handler);
  11215. return *this;
  11216. }
  11217. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  11218. pre_request_handler_ = std::move(handler);
  11219. return *this;
  11220. }
  11221. inline Server &Server::set_logger(Logger logger) {
  11222. logger_ = std::move(logger);
  11223. return *this;
  11224. }
  11225. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  11226. error_logger_ = std::move(error_logger);
  11227. return *this;
  11228. }
  11229. inline Server &Server::set_pre_compression_logger(Logger logger) {
  11230. pre_compression_logger_ = std::move(logger);
  11231. return *this;
  11232. }
  11233. inline Server &
  11234. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  11235. expect_100_continue_handler_ = std::move(handler);
  11236. return *this;
  11237. }
  11238. inline Server &Server::set_start_handler(StartHandler handler) {
  11239. start_handler_ = std::move(handler);
  11240. return *this;
  11241. }
  11242. inline Server &Server::set_address_family(int family) {
  11243. address_family_ = family;
  11244. return *this;
  11245. }
  11246. inline Server &Server::set_tcp_nodelay(bool on) {
  11247. tcp_nodelay_ = on;
  11248. return *this;
  11249. }
  11250. inline Server &Server::set_ipv6_v6only(bool on) {
  11251. ipv6_v6only_ = on;
  11252. return *this;
  11253. }
  11254. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  11255. socket_options_ = std::move(socket_options);
  11256. return *this;
  11257. }
  11258. inline Server &Server::set_default_headers(Headers headers) {
  11259. default_headers_ = std::move(headers);
  11260. return *this;
  11261. }
  11262. inline Server &Server::set_header_writer(
  11263. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11264. header_writer_ = writer;
  11265. return *this;
  11266. }
  11267. inline Server &
  11268. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  11269. trusted_proxies_ = proxies;
  11270. return *this;
  11271. }
  11272. inline Server &Server::set_keep_alive_max_count(size_t count) {
  11273. keep_alive_max_count_ = count;
  11274. return *this;
  11275. }
  11276. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  11277. keep_alive_timeout_sec_ = sec;
  11278. return *this;
  11279. }
  11280. template <class Rep, class Period>
  11281. inline Server &Server::set_keep_alive_timeout(
  11282. const std::chrono::duration<Rep, Period> &duration) {
  11283. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  11284. set_keep_alive_timeout(sec);
  11285. });
  11286. return *this;
  11287. }
  11288. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  11289. read_timeout_sec_ = sec;
  11290. read_timeout_usec_ = usec;
  11291. return *this;
  11292. }
  11293. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  11294. write_timeout_sec_ = sec;
  11295. write_timeout_usec_ = usec;
  11296. return *this;
  11297. }
  11298. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  11299. idle_interval_sec_ = sec;
  11300. idle_interval_usec_ = usec;
  11301. return *this;
  11302. }
  11303. inline Server &Server::set_payload_max_length(size_t length) {
  11304. payload_max_length_ = length;
  11305. return *this;
  11306. }
  11307. inline Server &Server::set_static_file_compression(bool on) {
  11308. static_file_compression_ = on;
  11309. return *this;
  11310. }
  11311. inline Server &Server::set_static_file_compression_min_length(size_t length) {
  11312. static_file_compression_min_length_ = length;
  11313. return *this;
  11314. }
  11315. inline Server &Server::set_static_file_compression_max_length(size_t length) {
  11316. static_file_compression_max_length_ = length;
  11317. return *this;
  11318. }
  11319. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  11320. websocket_max_missed_pongs_ = count;
  11321. return *this;
  11322. }
  11323. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  11324. websocket_ping_interval_sec_ = sec;
  11325. return *this;
  11326. }
  11327. template <class Rep, class Period>
  11328. inline Server &Server::set_websocket_ping_interval(
  11329. const std::chrono::duration<Rep, Period> &duration) {
  11330. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  11331. set_websocket_ping_interval(sec);
  11332. });
  11333. return *this;
  11334. }
  11335. inline bool Server::bind_to_port(const std::string &host, int port,
  11336. int socket_flags) {
  11337. auto ret = bind_internal(host, port, socket_flags);
  11338. if (ret == -1) { is_decommissioned = true; }
  11339. return ret >= 0;
  11340. }
  11341. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  11342. auto ret = bind_internal(host, 0, socket_flags);
  11343. if (ret == -1) { is_decommissioned = true; }
  11344. return ret;
  11345. }
  11346. inline bool Server::listen_after_bind() { return listen_internal(); }
  11347. inline bool Server::listen(const std::string &host, int port,
  11348. int socket_flags) {
  11349. return bind_to_port(host, port, socket_flags) && listen_internal();
  11350. }
  11351. inline bool Server::is_running() const { return is_running_; }
  11352. inline void Server::wait_until_ready() const {
  11353. while (!is_running_ && !is_decommissioned) {
  11354. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  11355. }
  11356. }
  11357. inline void Server::stop() noexcept {
  11358. // Release the listening socket whether or not the accept loop is running:
  11359. // bind_to_port() without listen_after_bind() still owns the descriptor. The
  11360. // exchange is what makes this safe to call concurrently with the accept loop.
  11361. socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
  11362. if (sock != INVALID_SOCKET) {
  11363. detail::shutdown_socket(sock);
  11364. detail::close_socket(sock);
  11365. }
  11366. is_decommissioned = false;
  11367. }
  11368. inline void Server::decommission() { is_decommissioned = true; }
  11369. inline bool Server::parse_request_line(const char *s, Request &req) const {
  11370. auto len = strlen(s);
  11371. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  11372. len -= 2;
  11373. {
  11374. size_t count = 0;
  11375. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  11376. switch (count) {
  11377. case 0: req.method = std::string(b, e); break;
  11378. case 1: req.target = std::string(b, e); break;
  11379. case 2: req.version = std::string(b, e); break;
  11380. default: break;
  11381. }
  11382. count++;
  11383. });
  11384. if (count != 3) { return false; }
  11385. }
  11386. // A method outside the built-in set is accepted only when a handler has been
  11387. // registered for it with CustomRoute().
  11388. const auto &methods = builtin_methods();
  11389. if (methods.find(req.method) == methods.end() &&
  11390. !find_custom_entry(req.method)) {
  11391. output_error_log(Error::InvalidHTTPMethod, &req);
  11392. return false;
  11393. }
  11394. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  11395. output_error_log(Error::InvalidHTTPVersion, &req);
  11396. return false;
  11397. }
  11398. if (!detail::fields::is_request_target(req.target)) { return false; }
  11399. {
  11400. // Skip URL fragment
  11401. for (size_t i = 0; i < req.target.size(); i++) {
  11402. if (req.target[i] == '#') {
  11403. req.target.erase(i);
  11404. break;
  11405. }
  11406. }
  11407. detail::divide(req.target, '?',
  11408. [&](const char *lhs_data, std::size_t lhs_size,
  11409. const char *rhs_data, std::size_t rhs_size) {
  11410. req.path =
  11411. decode_path_component(std::string(lhs_data, lhs_size));
  11412. detail::parse_query_text(rhs_data, rhs_size, req.params);
  11413. });
  11414. }
  11415. return true;
  11416. }
  11417. inline bool Server::write_response(Stream &strm, bool close_connection,
  11418. Request &req, Response &res) {
  11419. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  11420. // incorrectly to the error content.
  11421. req.ranges.clear();
  11422. return write_response_core(strm, close_connection, req, res, false);
  11423. }
  11424. inline bool Server::write_response_with_content(Stream &strm,
  11425. bool close_connection,
  11426. const Request &req,
  11427. Response &res) {
  11428. return write_response_core(strm, close_connection, req, res, true);
  11429. }
  11430. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  11431. const Request &req, Response &res,
  11432. bool need_apply_ranges) {
  11433. assert(res.status != -1);
  11434. if (400 <= res.status && error_handler_ &&
  11435. error_handler_(req, res) == HandlerResponse::Handled) {
  11436. need_apply_ranges = true;
  11437. }
  11438. std::string content_type;
  11439. std::string boundary;
  11440. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  11441. // Prepare additional headers
  11442. if (close_connection ||
  11443. detail::has_header_token(req.headers, "Connection", "close") ||
  11444. 400 <= res.status || // Don't leave connections open after errors
  11445. // The client withholds the body until `100 Continue`, which was never
  11446. // sent, so whether and when the body follows is unknown.
  11447. (req.expect_100_continue_pending_ && detail::has_framed_body(req))) {
  11448. res.set_header("Connection", "close");
  11449. } else {
  11450. std::string s = "timeout=";
  11451. s += std::to_string(keep_alive_timeout_sec_);
  11452. s += ", max=";
  11453. s += std::to_string(keep_alive_max_count_);
  11454. res.set_header("Keep-Alive", s);
  11455. }
  11456. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  11457. !res.has_header("Content-Type")) {
  11458. res.set_header("Content-Type", "text/plain");
  11459. }
  11460. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  11461. !res.has_header("Content-Length")) {
  11462. res.set_header("Content-Length", "0");
  11463. }
  11464. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  11465. res.set_header("Accept-Ranges", "bytes");
  11466. }
  11467. if (post_routing_handler_) { post_routing_handler_(req, res); }
  11468. // Response line and headers
  11469. detail::BufferStream bstrm;
  11470. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  11471. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  11472. // Combine a small body with the headers so the whole response leaves in a
  11473. // single write. A large body is written on its own instead: a copy of it
  11474. // costs more than the extra write saves.
  11475. auto send_body = req.method != "HEAD";
  11476. auto body_is_separate = false;
  11477. auto provider_done = false;
  11478. if (send_body && !res.body.empty() && !res.content_provider_) {
  11479. if (res.body.size() < CPPHTTPLIB_SEND_BUFSIZ) {
  11480. bstrm.write(res.body.data(), res.body.size());
  11481. } else {
  11482. body_is_separate = true;
  11483. }
  11484. } else if (send_body && res.content_provider_ &&
  11485. res.is_file_content_provider_ &&
  11486. res.content_length_ < CPPHTTPLIB_SEND_BUFSIZ) {
  11487. // A small file is read into the same buffer. Other providers may produce
  11488. // their data over time, so they are never held back.
  11489. if (!write_content_with_provider(bstrm, req, res, boundary, content_type)) {
  11490. return false;
  11491. }
  11492. provider_done = true;
  11493. }
  11494. // Log before writing to avoid race condition with client-side code that
  11495. // accesses logger-captured data immediately after receiving the response.
  11496. output_log(req, res);
  11497. // Flush buffer
  11498. auto &data = bstrm.get_buffer();
  11499. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  11500. if (body_is_separate) {
  11501. return detail::write_data(strm, res.body.data(), res.body.size());
  11502. }
  11503. // Streaming body
  11504. if (send_body && res.content_provider_) {
  11505. if (!provider_done &&
  11506. !write_content_with_provider(strm, req, res, boundary, content_type)) {
  11507. return false;
  11508. }
  11509. res.content_provider_success_ = true;
  11510. }
  11511. return true;
  11512. }
  11513. inline bool
  11514. Server::write_content_with_provider(Stream &strm, const Request &req,
  11515. Response &res, const std::string &boundary,
  11516. const std::string &content_type) {
  11517. auto is_shutting_down = [this]() {
  11518. return this->svr_sock_ == INVALID_SOCKET;
  11519. };
  11520. if (res.content_length_ > 0) {
  11521. // Only a 206 response is served as a partial representation, matching the
  11522. // condition `apply_ranges()` used to decide the Content-Length and the
  11523. // multipart boundary. Since `detail::range_error()` validates `req.ranges`
  11524. // only for a 2xx status, slicing under any other status would write a body
  11525. // that disagrees with the header already sent, from an unchecked offset.
  11526. auto is_partial =
  11527. !req.ranges.empty() && res.status == StatusCode::PartialContent_206;
  11528. if (!is_partial) {
  11529. return detail::write_content(strm, res.content_provider_, 0,
  11530. res.content_length_, is_shutting_down);
  11531. } else if (req.ranges.size() == 1) {
  11532. auto offset_and_length = detail::get_range_offset_and_length(
  11533. req.ranges[0], res.content_length_);
  11534. return detail::write_content(strm, res.content_provider_,
  11535. offset_and_length.first,
  11536. offset_and_length.second, is_shutting_down);
  11537. } else {
  11538. return detail::write_multipart_ranges_data(
  11539. strm, req, res, boundary, content_type, res.content_length_,
  11540. is_shutting_down);
  11541. }
  11542. } else {
  11543. if (res.is_chunked_content_provider_) {
  11544. // Use the coding `apply_ranges()` chose when it wrote the headers;
  11545. // re-negotiating here would disagree with them, e.g. once a handler's
  11546. // own Content-Encoding header suppresses the negotiation.
  11547. auto compressor = detail::make_compressor(res.content_coding_);
  11548. if (!compressor) {
  11549. compressor = detail::make_unique<detail::nocompressor>();
  11550. }
  11551. return detail::write_content_chunked(strm, res.content_provider_,
  11552. is_shutting_down, *compressor);
  11553. } else {
  11554. return detail::write_content_without_length(strm, res.content_provider_,
  11555. is_shutting_down);
  11556. }
  11557. }
  11558. }
  11559. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  11560. FormFields::iterator cur_field;
  11561. FormFiles::iterator cur_file;
  11562. auto is_text_field = false;
  11563. size_t count = 0;
  11564. if (read_content_core(
  11565. strm, req, res,
  11566. // Regular
  11567. [&](const char *buf, size_t n) {
  11568. // Prevent arithmetic overflow when checking sizes.
  11569. // Avoid computing (req.body.size() + n) directly because
  11570. // adding two unsigned `size_t` values can wrap around and
  11571. // produce a small result instead of indicating overflow.
  11572. // Instead, check using subtraction: ensure `n` does not
  11573. // exceed the remaining capacity `max_size() - size()`.
  11574. if (req.body.size() >= req.body.max_size() ||
  11575. n > req.body.max_size() - req.body.size()) {
  11576. return false;
  11577. }
  11578. // Limit decompressed body size to payload_max_length_ to protect
  11579. // against "zip bomb" attacks where a small compressed payload
  11580. // decompresses to a massive size.
  11581. if (payload_max_length_ > 0 &&
  11582. (req.body.size() >= payload_max_length_ ||
  11583. n > payload_max_length_ - req.body.size())) {
  11584. return false;
  11585. }
  11586. req.body.append(buf, n);
  11587. return true;
  11588. },
  11589. // Multipart FormData
  11590. [&](const FormData &file) {
  11591. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  11592. output_error_log(Error::TooManyFormDataFiles, &req);
  11593. return false;
  11594. }
  11595. if (file.filename.empty()) {
  11596. cur_field = req.form.fields.emplace(
  11597. file.name, FormField{file.name, file.content, file.headers});
  11598. is_text_field = true;
  11599. } else {
  11600. cur_file = req.form.files.emplace(file.name, file);
  11601. is_text_field = false;
  11602. }
  11603. return true;
  11604. },
  11605. [&](const char *buf, size_t n) {
  11606. if (is_text_field) {
  11607. auto &content = cur_field->second.content;
  11608. if (content.size() + n > content.max_size()) { return false; }
  11609. content.append(buf, n);
  11610. } else {
  11611. auto &content = cur_file->second.content;
  11612. if (content.size() + n > content.max_size()) { return false; }
  11613. content.append(buf, n);
  11614. }
  11615. return true;
  11616. })) {
  11617. const auto &content_type = req.get_header_value("Content-Type");
  11618. if (detail::extract_media_type(content_type) ==
  11619. "application/x-www-form-urlencoded") {
  11620. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  11621. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  11622. output_error_log(Error::ExceedMaxPayloadSize, &req);
  11623. return false;
  11624. }
  11625. detail::parse_query_text(req.body, req.params);
  11626. }
  11627. return true;
  11628. }
  11629. return false;
  11630. }
  11631. inline bool Server::read_content_with_content_receiver(
  11632. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11633. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  11634. return read_content_core(strm, req, res, std::move(receiver),
  11635. std::move(multipart_header),
  11636. std::move(multipart_receiver));
  11637. }
  11638. inline bool Server::read_content_core(
  11639. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11640. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  11641. detail::FormDataParser multipart_form_data_parser;
  11642. ContentReceiverWithProgress out;
  11643. if (req.is_multipart_form_data()) {
  11644. const auto &content_type = req.get_header_value("Content-Type");
  11645. std::string boundary;
  11646. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  11647. res.status = StatusCode::BadRequest_400;
  11648. output_error_log(Error::MultipartParsing, &req);
  11649. return false;
  11650. }
  11651. multipart_form_data_parser.set_boundary(std::move(boundary));
  11652. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  11653. return multipart_form_data_parser.parse(buf, n, multipart_header,
  11654. multipart_receiver);
  11655. };
  11656. } else {
  11657. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  11658. size_t /*len*/) { return receiver(buf, n); };
  11659. }
  11660. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  11661. // For non-SSL builds we still scan non-persistent connections for stray
  11662. // body bytes so the payload limit is enforced (413). On keep-alive,
  11663. // pending bytes may be the next request (issue #2450), so skip.
  11664. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  11665. if (!req.has_header("Content-Length") &&
  11666. !detail::is_chunked_transfer_encoding(req.headers)) {
  11667. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  11668. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  11669. auto has_data = strm.is_readable();
  11670. if (!has_data) {
  11671. auto s = strm.socket();
  11672. if (s != INVALID_SOCKET) {
  11673. has_data = detail::select_read(s, 0, 0) > 0;
  11674. }
  11675. }
  11676. if (has_data) {
  11677. // Route through the same decompressing reader used by the
  11678. // length-framed and chunked paths below, so payload_max_length_ is
  11679. // enforced on the decompressed size here too instead of only on the
  11680. // compressed wire bytes.
  11681. return detail::read_content(strm, req, payload_max_length_, res.status,
  11682. nullptr, out, true);
  11683. }
  11684. }
  11685. return true;
  11686. }
  11687. #else
  11688. if (!req.has_header("Content-Length") &&
  11689. !detail::is_chunked_transfer_encoding(req.headers)) {
  11690. return true;
  11691. }
  11692. #endif
  11693. // The client is waiting for this before it sends the body.
  11694. if (req.expect_100_continue_pending_) {
  11695. req.expect_100_continue_pending_ = false;
  11696. detail::write_response_line(strm, StatusCode::Continue_100);
  11697. strm.write("\r\n");
  11698. }
  11699. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  11700. out, true)) {
  11701. return false;
  11702. }
  11703. req.body_consumed_ = true;
  11704. if (req.is_multipart_form_data()) {
  11705. if (!multipart_form_data_parser.is_valid()) {
  11706. res.status = StatusCode::BadRequest_400;
  11707. output_error_log(Error::MultipartParsing, &req);
  11708. return false;
  11709. }
  11710. }
  11711. return true;
  11712. }
  11713. inline bool Server::handle_file_request(Request &req, Response &res) {
  11714. for (const auto &entry : base_dirs_) {
  11715. // Prefix match, on a path segment boundary. A mount point of "/mount"
  11716. // covers "/mount" and "/mount/...", but must not swallow "/mountdir/...".
  11717. // One that already ends in '/' (the root mount among them) carries its own
  11718. // boundary; set_mount_point() guarantees the mount point is not empty.
  11719. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point) &&
  11720. (entry.mount_point.back() == '/' ||
  11721. req.path.size() == entry.mount_point.size() ||
  11722. req.path[entry.mount_point.size()] == '/')) {
  11723. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  11724. if (detail::is_valid_path(sub_path)) {
  11725. auto path = entry.base_dir + sub_path;
  11726. if (path.back() == '/') { path += "index.html"; }
  11727. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  11728. // but symlinks/junctions can still escape the base directory.
  11729. if (!entry.resolved_base_dir.empty()) {
  11730. std::string resolved_path;
  11731. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  11732. !detail::is_path_within_base(resolved_path,
  11733. entry.resolved_base_dir)) {
  11734. res.status = StatusCode::Forbidden_403;
  11735. return true;
  11736. }
  11737. }
  11738. detail::FileStat stat(path);
  11739. if (stat.is_dir()) {
  11740. // Relative, so "//dir" cannot name another host; "./" keeps a ':'
  11741. // in the name from reading as a scheme.
  11742. auto name = req.path.substr(req.path.rfind('/') + 1);
  11743. res.set_redirect("./" + encode_path_component(name) + "/",
  11744. StatusCode::MovedPermanently_301);
  11745. return true;
  11746. }
  11747. if (stat.is_file()) {
  11748. for (const auto &kv : entry.headers) {
  11749. res.set_header(kv.first, kv.second);
  11750. }
  11751. auto content_type_of = [&]() {
  11752. return detail::find_content_type(
  11753. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  11754. };
  11755. // Only the ETag needs the content type this early, and only to name
  11756. // the coding. Deciding it here would otherwise put a regex in front
  11757. // of the 304 below, which serving a file never used to pay for.
  11758. std::string content_type;
  11759. auto encoding = detail::EncodingType::None;
  11760. if (static_file_compression_) {
  11761. content_type = content_type_of();
  11762. encoding =
  11763. static_file_encoding(req, res, content_type, stat.size());
  11764. }
  11765. // The ETag names the representation actually sent, so a client that
  11766. // cached the compressed form revalidates against the compressed ETag
  11767. // and still gets a 304, while one that took identity keeps the plain
  11768. // ETag.
  11769. auto etag = detail::compute_etag(
  11770. stat, encoding == detail::EncodingType::None
  11771. ? std::string()
  11772. : std::string("-") + detail::encoding_name(encoding));
  11773. if (!etag.empty()) { res.set_header("ETag", etag); }
  11774. auto mtime = stat.mtime();
  11775. auto last_modified = detail::file_mtime_to_http_date(mtime);
  11776. if (!last_modified.empty()) {
  11777. res.set_header("Last-Modified", last_modified);
  11778. }
  11779. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  11780. check_if_range(req, etag, mtime);
  11781. auto mm = std::make_shared<detail::mmap>(path.c_str());
  11782. if (!mm->is_open()) {
  11783. output_error_log(Error::OpenFile, &req);
  11784. return false;
  11785. }
  11786. if (!static_file_compression_) { content_type = content_type_of(); }
  11787. detail::set_file_content_provider(res, mm, content_type, encoding);
  11788. if (req.method != "HEAD" && file_request_handler_) {
  11789. file_request_handler_(req, res);
  11790. }
  11791. return true;
  11792. } else {
  11793. output_error_log(Error::OpenFile, &req);
  11794. }
  11795. }
  11796. }
  11797. }
  11798. return false;
  11799. }
  11800. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  11801. const std::string &etag,
  11802. time_t mtime) const {
  11803. // Handle conditional GET:
  11804. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  11805. // 2. If-Modified-Since is checked only when If-None-Match is absent
  11806. if (req.has_header("If-None-Match")) {
  11807. if (!etag.empty()) {
  11808. auto val =
  11809. detail::get_combined_header_value(req.headers, "If-None-Match");
  11810. // NOTE: We use exact string matching here. This works correctly
  11811. // because our server always generates weak ETags (W/"..."), and
  11812. // clients typically send back the same ETag they received.
  11813. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  11814. // If-None-Match, where W/"x" and "x" would match, but this
  11815. // simplified implementation requires exact matches.
  11816. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  11817. [&](const char *b, const char *e) {
  11818. auto seg_len = static_cast<size_t>(e - b);
  11819. return (seg_len == 1 && *b == '*') ||
  11820. (seg_len == etag.size() &&
  11821. std::equal(b, e, etag.begin()));
  11822. });
  11823. if (ret) {
  11824. res.status = StatusCode::NotModified_304;
  11825. return true;
  11826. }
  11827. }
  11828. } else if (req.has_header("If-Modified-Since")) {
  11829. auto val = req.get_header_value("If-Modified-Since");
  11830. auto t = detail::parse_http_date(val);
  11831. if (t != static_cast<time_t>(-1) && mtime <= t) {
  11832. res.status = StatusCode::NotModified_304;
  11833. return true;
  11834. }
  11835. }
  11836. return false;
  11837. }
  11838. inline bool Server::check_if_range(Request &req, const std::string &etag,
  11839. time_t mtime) const {
  11840. // Handle If-Range for partial content requests (RFC 9110
  11841. // Section 13.1.5). If-Range is only evaluated when Range header is
  11842. // present. If the validator matches, serve partial content; otherwise
  11843. // serve full content.
  11844. if (!req.ranges.empty() && req.has_header("If-Range")) {
  11845. auto val = req.get_header_value("If-Range");
  11846. auto is_valid_range = [&]() {
  11847. if (detail::is_strong_etag(val)) {
  11848. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  11849. // comparison.
  11850. return (!etag.empty() && val == etag);
  11851. } else if (detail::is_weak_etag(val)) {
  11852. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  11853. return false;
  11854. } else {
  11855. // HTTP-date comparison
  11856. auto t = detail::parse_http_date(val);
  11857. return (t != static_cast<time_t>(-1) && mtime <= t);
  11858. }
  11859. };
  11860. if (!is_valid_range()) {
  11861. // Validator doesn't match: ignore Range and serve full content
  11862. req.ranges.clear();
  11863. return false;
  11864. }
  11865. }
  11866. return true;
  11867. }
  11868. inline socket_t
  11869. Server::create_server_socket(const std::string &host, int port,
  11870. int socket_flags,
  11871. SocketOptions socket_options) const {
  11872. return detail::create_socket(
  11873. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  11874. ipv6_v6only_, std::move(socket_options),
  11875. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  11876. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  11877. output_error_log(Error::BindIPAddress, nullptr);
  11878. return false;
  11879. }
  11880. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  11881. output_error_log(Error::Listen, nullptr);
  11882. return false;
  11883. }
  11884. return true;
  11885. });
  11886. }
  11887. inline int Server::bind_internal(const std::string &host, int port,
  11888. int socket_flags) {
  11889. if (is_decommissioned) { return -1; }
  11890. if (!is_valid()) { return -1; }
  11891. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  11892. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  11893. if (port == 0) {
  11894. struct sockaddr_storage addr;
  11895. socklen_t addr_len = sizeof(addr);
  11896. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  11897. &addr_len) == -1) {
  11898. output_error_log(Error::GetSockName, nullptr);
  11899. return -1;
  11900. }
  11901. if (addr.ss_family == AF_INET) {
  11902. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  11903. } else if (addr.ss_family == AF_INET6) {
  11904. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  11905. } else {
  11906. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  11907. return -1;
  11908. }
  11909. } else {
  11910. return port;
  11911. }
  11912. }
  11913. inline bool Server::listen_internal() {
  11914. // A stop() between bind and listen leaves nothing to accept on. Report
  11915. // failure instead of returning success without ever serving, and mark the
  11916. // server decommissioned the way any failed listen does so that a concurrent
  11917. // wait_until_ready() wakes up instead of spinning forever.
  11918. if (is_decommissioned || svr_sock_ == INVALID_SOCKET) {
  11919. is_decommissioned = true;
  11920. return false;
  11921. }
  11922. auto ret = true;
  11923. is_running_ = true;
  11924. auto se = detail::scope_exit([&]() { is_running_ = false; });
  11925. if (start_handler_) { start_handler_(); }
  11926. {
  11927. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  11928. while (svr_sock_ != INVALID_SOCKET) {
  11929. #ifndef _WIN32
  11930. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  11931. #endif
  11932. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  11933. idle_interval_usec_);
  11934. if (val == 0) { // Timeout
  11935. task_queue->on_idle();
  11936. continue;
  11937. }
  11938. #ifndef _WIN32
  11939. }
  11940. #endif
  11941. #if defined _WIN32
  11942. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  11943. // OVERLAPPED
  11944. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  11945. #elif defined SOCK_CLOEXEC
  11946. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  11947. #else
  11948. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  11949. #endif
  11950. if (sock == INVALID_SOCKET) {
  11951. // NOTE: Winsock reports failures through WSAGetLastError() and never
  11952. // touches the CRT errno, so the two have to be asked platform by
  11953. // platform rather than by testing errno here.
  11954. if (detail::is_accept_resource_error()) {
  11955. // The per-process descriptor limit or the network stack's buffer
  11956. // space has been reached. Try to accept new connections after a
  11957. // short sleep.
  11958. std::this_thread::sleep_for(std::chrono::microseconds{1});
  11959. continue;
  11960. } else if (detail::is_accept_transient_error()) {
  11961. continue;
  11962. }
  11963. // Take the descriptor out of svr_sock_ before closing it: a later
  11964. // stop() would otherwise shutdown()/close() a value the OS may have
  11965. // reused, and keep_alive() watches svr_sock_ to notice the server is
  11966. // gone. The exchange also settles the race with a concurrent stop(),
  11967. // since whichever side takes the descriptor closes it exactly once.
  11968. auto listen_sock = svr_sock_.exchange(INVALID_SOCKET);
  11969. if (listen_sock != INVALID_SOCKET) {
  11970. detail::close_socket(listen_sock);
  11971. ret = false;
  11972. output_error_log(Error::Connection, nullptr);
  11973. } else {
  11974. ; // The server socket was closed by user.
  11975. }
  11976. break;
  11977. }
  11978. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  11979. read_timeout_sec_, read_timeout_usec_);
  11980. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  11981. write_timeout_sec_, write_timeout_usec_);
  11982. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  11983. if (!task_queue->enqueue(
  11984. [this, sock]() { process_and_close_socket(sock); })) {
  11985. output_error_log(Error::ResourceExhaustion, nullptr);
  11986. detail::shutdown_socket(sock);
  11987. detail::close_socket(sock);
  11988. }
  11989. }
  11990. task_queue->shutdown();
  11991. }
  11992. is_decommissioned = !ret;
  11993. return ret;
  11994. }
  11995. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  11996. if (pre_routing_handler_ &&
  11997. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  11998. return true;
  11999. }
  12000. // File handler
  12001. if ((req.method == "GET" || req.method == "HEAD") &&
  12002. handle_file_request(req, res)) {
  12003. return true;
  12004. }
  12005. const auto *custom = find_custom_entry(req.method);
  12006. // The second clause mirrors what expect_content() does unconditionally for
  12007. // POST/PUT/PATCH/DELETE: a content reader route fires even when the request
  12008. // carries no body. Without it a body-less PROPFIND (RFC 4918 treats one as
  12009. // `allprop`) would skip its handler and fall through to 404.
  12010. if (detail::expect_content(req) ||
  12011. (custom && !custom->handlers_for_content_reader.empty())) {
  12012. // Content reader handler
  12013. {
  12014. // Track whether the ContentReader was aborted due to the decompressed
  12015. // payload exceeding `payload_max_length_`.
  12016. // The user handler runs after the lambda returns, so we must restore the
  12017. // 413 status if the handler overwrites it.
  12018. bool content_reader_payload_too_large = false;
  12019. ContentReader reader(
  12020. [&](ContentReceiver receiver) {
  12021. auto result = read_content_with_content_receiver(
  12022. strm, req, res, std::move(receiver), nullptr, nullptr);
  12023. if (!result) {
  12024. output_error_log(Error::Read, &req);
  12025. if (res.status == StatusCode::PayloadTooLarge_413) {
  12026. content_reader_payload_too_large = true;
  12027. }
  12028. }
  12029. return result;
  12030. },
  12031. [&](FormDataHeader header, ContentReceiver receiver) {
  12032. auto result = read_content_with_content_receiver(
  12033. strm, req, res, nullptr, std::move(header),
  12034. std::move(receiver));
  12035. if (!result) {
  12036. output_error_log(Error::Read, &req);
  12037. if (res.status == StatusCode::PayloadTooLarge_413) {
  12038. content_reader_payload_too_large = true;
  12039. }
  12040. }
  12041. return result;
  12042. });
  12043. bool dispatched = false;
  12044. if (req.method == "POST") {
  12045. dispatched = dispatch_request_for_content_reader(
  12046. req, res, std::move(reader), post_handlers_for_content_reader_);
  12047. } else if (req.method == "PUT") {
  12048. dispatched = dispatch_request_for_content_reader(
  12049. req, res, std::move(reader), put_handlers_for_content_reader_);
  12050. } else if (req.method == "PATCH") {
  12051. dispatched = dispatch_request_for_content_reader(
  12052. req, res, std::move(reader), patch_handlers_for_content_reader_);
  12053. } else if (req.method == "DELETE") {
  12054. dispatched = dispatch_request_for_content_reader(
  12055. req, res, std::move(reader), delete_handlers_for_content_reader_);
  12056. } else if (custom) {
  12057. dispatched = dispatch_request_for_content_reader(
  12058. req, res, std::move(reader), custom->handlers_for_content_reader);
  12059. }
  12060. if (dispatched) {
  12061. if (content_reader_payload_too_large) {
  12062. // Enforce the limit: override any status the handler may have set
  12063. // and return false so the error path sends a plain 413 response.
  12064. res.status = StatusCode::PayloadTooLarge_413;
  12065. res.body.clear();
  12066. res.content_length_ = 0;
  12067. res.content_provider_ = nullptr;
  12068. return false;
  12069. }
  12070. return true;
  12071. }
  12072. }
  12073. // NOTE: `req.body` is not read here. For a regular handler the body is
  12074. // read inside dispatch_request(), after the route has matched and the
  12075. // pre-request handler has approved the request, so that a rejected
  12076. // request (e.g. failed authentication) never forces us to buffer a
  12077. // potentially large body.
  12078. }
  12079. // Regular handler
  12080. if (req.method == "GET" || req.method == "HEAD") {
  12081. return dispatch_request(req, res, get_handlers_, strm);
  12082. } else if (req.method == "POST") {
  12083. return dispatch_request(req, res, post_handlers_, strm);
  12084. } else if (req.method == "PUT") {
  12085. return dispatch_request(req, res, put_handlers_, strm);
  12086. } else if (req.method == "DELETE") {
  12087. return dispatch_request(req, res, delete_handlers_, strm);
  12088. } else if (req.method == "OPTIONS") {
  12089. return dispatch_request(req, res, options_handlers_, strm);
  12090. } else if (req.method == "PATCH") {
  12091. return dispatch_request(req, res, patch_handlers_, strm);
  12092. } else if (custom) {
  12093. return dispatch_request(req, res, custom->handlers, strm);
  12094. }
  12095. res.status = StatusCode::BadRequest_400;
  12096. return false;
  12097. }
  12098. inline bool Server::dispatch_request(Request &req, Response &res,
  12099. const Handlers &handlers, Stream &strm) {
  12100. for (const auto &x : handlers) {
  12101. const auto &matcher = x.first;
  12102. const auto &handler = x.second;
  12103. if (matcher->match(req)) {
  12104. req.matched_route = matcher->pattern();
  12105. // Run the pre-request handler before reading the body so a rejected
  12106. // request (e.g. failed authentication) never forces us to buffer a
  12107. // potentially large body. `req.matched_route` is available here.
  12108. if (pre_request_handler_ &&
  12109. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  12110. return true;
  12111. }
  12112. // The route matched and the request was approved; read the body now.
  12113. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  12114. output_error_log(Error::Read, &req);
  12115. return false;
  12116. }
  12117. handler(req, res);
  12118. return true;
  12119. }
  12120. }
  12121. return false;
  12122. }
  12123. // Decides the content coding for a response served straight from a file. Both
  12124. // the ETag, which has to name the representation actually sent, and
  12125. // `apply_static_file_compression()` go through this, so the two cannot drift
  12126. // apart.
  12127. inline detail::EncodingType
  12128. Server::static_file_encoding(const Request &req, const Response &res,
  12129. const std::string &content_type,
  12130. size_t length) const {
  12131. if (!static_file_compression_) { return detail::EncodingType::None; }
  12132. // Nothing to compress, and an empty file already answers with
  12133. // `Content-Length: 0`. Checked on its own so that a zero floor still cannot
  12134. // turn an empty body into a 20-byte gzip stream.
  12135. if (length == 0) { return detail::EncodingType::None; }
  12136. // A file that already fits in a single packet gains nothing from being made
  12137. // smaller, since it still travels in that one segment, and a file of a few
  12138. // bytes comes out larger than it went in.
  12139. if (length < static_file_compression_min_length_) {
  12140. return detail::EncodingType::None;
  12141. }
  12142. // RFC 9110 applies Range to the representation after content coding, so a
  12143. // compressed 206 would mean compressing the whole file and then slicing it.
  12144. // Serve ranges from the identity representation instead.
  12145. if (!req.ranges.empty()) { return detail::EncodingType::None; }
  12146. if (static_file_compression_max_length_ > 0 &&
  12147. length > static_file_compression_max_length_) {
  12148. return detail::EncodingType::None;
  12149. }
  12150. return detail::encoding_type(req, res, content_type);
  12151. }
  12152. // Compresses a file-backed content provider into `res.body` and takes over the
  12153. // framing headers. Returns false when the response is left untouched.
  12154. inline bool Server::apply_static_file_compression(const Request &req,
  12155. Response &res) const {
  12156. auto type = res.content_coding_;
  12157. if (type == detail::EncodingType::None || !res.content_provider_) {
  12158. return false;
  12159. }
  12160. auto compressor = detail::make_compressor(type);
  12161. if (!compressor) { return false; }
  12162. output_pre_compression_log(req, res);
  12163. std::string compressed;
  12164. if (!detail::compress_content_provider(res.content_provider_,
  12165. res.content_length_, *compressor,
  12166. compressed)) {
  12167. return false;
  12168. }
  12169. res.body.swap(compressed);
  12170. // The provider was consumed in full, so a resource releaser registered with
  12171. // it should hear about a success when the response goes away.
  12172. res.content_provider_success_ = true;
  12173. res.content_provider_ = nullptr;
  12174. res.content_length_ = 0;
  12175. res.content_coding_ = detail::EncodingType::None;
  12176. res.set_header("Content-Encoding", detail::encoding_name(type));
  12177. res.set_header("Vary", "Accept-Encoding");
  12178. res.set_header("Content-Length", std::to_string(res.body.size()));
  12179. return true;
  12180. }
  12181. inline void Server::apply_ranges(const Request &req, Response &res,
  12182. std::string &content_type,
  12183. std::string &boundary) const {
  12184. // A known-length content provider leaves `res.body` empty, so the compressor
  12185. // at the end of this function never runs for one (issue #2545). A file-backed
  12186. // provider is fully readable right here, so compress it and answer with an
  12187. // ordinary body: `Content-Length` and HEAD keep working, and the response
  12188. // takes the same path as `set_content()` from here on. Range requests never
  12189. // get a content coding, so `Content-Range` still names identity bytes and
  12190. // none of the framing below applies.
  12191. if (apply_static_file_compression(req, res)) { return; }
  12192. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  12193. auto it = res.headers.find("Content-Type");
  12194. if (it != res.headers.end()) {
  12195. content_type = it->second;
  12196. res.headers.erase(it);
  12197. }
  12198. boundary = detail::make_multipart_data_boundary();
  12199. res.set_header("Content-Type",
  12200. "multipart/byteranges; boundary=" + boundary);
  12201. }
  12202. auto type = detail::encoding_type(req, res);
  12203. if (res.body.empty()) {
  12204. if (res.content_length_ > 0) {
  12205. size_t length = 0;
  12206. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  12207. length = res.content_length_;
  12208. } else if (req.ranges.size() == 1) {
  12209. auto offset_and_length = detail::get_range_offset_and_length(
  12210. req.ranges[0], res.content_length_);
  12211. length = offset_and_length.second;
  12212. auto content_range = detail::make_content_range_header_field(
  12213. offset_and_length, res.content_length_);
  12214. res.set_header("Content-Range", content_range);
  12215. } else {
  12216. length = detail::get_multipart_ranges_data_length(
  12217. req, boundary, content_type, res.content_length_);
  12218. }
  12219. res.set_header("Content-Length", std::to_string(length));
  12220. } else {
  12221. if (res.content_provider_) {
  12222. if (res.is_chunked_content_provider_) {
  12223. res.set_header("Transfer-Encoding", "chunked");
  12224. res.content_coding_ = type;
  12225. if (type != detail::EncodingType::None) {
  12226. res.set_header("Content-Encoding", detail::encoding_name(type));
  12227. res.set_header("Vary", "Accept-Encoding");
  12228. }
  12229. }
  12230. }
  12231. }
  12232. } else {
  12233. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  12234. ;
  12235. } else if (req.ranges.size() == 1) {
  12236. auto offset_and_length =
  12237. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  12238. auto offset = offset_and_length.first;
  12239. auto length = offset_and_length.second;
  12240. auto content_range = detail::make_content_range_header_field(
  12241. offset_and_length, res.body.size());
  12242. res.set_header("Content-Range", content_range);
  12243. assert(offset + length <= res.body.size());
  12244. res.body = res.body.substr(offset, length);
  12245. } else {
  12246. std::string data;
  12247. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  12248. res.body.size(), data);
  12249. res.body.swap(data);
  12250. }
  12251. if (type != detail::EncodingType::None) {
  12252. output_pre_compression_log(req, res);
  12253. if (auto compressor = detail::make_compressor(type)) {
  12254. std::string compressed;
  12255. if (compressor->compress(res.body.data(), res.body.size(), true,
  12256. [&](const char *data, size_t data_len) {
  12257. compressed.append(data, data_len);
  12258. return true;
  12259. })) {
  12260. res.body.swap(compressed);
  12261. res.set_header("Content-Encoding", detail::encoding_name(type));
  12262. res.set_header("Vary", "Accept-Encoding");
  12263. }
  12264. }
  12265. }
  12266. res.content_length_ = res.body.size();
  12267. res.set_header("Content-Length", std::to_string(res.content_length_));
  12268. }
  12269. }
  12270. inline bool Server::dispatch_request_for_content_reader(
  12271. Request &req, Response &res, ContentReader content_reader,
  12272. const HandlersForContentReader &handlers) const {
  12273. for (const auto &x : handlers) {
  12274. const auto &matcher = x.first;
  12275. const auto &handler = x.second;
  12276. if (matcher->match(req)) {
  12277. req.matched_route = matcher->pattern();
  12278. if (!pre_request_handler_ ||
  12279. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  12280. handler(req, res, content_reader);
  12281. }
  12282. return true;
  12283. }
  12284. }
  12285. return false;
  12286. }
  12287. inline std::string
  12288. get_client_ip(const std::string &x_forwarded_for,
  12289. const std::vector<std::string> &trusted_proxies) {
  12290. // X-Forwarded-For is a comma-separated list per RFC 7239
  12291. std::vector<std::string> ip_list;
  12292. detail::split(x_forwarded_for.data(),
  12293. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  12294. [&](const char *b, const char *e) {
  12295. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  12296. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  12297. });
  12298. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  12299. // no segments. Signal "no client IP derived" with an empty string so the
  12300. // caller can fall back to the connection-level remote address.
  12301. if (ip_list.empty()) { return std::string(); }
  12302. // Each hop appends the address it received the request from, so the rightmost
  12303. // entries are the ones written by our own infrastructure while the leftmost
  12304. // are whatever the original client chose to send. Walk from the right and
  12305. // skip trusted proxies; the first address that is not a trusted proxy is the
  12306. // furthest point still attributable to a real hop, i.e. the client. Scanning
  12307. // from the left instead lets a client forge an arbitrary address by following
  12308. // it with a trusted proxy's address, which the left-to-right scan then
  12309. // returned as the client.
  12310. for (size_t i = ip_list.size(); i-- > 0;) {
  12311. const auto &ip = ip_list[i];
  12312. auto is_trusted_proxy =
  12313. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  12314. [&](const std::string &proxy) { return ip == proxy; });
  12315. if (!is_trusted_proxy) { return ip; }
  12316. }
  12317. // Every hop was a trusted proxy; fall back to the first entry.
  12318. return ip_list.front();
  12319. }
  12320. inline bool
  12321. Server::process_request(Stream &strm, const std::string &remote_addr,
  12322. int remote_port, const std::string &local_addr,
  12323. int local_port, bool close_connection,
  12324. bool &connection_closed,
  12325. const std::function<void(Request &)> &setup_request,
  12326. bool *websocket_upgraded) {
  12327. std::array<char, 2048> buf{};
  12328. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  12329. // Connection has been closed on client
  12330. if (!line_reader.getline()) { return false; }
  12331. // RFC 9112 2.2: ignore an empty line received before the request-line. Some
  12332. // clients send an extra CRLF after a request body, which would otherwise be
  12333. // parsed as the next request on a persistent connection.
  12334. if (strcmp(line_reader.ptr(), "\r\n") == 0 && !line_reader.getline()) {
  12335. return false;
  12336. }
  12337. Request req;
  12338. req.start_time_ = std::chrono::steady_clock::now();
  12339. req.remote_addr = remote_addr;
  12340. req.remote_port = remote_port;
  12341. req.local_addr = local_addr;
  12342. req.local_port = local_port;
  12343. Response res;
  12344. res.version = "HTTP/1.1";
  12345. res.headers = default_headers_;
  12346. // RFC 9112 §9.6: a server that sends the "close" connection option must
  12347. // close the connection after that response, whichever path wrote it (an
  12348. // error status, a handler, or a rejected request). Reading on would also
  12349. // parse whatever the client sent next on a connection it considers done.
  12350. auto honor_connection_close = detail::scope_exit([&] {
  12351. if (detail::has_header_token(res.headers, "Connection", "close")) {
  12352. connection_closed = true;
  12353. }
  12354. });
  12355. // Request line and headers. A rejected message leaves the rest of it (and
  12356. // any body) unread, so the connection cannot be reused: the leftover bytes
  12357. // would be parsed as the next request.
  12358. if (!parse_request_line(line_reader.ptr(), req)) {
  12359. connection_closed = true;
  12360. res.status = StatusCode::BadRequest_400;
  12361. output_error_log(Error::InvalidRequestLine, &req);
  12362. return write_response(strm, close_connection, req, res);
  12363. }
  12364. // Request headers
  12365. if (!detail::read_headers(strm, req.headers)) {
  12366. connection_closed = true;
  12367. res.status = StatusCode::BadRequest_400;
  12368. output_error_log(Error::InvalidHeaders, &req);
  12369. return write_response(strm, close_connection, req, res);
  12370. }
  12371. // RFC 9112 §6.3: Reject requests whose framing is invalid or ambiguous,
  12372. // which would otherwise let an intermediary and this parser disagree on
  12373. // where the body ends and enable request smuggling. Three cases: a
  12374. // Content-Length that is not a valid decimal length (e.g. "42, 42", "+42"
  12375. // or empty), which would otherwise be read as "no body"; a non-zero
  12376. // Content-Length alongside any Transfer-Encoding (Content-Length: 0 is
  12377. // tolerated for compatibility with existing clients); and a
  12378. // Transfer-Encoding whose final coding is not chunked, which leaves the body
  12379. // length undeterminable. None of them may fall through to the "no body"
  12380. // path, or the body bytes are parsed as the next request on a persistent
  12381. // connection.
  12382. auto is_invalid_content_length = false;
  12383. detail::get_header_value_u64(req.headers, "Content-Length", 0, 0,
  12384. is_invalid_content_length);
  12385. if (is_invalid_content_length ||
  12386. detail::has_conflicting_content_length(req.headers) ||
  12387. (req.has_header("Transfer-Encoding") &&
  12388. !detail::is_chunked_transfer_encoding(req.headers))) {
  12389. connection_closed = true;
  12390. res.status = StatusCode::BadRequest_400;
  12391. return write_response(strm, close_connection, req, res);
  12392. }
  12393. // RFC 9112 §3.2: Reject more than one Host field line or an invalid Host
  12394. // value, so that every recipient of the request sees the same authority.
  12395. if (req.get_header_value_count("Host") > 1 ||
  12396. !detail::fields::is_host(req.get_header_value("Host"))) {
  12397. connection_closed = true;
  12398. res.status = StatusCode::BadRequest_400;
  12399. output_error_log(Error::InvalidHeaders, &req);
  12400. return write_response(strm, close_connection, req, res);
  12401. }
  12402. // Check if the request URI doesn't exceed the limit
  12403. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  12404. connection_closed = true;
  12405. res.status = StatusCode::UriTooLong_414;
  12406. output_error_log(Error::ExceedUriMaxLength, &req);
  12407. return write_response(strm, close_connection, req, res);
  12408. }
  12409. if (detail::has_header_token(req.headers, "Connection", "close")) {
  12410. connection_closed = true;
  12411. }
  12412. if (req.version == "HTTP/1.0" &&
  12413. !detail::has_header_token(req.headers, "Connection", "keep-alive")) {
  12414. connection_closed = true;
  12415. }
  12416. // Only honor X-Forwarded-For if the peer on the actual TCP connection is
  12417. // itself a trusted proxy. Otherwise any direct client could spoof
  12418. // remote_addr simply by sending an arbitrary X-Forwarded-For header.
  12419. auto is_trusted_peer = std::any_of(
  12420. trusted_proxies_.begin(), trusted_proxies_.end(),
  12421. [&](const std::string &proxy) { return proxy == remote_addr; });
  12422. if (is_trusted_peer && req.has_header("X-Forwarded-For")) {
  12423. // Some proxies append the address they observed as a separate
  12424. // X-Forwarded-For field line instead of extending the one the client sent
  12425. // (e.g. HAProxy's "option forwardfor"), so the whole combined value has to
  12426. // be scanned. Reading only the first occurrence would hand back the
  12427. // client-supplied, and therefore forgeable, value.
  12428. auto x_forwarded_for =
  12429. detail::get_combined_header_value(req.headers, "X-Forwarded-For");
  12430. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  12431. req.remote_addr = derived.empty() ? remote_addr : derived;
  12432. } else {
  12433. req.remote_addr = remote_addr;
  12434. }
  12435. req.remote_port = remote_port;
  12436. req.local_addr = local_addr;
  12437. req.local_port = local_port;
  12438. if (req.has_header("Accept")) {
  12439. auto accept_header =
  12440. detail::get_combined_header_value(req.headers, "Accept");
  12441. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  12442. connection_closed = true;
  12443. res.status = StatusCode::BadRequest_400;
  12444. output_error_log(Error::HTTPParsing, &req);
  12445. return write_response(strm, close_connection, req, res);
  12446. }
  12447. }
  12448. if (req.has_header("Range")) {
  12449. const auto &range_header_value = req.get_header_value("Range");
  12450. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  12451. connection_closed = true;
  12452. res.status = StatusCode::RangeNotSatisfiable_416;
  12453. output_error_log(Error::InvalidRangeHeader, &req);
  12454. return write_response(strm, close_connection, req, res);
  12455. }
  12456. }
  12457. if (setup_request) { setup_request(req); }
  12458. // RFC 9110 10.1.1: Expect is a comma-separated list whose value is
  12459. // case-insensitive, and a 100-continue expectation in an HTTP/1.0 request
  12460. // must be ignored. An expectation we do not recognize is left alone; the
  12461. // 417 the section allows for one is a MAY, not a requirement.
  12462. //
  12463. // `100 Continue` itself is deferred until the body is actually read (see
  12464. // read_content_core), so a request rejected by a later handler never
  12465. // invites the client to send a body nobody will read.
  12466. if (req.version != "HTTP/1.0" &&
  12467. detail::has_header_token(req.headers, "Expect", "100-continue")) {
  12468. int status = StatusCode::Continue_100;
  12469. if (expect_100_continue_handler_) {
  12470. status = expect_100_continue_handler_(req, res);
  12471. }
  12472. if (status == StatusCode::Continue_100) {
  12473. req.expect_100_continue_pending_ = true;
  12474. } else {
  12475. if (res.status == -1) { res.status = status; }
  12476. connection_closed = true;
  12477. return write_response(strm, true, req, res);
  12478. }
  12479. }
  12480. // Setup `is_connection_closed` method
  12481. auto sock = strm.socket();
  12482. req.is_connection_closed = [sock]() {
  12483. return !detail::is_socket_alive(sock);
  12484. };
  12485. // WebSocket upgrade
  12486. // Run pre_routing_handler_ and pre_request_handler_ before upgrading so
  12487. // that authentication and other middleware can reject the request with an
  12488. // HTTP response (e.g., 401) before the protocol switches.
  12489. if (detail::is_websocket_upgrade(req)) {
  12490. if (pre_routing_handler_ &&
  12491. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  12492. if (res.status == -1) { res.status = StatusCode::OK_200; }
  12493. return write_response_with_content(strm, close_connection, req, res);
  12494. }
  12495. // Find matching WebSocket handler
  12496. for (const auto &entry : websocket_handlers_) {
  12497. if (entry.matcher->match(req)) {
  12498. req.matched_route = entry.matcher->pattern();
  12499. if (pre_request_handler_ &&
  12500. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  12501. if (res.status == -1) { res.status = StatusCode::OK_200; }
  12502. return write_response_with_content(strm, close_connection, req, res);
  12503. }
  12504. // Compute accept key
  12505. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  12506. auto accept_key = detail::websocket_accept_key(client_key);
  12507. // Negotiate subprotocol
  12508. std::string selected_subprotocol;
  12509. if (entry.sub_protocol_selector) {
  12510. auto protocol_header = detail::get_combined_header_value(
  12511. req.headers, "Sec-WebSocket-Protocol");
  12512. if (!protocol_header.empty()) {
  12513. std::vector<std::string> protocols;
  12514. detail::split(protocol_header.data(),
  12515. protocol_header.data() + protocol_header.size(), ',',
  12516. [&](const char *b, const char *e) {
  12517. protocols.emplace_back(b, e);
  12518. });
  12519. selected_subprotocol = entry.sub_protocol_selector(protocols);
  12520. // Ignore a selection the client did not offer (RFC 6455 4.2.2)
  12521. if (std::find(protocols.begin(), protocols.end(),
  12522. selected_subprotocol) == protocols.end()) {
  12523. selected_subprotocol.clear();
  12524. }
  12525. }
  12526. }
  12527. // Send 101 Switching Protocols
  12528. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  12529. "Upgrade: websocket\r\n"
  12530. "Connection: Upgrade\r\n"
  12531. "Sec-WebSocket-Accept: " +
  12532. accept_key + "\r\n";
  12533. if (!selected_subprotocol.empty()) {
  12534. if (!detail::fields::is_field_value(selected_subprotocol)) {
  12535. return false;
  12536. }
  12537. handshake_response +=
  12538. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  12539. }
  12540. handshake_response += "\r\n";
  12541. if (strm.write(handshake_response.data(), handshake_response.size()) <
  12542. 0) {
  12543. return false;
  12544. }
  12545. connection_closed = true;
  12546. if (websocket_upgraded) { *websocket_upgraded = true; }
  12547. {
  12548. #ifdef CPPHTTPLIB_SSL_ENABLED
  12549. if (req.ssl) {
  12550. // wss: the heartbeat ping thread and the read path enter the same
  12551. // TLS session from different threads. Hand the WebSocket a stream
  12552. // that serializes every TLS call, so the shared SSLSocketStream on
  12553. // the plain HTTP/HTTPS paths stays untouched.
  12554. auto ws_strm =
  12555. std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  12556. strm.socket(), const_cast<tls::session_t>(req.ssl),
  12557. CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
  12558. write_timeout_sec_, write_timeout_usec_));
  12559. ws::WebSocket ws(std::move(ws_strm), req, true,
  12560. websocket_ping_interval_sec_,
  12561. websocket_max_missed_pongs_);
  12562. entry.handler(req, ws);
  12563. return true;
  12564. }
  12565. #endif
  12566. // Use WebSocket-specific read timeout instead of HTTP timeout
  12567. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND,
  12568. 0);
  12569. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  12570. websocket_max_missed_pongs_);
  12571. entry.handler(req, ws);
  12572. }
  12573. return true;
  12574. }
  12575. }
  12576. // No matching handler - fall through to 404
  12577. }
  12578. // Routing
  12579. auto routed = false;
  12580. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12581. routed = routing(req, res, strm);
  12582. #else
  12583. try {
  12584. routed = routing(req, res, strm);
  12585. } catch (std::exception &) {
  12586. if (exception_handler_) {
  12587. auto ep = std::current_exception();
  12588. exception_handler_(req, res, ep);
  12589. routed = true;
  12590. } else {
  12591. res.status = StatusCode::InternalServerError_500;
  12592. }
  12593. } catch (...) {
  12594. if (exception_handler_) {
  12595. auto ep = std::current_exception();
  12596. exception_handler_(req, res, ep);
  12597. routed = true;
  12598. } else {
  12599. res.status = StatusCode::InternalServerError_500;
  12600. }
  12601. }
  12602. #endif
  12603. auto ret = false;
  12604. if (routed) {
  12605. if (res.status == -1) {
  12606. res.status = req.ranges.empty() ? StatusCode::OK_200
  12607. : StatusCode::PartialContent_206;
  12608. }
  12609. // Serve file content by using a content provider
  12610. auto file_open_error = false;
  12611. if (!res.file_content_path_.empty()) {
  12612. const auto &path = res.file_content_path_;
  12613. auto mm = std::make_shared<detail::mmap>(path.c_str());
  12614. if (!mm->is_open()) {
  12615. res.body.clear();
  12616. res.content_length_ = 0;
  12617. res.content_provider_ = nullptr;
  12618. res.status = StatusCode::NotFound_404;
  12619. output_error_log(Error::OpenFile, &req);
  12620. file_open_error = true;
  12621. } else {
  12622. auto content_type = res.file_content_content_type_;
  12623. if (content_type.empty()) {
  12624. content_type = detail::find_content_type(
  12625. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  12626. }
  12627. detail::set_file_content_provider(
  12628. res, mm, content_type,
  12629. static_file_encoding(req, res, content_type, mm->size()));
  12630. }
  12631. }
  12632. if (file_open_error) {
  12633. ret = write_response(strm, close_connection, req, res);
  12634. } else if (detail::range_error(req, res)) {
  12635. res.body.clear();
  12636. res.content_length_ = 0;
  12637. res.content_provider_ = nullptr;
  12638. res.status = StatusCode::RangeNotSatisfiable_416;
  12639. ret = write_response(strm, close_connection, req, res);
  12640. } else {
  12641. ret = write_response_with_content(strm, close_connection, req, res);
  12642. }
  12643. } else {
  12644. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  12645. ret = write_response(strm, close_connection, req, res);
  12646. }
  12647. // Drain any unconsumed framed body to prevent request smuggling on
  12648. // keep-alive. Without framing there is no body to drain — reading would
  12649. // consume the next request (issue #2450). If the response has committed the
  12650. // connection to close, there is no next request to protect.
  12651. if (!req.body_consumed_ && detail::has_framed_body(req) &&
  12652. !detail::has_header_token(res.headers, "Connection", "close")) {
  12653. int dummy_status;
  12654. if (!detail::read_content(
  12655. strm, req, payload_max_length_, dummy_status, nullptr,
  12656. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  12657. connection_closed = true;
  12658. }
  12659. }
  12660. return ret;
  12661. }
  12662. inline bool Server::is_valid() const { return !has_invalid_registration_; }
  12663. inline bool Server::process_and_close_socket(socket_t sock) {
  12664. std::string remote_addr;
  12665. int remote_port = 0;
  12666. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  12667. std::string local_addr;
  12668. int local_port = 0;
  12669. detail::get_local_ip_and_port(sock, local_addr, local_port);
  12670. bool websocket_upgraded = false;
  12671. auto ret = serve_guarded([&]() {
  12672. return detail::process_server_socket(
  12673. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  12674. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12675. write_timeout_usec_,
  12676. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  12677. return process_request(strm, remote_addr, remote_port, local_addr,
  12678. local_port, close_connection,
  12679. connection_closed, nullptr,
  12680. &websocket_upgraded);
  12681. });
  12682. });
  12683. detail::drain_and_close_socket(sock);
  12684. return ret;
  12685. }
  12686. inline void Server::output_log(const Request &req, const Response &res) const {
  12687. if (logger_) {
  12688. std::lock_guard<std::mutex> guard(logger_mutex_);
  12689. logger_(req, res);
  12690. }
  12691. }
  12692. inline void Server::output_pre_compression_log(const Request &req,
  12693. const Response &res) const {
  12694. if (pre_compression_logger_) {
  12695. std::lock_guard<std::mutex> guard(logger_mutex_);
  12696. pre_compression_logger_(req, res);
  12697. }
  12698. }
  12699. inline void Server::output_error_log(const Error &err,
  12700. const Request *req) const {
  12701. if (error_logger_) {
  12702. std::lock_guard<std::mutex> guard(logger_mutex_);
  12703. error_logger_(err, req);
  12704. }
  12705. }
  12706. /*
  12707. * Group 5: ClientImpl and Client (Universal) implementation
  12708. */
  12709. // HTTP client implementation
  12710. inline ClientImpl::ClientImpl(const std::string &host)
  12711. : ClientImpl(host, 80, std::string(), std::string()) {}
  12712. inline ClientImpl::ClientImpl(const std::string &host, int port)
  12713. : ClientImpl(host, port, std::string(), std::string()) {}
  12714. inline ClientImpl::ClientImpl(const std::string &host, int port,
  12715. const std::string &client_cert_path,
  12716. const std::string &client_key_path)
  12717. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  12718. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  12719. inline ClientImpl::~ClientImpl() {
  12720. // Wait until all the requests in flight are handled.
  12721. size_t retry_count = 10;
  12722. while (retry_count-- > 0) {
  12723. {
  12724. std::lock_guard<std::mutex> guard(socket_mutex_);
  12725. if (socket_requests_in_flight_ == 0) { break; }
  12726. }
  12727. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  12728. }
  12729. std::lock_guard<std::mutex> guard(socket_mutex_);
  12730. shutdown_socket(socket_);
  12731. close_socket(socket_);
  12732. }
  12733. inline bool ClientImpl::is_valid() const { return true; }
  12734. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  12735. client_cert_path_ = rhs.client_cert_path_;
  12736. client_key_path_ = rhs.client_key_path_;
  12737. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  12738. read_timeout_sec_ = rhs.read_timeout_sec_;
  12739. read_timeout_usec_ = rhs.read_timeout_usec_;
  12740. write_timeout_sec_ = rhs.write_timeout_sec_;
  12741. write_timeout_usec_ = rhs.write_timeout_usec_;
  12742. max_timeout_msec_ = rhs.max_timeout_msec_;
  12743. basic_auth_username_ = rhs.basic_auth_username_;
  12744. basic_auth_password_ = rhs.basic_auth_password_;
  12745. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  12746. keep_alive_ = rhs.keep_alive_;
  12747. follow_location_ = rhs.follow_location_;
  12748. path_encode_ = rhs.path_encode_;
  12749. address_family_ = rhs.address_family_;
  12750. tcp_nodelay_ = rhs.tcp_nodelay_;
  12751. ipv6_v6only_ = rhs.ipv6_v6only_;
  12752. socket_options_ = rhs.socket_options_;
  12753. compress_ = rhs.compress_;
  12754. decompress_ = rhs.decompress_;
  12755. payload_max_length_ = rhs.payload_max_length_;
  12756. has_payload_max_length_ = rhs.has_payload_max_length_;
  12757. interface_ = rhs.interface_;
  12758. proxy_host_ = rhs.proxy_host_;
  12759. proxy_port_ = rhs.proxy_port_;
  12760. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  12761. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  12762. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  12763. no_proxy_entries_ = rhs.no_proxy_entries_;
  12764. logger_ = rhs.logger_;
  12765. error_logger_ = rhs.error_logger_;
  12766. #ifdef CPPHTTPLIB_SSL_ENABLED
  12767. digest_auth_username_ = rhs.digest_auth_username_;
  12768. digest_auth_password_ = rhs.digest_auth_password_;
  12769. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  12770. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  12771. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  12772. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  12773. server_certificate_verification_ = rhs.server_certificate_verification_;
  12774. server_hostname_verification_ = rhs.server_hostname_verification_;
  12775. system_ca_mode_ = rhs.system_ca_mode_;
  12776. #endif
  12777. }
  12778. inline bool
  12779. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  12780. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  12781. if (no_proxy_entries_.empty()) { return true; }
  12782. // host_ is const so its normalized form is invariant; cache it. The
  12783. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  12784. if (host == host_) {
  12785. if (!host_normalized_valid_) {
  12786. host_normalized_ = detail::normalize_target(host_);
  12787. host_normalized_valid_ = true;
  12788. }
  12789. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  12790. }
  12791. auto target = detail::normalize_target(host);
  12792. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  12793. }
  12794. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  12795. if (is_proxy_enabled_for_host(host_)) {
  12796. return detail::create_client_socket(
  12797. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  12798. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  12799. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  12800. write_timeout_sec_, write_timeout_usec_, interface_, error);
  12801. }
  12802. // Check is custom IP or hostname specified for host_
  12803. std::string connect_host;
  12804. std::string ip;
  12805. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  12806. return detail::create_client_socket(
  12807. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  12808. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  12809. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12810. write_timeout_usec_, interface_, error);
  12811. }
  12812. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  12813. Error &error) {
  12814. auto sock = create_client_socket(error);
  12815. if (sock == INVALID_SOCKET) { return false; }
  12816. socket.sock = sock;
  12817. return true;
  12818. }
  12819. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  12820. return create_and_connect_socket(socket, error);
  12821. }
  12822. inline bool ClientImpl::setup_proxy_connection(
  12823. Socket & /*socket*/,
  12824. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  12825. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  12826. return true;
  12827. }
  12828. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  12829. bool /*shutdown_gracefully*/) {
  12830. // If there are any requests in flight from threads other than us, then it's
  12831. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  12832. assert(socket_requests_in_flight_ == 0 ||
  12833. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12834. }
  12835. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  12836. if (socket.sock == INVALID_SOCKET) { return; }
  12837. detail::shutdown_socket(socket.sock);
  12838. }
  12839. inline void ClientImpl::close_socket(Socket &socket) {
  12840. // If there are requests in flight in another thread, usually closing
  12841. // the socket will be fine and they will simply receive an error when
  12842. // using the closed socket, but it is still a bug since rarely the OS
  12843. // may reassign the socket id to be used for a new socket, and then
  12844. // suddenly they will be operating on a live socket that is different
  12845. // than the one they intended!
  12846. assert(socket_requests_in_flight_ == 0 ||
  12847. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12848. // It is also a bug if this happens while SSL is still active
  12849. #ifdef CPPHTTPLIB_SSL_ENABLED
  12850. assert(socket.ssl == nullptr);
  12851. #endif
  12852. if (socket.sock == INVALID_SOCKET) { return; }
  12853. detail::close_socket(socket.sock);
  12854. socket.sock = INVALID_SOCKET;
  12855. }
  12856. inline void ClientImpl::disconnect(bool gracefully) {
  12857. shutdown_ssl(socket_, gracefully);
  12858. shutdown_socket(socket_);
  12859. close_socket(socket_);
  12860. }
  12861. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  12862. Response &res,
  12863. bool skip_100_continue) const {
  12864. std::array<char, 2048> buf{};
  12865. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  12866. if (!line_reader.getline()) { return false; }
  12867. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12868. res.reason)) {
  12869. return req.method == "CONNECT";
  12870. }
  12871. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  12872. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  12873. if (!line_reader.getline()) { return false; } // CRLF
  12874. if (!line_reader.getline()) { return false; } // next response line
  12875. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12876. res.reason)) {
  12877. return false;
  12878. }
  12879. }
  12880. return true;
  12881. }
  12882. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  12883. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  12884. auto ret = send_(req, res, error);
  12885. if (error == Error::SSLPeerCouldBeClosed_) {
  12886. assert(!ret);
  12887. ret = send_(req, res, error);
  12888. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  12889. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  12890. }
  12891. return ret;
  12892. }
  12893. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  12894. {
  12895. std::lock_guard<std::mutex> guard(socket_mutex_);
  12896. // Set this to false immediately - if it ever gets set to true by the end
  12897. // of the request, we know another thread instructed us to close the
  12898. // socket.
  12899. socket_should_be_closed_when_request_is_done_ = false;
  12900. auto is_alive = false;
  12901. if (socket_.is_open()) {
  12902. is_alive = detail::is_socket_alive(socket_.sock);
  12903. #ifdef CPPHTTPLIB_SSL_ENABLED
  12904. if (is_alive && is_ssl()) {
  12905. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12906. is_alive = false;
  12907. }
  12908. }
  12909. #endif
  12910. if (!is_alive) {
  12911. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  12912. disconnect(/*gracefully=*/false);
  12913. }
  12914. }
  12915. if (!is_alive) {
  12916. if (!ensure_socket_connection(socket_, error)) {
  12917. output_error_log(error, &req);
  12918. return false;
  12919. }
  12920. {
  12921. auto success = true;
  12922. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  12923. error)) {
  12924. if (!success) { output_error_log(error, &req); }
  12925. return success;
  12926. }
  12927. }
  12928. }
  12929. // Mark the current socket as being in use so that it cannot be closed by
  12930. // anyone else while this request is ongoing, even though we will be
  12931. // releasing the mutex.
  12932. if (socket_requests_in_flight_ > 1) {
  12933. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  12934. }
  12935. socket_requests_in_flight_ += 1;
  12936. socket_requests_are_from_thread_ = std::this_thread::get_id();
  12937. }
  12938. for (const auto &header : default_headers_) {
  12939. if (req.headers.find(header.first) == req.headers.end()) {
  12940. req.headers.insert(header);
  12941. }
  12942. }
  12943. auto ret = false;
  12944. auto close_connection = !keep_alive_;
  12945. auto se = detail::scope_exit([&]() {
  12946. // Briefly lock mutex in order to mark that a request is no longer ongoing
  12947. std::lock_guard<std::mutex> guard(socket_mutex_);
  12948. socket_requests_in_flight_ -= 1;
  12949. if (socket_requests_in_flight_ <= 0) {
  12950. assert(socket_requests_in_flight_ == 0);
  12951. socket_requests_are_from_thread_ = std::thread::id();
  12952. }
  12953. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  12954. !ret) {
  12955. disconnect(/*gracefully=*/true);
  12956. }
  12957. });
  12958. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  12959. return handle_request(strm, req, res, close_connection, error);
  12960. });
  12961. if (!ret) {
  12962. if (error == Error::Success) {
  12963. error = Error::Unknown;
  12964. output_error_log(error, &req);
  12965. }
  12966. }
  12967. return ret;
  12968. }
  12969. inline Result ClientImpl::send(const Request &req) {
  12970. auto req2 = req;
  12971. return send_(std::move(req2));
  12972. }
  12973. inline Result ClientImpl::send_(Request &&req) {
  12974. auto res = detail::make_unique<Response>();
  12975. auto error = Error::Success;
  12976. auto ret = send(req, *res, error);
  12977. #ifdef CPPHTTPLIB_SSL_ENABLED
  12978. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  12979. last_ssl_error_, last_backend_error_};
  12980. #else
  12981. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  12982. #endif
  12983. }
  12984. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  12985. const std::string &ct) {
  12986. (void)for_stream;
  12987. // Default headers are meant for the origin and may carry its credentials, so
  12988. // keep them off the CONNECT request the proxy reads.
  12989. if (r.method != "CONNECT") {
  12990. for (const auto &header : default_headers_) {
  12991. if (!r.has_header(header.first)) { r.headers.insert(header); }
  12992. }
  12993. }
  12994. // RFC 9110 5.3 recommends sending control data such as Host first, so
  12995. // prepend it rather than appending it after the caller's own fields.
  12996. if (!r.has_header("Host")) {
  12997. r.headers.emplace_front(
  12998. "Host", detail::make_default_host_header_value(host_, port_, is_ssl(),
  12999. address_family_));
  13000. }
  13001. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  13002. if (!r.content_receiver) {
  13003. if (!r.has_header("Accept-Encoding")) {
  13004. std::string accept_encoding;
  13005. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13006. accept_encoding = "br";
  13007. #endif
  13008. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13009. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  13010. accept_encoding += "gzip, deflate";
  13011. #endif
  13012. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13013. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  13014. accept_encoding += "zstd";
  13015. #endif
  13016. r.set_header("Accept-Encoding", accept_encoding);
  13017. }
  13018. detail::add_default_user_agent_header(r);
  13019. }
  13020. if (!r.body.empty()) {
  13021. if (!ct.empty() && !r.has_header("Content-Type")) {
  13022. r.headers.emplace("Content-Type", ct);
  13023. }
  13024. if (!r.has_header("Content-Length")) {
  13025. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  13026. }
  13027. }
  13028. }
  13029. inline ClientImpl::StreamHandle
  13030. ClientImpl::open_stream(const std::string &method, const std::string &path,
  13031. const Params &params, const Headers &headers,
  13032. const std::string &body,
  13033. const std::string &content_type) {
  13034. StreamHandle handle;
  13035. handle.response = detail::make_unique<Response>();
  13036. handle.error = Error::Success;
  13037. // Encode the target exactly like the buffered send path does, so that the
  13038. // same `path` produces the same request line through either API.
  13039. auto raw_query_path =
  13040. params.empty() ? path : append_query_params(path, params);
  13041. auto query_path = detail::encode_request_target(raw_query_path, path_encode_);
  13042. handle.connection_ = detail::make_unique<ClientConnection>();
  13043. {
  13044. std::lock_guard<std::mutex> guard(socket_mutex_);
  13045. auto is_alive = false;
  13046. if (socket_.is_open()) {
  13047. is_alive = detail::is_socket_alive(socket_.sock);
  13048. #ifdef CPPHTTPLIB_SSL_ENABLED
  13049. if (is_alive && is_ssl()) {
  13050. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  13051. is_alive = false;
  13052. }
  13053. }
  13054. #endif
  13055. if (!is_alive) { disconnect(/*gracefully=*/false); }
  13056. }
  13057. if (!is_alive) {
  13058. if (!ensure_socket_connection(socket_, handle.error)) {
  13059. handle.response.reset();
  13060. return handle;
  13061. }
  13062. {
  13063. auto success = true;
  13064. auto start_time = std::chrono::steady_clock::now();
  13065. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  13066. success, handle.error)) {
  13067. if (!success) { handle.response.reset(); }
  13068. return handle;
  13069. }
  13070. }
  13071. }
  13072. transfer_socket_ownership_to_handle(handle);
  13073. }
  13074. #ifdef CPPHTTPLIB_SSL_ENABLED
  13075. if (is_ssl() && handle.connection_->session) {
  13076. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  13077. handle.connection_->sock, handle.connection_->session,
  13078. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13079. write_timeout_usec_);
  13080. } else {
  13081. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  13082. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  13083. write_timeout_sec_, write_timeout_usec_);
  13084. }
  13085. #else
  13086. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  13087. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  13088. write_timeout_sec_, write_timeout_usec_);
  13089. #endif
  13090. handle.stream_ = handle.socket_stream_.get();
  13091. Request req;
  13092. req.method = method;
  13093. req.path = query_path;
  13094. req.headers = headers;
  13095. req.body = body;
  13096. prepare_default_headers(req, true, content_type);
  13097. auto &strm = *handle.stream_;
  13098. // Build the request line and headers in memory first, like write_request()
  13099. // does, so that a rejected header leaves nothing on the wire.
  13100. {
  13101. detail::BufferStream bstrm;
  13102. if (detail::write_request_line(bstrm, req.method, req.path) < 0) {
  13103. handle.error = Error::Write;
  13104. handle.response.reset();
  13105. return handle;
  13106. }
  13107. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  13108. handle.error)) {
  13109. handle.response.reset();
  13110. return handle;
  13111. }
  13112. const auto &data = bstrm.get_buffer();
  13113. if (!detail::write_data(strm, data.data(), data.size())) {
  13114. handle.error = Error::Write;
  13115. handle.response.reset();
  13116. return handle;
  13117. }
  13118. }
  13119. if (!body.empty()) {
  13120. if (strm.write(body.data(), body.size()) < 0) {
  13121. handle.error = Error::Write;
  13122. handle.response.reset();
  13123. return handle;
  13124. }
  13125. }
  13126. if (!read_response_line(strm, req, *handle.response) ||
  13127. !detail::read_headers(strm, handle.response->headers)) {
  13128. handle.error = Error::Read;
  13129. handle.response.reset();
  13130. return handle;
  13131. }
  13132. // Same framing check as ClientImpl::process_request(). A HEAD or bodyless
  13133. // (204/304) response legitimately carries framing headers with no body.
  13134. if (method != "HEAD" &&
  13135. handle.response->status != StatusCode::NoContent_204 &&
  13136. handle.response->status != StatusCode::NotModified_304 &&
  13137. detail::has_conflicting_content_length(handle.response->headers)) {
  13138. handle.error = Error::Read;
  13139. handle.response.reset();
  13140. return handle;
  13141. }
  13142. handle.body_reader_.stream = handle.stream_;
  13143. handle.body_reader_.payload_max_length = payload_max_length_;
  13144. if (handle.response->has_header("Content-Length")) {
  13145. bool is_invalid = false;
  13146. auto content_length = detail::get_header_value_u64(
  13147. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  13148. if (is_invalid) {
  13149. handle.error = Error::Read;
  13150. handle.response.reset();
  13151. return handle;
  13152. }
  13153. handle.body_reader_.has_content_length = true;
  13154. handle.body_reader_.content_length = content_length;
  13155. }
  13156. handle.body_reader_.chunked =
  13157. detail::is_chunked_transfer_encoding(handle.response->headers);
  13158. auto content_encoding = detail::get_combined_header_value(
  13159. handle.response->headers, "Content-Encoding");
  13160. if (!content_encoding.empty()) {
  13161. // Same policy as prepare_content_receiver(): reject a coding we know about
  13162. // but were not built with, pass an unrecognized one through as-is.
  13163. handle.decompressor_ = detail::create_decompressor(content_encoding);
  13164. if (!handle.decompressor_) {
  13165. if (detail::is_known_content_encoding(content_encoding)) {
  13166. handle.error = Error::UnsupportedContentEncoding;
  13167. handle.response.reset();
  13168. return handle;
  13169. }
  13170. } else if (!handle.decompressor_->is_valid()) {
  13171. handle.error = Error::Compression;
  13172. handle.response.reset();
  13173. return handle;
  13174. }
  13175. }
  13176. return handle;
  13177. }
  13178. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  13179. if (!is_valid() || !response) { return -1; }
  13180. if (decompressor_) { return read_with_decompression(buf, len); }
  13181. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  13182. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  13183. trailers_parsed_ = true;
  13184. if (body_reader_.chunked_decoder) {
  13185. if (!body_reader_.chunked_decoder->parse_trailers_into(
  13186. response->trailers, response->headers)) {
  13187. return n;
  13188. }
  13189. } else {
  13190. detail::ChunkedDecoder dec(*stream_);
  13191. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  13192. return n;
  13193. }
  13194. }
  13195. }
  13196. return n;
  13197. }
  13198. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  13199. size_t len) {
  13200. if (decompress_offset_ < decompress_buffer_.size()) {
  13201. auto available = decompress_buffer_.size() - decompress_offset_;
  13202. auto to_copy = (std::min)(len, available);
  13203. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  13204. decompress_offset_ += to_copy;
  13205. decompressed_bytes_read_ += to_copy;
  13206. return static_cast<ssize_t>(to_copy);
  13207. }
  13208. decompress_buffer_.clear();
  13209. decompress_offset_ = 0;
  13210. constexpr size_t kDecompressionBufferSize = 8192;
  13211. char compressed_buf[kDecompressionBufferSize];
  13212. while (true) {
  13213. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  13214. sizeof(compressed_buf));
  13215. if (n <= 0) { return n; }
  13216. bool decompress_ok = decompressor_->decompress(
  13217. compressed_buf, static_cast<size_t>(n),
  13218. [this](const char *data, size_t data_len) {
  13219. decompress_buffer_.append(data, data_len);
  13220. auto limit = body_reader_.payload_max_length;
  13221. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  13222. return false;
  13223. }
  13224. return true;
  13225. });
  13226. if (!decompress_ok) {
  13227. body_reader_.last_error = Error::Read;
  13228. return -1;
  13229. }
  13230. if (!decompress_buffer_.empty()) { break; }
  13231. }
  13232. auto to_copy = (std::min)(len, decompress_buffer_.size());
  13233. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  13234. decompress_offset_ = to_copy;
  13235. decompressed_bytes_read_ += to_copy;
  13236. return static_cast<ssize_t>(to_copy);
  13237. }
  13238. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  13239. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  13240. return;
  13241. }
  13242. trailers_parsed_ = true;
  13243. const auto bufsiz = 128;
  13244. char line_buf[bufsiz];
  13245. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  13246. if (!line_reader.getline()) { return; }
  13247. if (!detail::parse_trailers(line_reader, response->trailers,
  13248. response->headers)) {
  13249. return;
  13250. }
  13251. }
  13252. namespace detail {
  13253. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  13254. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  13255. size_t &out_chunk_offset,
  13256. size_t &out_chunk_total) {
  13257. if (finished) { return 0; }
  13258. if (chunk_remaining == 0) {
  13259. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  13260. if (!lr.getline()) { return -1; }
  13261. // Everything below is bounded by eol rather than by the buffer's NUL, so
  13262. // the line terminator is never mistaken for line content.
  13263. const char *eol = lr.ptr() + lr.size();
  13264. if (lr.end_with_crlf()) {
  13265. eol -= 2;
  13266. } else if (eol != lr.ptr() && eol[-1] == '\n') {
  13267. // Only reachable under CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR, where
  13268. // getline() ends the line on a bare LF. That LF is the terminator, so it
  13269. // has to come off here or the check below would reject the line.
  13270. eol -= 1;
  13271. }
  13272. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  13273. const char *p = lr.ptr();
  13274. int v = 0;
  13275. if (p == eol || !is_hex(*p, v)) { return -1; }
  13276. size_t chunk_len = 0;
  13277. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  13278. for (; p < eol && is_hex(*p, v); ++p) {
  13279. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  13280. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  13281. }
  13282. while (p < eol && is_space_or_tab(*p)) {
  13283. ++p;
  13284. }
  13285. // RFC 9112 §7.1.1: only a chunk-ext may sit between the size and the line
  13286. // terminator, and it is built from tokens and quoted-strings, so it never
  13287. // holds a CR, LF or any other control character. getline() reads up to the
  13288. // CRLF, so a bare LF left in here would be swallowed as extension text
  13289. // while an intermediary that ends the line on it delimits the chunks
  13290. // differently, and the two disagree on where the body ends (request
  13291. // smuggling).
  13292. if (p < eol && *p != ';') { return -1; }
  13293. for (; p < eol; ++p) {
  13294. if (!is_space_or_tab(*p) && !fields::is_field_vchar(*p)) { return -1; }
  13295. }
  13296. if (chunk_len == 0) {
  13297. chunk_remaining = 0;
  13298. finished = true;
  13299. out_chunk_offset = 0;
  13300. out_chunk_total = 0;
  13301. return 0;
  13302. }
  13303. chunk_remaining = chunk_len;
  13304. last_chunk_total = chunk_remaining;
  13305. last_chunk_offset = 0;
  13306. }
  13307. auto to_read = (std::min)(chunk_remaining, len);
  13308. auto n = strm.read(buf, to_read);
  13309. if (n <= 0) { return -1; }
  13310. auto offset_before = last_chunk_offset;
  13311. last_chunk_offset += static_cast<size_t>(n);
  13312. chunk_remaining -= static_cast<size_t>(n);
  13313. out_chunk_offset = offset_before;
  13314. out_chunk_total = last_chunk_total;
  13315. if (chunk_remaining == 0) {
  13316. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  13317. if (!lr.getline()) { return -1; }
  13318. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  13319. }
  13320. return n;
  13321. }
  13322. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  13323. const Headers &src_headers) {
  13324. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  13325. if (!lr.getline()) { return false; }
  13326. return parse_trailers(lr, dest, src_headers);
  13327. }
  13328. } // namespace detail
  13329. inline void
  13330. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  13331. handle.connection_->sock = socket_.sock;
  13332. #ifdef CPPHTTPLIB_SSL_ENABLED
  13333. handle.connection_->session = socket_.ssl;
  13334. socket_.ssl = nullptr;
  13335. #endif
  13336. socket_.sock = INVALID_SOCKET;
  13337. }
  13338. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  13339. Response &res, bool close_connection,
  13340. Error &error) {
  13341. if (req.path.empty()) {
  13342. error = Error::Connection;
  13343. output_error_log(error, &req);
  13344. return false;
  13345. }
  13346. auto req_save = req;
  13347. bool ret;
  13348. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  13349. auto req2 = req;
  13350. req2.path = "http://" +
  13351. detail::make_host_and_port_string(host_, port_, false) +
  13352. req.path;
  13353. ret = process_request(strm, req2, res, close_connection, error);
  13354. req = std::move(req2);
  13355. req.path = req_save.path;
  13356. } else {
  13357. ret = process_request(strm, req, res, close_connection, error);
  13358. }
  13359. if (!ret) { return false; }
  13360. if (detail::has_header_token(res.headers, "Connection", "close") ||
  13361. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  13362. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  13363. // for this to be safe.
  13364. // This is safe to call because handle_request is only called by send_
  13365. // which locks the request mutex during the process. It would be a bug
  13366. // to call it from a different thread since it's a thread-safety issue
  13367. // to do these things to the socket if another thread is using the socket.
  13368. std::lock_guard<std::mutex> guard(socket_mutex_);
  13369. disconnect(/*gracefully=*/true);
  13370. }
  13371. if (300 < res.status && res.status < 400 && follow_location_) {
  13372. req = std::move(req_save);
  13373. ret = redirect(req, res, error);
  13374. }
  13375. #ifdef CPPHTTPLIB_SSL_ENABLED
  13376. if ((res.status == StatusCode::Unauthorized_401 ||
  13377. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  13378. req.authorization_count_ < 5) {
  13379. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  13380. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  13381. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  13382. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  13383. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  13384. return ret;
  13385. }
  13386. const auto &username =
  13387. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  13388. const auto &password =
  13389. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  13390. if (!username.empty() && !password.empty()) {
  13391. std::map<std::string, std::string> auth;
  13392. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  13393. Request new_req = req;
  13394. new_req.authorization_count_ += 1;
  13395. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  13396. : "Authorization");
  13397. new_req.headers.insert(detail::make_digest_authentication_header(
  13398. req, auth, new_req.authorization_count_, detail::random_string(10),
  13399. username, password, is_proxy));
  13400. Response new_res;
  13401. ret = send(new_req, new_res, error);
  13402. if (ret) { res = std::move(new_res); }
  13403. }
  13404. }
  13405. }
  13406. #endif
  13407. return ret;
  13408. }
  13409. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  13410. if (req.redirect_count_ == 0) {
  13411. error = Error::ExceedRedirectCount;
  13412. output_error_log(error, &req);
  13413. return false;
  13414. }
  13415. auto location = res.get_header_value("location");
  13416. if (location.empty()) { return false; }
  13417. detail::UrlComponents uc;
  13418. if (!detail::parse_url(detail::resolve_relative_location(location, req.path),
  13419. uc)) {
  13420. return false;
  13421. }
  13422. // Only follow http/https redirects
  13423. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  13424. return false;
  13425. }
  13426. auto scheme = is_ssl() ? "https" : "http";
  13427. auto next_scheme = std::move(uc.scheme);
  13428. auto next_host = std::move(uc.host);
  13429. auto port_str = std::move(uc.port);
  13430. auto next_path = std::move(uc.path);
  13431. auto next_query = std::move(uc.query);
  13432. auto next_port = port_;
  13433. if (!port_str.empty()) {
  13434. if (!detail::parse_port(port_str, next_port)) { return false; }
  13435. } else if (!next_scheme.empty()) {
  13436. next_port = next_scheme == "https" ? 443 : 80;
  13437. }
  13438. if (next_scheme.empty()) { next_scheme = scheme; }
  13439. if (next_host.empty()) { next_host = host_; }
  13440. if (next_path.empty()) { next_path = "/"; }
  13441. auto path = std::move(next_path) + next_query;
  13442. // Same host redirect - use current client
  13443. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  13444. return detail::redirect(*this, req, res, path, location, error);
  13445. }
  13446. // Cross-host/scheme redirect - create new client with robust setup
  13447. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  13448. path, location, error);
  13449. }
  13450. // New method for robust redirect client creation
  13451. inline bool ClientImpl::create_redirect_client(
  13452. const std::string &scheme, const std::string &host, int port, Request &req,
  13453. Response &res, const std::string &path, const std::string &location,
  13454. Error &error) {
  13455. // Determine if we need SSL
  13456. auto need_ssl = (scheme == "https");
  13457. // Clean up request headers that are host/client specific
  13458. // Remove headers that should not be carried over to new host
  13459. auto headers_to_remove = std::vector<std::string>{
  13460. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  13461. for (const auto &header_name : headers_to_remove) {
  13462. auto it = req.headers.find(header_name);
  13463. while (it != req.headers.end()) {
  13464. it = req.headers.erase(it);
  13465. it = req.headers.find(header_name);
  13466. }
  13467. }
  13468. // Create appropriate client type and handle redirect
  13469. if (need_ssl) {
  13470. #ifdef CPPHTTPLIB_SSL_ENABLED
  13471. // Create SSL client for HTTPS redirect
  13472. SSLClient redirect_client(host, port);
  13473. // Setup basic client configuration first
  13474. setup_redirect_client(redirect_client);
  13475. redirect_client.enable_server_certificate_verification(
  13476. server_certificate_verification_);
  13477. redirect_client.enable_server_hostname_verification(
  13478. server_hostname_verification_);
  13479. redirect_client.system_ca_mode_ = system_ca_mode_;
  13480. // Transfer CA certificate to redirect client
  13481. if (!ca_cert_pem_.empty()) {
  13482. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  13483. ca_cert_pem_.size());
  13484. }
  13485. if (!ca_cert_file_path_.empty()) {
  13486. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  13487. }
  13488. // Client certificates are set through constructor for SSLClient
  13489. // NOTE: SSLClient constructor already takes client_cert_path and
  13490. // client_key_path so we need to create it properly if client certs are
  13491. // needed
  13492. // Execute the redirect
  13493. return detail::redirect(redirect_client, req, res, path, location, error);
  13494. #else
  13495. // SSL not supported - set appropriate error
  13496. error = Error::SSLConnection;
  13497. output_error_log(error, &req);
  13498. return false;
  13499. #endif
  13500. } else {
  13501. // HTTP redirect
  13502. ClientImpl redirect_client(host, port);
  13503. // Setup client with robust configuration
  13504. setup_redirect_client(redirect_client);
  13505. // Execute the redirect
  13506. return detail::redirect(redirect_client, req, res, path, location, error);
  13507. }
  13508. }
  13509. // New method for robust client setup (based on basic_manual_redirect.cpp
  13510. // logic)
  13511. template <typename ClientType>
  13512. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  13513. // Copy basic settings first
  13514. client.set_connection_timeout(connection_timeout_sec_);
  13515. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  13516. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  13517. client.set_keep_alive(keep_alive_);
  13518. client.set_follow_location(
  13519. true); // Enable redirects to handle multi-step redirects
  13520. client.set_path_encode(path_encode_);
  13521. client.set_compress(compress_);
  13522. client.set_decompress(decompress_);
  13523. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  13524. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  13525. // 15.4, credentials must not be forwarded when redirecting to a different
  13526. // host. This function is only called for cross-host redirects; same-host
  13527. // redirects are handled directly in ClientImpl::redirect().
  13528. // Copy the proxy configuration unconditionally; the per-target bypass is
  13529. // re-evaluated at send time, so a later hop to a non-bypassed host can
  13530. // still use the proxy.
  13531. client.no_proxy_entries_ = no_proxy_entries_;
  13532. if (!proxy_host_.empty() && proxy_port_ != -1) {
  13533. client.set_proxy(proxy_host_, proxy_port_);
  13534. if (!proxy_basic_auth_username_.empty() ||
  13535. !proxy_basic_auth_password_.empty()) {
  13536. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  13537. proxy_basic_auth_password_);
  13538. }
  13539. if (!proxy_bearer_token_auth_token_.empty()) {
  13540. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  13541. }
  13542. #ifdef CPPHTTPLIB_SSL_ENABLED
  13543. if (!proxy_digest_auth_username_.empty()) {
  13544. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  13545. proxy_digest_auth_password_);
  13546. }
  13547. #endif
  13548. }
  13549. // Copy network and socket settings
  13550. client.set_address_family(address_family_);
  13551. client.set_tcp_nodelay(tcp_nodelay_);
  13552. client.set_ipv6_v6only(ipv6_v6only_);
  13553. if (socket_options_) { client.set_socket_options(socket_options_); }
  13554. if (!interface_.empty()) { client.set_interface(interface_); }
  13555. // Copy logging and headers
  13556. if (logger_) { client.set_logger(logger_); }
  13557. if (error_logger_) { client.set_error_logger(error_logger_); }
  13558. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  13559. // Each new client should generate its own headers based on its target host
  13560. }
  13561. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  13562. const Request &req,
  13563. Error &error) const {
  13564. auto is_shutting_down = []() { return false; };
  13565. if (req.is_chunked_content_provider_) {
  13566. auto compressor = compress_ ? detail::create_compressor().first
  13567. : std::unique_ptr<detail::compressor>();
  13568. if (!compressor) {
  13569. compressor = detail::make_unique<detail::nocompressor>();
  13570. }
  13571. return detail::write_content_chunked(strm, req.content_provider_,
  13572. is_shutting_down, *compressor, error);
  13573. } else {
  13574. return detail::write_content_with_progress(
  13575. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  13576. req.upload_progress, error);
  13577. }
  13578. }
  13579. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  13580. bool close_connection, Error &error,
  13581. bool skip_body, bool &rejected_locally) {
  13582. rejected_locally = false;
  13583. // Prepare additional headers
  13584. if (close_connection) {
  13585. if (!req.has_header("Connection")) {
  13586. req.set_header("Connection", "close");
  13587. }
  13588. }
  13589. std::string ct_for_defaults;
  13590. if (!req.has_header("Content-Type") && !req.body.empty()) {
  13591. ct_for_defaults = "text/plain";
  13592. }
  13593. prepare_default_headers(req, false, ct_for_defaults);
  13594. if (req.body.empty()) {
  13595. if (req.content_provider_) {
  13596. if (!req.is_chunked_content_provider_) {
  13597. if (!req.has_header("Content-Length")) {
  13598. auto length = std::to_string(req.content_length_);
  13599. req.set_header("Content-Length", length);
  13600. }
  13601. }
  13602. } else {
  13603. if (req.method == "POST" || req.method == "PUT" ||
  13604. req.method == "PATCH") {
  13605. req.set_header("Content-Length", "0");
  13606. }
  13607. }
  13608. }
  13609. // A CONNECT request is read by the proxy; everything sent through the tunnel
  13610. // it opens is read by the origin. Each credential goes only to its own hop.
  13611. auto is_connect = req.method == "CONNECT";
  13612. if (!is_connect && !req.has_header("Authorization")) {
  13613. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  13614. req.headers.insert(make_basic_authentication_header(
  13615. basic_auth_username_, basic_auth_password_, false));
  13616. } else if (!bearer_token_auth_token_.empty()) {
  13617. req.headers.insert(make_bearer_token_authentication_header(
  13618. bearer_token_auth_token_, false));
  13619. }
  13620. }
  13621. // Proxy-Authorization is only sent when the proxy reads this message —
  13622. // otherwise NO_PROXY-matched requests, and requests inside a TLS tunnel,
  13623. // would leak proxy credentials to the destination server.
  13624. if (is_proxy_enabled_for_host(host_) && (!is_ssl() || is_connect)) {
  13625. if ((!proxy_basic_auth_username_.empty() ||
  13626. !proxy_basic_auth_password_.empty()) &&
  13627. !req.has_header("Proxy-Authorization")) {
  13628. req.headers.insert(make_basic_authentication_header(
  13629. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  13630. }
  13631. if (!proxy_bearer_token_auth_token_.empty() &&
  13632. !req.has_header("Proxy-Authorization")) {
  13633. req.headers.insert(make_bearer_token_authentication_header(
  13634. proxy_bearer_token_auth_token_, true));
  13635. }
  13636. }
  13637. // Request line and headers
  13638. {
  13639. detail::BufferStream bstrm;
  13640. // Extract the query from req.path. The encoding itself is delegated to
  13641. // `encode_request_target`; the raw query is still needed here to decide
  13642. // between populating `req.params` from it and falling back to building a
  13643. // query out of caller-supplied `req.params`.
  13644. auto query_pos = req.path.find('?');
  13645. auto query_part = query_pos == std::string::npos
  13646. ? std::string()
  13647. : req.path.substr(query_pos + 1);
  13648. auto path_with_query =
  13649. detail::encode_request_target(req.path, path_encode_);
  13650. if (!query_part.empty()) {
  13651. // The query already came in through `req.path`; still populate
  13652. // `req.params` for handlers/users who read them.
  13653. detail::parse_query_text(query_part, req.params);
  13654. } else if (!req.params.empty()) {
  13655. // No query in `req.path`; build one from `req.params` so existing
  13656. // callers that pass `Params` separately continue to work.
  13657. path_with_query = append_query_params(path_with_query, req.params);
  13658. }
  13659. // Write request line and headers
  13660. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  13661. // A rejected method (not a token, e.g. carrying CR/LF) or target (e.g.
  13662. // CR/LF in a caller-supplied path under set_path_encode(false)) must
  13663. // fail the request cleanly instead of emitting a request-line-less,
  13664. // header-injecting request.
  13665. error = Error::Write;
  13666. rejected_locally = true;
  13667. output_error_log(error, &req);
  13668. return false;
  13669. }
  13670. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  13671. error)) {
  13672. rejected_locally = true;
  13673. output_error_log(error, &req);
  13674. return false;
  13675. }
  13676. // Flush buffer
  13677. auto &data = bstrm.get_buffer();
  13678. if (!detail::write_data(strm, data.data(), data.size())) {
  13679. error = Error::Write;
  13680. output_error_log(error, &req);
  13681. return false;
  13682. }
  13683. }
  13684. // After sending request line and headers, wait briefly for an early server
  13685. // response (e.g. 4xx) and avoid sending a potentially large request body
  13686. // unnecessarily. This workaround is only enabled on Windows because Unix
  13687. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  13688. // buffering can accept large writes even when the peer already responded.
  13689. // Check the stream first (which covers SSL via `is_readable()`), then
  13690. // fall back to select on the socket. Only perform the wait for very large
  13691. // request bodies to avoid interfering with normal small requests and
  13692. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  13693. // response. Skip this check when using Expect: 100-continue, as the protocol
  13694. // handles early responses properly.
  13695. #if defined(_WIN32)
  13696. if (!skip_body &&
  13697. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  13698. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  13699. auto start = std::chrono::high_resolution_clock::now();
  13700. for (;;) {
  13701. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  13702. // from SSL internals. If the underlying socket is readable, assume an
  13703. // early response may be present.
  13704. auto sock = strm.socket();
  13705. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  13706. return false;
  13707. }
  13708. // Fallback to stream-level check for non-socket streams or when the
  13709. // socket isn't reporting readable. Avoid using `is_readable()` for
  13710. // SSL, since `SSL_pending()` may report buffered records that do not
  13711. // indicate a complete application-level response yet.
  13712. if (!is_ssl() && strm.is_readable()) { return false; }
  13713. auto now = std::chrono::high_resolution_clock::now();
  13714. auto elapsed =
  13715. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  13716. .count();
  13717. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  13718. break;
  13719. }
  13720. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  13721. }
  13722. }
  13723. #endif
  13724. // Body
  13725. if (skip_body) { return true; }
  13726. return write_request_body(strm, req, error);
  13727. }
  13728. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  13729. Error &error) {
  13730. if (req.body.empty()) {
  13731. return write_content_with_provider(strm, req, error);
  13732. }
  13733. if (req.upload_progress) {
  13734. auto body_size = req.body.size();
  13735. size_t written = 0;
  13736. auto data = req.body.data();
  13737. while (written < body_size) {
  13738. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  13739. if (!detail::write_data(strm, data + written, to_write)) {
  13740. error = Error::Write;
  13741. output_error_log(error, &req);
  13742. return false;
  13743. }
  13744. written += to_write;
  13745. if (!req.upload_progress(written, body_size)) {
  13746. error = Error::Canceled;
  13747. output_error_log(error, &req);
  13748. return false;
  13749. }
  13750. }
  13751. } else {
  13752. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  13753. error = Error::Write;
  13754. output_error_log(error, &req);
  13755. return false;
  13756. }
  13757. }
  13758. return true;
  13759. }
  13760. inline std::unique_ptr<Response>
  13761. ClientImpl::send_with_content_provider_and_receiver(
  13762. Request &req, const char *body, size_t content_length,
  13763. ContentProvider content_provider,
  13764. ContentProviderWithoutLength content_provider_without_length,
  13765. const std::string &content_type, ContentReceiver content_receiver,
  13766. Error &error) {
  13767. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  13768. auto enc = compress_
  13769. ? detail::create_compressor()
  13770. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  13771. nullptr, nullptr);
  13772. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  13773. if (enc.first && !content_provider_without_length) {
  13774. auto &compressor = enc.first;
  13775. if (content_provider) {
  13776. auto ok = true;
  13777. auto finished = false;
  13778. size_t offset = 0;
  13779. DataSink data_sink;
  13780. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  13781. if (ok) {
  13782. auto last = offset + data_len == content_length;
  13783. auto ret = compressor->compress(
  13784. data, data_len, last,
  13785. [&](const char *compressed_data, size_t compressed_data_len) {
  13786. req.body.append(compressed_data, compressed_data_len);
  13787. return true;
  13788. });
  13789. if (ret) {
  13790. offset += data_len;
  13791. } else {
  13792. ok = false;
  13793. }
  13794. }
  13795. return ok;
  13796. };
  13797. // As in detail::write_content_with_progress(): the body is framed by
  13798. // content_length, so a provider that finishes early has truncated it.
  13799. // Stop and report that instead of calling the provider forever.
  13800. data_sink.done = [&]() { finished = true; };
  13801. while (ok && !finished && offset < content_length) {
  13802. if (!content_provider(offset, content_length - offset, data_sink)) {
  13803. error = Error::Canceled;
  13804. output_error_log(error, &req);
  13805. return nullptr;
  13806. }
  13807. }
  13808. // A short body here means either the provider stopped early or the
  13809. // compressor gave up. The branch below reports a failing compressor as
  13810. // Error::Compression, so keep the two distinguishable.
  13811. if (offset < content_length) {
  13812. error = ok ? Error::Write : Error::Compression;
  13813. output_error_log(error, &req);
  13814. return nullptr;
  13815. }
  13816. } else {
  13817. if (!compressor->compress(body, content_length, true,
  13818. [&](const char *data, size_t data_len) {
  13819. req.body.append(data, data_len);
  13820. return true;
  13821. })) {
  13822. error = Error::Compression;
  13823. output_error_log(error, &req);
  13824. return nullptr;
  13825. }
  13826. }
  13827. } else {
  13828. if (content_provider) {
  13829. req.content_length_ = content_length;
  13830. req.content_provider_ = std::move(content_provider);
  13831. req.is_chunked_content_provider_ = false;
  13832. } else if (content_provider_without_length) {
  13833. req.content_length_ = 0;
  13834. req.content_provider_ = detail::ContentProviderAdapter(
  13835. std::move(content_provider_without_length));
  13836. req.is_chunked_content_provider_ = true;
  13837. req.set_header("Transfer-Encoding", "chunked");
  13838. } else {
  13839. req.body.assign(body, content_length);
  13840. }
  13841. }
  13842. if (content_receiver) {
  13843. req.content_receiver =
  13844. [content_receiver](const char *data, size_t data_length,
  13845. size_t /*offset*/, size_t /*total_length*/) {
  13846. return content_receiver(data, data_length);
  13847. };
  13848. }
  13849. auto res = detail::make_unique<Response>();
  13850. return send(req, *res, error) ? std::move(res) : nullptr;
  13851. }
  13852. inline Result ClientImpl::send_with_content_provider_and_receiver(
  13853. const std::string &method, const std::string &path, const Headers &headers,
  13854. const char *body, size_t content_length, ContentProvider content_provider,
  13855. ContentProviderWithoutLength content_provider_without_length,
  13856. const std::string &content_type, ContentReceiver content_receiver,
  13857. UploadProgress progress) {
  13858. Request req;
  13859. req.method = method;
  13860. req.headers = headers;
  13861. req.path = path;
  13862. req.upload_progress = std::move(progress);
  13863. if (max_timeout_msec_ > 0) {
  13864. req.start_time_ = std::chrono::steady_clock::now();
  13865. }
  13866. auto error = Error::Success;
  13867. auto res = send_with_content_provider_and_receiver(
  13868. req, body, content_length, std::move(content_provider),
  13869. std::move(content_provider_without_length), content_type,
  13870. std::move(content_receiver), error);
  13871. #ifdef CPPHTTPLIB_SSL_ENABLED
  13872. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  13873. last_backend_error_};
  13874. #else
  13875. return Result{std::move(res), error, std::move(req.headers)};
  13876. #endif
  13877. }
  13878. inline void ClientImpl::output_log(const Request &req,
  13879. const Response &res) const {
  13880. if (logger_) {
  13881. std::lock_guard<std::mutex> guard(logger_mutex_);
  13882. logger_(req, res);
  13883. }
  13884. }
  13885. inline void ClientImpl::output_error_log(const Error &err,
  13886. const Request *req) const {
  13887. if (error_logger_) {
  13888. std::lock_guard<std::mutex> guard(logger_mutex_);
  13889. error_logger_(err, req);
  13890. }
  13891. }
  13892. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  13893. Response &res, bool close_connection,
  13894. Error &error) {
  13895. // Auto-add Expect: 100-continue for large bodies
  13896. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  13897. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  13898. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  13899. req.set_header("Expect", "100-continue");
  13900. }
  13901. }
  13902. // Check for Expect: 100-continue
  13903. auto expect_100_continue =
  13904. detail::has_header_token(req.headers, "Expect", "100-continue");
  13905. // Send request (skip body if using Expect: 100-continue)
  13906. auto rejected_locally = false;
  13907. auto write_request_success =
  13908. write_request(strm, req, close_connection, error, expect_100_continue,
  13909. rejected_locally);
  13910. // A failed write normally still reads the response below, since the server
  13911. // may have answered early (e.g. 413/414) and closed while the body was being
  13912. // sent. A request rejected before any byte reached the socket gets no such
  13913. // response, and waiting for one would block until the read timeout.
  13914. if (rejected_locally) { return false; }
  13915. #ifdef CPPHTTPLIB_SSL_ENABLED
  13916. if (is_ssl() && !expect_100_continue) {
  13917. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  13918. if (!is_proxy_enabled) {
  13919. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  13920. error = Error::SSLPeerCouldBeClosed_;
  13921. output_error_log(error, &req);
  13922. return false;
  13923. }
  13924. }
  13925. }
  13926. #endif
  13927. // Handle Expect: 100-continue.
  13928. //
  13929. // Wait for an interim/early response by attempting to read the status line
  13930. // under a short timeout, instead of trusting raw socket readability. Over
  13931. // TLS, post-handshake records (e.g. session tickets) make the socket
  13932. // readable without any HTTP response being available; relying on
  13933. // `select_read` there caused the body to be withheld forever and the
  13934. // request to fail with `Read` (#2458). If no status line arrives within the
  13935. // timeout, send the body anyway (matching curl's behavior).
  13936. auto status_line_read = false;
  13937. if (expect_100_continue && write_request_success) {
  13938. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  13939. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  13940. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  13941. strm.set_read_timeout(sec, usec);
  13942. status_line_read = read_response_line(strm, req, res, false);
  13943. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  13944. }
  13945. if (!status_line_read) {
  13946. // No interim response within the timeout: send the body and handle the
  13947. // response as usual.
  13948. if (!write_request_body(strm, req, error)) { return false; }
  13949. expect_100_continue = false; // Switch to normal response handling
  13950. }
  13951. }
  13952. // Receive response and headers
  13953. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  13954. if ((!status_line_read &&
  13955. !read_response_line(strm, req, res, !expect_100_continue)) ||
  13956. !detail::read_headers(strm, res.headers)) {
  13957. if (write_request_success) { error = Error::Read; }
  13958. output_error_log(error, &req);
  13959. return false;
  13960. }
  13961. if (!write_request_success) { return false; }
  13962. // Handle Expect: 100-continue response
  13963. if (expect_100_continue) {
  13964. if (res.status == StatusCode::Continue_100) {
  13965. // Server accepted, send the body
  13966. if (!write_request_body(strm, req, error)) { return false; }
  13967. // Read the actual response
  13968. res.headers.clear();
  13969. res.body.clear();
  13970. if (!read_response_line(strm, req, res) ||
  13971. !detail::read_headers(strm, res.headers)) {
  13972. error = Error::Read;
  13973. output_error_log(error, &req);
  13974. return false;
  13975. }
  13976. }
  13977. // If not 100 Continue, server returned an error; proceed with that response
  13978. }
  13979. // Body
  13980. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  13981. req.method != "CONNECT") {
  13982. // Reject ambiguous framing (RFC 9112 §6.3). Unlike a request, a response
  13983. // whose final transfer coding is not chunked is not ambiguous: its body
  13984. // runs until the server closes the connection, so it is not rejected.
  13985. // HEAD/204 are excluded above and a 304 carries no body.
  13986. if (res.status != StatusCode::NotModified_304 &&
  13987. detail::has_conflicting_content_length(res.headers)) {
  13988. error = Error::Read;
  13989. output_error_log(error, &req);
  13990. return false;
  13991. }
  13992. auto redirect = 300 < res.status && res.status < 400 &&
  13993. res.status != StatusCode::NotModified_304 &&
  13994. follow_location_;
  13995. if (req.response_handler && !redirect) {
  13996. if (!req.response_handler(res)) {
  13997. error = Error::Canceled;
  13998. output_error_log(error, &req);
  13999. return false;
  14000. }
  14001. }
  14002. auto out =
  14003. req.content_receiver
  14004. ? static_cast<ContentReceiverWithProgress>(
  14005. [&](const char *buf, size_t n, size_t off, size_t len) {
  14006. if (redirect) { return true; }
  14007. auto ret = req.content_receiver(buf, n, off, len);
  14008. if (!ret) {
  14009. error = Error::Canceled;
  14010. output_error_log(error, &req);
  14011. }
  14012. return ret;
  14013. })
  14014. : static_cast<ContentReceiverWithProgress>(
  14015. [&](const char *buf, size_t n, size_t /*off*/,
  14016. size_t /*len*/) {
  14017. assert(res.body.size() + n <= res.body.max_size());
  14018. if (payload_max_length_ > 0 &&
  14019. (res.body.size() >= payload_max_length_ ||
  14020. n > payload_max_length_ - res.body.size())) {
  14021. return false;
  14022. }
  14023. res.body.append(buf, n);
  14024. return true;
  14025. });
  14026. auto progress = [&](size_t current, size_t total) {
  14027. if (!req.download_progress || redirect) { return true; }
  14028. auto ret = req.download_progress(current, total);
  14029. if (!ret) {
  14030. error = Error::Canceled;
  14031. output_error_log(error, &req);
  14032. }
  14033. return ret;
  14034. };
  14035. if (res.has_header("Content-Length")) {
  14036. if (!req.content_receiver) {
  14037. auto len = res.get_header_value_u64("Content-Length");
  14038. if (len > res.body.max_size()) {
  14039. error = Error::Read;
  14040. output_error_log(error, &req);
  14041. return false;
  14042. }
  14043. // Cap the reservation by payload_max_length_ to avoid OOM when a
  14044. // hostile or malformed server sends an enormous Content-Length.
  14045. // The actual body read below is bounded by payload_max_length_,
  14046. // so reserving more than that is never useful.
  14047. auto reserve_len = static_cast<size_t>(len);
  14048. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  14049. reserve_len = payload_max_length_;
  14050. }
  14051. res.body.reserve(reserve_len);
  14052. }
  14053. }
  14054. if (res.status != StatusCode::NotModified_304) {
  14055. auto content_status = 0;
  14056. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  14057. ? (std::numeric_limits<size_t>::max)()
  14058. : payload_max_length_;
  14059. if (!detail::read_content(strm, res, max_length, content_status,
  14060. std::move(progress), std::move(out),
  14061. decompress_)) {
  14062. if (error != Error::Canceled) {
  14063. // Tell the caller apart from a plain read failure when the body could
  14064. // not be decoded because of its Content-Encoding.
  14065. switch (content_status) {
  14066. case StatusCode::UnsupportedMediaType_415:
  14067. error = Error::UnsupportedContentEncoding;
  14068. break;
  14069. case StatusCode::InternalServerError_500:
  14070. error = Error::Compression;
  14071. break;
  14072. default: error = Error::Read; break;
  14073. }
  14074. }
  14075. output_error_log(error, &req);
  14076. return false;
  14077. }
  14078. }
  14079. }
  14080. // Log
  14081. output_log(req, res);
  14082. return true;
  14083. }
  14084. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  14085. const std::string &boundary, const UploadFormDataItems &items,
  14086. const FormDataProviderItems &provider_items) const {
  14087. size_t cur_item = 0;
  14088. size_t cur_start = 0;
  14089. // cur_item and cur_start are copied to within the std::function and
  14090. // maintain state between successive calls
  14091. return [&, cur_item, cur_start](size_t offset,
  14092. DataSink &sink) mutable -> bool {
  14093. if (!offset && !items.empty()) {
  14094. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  14095. return true;
  14096. } else if (cur_item < provider_items.size()) {
  14097. if (!cur_start) {
  14098. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  14099. provider_items[cur_item], boundary);
  14100. offset += begin.size();
  14101. cur_start = offset;
  14102. sink.os << begin;
  14103. }
  14104. DataSink cur_sink;
  14105. auto has_data = true;
  14106. cur_sink.write = sink.write;
  14107. // Forward is_writable so a provider item asking whether it may keep
  14108. // going gets the outer sink's answer rather than the default `true`.
  14109. cur_sink.is_writable = sink.is_writable;
  14110. cur_sink.done = [&]() { has_data = false; };
  14111. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  14112. return false;
  14113. }
  14114. if (!has_data) {
  14115. sink.os << detail::serialize_multipart_formdata_item_end();
  14116. cur_item++;
  14117. cur_start = 0;
  14118. }
  14119. return true;
  14120. } else {
  14121. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  14122. sink.done();
  14123. return true;
  14124. }
  14125. };
  14126. }
  14127. inline bool ClientImpl::process_socket(
  14128. const Socket &socket,
  14129. std::chrono::time_point<std::chrono::steady_clock> start_time,
  14130. std::function<bool(Stream &strm)> callback) {
  14131. return detail::process_client_socket(
  14132. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  14133. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  14134. }
  14135. inline bool ClientImpl::is_ssl() const { return false; }
  14136. inline Result ClientImpl::Get(const std::string &path,
  14137. DownloadProgress progress) {
  14138. return Get(path, Headers(), std::move(progress));
  14139. }
  14140. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  14141. DownloadProgress progress) {
  14142. return Get(path, params, Headers(), std::move(progress));
  14143. }
  14144. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  14145. const Headers &headers,
  14146. DownloadProgress progress) {
  14147. if (params.empty()) { return Get(path, headers); }
  14148. std::string path_with_query = append_query_params(path, params);
  14149. return Get(path_with_query, headers, std::move(progress));
  14150. }
  14151. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  14152. DownloadProgress progress) {
  14153. Request req;
  14154. req.method = "GET";
  14155. req.path = path;
  14156. req.headers = headers;
  14157. req.download_progress = std::move(progress);
  14158. if (max_timeout_msec_ > 0) {
  14159. req.start_time_ = std::chrono::steady_clock::now();
  14160. }
  14161. return send_(std::move(req));
  14162. }
  14163. inline Result ClientImpl::Get(const std::string &path,
  14164. ContentReceiver content_receiver,
  14165. DownloadProgress progress) {
  14166. return Get(path, Headers(), nullptr, std::move(content_receiver),
  14167. std::move(progress));
  14168. }
  14169. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  14170. ContentReceiver content_receiver,
  14171. DownloadProgress progress) {
  14172. return Get(path, headers, nullptr, std::move(content_receiver),
  14173. std::move(progress));
  14174. }
  14175. inline Result ClientImpl::Get(const std::string &path,
  14176. ResponseHandler response_handler,
  14177. ContentReceiver content_receiver,
  14178. DownloadProgress progress) {
  14179. return Get(path, Headers(), std::move(response_handler),
  14180. std::move(content_receiver), std::move(progress));
  14181. }
  14182. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  14183. ResponseHandler response_handler,
  14184. ContentReceiver content_receiver,
  14185. DownloadProgress progress) {
  14186. Request req;
  14187. req.method = "GET";
  14188. req.path = path;
  14189. req.headers = headers;
  14190. req.response_handler = std::move(response_handler);
  14191. req.content_receiver =
  14192. [content_receiver](const char *data, size_t data_length,
  14193. size_t /*offset*/, size_t /*total_length*/) {
  14194. return content_receiver(data, data_length);
  14195. };
  14196. req.download_progress = std::move(progress);
  14197. if (max_timeout_msec_ > 0) {
  14198. req.start_time_ = std::chrono::steady_clock::now();
  14199. }
  14200. return send_(std::move(req));
  14201. }
  14202. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  14203. const Headers &headers,
  14204. ContentReceiver content_receiver,
  14205. DownloadProgress progress) {
  14206. return Get(path, params, headers, nullptr, std::move(content_receiver),
  14207. std::move(progress));
  14208. }
  14209. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  14210. const Headers &headers,
  14211. ResponseHandler response_handler,
  14212. ContentReceiver content_receiver,
  14213. DownloadProgress progress) {
  14214. if (params.empty()) {
  14215. return Get(path, headers, std::move(response_handler),
  14216. std::move(content_receiver), std::move(progress));
  14217. }
  14218. std::string path_with_query = append_query_params(path, params);
  14219. return Get(path_with_query, headers, std::move(response_handler),
  14220. std::move(content_receiver), std::move(progress));
  14221. }
  14222. inline Result ClientImpl::Head(const std::string &path) {
  14223. return Head(path, Headers());
  14224. }
  14225. inline Result ClientImpl::Head(const std::string &path,
  14226. const Headers &headers) {
  14227. Request req;
  14228. req.method = "HEAD";
  14229. req.headers = headers;
  14230. req.path = path;
  14231. if (max_timeout_msec_ > 0) {
  14232. req.start_time_ = std::chrono::steady_clock::now();
  14233. }
  14234. return send_(std::move(req));
  14235. }
  14236. inline Result ClientImpl::Post(const std::string &path) {
  14237. return Post(path, std::string(), std::string());
  14238. }
  14239. inline Result ClientImpl::Post(const std::string &path,
  14240. const Headers &headers) {
  14241. return Post(path, headers, nullptr, 0, std::string());
  14242. }
  14243. inline Result ClientImpl::Post(const std::string &path, const char *body,
  14244. size_t content_length,
  14245. const std::string &content_type,
  14246. UploadProgress progress) {
  14247. return Post(path, Headers(), body, content_length, content_type, progress);
  14248. }
  14249. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  14250. const std::string &content_type,
  14251. UploadProgress progress) {
  14252. return Post(path, Headers(), body, content_type, progress);
  14253. }
  14254. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  14255. return Post(path, Headers(), params);
  14256. }
  14257. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  14258. ContentProvider content_provider,
  14259. const std::string &content_type,
  14260. UploadProgress progress) {
  14261. return Post(path, Headers(), content_length, std::move(content_provider),
  14262. content_type, progress);
  14263. }
  14264. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  14265. ContentProvider content_provider,
  14266. const std::string &content_type,
  14267. ContentReceiver content_receiver,
  14268. UploadProgress progress) {
  14269. return Post(path, Headers(), content_length, std::move(content_provider),
  14270. content_type, std::move(content_receiver), progress);
  14271. }
  14272. inline Result ClientImpl::Post(const std::string &path,
  14273. ContentProviderWithoutLength content_provider,
  14274. const std::string &content_type,
  14275. UploadProgress progress) {
  14276. return Post(path, Headers(), std::move(content_provider), content_type,
  14277. progress);
  14278. }
  14279. inline Result ClientImpl::Post(const std::string &path,
  14280. ContentProviderWithoutLength content_provider,
  14281. const std::string &content_type,
  14282. ContentReceiver content_receiver,
  14283. UploadProgress progress) {
  14284. return Post(path, Headers(), std::move(content_provider), content_type,
  14285. std::move(content_receiver), progress);
  14286. }
  14287. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14288. const Params &params) {
  14289. auto query = detail::params_to_query_str(params);
  14290. return Post(path, headers, query, "application/x-www-form-urlencoded");
  14291. }
  14292. inline Result ClientImpl::Post(const std::string &path,
  14293. const UploadFormDataItems &items,
  14294. UploadProgress progress) {
  14295. return Post(path, Headers(), items, progress);
  14296. }
  14297. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14298. const UploadFormDataItems &items,
  14299. UploadProgress progress) {
  14300. const auto &boundary = detail::make_multipart_data_boundary();
  14301. const auto &content_type =
  14302. detail::serialize_multipart_formdata_get_content_type(boundary);
  14303. auto content_length = detail::get_multipart_content_length(items, boundary);
  14304. return Post(path, headers, content_length,
  14305. detail::make_multipart_content_provider(items, boundary),
  14306. content_type, progress);
  14307. }
  14308. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14309. const UploadFormDataItems &items,
  14310. const std::string &boundary,
  14311. UploadProgress progress) {
  14312. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14313. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14314. }
  14315. const auto &content_type =
  14316. detail::serialize_multipart_formdata_get_content_type(boundary);
  14317. auto content_length = detail::get_multipart_content_length(items, boundary);
  14318. return Post(path, headers, content_length,
  14319. detail::make_multipart_content_provider(items, boundary),
  14320. content_type, progress);
  14321. }
  14322. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14323. const char *body, size_t content_length,
  14324. const std::string &content_type,
  14325. UploadProgress progress) {
  14326. return send_with_content_provider_and_receiver(
  14327. "POST", path, headers, body, content_length, nullptr, nullptr,
  14328. content_type, nullptr, progress);
  14329. }
  14330. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14331. const std::string &body,
  14332. const std::string &content_type,
  14333. UploadProgress progress) {
  14334. return send_with_content_provider_and_receiver(
  14335. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  14336. content_type, nullptr, progress);
  14337. }
  14338. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14339. size_t content_length,
  14340. ContentProvider content_provider,
  14341. const std::string &content_type,
  14342. UploadProgress progress) {
  14343. return send_with_content_provider_and_receiver(
  14344. "POST", path, headers, nullptr, content_length,
  14345. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14346. }
  14347. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14348. size_t content_length,
  14349. ContentProvider content_provider,
  14350. const std::string &content_type,
  14351. ContentReceiver content_receiver,
  14352. DownloadProgress progress) {
  14353. return send_with_content_provider_and_receiver(
  14354. "POST", path, headers, nullptr, content_length,
  14355. std::move(content_provider), nullptr, content_type,
  14356. std::move(content_receiver), std::move(progress));
  14357. }
  14358. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14359. ContentProviderWithoutLength content_provider,
  14360. const std::string &content_type,
  14361. UploadProgress progress) {
  14362. return send_with_content_provider_and_receiver(
  14363. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14364. content_type, nullptr, progress);
  14365. }
  14366. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14367. ContentProviderWithoutLength content_provider,
  14368. const std::string &content_type,
  14369. ContentReceiver content_receiver,
  14370. DownloadProgress progress) {
  14371. return send_with_content_provider_and_receiver(
  14372. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14373. content_type, std::move(content_receiver), std::move(progress));
  14374. }
  14375. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14376. const UploadFormDataItems &items,
  14377. const FormDataProviderItems &provider_items,
  14378. UploadProgress progress) {
  14379. const auto &boundary = detail::make_multipart_data_boundary();
  14380. const auto &content_type =
  14381. detail::serialize_multipart_formdata_get_content_type(boundary);
  14382. return send_with_content_provider_and_receiver(
  14383. "POST", path, headers, nullptr, 0, nullptr,
  14384. get_multipart_content_provider(boundary, items, provider_items),
  14385. content_type, nullptr, progress);
  14386. }
  14387. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14388. const std::string &body,
  14389. const std::string &content_type,
  14390. ContentReceiver content_receiver,
  14391. DownloadProgress progress) {
  14392. Request req;
  14393. req.method = "POST";
  14394. req.path = path;
  14395. req.headers = headers;
  14396. req.body = body;
  14397. req.content_receiver =
  14398. [content_receiver](const char *data, size_t data_length,
  14399. size_t /*offset*/, size_t /*total_length*/) {
  14400. return content_receiver(data, data_length);
  14401. };
  14402. req.download_progress = std::move(progress);
  14403. if (max_timeout_msec_ > 0) {
  14404. req.start_time_ = std::chrono::steady_clock::now();
  14405. }
  14406. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14407. return send_(std::move(req));
  14408. }
  14409. inline Result ClientImpl::Put(const std::string &path) {
  14410. return Put(path, std::string(), std::string());
  14411. }
  14412. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  14413. return Put(path, headers, nullptr, 0, std::string());
  14414. }
  14415. inline Result ClientImpl::Put(const std::string &path, const char *body,
  14416. size_t content_length,
  14417. const std::string &content_type,
  14418. UploadProgress progress) {
  14419. return Put(path, Headers(), body, content_length, content_type, progress);
  14420. }
  14421. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  14422. const std::string &content_type,
  14423. UploadProgress progress) {
  14424. return Put(path, Headers(), body, content_type, progress);
  14425. }
  14426. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  14427. return Put(path, Headers(), params);
  14428. }
  14429. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  14430. ContentProvider content_provider,
  14431. const std::string &content_type,
  14432. UploadProgress progress) {
  14433. return Put(path, Headers(), content_length, std::move(content_provider),
  14434. content_type, progress);
  14435. }
  14436. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  14437. ContentProvider content_provider,
  14438. const std::string &content_type,
  14439. ContentReceiver content_receiver,
  14440. UploadProgress progress) {
  14441. return Put(path, Headers(), content_length, std::move(content_provider),
  14442. content_type, std::move(content_receiver), progress);
  14443. }
  14444. inline Result ClientImpl::Put(const std::string &path,
  14445. ContentProviderWithoutLength content_provider,
  14446. const std::string &content_type,
  14447. UploadProgress progress) {
  14448. return Put(path, Headers(), std::move(content_provider), content_type,
  14449. progress);
  14450. }
  14451. inline Result ClientImpl::Put(const std::string &path,
  14452. ContentProviderWithoutLength content_provider,
  14453. const std::string &content_type,
  14454. ContentReceiver content_receiver,
  14455. UploadProgress progress) {
  14456. return Put(path, Headers(), std::move(content_provider), content_type,
  14457. std::move(content_receiver), progress);
  14458. }
  14459. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14460. const Params &params) {
  14461. auto query = detail::params_to_query_str(params);
  14462. return Put(path, headers, query, "application/x-www-form-urlencoded");
  14463. }
  14464. inline Result ClientImpl::Put(const std::string &path,
  14465. const UploadFormDataItems &items,
  14466. UploadProgress progress) {
  14467. return Put(path, Headers(), items, progress);
  14468. }
  14469. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14470. const UploadFormDataItems &items,
  14471. UploadProgress progress) {
  14472. const auto &boundary = detail::make_multipart_data_boundary();
  14473. const auto &content_type =
  14474. detail::serialize_multipart_formdata_get_content_type(boundary);
  14475. auto content_length = detail::get_multipart_content_length(items, boundary);
  14476. return Put(path, headers, content_length,
  14477. detail::make_multipart_content_provider(items, boundary),
  14478. content_type, progress);
  14479. }
  14480. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14481. const UploadFormDataItems &items,
  14482. const std::string &boundary,
  14483. UploadProgress progress) {
  14484. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14485. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14486. }
  14487. const auto &content_type =
  14488. detail::serialize_multipart_formdata_get_content_type(boundary);
  14489. auto content_length = detail::get_multipart_content_length(items, boundary);
  14490. return Put(path, headers, content_length,
  14491. detail::make_multipart_content_provider(items, boundary),
  14492. content_type, progress);
  14493. }
  14494. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14495. const char *body, size_t content_length,
  14496. const std::string &content_type,
  14497. UploadProgress progress) {
  14498. return send_with_content_provider_and_receiver(
  14499. "PUT", path, headers, body, content_length, nullptr, nullptr,
  14500. content_type, nullptr, progress);
  14501. }
  14502. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14503. const std::string &body,
  14504. const std::string &content_type,
  14505. UploadProgress progress) {
  14506. return send_with_content_provider_and_receiver(
  14507. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  14508. content_type, nullptr, progress);
  14509. }
  14510. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14511. size_t content_length,
  14512. ContentProvider content_provider,
  14513. const std::string &content_type,
  14514. UploadProgress progress) {
  14515. return send_with_content_provider_and_receiver(
  14516. "PUT", path, headers, nullptr, content_length,
  14517. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14518. }
  14519. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14520. size_t content_length,
  14521. ContentProvider content_provider,
  14522. const std::string &content_type,
  14523. ContentReceiver content_receiver,
  14524. UploadProgress progress) {
  14525. return send_with_content_provider_and_receiver(
  14526. "PUT", path, headers, nullptr, content_length,
  14527. std::move(content_provider), nullptr, content_type,
  14528. std::move(content_receiver), progress);
  14529. }
  14530. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14531. ContentProviderWithoutLength content_provider,
  14532. const std::string &content_type,
  14533. UploadProgress progress) {
  14534. return send_with_content_provider_and_receiver(
  14535. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14536. content_type, nullptr, progress);
  14537. }
  14538. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14539. ContentProviderWithoutLength content_provider,
  14540. const std::string &content_type,
  14541. ContentReceiver content_receiver,
  14542. UploadProgress progress) {
  14543. return send_with_content_provider_and_receiver(
  14544. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14545. content_type, std::move(content_receiver), progress);
  14546. }
  14547. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14548. const UploadFormDataItems &items,
  14549. const FormDataProviderItems &provider_items,
  14550. UploadProgress progress) {
  14551. const auto &boundary = detail::make_multipart_data_boundary();
  14552. const auto &content_type =
  14553. detail::serialize_multipart_formdata_get_content_type(boundary);
  14554. return send_with_content_provider_and_receiver(
  14555. "PUT", path, headers, nullptr, 0, nullptr,
  14556. get_multipart_content_provider(boundary, items, provider_items),
  14557. content_type, nullptr, progress);
  14558. }
  14559. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14560. const std::string &body,
  14561. const std::string &content_type,
  14562. ContentReceiver content_receiver,
  14563. DownloadProgress progress) {
  14564. Request req;
  14565. req.method = "PUT";
  14566. req.path = path;
  14567. req.headers = headers;
  14568. req.body = body;
  14569. req.content_receiver =
  14570. [content_receiver](const char *data, size_t data_length,
  14571. size_t /*offset*/, size_t /*total_length*/) {
  14572. return content_receiver(data, data_length);
  14573. };
  14574. req.download_progress = std::move(progress);
  14575. if (max_timeout_msec_ > 0) {
  14576. req.start_time_ = std::chrono::steady_clock::now();
  14577. }
  14578. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14579. return send_(std::move(req));
  14580. }
  14581. inline Result ClientImpl::Patch(const std::string &path) {
  14582. return Patch(path, std::string(), std::string());
  14583. }
  14584. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14585. UploadProgress progress) {
  14586. return Patch(path, headers, nullptr, 0, std::string(), progress);
  14587. }
  14588. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  14589. size_t content_length,
  14590. const std::string &content_type,
  14591. UploadProgress progress) {
  14592. return Patch(path, Headers(), body, content_length, content_type, progress);
  14593. }
  14594. inline Result ClientImpl::Patch(const std::string &path,
  14595. const std::string &body,
  14596. const std::string &content_type,
  14597. UploadProgress progress) {
  14598. return Patch(path, Headers(), body, content_type, progress);
  14599. }
  14600. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  14601. return Patch(path, Headers(), params);
  14602. }
  14603. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  14604. ContentProvider content_provider,
  14605. const std::string &content_type,
  14606. UploadProgress progress) {
  14607. return Patch(path, Headers(), content_length, std::move(content_provider),
  14608. content_type, progress);
  14609. }
  14610. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  14611. ContentProvider content_provider,
  14612. const std::string &content_type,
  14613. ContentReceiver content_receiver,
  14614. UploadProgress progress) {
  14615. return Patch(path, Headers(), content_length, std::move(content_provider),
  14616. content_type, std::move(content_receiver), progress);
  14617. }
  14618. inline Result ClientImpl::Patch(const std::string &path,
  14619. ContentProviderWithoutLength content_provider,
  14620. const std::string &content_type,
  14621. UploadProgress progress) {
  14622. return Patch(path, Headers(), std::move(content_provider), content_type,
  14623. progress);
  14624. }
  14625. inline Result ClientImpl::Patch(const std::string &path,
  14626. ContentProviderWithoutLength content_provider,
  14627. const std::string &content_type,
  14628. ContentReceiver content_receiver,
  14629. UploadProgress progress) {
  14630. return Patch(path, Headers(), std::move(content_provider), content_type,
  14631. std::move(content_receiver), progress);
  14632. }
  14633. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14634. const Params &params) {
  14635. auto query = detail::params_to_query_str(params);
  14636. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  14637. }
  14638. inline Result ClientImpl::Patch(const std::string &path,
  14639. const UploadFormDataItems &items,
  14640. UploadProgress progress) {
  14641. return Patch(path, Headers(), items, progress);
  14642. }
  14643. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14644. const UploadFormDataItems &items,
  14645. UploadProgress progress) {
  14646. const auto &boundary = detail::make_multipart_data_boundary();
  14647. const auto &content_type =
  14648. detail::serialize_multipart_formdata_get_content_type(boundary);
  14649. auto content_length = detail::get_multipart_content_length(items, boundary);
  14650. return Patch(path, headers, content_length,
  14651. detail::make_multipart_content_provider(items, boundary),
  14652. content_type, progress);
  14653. }
  14654. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14655. const UploadFormDataItems &items,
  14656. const std::string &boundary,
  14657. UploadProgress progress) {
  14658. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14659. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14660. }
  14661. const auto &content_type =
  14662. detail::serialize_multipart_formdata_get_content_type(boundary);
  14663. auto content_length = detail::get_multipart_content_length(items, boundary);
  14664. return Patch(path, headers, content_length,
  14665. detail::make_multipart_content_provider(items, boundary),
  14666. content_type, progress);
  14667. }
  14668. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14669. const char *body, size_t content_length,
  14670. const std::string &content_type,
  14671. UploadProgress progress) {
  14672. return send_with_content_provider_and_receiver(
  14673. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  14674. content_type, nullptr, progress);
  14675. }
  14676. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14677. const std::string &body,
  14678. const std::string &content_type,
  14679. UploadProgress progress) {
  14680. return send_with_content_provider_and_receiver(
  14681. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  14682. content_type, nullptr, progress);
  14683. }
  14684. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14685. size_t content_length,
  14686. ContentProvider content_provider,
  14687. const std::string &content_type,
  14688. UploadProgress progress) {
  14689. return send_with_content_provider_and_receiver(
  14690. "PATCH", path, headers, nullptr, content_length,
  14691. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14692. }
  14693. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14694. size_t content_length,
  14695. ContentProvider content_provider,
  14696. const std::string &content_type,
  14697. ContentReceiver content_receiver,
  14698. UploadProgress progress) {
  14699. return send_with_content_provider_and_receiver(
  14700. "PATCH", path, headers, nullptr, content_length,
  14701. std::move(content_provider), nullptr, content_type,
  14702. std::move(content_receiver), progress);
  14703. }
  14704. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14705. ContentProviderWithoutLength content_provider,
  14706. const std::string &content_type,
  14707. UploadProgress progress) {
  14708. return send_with_content_provider_and_receiver(
  14709. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14710. content_type, nullptr, progress);
  14711. }
  14712. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14713. ContentProviderWithoutLength content_provider,
  14714. const std::string &content_type,
  14715. ContentReceiver content_receiver,
  14716. UploadProgress progress) {
  14717. return send_with_content_provider_and_receiver(
  14718. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14719. content_type, std::move(content_receiver), progress);
  14720. }
  14721. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14722. const UploadFormDataItems &items,
  14723. const FormDataProviderItems &provider_items,
  14724. UploadProgress progress) {
  14725. const auto &boundary = detail::make_multipart_data_boundary();
  14726. const auto &content_type =
  14727. detail::serialize_multipart_formdata_get_content_type(boundary);
  14728. return send_with_content_provider_and_receiver(
  14729. "PATCH", path, headers, nullptr, 0, nullptr,
  14730. get_multipart_content_provider(boundary, items, provider_items),
  14731. content_type, nullptr, progress);
  14732. }
  14733. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14734. const std::string &body,
  14735. const std::string &content_type,
  14736. ContentReceiver content_receiver,
  14737. DownloadProgress progress) {
  14738. Request req;
  14739. req.method = "PATCH";
  14740. req.path = path;
  14741. req.headers = headers;
  14742. req.body = body;
  14743. req.content_receiver =
  14744. [content_receiver](const char *data, size_t data_length,
  14745. size_t /*offset*/, size_t /*total_length*/) {
  14746. return content_receiver(data, data_length);
  14747. };
  14748. req.download_progress = std::move(progress);
  14749. if (max_timeout_msec_ > 0) {
  14750. req.start_time_ = std::chrono::steady_clock::now();
  14751. }
  14752. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14753. return send_(std::move(req));
  14754. }
  14755. inline Result ClientImpl::Delete(const std::string &path,
  14756. DownloadProgress progress) {
  14757. return Delete(path, Headers(), std::string(), std::string(), progress);
  14758. }
  14759. inline Result ClientImpl::Delete(const std::string &path,
  14760. const Headers &headers,
  14761. DownloadProgress progress) {
  14762. return Delete(path, headers, std::string(), std::string(), progress);
  14763. }
  14764. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  14765. size_t content_length,
  14766. const std::string &content_type,
  14767. DownloadProgress progress) {
  14768. return Delete(path, Headers(), body, content_length, content_type, progress);
  14769. }
  14770. inline Result ClientImpl::Delete(const std::string &path,
  14771. const std::string &body,
  14772. const std::string &content_type,
  14773. DownloadProgress progress) {
  14774. return Delete(path, Headers(), body.data(), body.size(), content_type,
  14775. progress);
  14776. }
  14777. inline Result ClientImpl::Delete(const std::string &path,
  14778. const Headers &headers,
  14779. const std::string &body,
  14780. const std::string &content_type,
  14781. DownloadProgress progress) {
  14782. return Delete(path, headers, body.data(), body.size(), content_type,
  14783. progress);
  14784. }
  14785. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  14786. DownloadProgress progress) {
  14787. return Delete(path, Headers(), params, progress);
  14788. }
  14789. inline Result ClientImpl::Delete(const std::string &path,
  14790. const Headers &headers, const Params &params,
  14791. DownloadProgress progress) {
  14792. auto query = detail::params_to_query_str(params);
  14793. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  14794. progress);
  14795. }
  14796. inline Result ClientImpl::Delete(const std::string &path,
  14797. const Headers &headers, const char *body,
  14798. size_t content_length,
  14799. const std::string &content_type,
  14800. DownloadProgress progress) {
  14801. Request req;
  14802. req.method = "DELETE";
  14803. req.headers = headers;
  14804. req.path = path;
  14805. req.download_progress = std::move(progress);
  14806. if (max_timeout_msec_ > 0) {
  14807. req.start_time_ = std::chrono::steady_clock::now();
  14808. }
  14809. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14810. req.body.assign(body, content_length);
  14811. return send_(std::move(req));
  14812. }
  14813. inline Result ClientImpl::Options(const std::string &path) {
  14814. return Options(path, Headers());
  14815. }
  14816. inline Result ClientImpl::Options(const std::string &path,
  14817. const Headers &headers) {
  14818. Request req;
  14819. req.method = "OPTIONS";
  14820. req.headers = headers;
  14821. req.path = path;
  14822. if (max_timeout_msec_ > 0) {
  14823. req.start_time_ = std::chrono::steady_clock::now();
  14824. }
  14825. return send_(std::move(req));
  14826. }
  14827. inline void ClientImpl::stop() {
  14828. std::lock_guard<std::mutex> guard(socket_mutex_);
  14829. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  14830. // do is to shutdown_socket, so that threads using this socket suddenly
  14831. // discover they can't read/write any more and error out. Everything else
  14832. // (closing the socket, shutting ssl down) is unsafe because these actions
  14833. // are not thread-safe.
  14834. if (socket_requests_in_flight_ > 0) {
  14835. shutdown_socket(socket_);
  14836. // Aside from that, we set a flag for the socket to be closed when we're
  14837. // done.
  14838. socket_should_be_closed_when_request_is_done_ = true;
  14839. return;
  14840. }
  14841. disconnect(/*gracefully=*/true);
  14842. }
  14843. inline std::string ClientImpl::host() const { return host_; }
  14844. inline int ClientImpl::port() const { return port_; }
  14845. inline size_t ClientImpl::is_socket_open() const {
  14846. std::lock_guard<std::mutex> guard(socket_mutex_);
  14847. return socket_.is_open();
  14848. }
  14849. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  14850. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  14851. connection_timeout_sec_ = sec;
  14852. connection_timeout_usec_ = usec;
  14853. }
  14854. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  14855. read_timeout_sec_ = sec;
  14856. read_timeout_usec_ = usec;
  14857. }
  14858. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  14859. write_timeout_sec_ = sec;
  14860. write_timeout_usec_ = usec;
  14861. }
  14862. inline void ClientImpl::set_max_timeout(time_t msec) {
  14863. max_timeout_msec_ = msec;
  14864. }
  14865. inline void ClientImpl::set_basic_auth(const std::string &username,
  14866. const std::string &password) {
  14867. basic_auth_username_ = username;
  14868. basic_auth_password_ = password;
  14869. }
  14870. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  14871. bearer_token_auth_token_ = token;
  14872. }
  14873. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  14874. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  14875. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  14876. inline void
  14877. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14878. addr_map_ = std::move(addr_map);
  14879. }
  14880. inline void ClientImpl::set_default_headers(Headers headers) {
  14881. default_headers_ = std::move(headers);
  14882. }
  14883. inline void ClientImpl::set_header_writer(
  14884. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14885. header_writer_ = writer;
  14886. }
  14887. inline void ClientImpl::set_address_family(int family) {
  14888. address_family_ = family;
  14889. }
  14890. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  14891. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  14892. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  14893. socket_options_ = std::move(socket_options);
  14894. }
  14895. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  14896. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  14897. inline void ClientImpl::set_payload_max_length(size_t length) {
  14898. payload_max_length_ = length;
  14899. has_payload_max_length_ = true;
  14900. }
  14901. inline void ClientImpl::set_interface(const std::string &intf) {
  14902. interface_ = intf;
  14903. }
  14904. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  14905. proxy_host_ = host;
  14906. proxy_port_ = port;
  14907. std::lock_guard<std::mutex> guard(socket_mutex_);
  14908. disconnect(/*gracefully=*/true);
  14909. }
  14910. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  14911. const std::string &password) {
  14912. proxy_basic_auth_username_ = username;
  14913. proxy_basic_auth_password_ = password;
  14914. }
  14915. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  14916. proxy_bearer_token_auth_token_ = token;
  14917. }
  14918. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  14919. std::vector<detail::NoProxyEntry> parsed;
  14920. parsed.reserve(patterns.size());
  14921. for (const auto &p : patterns) {
  14922. auto trimmed = detail::trim_copy(p);
  14923. if (trimmed.empty()) { continue; }
  14924. detail::NoProxyEntry entry;
  14925. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  14926. parsed.push_back(std::move(entry));
  14927. }
  14928. }
  14929. no_proxy_entries_ = std::move(parsed);
  14930. std::lock_guard<std::mutex> guard(socket_mutex_);
  14931. disconnect(/*gracefully=*/true);
  14932. }
  14933. #ifdef CPPHTTPLIB_SSL_ENABLED
  14934. inline void ClientImpl::set_digest_auth(const std::string &username,
  14935. const std::string &password) {
  14936. digest_auth_username_ = username;
  14937. digest_auth_password_ = password;
  14938. }
  14939. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  14940. const std::string &ca_cert_dir_path) {
  14941. ca_cert_file_path_ = ca_cert_file_path;
  14942. ca_cert_dir_path_ = ca_cert_dir_path;
  14943. }
  14944. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  14945. const std::string &password) {
  14946. proxy_digest_auth_username_ = username;
  14947. proxy_digest_auth_password_ = password;
  14948. }
  14949. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  14950. server_certificate_verification_ = enabled;
  14951. }
  14952. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  14953. server_hostname_verification_ = enabled;
  14954. }
  14955. inline void ClientImpl::enable_system_ca(bool enabled) {
  14956. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  14957. }
  14958. #endif
  14959. inline void ClientImpl::set_logger(Logger logger) {
  14960. logger_ = std::move(logger);
  14961. }
  14962. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  14963. error_logger_ = std::move(error_logger);
  14964. }
  14965. /*
  14966. * SSL/TLS Common Implementation
  14967. */
  14968. inline ClientConnection::~ClientConnection() {
  14969. #ifdef CPPHTTPLIB_SSL_ENABLED
  14970. if (session) {
  14971. tls::shutdown(session, true);
  14972. tls::free_session(session);
  14973. session = nullptr;
  14974. }
  14975. #endif
  14976. if (sock != INVALID_SOCKET) {
  14977. detail::close_socket(sock);
  14978. sock = INVALID_SOCKET;
  14979. }
  14980. }
  14981. // Universal client implementation
  14982. inline Client::Client(const std::string &scheme_host_port)
  14983. : Client(scheme_host_port, std::string(), std::string()) {}
  14984. inline Client::Client(const std::string &scheme_host_port,
  14985. const std::string &client_cert_path,
  14986. const std::string &client_key_path) {
  14987. detail::UrlComponents uc;
  14988. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  14989. auto &scheme = uc.scheme;
  14990. #ifdef CPPHTTPLIB_SSL_ENABLED
  14991. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  14992. #else
  14993. if (!scheme.empty() && scheme != "http") {
  14994. #endif
  14995. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14996. std::string msg = "'" + scheme + "' scheme is not supported.";
  14997. throw std::invalid_argument(msg);
  14998. #endif
  14999. return;
  15000. }
  15001. auto is_ssl = scheme == "https";
  15002. auto host = std::move(uc.host);
  15003. auto port = is_ssl ? 443 : 80;
  15004. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  15005. if (is_ssl) {
  15006. #ifdef CPPHTTPLIB_SSL_ENABLED
  15007. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  15008. client_key_path);
  15009. is_ssl_ = is_ssl;
  15010. #endif
  15011. } else {
  15012. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  15013. client_key_path);
  15014. }
  15015. } else {
  15016. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  15017. // if port param below changes.
  15018. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  15019. client_cert_path, client_key_path);
  15020. }
  15021. }
  15022. inline Client::Client(const std::string &host, int port)
  15023. : Client(host, port, std::string(), std::string()) {}
  15024. inline Client::Client(const std::string &host, int port,
  15025. const std::string &client_cert_path,
  15026. const std::string &client_key_path)
  15027. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  15028. client_key_path)) {}
  15029. inline Client::~Client() = default;
  15030. inline bool Client::is_valid() const {
  15031. return cli_ != nullptr && cli_->is_valid();
  15032. }
  15033. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  15034. return cli_->Get(path, std::move(progress));
  15035. }
  15036. inline Result Client::Get(const std::string &path, const Headers &headers,
  15037. DownloadProgress progress) {
  15038. return cli_->Get(path, headers, std::move(progress));
  15039. }
  15040. inline Result Client::Get(const std::string &path,
  15041. ContentReceiver content_receiver,
  15042. DownloadProgress progress) {
  15043. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  15044. }
  15045. inline Result Client::Get(const std::string &path, const Headers &headers,
  15046. ContentReceiver content_receiver,
  15047. DownloadProgress progress) {
  15048. return cli_->Get(path, headers, std::move(content_receiver),
  15049. std::move(progress));
  15050. }
  15051. inline Result Client::Get(const std::string &path,
  15052. ResponseHandler response_handler,
  15053. ContentReceiver content_receiver,
  15054. DownloadProgress progress) {
  15055. return cli_->Get(path, std::move(response_handler),
  15056. std::move(content_receiver), std::move(progress));
  15057. }
  15058. inline Result Client::Get(const std::string &path, const Headers &headers,
  15059. ResponseHandler response_handler,
  15060. ContentReceiver content_receiver,
  15061. DownloadProgress progress) {
  15062. return cli_->Get(path, headers, std::move(response_handler),
  15063. std::move(content_receiver), std::move(progress));
  15064. }
  15065. inline Result Client::Get(const std::string &path, const Params &params,
  15066. DownloadProgress progress) {
  15067. return cli_->Get(path, params, std::move(progress));
  15068. }
  15069. inline Result Client::Get(const std::string &path, const Params &params,
  15070. const Headers &headers, DownloadProgress progress) {
  15071. return cli_->Get(path, params, headers, std::move(progress));
  15072. }
  15073. inline Result Client::Get(const std::string &path, const Params &params,
  15074. const Headers &headers,
  15075. ContentReceiver content_receiver,
  15076. DownloadProgress progress) {
  15077. return cli_->Get(path, params, headers, std::move(content_receiver),
  15078. std::move(progress));
  15079. }
  15080. inline Result Client::Get(const std::string &path, const Params &params,
  15081. const Headers &headers,
  15082. ResponseHandler response_handler,
  15083. ContentReceiver content_receiver,
  15084. DownloadProgress progress) {
  15085. return cli_->Get(path, params, headers, std::move(response_handler),
  15086. std::move(content_receiver), std::move(progress));
  15087. }
  15088. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  15089. inline Result Client::Head(const std::string &path, const Headers &headers) {
  15090. return cli_->Head(path, headers);
  15091. }
  15092. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  15093. inline Result Client::Post(const std::string &path, const Headers &headers) {
  15094. return cli_->Post(path, headers);
  15095. }
  15096. inline Result Client::Post(const std::string &path, const char *body,
  15097. size_t content_length,
  15098. const std::string &content_type,
  15099. UploadProgress progress) {
  15100. return cli_->Post(path, body, content_length, content_type, progress);
  15101. }
  15102. inline Result Client::Post(const std::string &path, const Headers &headers,
  15103. const char *body, size_t content_length,
  15104. const std::string &content_type,
  15105. UploadProgress progress) {
  15106. return cli_->Post(path, headers, body, content_length, content_type,
  15107. progress);
  15108. }
  15109. inline Result Client::Post(const std::string &path, const std::string &body,
  15110. const std::string &content_type,
  15111. UploadProgress progress) {
  15112. return cli_->Post(path, body, content_type, progress);
  15113. }
  15114. inline Result Client::Post(const std::string &path, const Headers &headers,
  15115. const std::string &body,
  15116. const std::string &content_type,
  15117. UploadProgress progress) {
  15118. return cli_->Post(path, headers, body, content_type, progress);
  15119. }
  15120. inline Result Client::Post(const std::string &path, size_t content_length,
  15121. ContentProvider content_provider,
  15122. const std::string &content_type,
  15123. UploadProgress progress) {
  15124. return cli_->Post(path, content_length, std::move(content_provider),
  15125. content_type, progress);
  15126. }
  15127. inline Result Client::Post(const std::string &path, size_t content_length,
  15128. ContentProvider content_provider,
  15129. const std::string &content_type,
  15130. ContentReceiver content_receiver,
  15131. UploadProgress progress) {
  15132. return cli_->Post(path, content_length, std::move(content_provider),
  15133. content_type, std::move(content_receiver), progress);
  15134. }
  15135. inline Result Client::Post(const std::string &path,
  15136. ContentProviderWithoutLength content_provider,
  15137. const std::string &content_type,
  15138. UploadProgress progress) {
  15139. return cli_->Post(path, std::move(content_provider), content_type, progress);
  15140. }
  15141. inline Result Client::Post(const std::string &path,
  15142. ContentProviderWithoutLength content_provider,
  15143. const std::string &content_type,
  15144. ContentReceiver content_receiver,
  15145. UploadProgress progress) {
  15146. return cli_->Post(path, std::move(content_provider), content_type,
  15147. std::move(content_receiver), progress);
  15148. }
  15149. inline Result Client::Post(const std::string &path, const Headers &headers,
  15150. size_t content_length,
  15151. ContentProvider content_provider,
  15152. const std::string &content_type,
  15153. UploadProgress progress) {
  15154. return cli_->Post(path, headers, content_length, std::move(content_provider),
  15155. content_type, progress);
  15156. }
  15157. inline Result Client::Post(const std::string &path, const Headers &headers,
  15158. size_t content_length,
  15159. ContentProvider content_provider,
  15160. const std::string &content_type,
  15161. ContentReceiver content_receiver,
  15162. DownloadProgress progress) {
  15163. return cli_->Post(path, headers, content_length, std::move(content_provider),
  15164. content_type, std::move(content_receiver), progress);
  15165. }
  15166. inline Result Client::Post(const std::string &path, const Headers &headers,
  15167. ContentProviderWithoutLength content_provider,
  15168. const std::string &content_type,
  15169. UploadProgress progress) {
  15170. return cli_->Post(path, headers, std::move(content_provider), content_type,
  15171. progress);
  15172. }
  15173. inline Result Client::Post(const std::string &path, const Headers &headers,
  15174. ContentProviderWithoutLength content_provider,
  15175. const std::string &content_type,
  15176. ContentReceiver content_receiver,
  15177. DownloadProgress progress) {
  15178. return cli_->Post(path, headers, std::move(content_provider), content_type,
  15179. std::move(content_receiver), progress);
  15180. }
  15181. inline Result Client::Post(const std::string &path, const Params &params) {
  15182. return cli_->Post(path, params);
  15183. }
  15184. inline Result Client::Post(const std::string &path, const Headers &headers,
  15185. const Params &params) {
  15186. return cli_->Post(path, headers, params);
  15187. }
  15188. inline Result Client::Post(const std::string &path,
  15189. const UploadFormDataItems &items,
  15190. UploadProgress progress) {
  15191. return cli_->Post(path, items, progress);
  15192. }
  15193. inline Result Client::Post(const std::string &path, const Headers &headers,
  15194. const UploadFormDataItems &items,
  15195. UploadProgress progress) {
  15196. return cli_->Post(path, headers, items, progress);
  15197. }
  15198. inline Result Client::Post(const std::string &path, const Headers &headers,
  15199. const UploadFormDataItems &items,
  15200. const std::string &boundary,
  15201. UploadProgress progress) {
  15202. return cli_->Post(path, headers, items, boundary, progress);
  15203. }
  15204. inline Result Client::Post(const std::string &path, const Headers &headers,
  15205. const UploadFormDataItems &items,
  15206. const FormDataProviderItems &provider_items,
  15207. UploadProgress progress) {
  15208. return cli_->Post(path, headers, items, provider_items, progress);
  15209. }
  15210. inline Result Client::Post(const std::string &path, const Headers &headers,
  15211. const std::string &body,
  15212. const std::string &content_type,
  15213. ContentReceiver content_receiver,
  15214. DownloadProgress progress) {
  15215. return cli_->Post(path, headers, body, content_type,
  15216. std::move(content_receiver), progress);
  15217. }
  15218. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  15219. inline Result Client::Put(const std::string &path, const Headers &headers) {
  15220. return cli_->Put(path, headers);
  15221. }
  15222. inline Result Client::Put(const std::string &path, const char *body,
  15223. size_t content_length,
  15224. const std::string &content_type,
  15225. UploadProgress progress) {
  15226. return cli_->Put(path, body, content_length, content_type, progress);
  15227. }
  15228. inline Result Client::Put(const std::string &path, const Headers &headers,
  15229. const char *body, size_t content_length,
  15230. const std::string &content_type,
  15231. UploadProgress progress) {
  15232. return cli_->Put(path, headers, body, content_length, content_type, progress);
  15233. }
  15234. inline Result Client::Put(const std::string &path, const std::string &body,
  15235. const std::string &content_type,
  15236. UploadProgress progress) {
  15237. return cli_->Put(path, body, content_type, progress);
  15238. }
  15239. inline Result Client::Put(const std::string &path, const Headers &headers,
  15240. const std::string &body,
  15241. const std::string &content_type,
  15242. UploadProgress progress) {
  15243. return cli_->Put(path, headers, body, content_type, progress);
  15244. }
  15245. inline Result Client::Put(const std::string &path, size_t content_length,
  15246. ContentProvider content_provider,
  15247. const std::string &content_type,
  15248. UploadProgress progress) {
  15249. return cli_->Put(path, content_length, std::move(content_provider),
  15250. content_type, progress);
  15251. }
  15252. inline Result Client::Put(const std::string &path, size_t content_length,
  15253. ContentProvider content_provider,
  15254. const std::string &content_type,
  15255. ContentReceiver content_receiver,
  15256. UploadProgress progress) {
  15257. return cli_->Put(path, content_length, std::move(content_provider),
  15258. content_type, std::move(content_receiver), progress);
  15259. }
  15260. inline Result Client::Put(const std::string &path,
  15261. ContentProviderWithoutLength content_provider,
  15262. const std::string &content_type,
  15263. UploadProgress progress) {
  15264. return cli_->Put(path, std::move(content_provider), content_type, progress);
  15265. }
  15266. inline Result Client::Put(const std::string &path,
  15267. ContentProviderWithoutLength content_provider,
  15268. const std::string &content_type,
  15269. ContentReceiver content_receiver,
  15270. UploadProgress progress) {
  15271. return cli_->Put(path, std::move(content_provider), content_type,
  15272. std::move(content_receiver), progress);
  15273. }
  15274. inline Result Client::Put(const std::string &path, const Headers &headers,
  15275. size_t content_length,
  15276. ContentProvider content_provider,
  15277. const std::string &content_type,
  15278. UploadProgress progress) {
  15279. return cli_->Put(path, headers, content_length, std::move(content_provider),
  15280. content_type, progress);
  15281. }
  15282. inline Result Client::Put(const std::string &path, const Headers &headers,
  15283. size_t content_length,
  15284. ContentProvider content_provider,
  15285. const std::string &content_type,
  15286. ContentReceiver content_receiver,
  15287. UploadProgress progress) {
  15288. return cli_->Put(path, headers, content_length, std::move(content_provider),
  15289. content_type, std::move(content_receiver), progress);
  15290. }
  15291. inline Result Client::Put(const std::string &path, const Headers &headers,
  15292. ContentProviderWithoutLength content_provider,
  15293. const std::string &content_type,
  15294. UploadProgress progress) {
  15295. return cli_->Put(path, headers, std::move(content_provider), content_type,
  15296. progress);
  15297. }
  15298. inline Result Client::Put(const std::string &path, const Headers &headers,
  15299. ContentProviderWithoutLength content_provider,
  15300. const std::string &content_type,
  15301. ContentReceiver content_receiver,
  15302. UploadProgress progress) {
  15303. return cli_->Put(path, headers, std::move(content_provider), content_type,
  15304. std::move(content_receiver), progress);
  15305. }
  15306. inline Result Client::Put(const std::string &path, const Params &params) {
  15307. return cli_->Put(path, params);
  15308. }
  15309. inline Result Client::Put(const std::string &path, const Headers &headers,
  15310. const Params &params) {
  15311. return cli_->Put(path, headers, params);
  15312. }
  15313. inline Result Client::Put(const std::string &path,
  15314. const UploadFormDataItems &items,
  15315. UploadProgress progress) {
  15316. return cli_->Put(path, items, progress);
  15317. }
  15318. inline Result Client::Put(const std::string &path, const Headers &headers,
  15319. const UploadFormDataItems &items,
  15320. UploadProgress progress) {
  15321. return cli_->Put(path, headers, items, progress);
  15322. }
  15323. inline Result Client::Put(const std::string &path, const Headers &headers,
  15324. const UploadFormDataItems &items,
  15325. const std::string &boundary,
  15326. UploadProgress progress) {
  15327. return cli_->Put(path, headers, items, boundary, progress);
  15328. }
  15329. inline Result Client::Put(const std::string &path, const Headers &headers,
  15330. const UploadFormDataItems &items,
  15331. const FormDataProviderItems &provider_items,
  15332. UploadProgress progress) {
  15333. return cli_->Put(path, headers, items, provider_items, progress);
  15334. }
  15335. inline Result Client::Put(const std::string &path, const Headers &headers,
  15336. const std::string &body,
  15337. const std::string &content_type,
  15338. ContentReceiver content_receiver,
  15339. DownloadProgress progress) {
  15340. return cli_->Put(path, headers, body, content_type, content_receiver,
  15341. progress);
  15342. }
  15343. inline Result Client::Patch(const std::string &path) {
  15344. return cli_->Patch(path);
  15345. }
  15346. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  15347. return cli_->Patch(path, headers);
  15348. }
  15349. inline Result Client::Patch(const std::string &path, const char *body,
  15350. size_t content_length,
  15351. const std::string &content_type,
  15352. UploadProgress progress) {
  15353. return cli_->Patch(path, body, content_length, content_type, progress);
  15354. }
  15355. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15356. const char *body, size_t content_length,
  15357. const std::string &content_type,
  15358. UploadProgress progress) {
  15359. return cli_->Patch(path, headers, body, content_length, content_type,
  15360. progress);
  15361. }
  15362. inline Result Client::Patch(const std::string &path, const std::string &body,
  15363. const std::string &content_type,
  15364. UploadProgress progress) {
  15365. return cli_->Patch(path, body, content_type, progress);
  15366. }
  15367. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15368. const std::string &body,
  15369. const std::string &content_type,
  15370. UploadProgress progress) {
  15371. return cli_->Patch(path, headers, body, content_type, progress);
  15372. }
  15373. inline Result Client::Patch(const std::string &path, size_t content_length,
  15374. ContentProvider content_provider,
  15375. const std::string &content_type,
  15376. UploadProgress progress) {
  15377. return cli_->Patch(path, content_length, std::move(content_provider),
  15378. content_type, progress);
  15379. }
  15380. inline Result Client::Patch(const std::string &path, size_t content_length,
  15381. ContentProvider content_provider,
  15382. const std::string &content_type,
  15383. ContentReceiver content_receiver,
  15384. UploadProgress progress) {
  15385. return cli_->Patch(path, content_length, std::move(content_provider),
  15386. content_type, std::move(content_receiver), progress);
  15387. }
  15388. inline Result Client::Patch(const std::string &path,
  15389. ContentProviderWithoutLength content_provider,
  15390. const std::string &content_type,
  15391. UploadProgress progress) {
  15392. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  15393. }
  15394. inline Result Client::Patch(const std::string &path,
  15395. ContentProviderWithoutLength content_provider,
  15396. const std::string &content_type,
  15397. ContentReceiver content_receiver,
  15398. UploadProgress progress) {
  15399. return cli_->Patch(path, std::move(content_provider), content_type,
  15400. std::move(content_receiver), progress);
  15401. }
  15402. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15403. size_t content_length,
  15404. ContentProvider content_provider,
  15405. const std::string &content_type,
  15406. UploadProgress progress) {
  15407. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  15408. content_type, progress);
  15409. }
  15410. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15411. size_t content_length,
  15412. ContentProvider content_provider,
  15413. const std::string &content_type,
  15414. ContentReceiver content_receiver,
  15415. UploadProgress progress) {
  15416. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  15417. content_type, std::move(content_receiver), progress);
  15418. }
  15419. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15420. ContentProviderWithoutLength content_provider,
  15421. const std::string &content_type,
  15422. UploadProgress progress) {
  15423. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  15424. progress);
  15425. }
  15426. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15427. ContentProviderWithoutLength content_provider,
  15428. const std::string &content_type,
  15429. ContentReceiver content_receiver,
  15430. UploadProgress progress) {
  15431. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  15432. std::move(content_receiver), progress);
  15433. }
  15434. inline Result Client::Patch(const std::string &path, const Params &params) {
  15435. return cli_->Patch(path, params);
  15436. }
  15437. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15438. const Params &params) {
  15439. return cli_->Patch(path, headers, params);
  15440. }
  15441. inline Result Client::Patch(const std::string &path,
  15442. const UploadFormDataItems &items,
  15443. UploadProgress progress) {
  15444. return cli_->Patch(path, items, progress);
  15445. }
  15446. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15447. const UploadFormDataItems &items,
  15448. UploadProgress progress) {
  15449. return cli_->Patch(path, headers, items, progress);
  15450. }
  15451. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15452. const UploadFormDataItems &items,
  15453. const std::string &boundary,
  15454. UploadProgress progress) {
  15455. return cli_->Patch(path, headers, items, boundary, progress);
  15456. }
  15457. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15458. const UploadFormDataItems &items,
  15459. const FormDataProviderItems &provider_items,
  15460. UploadProgress progress) {
  15461. return cli_->Patch(path, headers, items, provider_items, progress);
  15462. }
  15463. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15464. const std::string &body,
  15465. const std::string &content_type,
  15466. ContentReceiver content_receiver,
  15467. DownloadProgress progress) {
  15468. return cli_->Patch(path, headers, body, content_type, content_receiver,
  15469. progress);
  15470. }
  15471. inline Result Client::Delete(const std::string &path,
  15472. DownloadProgress progress) {
  15473. return cli_->Delete(path, progress);
  15474. }
  15475. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15476. DownloadProgress progress) {
  15477. return cli_->Delete(path, headers, progress);
  15478. }
  15479. inline Result Client::Delete(const std::string &path, const char *body,
  15480. size_t content_length,
  15481. const std::string &content_type,
  15482. DownloadProgress progress) {
  15483. return cli_->Delete(path, body, content_length, content_type, progress);
  15484. }
  15485. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15486. const char *body, size_t content_length,
  15487. const std::string &content_type,
  15488. DownloadProgress progress) {
  15489. return cli_->Delete(path, headers, body, content_length, content_type,
  15490. progress);
  15491. }
  15492. inline Result Client::Delete(const std::string &path, const std::string &body,
  15493. const std::string &content_type,
  15494. DownloadProgress progress) {
  15495. return cli_->Delete(path, body, content_type, progress);
  15496. }
  15497. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15498. const std::string &body,
  15499. const std::string &content_type,
  15500. DownloadProgress progress) {
  15501. return cli_->Delete(path, headers, body, content_type, progress);
  15502. }
  15503. inline Result Client::Delete(const std::string &path, const Params &params,
  15504. DownloadProgress progress) {
  15505. return cli_->Delete(path, params, progress);
  15506. }
  15507. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15508. const Params &params, DownloadProgress progress) {
  15509. return cli_->Delete(path, headers, params, progress);
  15510. }
  15511. inline Result Client::Options(const std::string &path) {
  15512. return cli_->Options(path);
  15513. }
  15514. inline Result Client::Options(const std::string &path, const Headers &headers) {
  15515. return cli_->Options(path, headers);
  15516. }
  15517. inline ClientImpl::StreamHandle
  15518. Client::open_stream(const std::string &method, const std::string &path,
  15519. const Params &params, const Headers &headers,
  15520. const std::string &body, const std::string &content_type) {
  15521. return cli_->open_stream(method, path, params, headers, body, content_type);
  15522. }
  15523. inline bool Client::send(Request &req, Response &res, Error &error) {
  15524. return cli_->send(req, res, error);
  15525. }
  15526. inline Result Client::send(const Request &req) { return cli_->send(req); }
  15527. inline void Client::stop() { cli_->stop(); }
  15528. inline std::string Client::host() const { return cli_->host(); }
  15529. inline int Client::port() const { return cli_->port(); }
  15530. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  15531. inline socket_t Client::socket() const { return cli_->socket(); }
  15532. inline void
  15533. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  15534. cli_->set_hostname_addr_map(std::move(addr_map));
  15535. }
  15536. inline void Client::set_default_headers(Headers headers) {
  15537. cli_->set_default_headers(std::move(headers));
  15538. }
  15539. inline void Client::set_header_writer(
  15540. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  15541. cli_->set_header_writer(writer);
  15542. }
  15543. inline void Client::set_address_family(int family) {
  15544. cli_->set_address_family(family);
  15545. }
  15546. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  15547. inline void Client::set_socket_options(SocketOptions socket_options) {
  15548. cli_->set_socket_options(std::move(socket_options));
  15549. }
  15550. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  15551. cli_->set_connection_timeout(sec, usec);
  15552. }
  15553. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  15554. cli_->set_read_timeout(sec, usec);
  15555. }
  15556. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  15557. cli_->set_write_timeout(sec, usec);
  15558. }
  15559. inline void Client::set_basic_auth(const std::string &username,
  15560. const std::string &password) {
  15561. cli_->set_basic_auth(username, password);
  15562. }
  15563. inline void Client::set_bearer_token_auth(const std::string &token) {
  15564. cli_->set_bearer_token_auth(token);
  15565. }
  15566. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  15567. inline void Client::set_follow_location(bool on) {
  15568. cli_->set_follow_location(on);
  15569. }
  15570. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  15571. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  15572. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  15573. inline void Client::set_payload_max_length(size_t length) {
  15574. cli_->set_payload_max_length(length);
  15575. }
  15576. inline void Client::set_interface(const std::string &intf) {
  15577. cli_->set_interface(intf);
  15578. }
  15579. inline void Client::set_proxy(const std::string &host, int port) {
  15580. cli_->set_proxy(host, port);
  15581. }
  15582. inline void Client::set_proxy_basic_auth(const std::string &username,
  15583. const std::string &password) {
  15584. cli_->set_proxy_basic_auth(username, password);
  15585. }
  15586. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  15587. cli_->set_proxy_bearer_token_auth(token);
  15588. }
  15589. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  15590. cli_->set_no_proxy(patterns);
  15591. }
  15592. inline void Client::set_logger(Logger logger) {
  15593. cli_->set_logger(std::move(logger));
  15594. }
  15595. inline void Client::set_error_logger(ErrorLogger error_logger) {
  15596. cli_->set_error_logger(std::move(error_logger));
  15597. }
  15598. /*
  15599. * Group 6: SSL Server and Client implementation
  15600. */
  15601. #ifdef CPPHTTPLIB_SSL_ENABLED
  15602. // SSL HTTP server implementation
  15603. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  15604. const char *client_ca_cert_file_path,
  15605. const char *client_ca_cert_dir_path,
  15606. const char *private_key_password) {
  15607. using namespace tls;
  15608. ctx_ = create_server_context();
  15609. if (!ctx_) { return; }
  15610. // Load server certificate and private key
  15611. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  15612. private_key_password)) {
  15613. last_ssl_error_ = static_cast<int>(get_error());
  15614. free_context(ctx_);
  15615. ctx_ = nullptr;
  15616. return;
  15617. }
  15618. // Load client CA certificates for client authentication
  15619. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  15620. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  15621. client_ca_cert_dir_path)) {
  15622. last_ssl_error_ = static_cast<int>(get_error());
  15623. free_context(ctx_);
  15624. ctx_ = nullptr;
  15625. return;
  15626. }
  15627. // Enable client certificate verification
  15628. set_verify_client(ctx_, true);
  15629. }
  15630. }
  15631. inline SSLServer::SSLServer(const PemMemory &pem) {
  15632. using namespace tls;
  15633. ctx_ = create_server_context();
  15634. if (ctx_) {
  15635. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  15636. pem.private_key_password)) {
  15637. last_ssl_error_ = static_cast<int>(get_error());
  15638. free_context(ctx_);
  15639. ctx_ = nullptr;
  15640. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  15641. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  15642. last_ssl_error_ = static_cast<int>(get_error());
  15643. free_context(ctx_);
  15644. ctx_ = nullptr;
  15645. } else {
  15646. set_verify_client(ctx_, true);
  15647. }
  15648. }
  15649. }
  15650. }
  15651. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  15652. using namespace tls;
  15653. ctx_ = create_server_context();
  15654. if (ctx_) {
  15655. if (!setup_callback(ctx_)) {
  15656. free_context(ctx_);
  15657. ctx_ = nullptr;
  15658. }
  15659. }
  15660. }
  15661. inline SSLServer::~SSLServer() {
  15662. if (ctx_) { tls::free_context(ctx_); }
  15663. }
  15664. inline bool SSLServer::is_valid() const {
  15665. return ctx_ != nullptr && Server::is_valid();
  15666. }
  15667. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  15668. using namespace tls;
  15669. // Create TLS session with mutex protection
  15670. session_t session = nullptr;
  15671. {
  15672. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15673. session = create_session(static_cast<ctx_t>(ctx_), sock);
  15674. }
  15675. if (!session) {
  15676. last_ssl_error_ = static_cast<int>(get_error());
  15677. detail::shutdown_socket(sock);
  15678. detail::close_socket(sock);
  15679. return false;
  15680. }
  15681. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  15682. bool handshake_done = false;
  15683. bool ret = false;
  15684. bool websocket_upgraded = false;
  15685. auto cleanup = detail::scope_exit([&] {
  15686. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  15687. free_session(session);
  15688. detail::shutdown_socket(sock);
  15689. detail::close_socket(sock);
  15690. });
  15691. // Perform TLS accept handshake with timeout
  15692. TlsError tls_err;
  15693. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  15694. &tls_err)) {
  15695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15696. // Map TlsError to legacy ssl_error for backward compatibility
  15697. if (tls_err.code == ErrorCode::WantRead) {
  15698. last_ssl_error_ = SSL_ERROR_WANT_READ;
  15699. } else if (tls_err.code == ErrorCode::WantWrite) {
  15700. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  15701. } else {
  15702. last_ssl_error_ = SSL_ERROR_SSL;
  15703. }
  15704. #else
  15705. last_ssl_error_ = static_cast<int>(get_error());
  15706. #endif
  15707. return false;
  15708. }
  15709. handshake_done = true;
  15710. std::string remote_addr;
  15711. int remote_port = 0;
  15712. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  15713. std::string local_addr;
  15714. int local_port = 0;
  15715. detail::get_local_ip_and_port(sock, local_addr, local_port);
  15716. ret = serve_guarded([&]() {
  15717. return detail::process_server_socket_ssl(
  15718. svr_sock_, session, sock, keep_alive_max_count_,
  15719. keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
  15720. write_timeout_sec_, write_timeout_usec_,
  15721. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  15722. return process_request(
  15723. strm, remote_addr, remote_port, local_addr, local_port,
  15724. close_connection, connection_closed,
  15725. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  15726. });
  15727. });
  15728. return ret;
  15729. }
  15730. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  15731. const char *key_pem,
  15732. const char *client_ca_pem,
  15733. const char *password) {
  15734. if (!ctx_) { return false; }
  15735. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15736. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  15737. return false;
  15738. }
  15739. if (client_ca_pem) {
  15740. return tls::update_server_client_ca(ctx_, client_ca_pem);
  15741. }
  15742. return true;
  15743. }
  15744. // SSL HTTP client implementation
  15745. inline SSLClient::~SSLClient() {
  15746. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  15747. // base function rather than the derived function once we get to the
  15748. // base class destructor, and won't free the SSL (causing a leak).
  15749. // This must happen before the context is freed below: some backends
  15750. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  15751. // context, so freeing the context first leaves close_notify reading
  15752. // freed memory.
  15753. shutdown_ssl_impl(socket_, true);
  15754. if (ctx_) {
  15755. tls::free_context(ctx_);
  15756. ctx_ = nullptr;
  15757. }
  15758. }
  15759. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  15760. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  15761. shutdown_ssl_impl(socket, shutdown_gracefully);
  15762. }
  15763. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  15764. bool shutdown_gracefully) {
  15765. if (socket.sock == INVALID_SOCKET) {
  15766. assert(socket.ssl == nullptr);
  15767. return;
  15768. }
  15769. if (socket.ssl) {
  15770. tls::shutdown(socket.ssl, shutdown_gracefully);
  15771. {
  15772. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15773. tls::free_session(socket.ssl);
  15774. }
  15775. socket.ssl = nullptr;
  15776. }
  15777. assert(socket.ssl == nullptr);
  15778. }
  15779. inline bool SSLClient::process_socket(
  15780. const Socket &socket,
  15781. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15782. std::function<bool(Stream &strm)> callback) {
  15783. assert(socket.ssl);
  15784. return detail::process_client_socket_ssl(
  15785. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  15786. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  15787. std::move(callback));
  15788. }
  15789. inline bool SSLClient::is_ssl() const { return true; }
  15790. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  15791. if (!is_valid()) {
  15792. error = Error::SSLConnection;
  15793. return false;
  15794. }
  15795. return ClientImpl::create_and_connect_socket(socket, error);
  15796. }
  15797. inline bool SSLClient::setup_proxy_connection(
  15798. Socket &socket,
  15799. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15800. Response &res, bool &success, Error &error) {
  15801. if (!is_proxy_enabled_for_host(host_)) { return true; }
  15802. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  15803. return false;
  15804. }
  15805. if (!initialize_ssl(socket, error)) {
  15806. success = false;
  15807. return false;
  15808. }
  15809. return true;
  15810. }
  15811. // Assumes that socket_mutex_ is locked and that there are no requests in
  15812. // flight
  15813. inline bool SSLClient::connect_with_proxy(
  15814. Socket &socket,
  15815. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15816. Response &res, bool &success, Error &error) {
  15817. success = true;
  15818. Response proxy_res;
  15819. if (!detail::process_client_socket(
  15820. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15821. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15822. start_time, [&](Stream &strm) {
  15823. Request req2;
  15824. req2.method = "CONNECT";
  15825. req2.path =
  15826. detail::make_host_and_port_string_always_port(host_, port_);
  15827. if (max_timeout_msec_ > 0) {
  15828. req2.start_time_ = std::chrono::steady_clock::now();
  15829. }
  15830. return process_request(strm, req2, proxy_res, false, error);
  15831. })) {
  15832. // Thread-safe to close everything because we are assuming there are no
  15833. // requests in flight
  15834. shutdown_ssl(socket, true);
  15835. shutdown_socket(socket);
  15836. close_socket(socket);
  15837. success = false;
  15838. return false;
  15839. }
  15840. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  15841. if (!proxy_digest_auth_username_.empty() &&
  15842. !proxy_digest_auth_password_.empty()) {
  15843. std::map<std::string, std::string> auth;
  15844. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  15845. // Close the current socket and create a new one for the authenticated
  15846. // request
  15847. shutdown_ssl(socket, true);
  15848. shutdown_socket(socket);
  15849. close_socket(socket);
  15850. // Create a new socket for the authenticated CONNECT request
  15851. if (!ensure_socket_connection(socket, error)) {
  15852. success = false;
  15853. output_error_log(error, nullptr);
  15854. return false;
  15855. }
  15856. proxy_res = Response();
  15857. if (!detail::process_client_socket(
  15858. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15859. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15860. start_time, [&](Stream &strm) {
  15861. Request req3;
  15862. req3.method = "CONNECT";
  15863. req3.path = detail::make_host_and_port_string_always_port(
  15864. host_, port_);
  15865. req3.headers.insert(detail::make_digest_authentication_header(
  15866. req3, auth, 1, detail::random_string(10),
  15867. proxy_digest_auth_username_, proxy_digest_auth_password_,
  15868. true));
  15869. if (max_timeout_msec_ > 0) {
  15870. req3.start_time_ = std::chrono::steady_clock::now();
  15871. }
  15872. return process_request(strm, req3, proxy_res, false, error);
  15873. })) {
  15874. // Thread-safe to close everything because we are assuming there are
  15875. // no requests in flight
  15876. shutdown_ssl(socket, true);
  15877. shutdown_socket(socket);
  15878. close_socket(socket);
  15879. success = false;
  15880. return false;
  15881. }
  15882. }
  15883. }
  15884. }
  15885. // If status code is not 200, proxy request is failed.
  15886. // Set error to ProxyConnection and return proxy response
  15887. // as the response of the request
  15888. if (proxy_res.status != StatusCode::OK_200) {
  15889. error = Error::ProxyConnection;
  15890. output_error_log(error, nullptr);
  15891. res = std::move(proxy_res);
  15892. // Thread-safe to close everything because we are assuming there are
  15893. // no requests in flight
  15894. shutdown_ssl(socket, true);
  15895. shutdown_socket(socket);
  15896. close_socket(socket);
  15897. return false;
  15898. }
  15899. return true;
  15900. }
  15901. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  15902. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  15903. if (is_proxy_enabled_for_host(host_)) { return true; }
  15904. if (!initialize_ssl(socket, error)) {
  15905. shutdown_socket(socket);
  15906. close_socket(socket);
  15907. return false;
  15908. }
  15909. return true;
  15910. }
  15911. // SSL HTTP client implementation
  15912. inline SSLClient::SSLClient(const std::string &host)
  15913. : SSLClient(host, 443, std::string(), std::string()) {}
  15914. inline SSLClient::SSLClient(const std::string &host, int port)
  15915. : SSLClient(host, port, std::string(), std::string()) {}
  15916. inline void SSLClient::init_ctx() {
  15917. ctx_ = tls::create_client_context();
  15918. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  15919. }
  15920. inline void SSLClient::reset_ctx_on_error() {
  15921. last_backend_error_ = tls::get_error();
  15922. tls::free_context(ctx_);
  15923. ctx_ = nullptr;
  15924. }
  15925. inline SSLClient::SSLClient(const std::string &host, int port,
  15926. const std::string &client_cert_path,
  15927. const std::string &client_key_path,
  15928. const std::string &private_key_password)
  15929. : ClientImpl(host, port, client_cert_path, client_key_path) {
  15930. init_ctx();
  15931. if (!ctx_) { return; }
  15932. if (!client_cert_path.empty() && !client_key_path.empty()) {
  15933. const char *password =
  15934. private_key_password.empty() ? nullptr : private_key_password.c_str();
  15935. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  15936. client_key_path.c_str(), password)) {
  15937. reset_ctx_on_error();
  15938. }
  15939. }
  15940. }
  15941. inline SSLClient::SSLClient(const std::string &host, int port,
  15942. const PemMemory &pem)
  15943. : ClientImpl(host, port) {
  15944. init_ctx();
  15945. if (!ctx_) { return; }
  15946. if (pem.cert_pem && pem.key_pem) {
  15947. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  15948. pem.private_key_password)) {
  15949. reset_ctx_on_error();
  15950. }
  15951. }
  15952. }
  15953. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  15954. if (ca_cert_store && ctx_) {
  15955. // set_ca_store takes ownership of ca_cert_store
  15956. tls::set_ca_store(ctx_, ca_cert_store);
  15957. ca_cert_store_set_ = true;
  15958. } else if (ca_cert_store) {
  15959. tls::free_ca_store(ca_cert_store);
  15960. }
  15961. }
  15962. inline void
  15963. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  15964. if (!ctx_) { return; }
  15965. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15966. server_certificate_verifier_set_ = static_cast<bool>(verifier);
  15967. #endif
  15968. tls::set_verify_callback(ctx_, verifier);
  15969. }
  15970. inline void SSLClient::set_session_verifier(
  15971. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  15972. session_verifier_ = std::move(verifier);
  15973. }
  15974. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15975. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  15976. enable_windows_cert_verification_ = enabled;
  15977. }
  15978. #endif
  15979. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  15980. std::size_t size) {
  15981. if (ctx_ && ca_cert && size > 0) {
  15982. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  15983. tls::load_ca_pem(ctx_, ca_cert, size);
  15984. }
  15985. }
  15986. inline bool SSLClient::load_certs() {
  15987. auto ret = true;
  15988. // call_once rather than the plain flag WebSocketClient::create_stream() uses:
  15989. // one client is shared across concurrent requests here.
  15990. std::call_once(initialize_cert_, [&]() {
  15991. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15992. ret = detail::load_client_ca_config(
  15993. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  15994. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  15995. last_backend_error_);
  15996. });
  15997. return ret;
  15998. }
  15999. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  16000. // Load CA certificates if server verification is enabled
  16001. if (server_certificate_verification_) {
  16002. if (!load_certs()) {
  16003. error = Error::SSLLoadingCerts;
  16004. output_error_log(error, nullptr);
  16005. return false;
  16006. }
  16007. }
  16008. detail::ClientTlsSessionOptions options;
  16009. options.server_hostname_verification = server_hostname_verification_;
  16010. options.session_verifier = session_verifier_;
  16011. options.ctx_mutex = &ctx_mutex_;
  16012. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  16013. // Skip Schannel when a custom CA cert is specified, as the Windows
  16014. // certificate store would not know about user-provided CA certificates.
  16015. // Also skip when system CA trust is explicitly disabled.
  16016. options.windows_cert_verification =
  16017. enable_windows_cert_verification_ &&
  16018. system_ca_mode_ != SystemCAMode::Disabled && ca_cert_file_path_.empty() &&
  16019. ca_cert_dir_path_.empty() && ca_cert_pem_.empty() && !ca_cert_store_set_;
  16020. // Only a verifier set through set_server_certificate_verifier() is seen
  16021. // here, not one installed with tls::set_verify_callback() directly.
  16022. options.server_certificate_verifier_set = server_certificate_verifier_set_;
  16023. #endif
  16024. tls::session_t session = nullptr;
  16025. // Use scope_exit to ensure session is freed on error paths
  16026. bool success = false;
  16027. auto session_guard = detail::scope_exit([&] {
  16028. if (!success) { tls::free_session(session); }
  16029. });
  16030. detail::ClientTlsSessionError tls_error;
  16031. if (!detail::setup_client_tls_session(
  16032. host_, ctx_, session, socket.sock, server_certificate_verification_,
  16033. connection_timeout_sec_, connection_timeout_usec_, &tls_error,
  16034. options)) {
  16035. error = tls_error.error;
  16036. last_ssl_error_ = tls_error.ssl_error;
  16037. last_backend_error_ = tls_error.backend_error;
  16038. output_error_log(error, nullptr);
  16039. return false;
  16040. }
  16041. success = true;
  16042. socket.ssl = session;
  16043. return true;
  16044. }
  16045. inline void Client::set_digest_auth(const std::string &username,
  16046. const std::string &password) {
  16047. cli_->set_digest_auth(username, password);
  16048. }
  16049. inline void Client::set_proxy_digest_auth(const std::string &username,
  16050. const std::string &password) {
  16051. cli_->set_proxy_digest_auth(username, password);
  16052. }
  16053. inline void Client::enable_server_certificate_verification(bool enabled) {
  16054. cli_->enable_server_certificate_verification(enabled);
  16055. }
  16056. inline void Client::enable_server_hostname_verification(bool enabled) {
  16057. cli_->enable_server_hostname_verification(enabled);
  16058. }
  16059. inline void Client::enable_system_ca(bool enabled) {
  16060. cli_->enable_system_ca(enabled);
  16061. }
  16062. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  16063. inline void Client::enable_windows_certificate_verification(bool enabled) {
  16064. if (is_ssl_) {
  16065. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  16066. enabled);
  16067. }
  16068. }
  16069. #endif
  16070. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  16071. const std::string &ca_cert_dir_path) {
  16072. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  16073. }
  16074. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  16075. if (is_ssl_) {
  16076. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  16077. } else if (ca_cert_store) {
  16078. tls::free_ca_store(ca_cert_store);
  16079. }
  16080. }
  16081. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  16082. if (is_ssl_) {
  16083. // Use the PEM-based path so the CA data is retained for redirect transfer
  16084. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  16085. }
  16086. }
  16087. inline void
  16088. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  16089. if (is_ssl_) {
  16090. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  16091. std::move(verifier));
  16092. }
  16093. }
  16094. inline void Client::set_session_verifier(
  16095. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  16096. if (is_ssl_) {
  16097. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  16098. }
  16099. }
  16100. inline tls::ctx_t Client::tls_context() const {
  16101. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  16102. return nullptr;
  16103. }
  16104. #endif // CPPHTTPLIB_SSL_ENABLED
  16105. /*
  16106. * Group 7: TLS abstraction layer - Common API
  16107. */
  16108. #ifdef CPPHTTPLIB_SSL_ENABLED
  16109. namespace tls {
  16110. // Helper for PeerCert construction
  16111. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  16112. return PeerCert(get_peer_cert(session));
  16113. }
  16114. namespace impl {
  16115. inline VerifyCallback &get_verify_callback() {
  16116. static thread_local VerifyCallback callback;
  16117. return callback;
  16118. }
  16119. inline VerifyCallback &get_mbedtls_verify_callback() {
  16120. static thread_local VerifyCallback callback;
  16121. return callback;
  16122. }
  16123. // Check if a string is an IPv4 address
  16124. inline bool is_ipv4_address(const std::string &str) {
  16125. int dots = 0;
  16126. for (char c : str) {
  16127. if (c == '.') {
  16128. dots++;
  16129. } else if (!detail::is_ascii_digit(c)) {
  16130. return false;
  16131. }
  16132. }
  16133. return dots == 3;
  16134. }
  16135. // Parse IPv4 address string to bytes
  16136. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  16137. const char *p = str.c_str();
  16138. for (int i = 0; i < 4; i++) {
  16139. if (i > 0) {
  16140. if (*p != '.') { return false; }
  16141. p++;
  16142. }
  16143. int val = 0;
  16144. int digits = 0;
  16145. while (detail::is_ascii_digit(*p)) {
  16146. val = val * 10 + (*p - '0');
  16147. if (val > 255) { return false; }
  16148. p++;
  16149. digits++;
  16150. }
  16151. if (digits == 0) { return false; }
  16152. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  16153. if (digits > 1 && *(p - digits) == '0') { return false; }
  16154. out[i] = static_cast<unsigned char>(val);
  16155. }
  16156. return *p == '\0';
  16157. }
  16158. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  16159. // `out` must have room for at least 16 bytes. Returns the address length
  16160. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  16161. // literal. Used to match a host against iPAddress SANs the same way the
  16162. // OpenSSL backend does via X509_check_ip.
  16163. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  16164. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  16165. struct in6_addr addr6 = {};
  16166. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  16167. memcpy(out, &addr6, 16);
  16168. return 16;
  16169. }
  16170. return 0;
  16171. }
  16172. #ifdef _WIN32
  16173. // Enumerate Windows system certificates and call callback with DER data
  16174. template <typename Callback>
  16175. inline bool enumerate_windows_system_certs(Callback cb) {
  16176. bool loaded = false;
  16177. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  16178. for (auto store_name : store_names) {
  16179. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  16180. if (hStore) {
  16181. PCCERT_CONTEXT pContext = nullptr;
  16182. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  16183. nullptr) {
  16184. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  16185. loaded = true;
  16186. }
  16187. }
  16188. CertCloseStore(hStore, 0);
  16189. }
  16190. }
  16191. return loaded;
  16192. }
  16193. #endif
  16194. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16195. // Enumerate macOS Keychain certificates and call callback with DER data
  16196. template <typename Callback>
  16197. inline bool enumerate_macos_keychain_certs(Callback cb) {
  16198. bool loaded = false;
  16199. const SecTrustSettingsDomain domains[] = {
  16200. kSecTrustSettingsDomainSystem,
  16201. kSecTrustSettingsDomainAdmin,
  16202. kSecTrustSettingsDomainUser,
  16203. };
  16204. for (auto domain : domains) {
  16205. CFArrayRef certs = nullptr;
  16206. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  16207. if (status != errSecSuccess || !certs) {
  16208. if (certs) CFRelease(certs);
  16209. continue;
  16210. }
  16211. CFIndex count = CFArrayGetCount(certs);
  16212. for (CFIndex i = 0; i < count; i++) {
  16213. SecCertificateRef cert =
  16214. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  16215. CFDataRef data = SecCertificateCopyData(cert);
  16216. if (data) {
  16217. if (cb(CFDataGetBytePtr(data),
  16218. static_cast<size_t>(CFDataGetLength(data)))) {
  16219. loaded = true;
  16220. }
  16221. CFRelease(data);
  16222. }
  16223. }
  16224. CFRelease(certs);
  16225. }
  16226. return loaded;
  16227. }
  16228. #endif
  16229. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  16230. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  16231. // Common CA certificate file paths on Linux/Unix
  16232. inline const char **system_ca_paths() {
  16233. static const char *paths[] = {
  16234. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  16235. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  16236. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  16237. "/etc/pki/tls/cacert.pem", // OpenELEC
  16238. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  16239. nullptr};
  16240. return paths;
  16241. }
  16242. // Common CA certificate directory paths on Linux/Unix
  16243. inline const char **system_ca_dirs() {
  16244. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  16245. "/etc/pki/tls/certs", // RHEL/CentOS
  16246. "/usr/share/ca-certificates", // Other
  16247. nullptr};
  16248. return dirs;
  16249. }
  16250. #endif
  16251. } // namespace impl
  16252. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  16253. const char *ca_dir) {
  16254. if (!ctx) { return false; }
  16255. bool success = true;
  16256. if (ca_file && *ca_file) {
  16257. if (!load_ca_file(ctx, ca_file)) { success = false; }
  16258. }
  16259. if (ca_dir && *ca_dir) {
  16260. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  16261. }
  16262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16263. // Set CA list for client certificate request (CertificateRequest message)
  16264. if (ca_file && *ca_file) {
  16265. auto list = SSL_load_client_CA_file(ca_file);
  16266. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  16267. }
  16268. #endif
  16269. return success;
  16270. }
  16271. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16272. const char *password) {
  16273. return set_client_cert_pem(ctx, cert, key, password);
  16274. }
  16275. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  16276. const char *key_path, const char *password) {
  16277. return set_client_cert_file(ctx, cert_path, key_path, password);
  16278. }
  16279. // PeerCert implementation
  16280. inline PeerCert::PeerCert() = default;
  16281. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  16282. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  16283. other.cert_ = nullptr;
  16284. }
  16285. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  16286. if (this != &other) {
  16287. if (cert_) { free_cert(cert_); }
  16288. cert_ = other.cert_;
  16289. other.cert_ = nullptr;
  16290. }
  16291. return *this;
  16292. }
  16293. inline PeerCert::~PeerCert() {
  16294. if (cert_) { free_cert(cert_); }
  16295. }
  16296. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  16297. inline std::string PeerCert::subject_cn() const {
  16298. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  16299. }
  16300. inline std::string PeerCert::issuer_name() const {
  16301. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  16302. }
  16303. inline bool PeerCert::check_hostname(const char *hostname) const {
  16304. return cert_ ? verify_hostname(cert_, hostname) : false;
  16305. }
  16306. inline std::vector<SanEntry> PeerCert::sans() const {
  16307. std::vector<SanEntry> result;
  16308. if (cert_) { get_cert_sans(cert_, result); }
  16309. return result;
  16310. }
  16311. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  16312. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  16313. }
  16314. inline std::string PeerCert::serial() const {
  16315. return cert_ ? get_cert_serial(cert_) : std::string();
  16316. }
  16317. // VerifyContext method implementations
  16318. inline std::string VerifyContext::subject_cn() const {
  16319. return cert ? get_cert_subject_cn(cert) : std::string();
  16320. }
  16321. inline std::string VerifyContext::issuer_name() const {
  16322. return cert ? get_cert_issuer_name(cert) : std::string();
  16323. }
  16324. inline bool VerifyContext::check_hostname(const char *hostname) const {
  16325. return cert ? verify_hostname(cert, hostname) : false;
  16326. }
  16327. inline std::vector<SanEntry> VerifyContext::sans() const {
  16328. std::vector<SanEntry> result;
  16329. if (cert) { get_cert_sans(cert, result); }
  16330. return result;
  16331. }
  16332. inline bool VerifyContext::validity(time_t &not_before,
  16333. time_t &not_after) const {
  16334. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  16335. }
  16336. inline std::string VerifyContext::serial() const {
  16337. return cert ? get_cert_serial(cert) : std::string();
  16338. }
  16339. // TlsError static method implementation
  16340. inline std::string TlsError::verify_error_to_string(long error_code) {
  16341. return verify_error_string(error_code);
  16342. }
  16343. } // namespace tls
  16344. // Request::peer_cert() implementation
  16345. inline tls::PeerCert Request::peer_cert() const {
  16346. return tls::get_peer_cert_from_session(ssl);
  16347. }
  16348. // Request::sni() implementation
  16349. inline std::string Request::sni() const {
  16350. if (!ssl) { return std::string(); }
  16351. const char *s = tls::get_sni(ssl);
  16352. return s ? std::string(s) : std::string();
  16353. }
  16354. #endif // CPPHTTPLIB_SSL_ENABLED
  16355. /*
  16356. * Group 8: TLS abstraction layer - OpenSSL backend
  16357. */
  16358. /*
  16359. * OpenSSL Backend Implementation
  16360. */
  16361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16362. namespace tls {
  16363. namespace impl {
  16364. // Helper to map OpenSSL SSL_get_error to ErrorCode
  16365. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  16366. switch (ssl_error) {
  16367. case SSL_ERROR_NONE: return ErrorCode::Success;
  16368. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16369. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16370. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16371. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16372. case SSL_ERROR_SSL:
  16373. default: return ErrorCode::Fatal;
  16374. }
  16375. }
  16376. // Helper: Create client CA list from PEM string
  16377. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  16378. // Caller takes ownership of returned list
  16379. inline STACK_OF(X509_NAME) *
  16380. create_client_ca_list_from_pem(const char *ca_pem) {
  16381. if (!ca_pem) { return nullptr; }
  16382. auto ca_list = sk_X509_NAME_new_null();
  16383. if (!ca_list) { return nullptr; }
  16384. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  16385. if (!bio) {
  16386. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  16387. return nullptr;
  16388. }
  16389. X509 *cert = nullptr;
  16390. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  16391. nullptr) {
  16392. const X509_NAME *name = X509_get_subject_name(cert);
  16393. if (name) {
  16394. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  16395. }
  16396. X509_free(cert);
  16397. }
  16398. BIO_free(bio);
  16399. return ca_list;
  16400. }
  16401. // OpenSSL verify callback wrapper
  16402. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  16403. auto &callback = get_verify_callback();
  16404. if (!callback) { return preverify_ok; }
  16405. // Get SSL object from X509_STORE_CTX
  16406. auto ssl = static_cast<SSL *>(
  16407. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  16408. if (!ssl) { return preverify_ok; }
  16409. // Get current certificate and depth
  16410. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  16411. int depth = X509_STORE_CTX_get_error_depth(ctx);
  16412. int error = X509_STORE_CTX_get_error(ctx);
  16413. // Build context
  16414. VerifyContext verify_ctx;
  16415. verify_ctx.session = static_cast<session_t>(ssl);
  16416. verify_ctx.cert = static_cast<cert_t>(cert);
  16417. verify_ctx.depth = depth;
  16418. verify_ctx.preverify_ok = (preverify_ok != 0);
  16419. verify_ctx.error_code = error;
  16420. verify_ctx.error_string =
  16421. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  16422. return callback(verify_ctx) ? 1 : 0;
  16423. }
  16424. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  16425. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  16426. // that must be released with release_store_objects
  16427. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  16428. OPENSSL_VERSION_NUMBER >= 0x30300000L
  16429. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16430. #endif
  16431. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  16432. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16433. return X509_STORE_get1_objects(store);
  16434. #else
  16435. return X509_STORE_get0_objects(store);
  16436. #endif
  16437. }
  16438. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  16439. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16440. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  16441. #else
  16442. (void)objs; // get0 variant returns an internal pointer; nothing to free
  16443. #endif
  16444. }
  16445. } // namespace impl
  16446. inline ctx_t create_client_context() {
  16447. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  16448. if (ctx) {
  16449. // Disable auto-retry to properly handle non-blocking I/O
  16450. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  16451. // Set minimum TLS version
  16452. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  16453. }
  16454. return static_cast<ctx_t>(ctx);
  16455. }
  16456. inline void free_context(ctx_t ctx) {
  16457. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  16458. }
  16459. inline bool set_min_version(ctx_t ctx, Version version) {
  16460. if (!ctx) return false;
  16461. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  16462. static_cast<int>(version)) == 1;
  16463. }
  16464. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16465. if (!ctx || !pem || len == 0) return false;
  16466. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16467. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16468. if (!store) return false;
  16469. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  16470. if (!bio) return false;
  16471. bool ok = true;
  16472. X509 *cert = nullptr;
  16473. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  16474. nullptr) {
  16475. if (X509_STORE_add_cert(store, cert) != 1) {
  16476. // Ignore duplicate errors
  16477. auto err = ERR_peek_last_error();
  16478. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  16479. ok = false;
  16480. }
  16481. }
  16482. X509_free(cert);
  16483. if (!ok) break;
  16484. }
  16485. BIO_free(bio);
  16486. // Clear any "no more certificates" errors
  16487. ERR_clear_error();
  16488. return ok;
  16489. }
  16490. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16491. if (!ctx || !file_path) return false;
  16492. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  16493. nullptr) == 1;
  16494. }
  16495. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16496. if (!ctx || !dir_path) return false;
  16497. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  16498. dir_path) == 1;
  16499. }
  16500. inline bool load_system_certs(ctx_t ctx) {
  16501. if (!ctx) return false;
  16502. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16503. #ifdef _WIN32
  16504. // Windows: Load from system certificate store (ROOT and CA)
  16505. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16506. if (!store) return false;
  16507. bool loaded_any = false;
  16508. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  16509. for (auto store_name : store_names) {
  16510. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  16511. if (!hStore) continue;
  16512. PCCERT_CONTEXT pContext = nullptr;
  16513. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  16514. nullptr) {
  16515. const unsigned char *data = pContext->pbCertEncoded;
  16516. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  16517. if (x509) {
  16518. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  16519. X509_free(x509);
  16520. }
  16521. }
  16522. CertCloseStore(hStore, 0);
  16523. }
  16524. return loaded_any;
  16525. #elif defined(__APPLE__)
  16526. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16527. // macOS: Load from Keychain
  16528. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16529. if (!store) return false;
  16530. bool loaded_any = false;
  16531. const SecTrustSettingsDomain domains[] = {
  16532. kSecTrustSettingsDomainSystem,
  16533. kSecTrustSettingsDomainAdmin,
  16534. kSecTrustSettingsDomainUser,
  16535. };
  16536. for (auto domain : domains) {
  16537. CFArrayRef certs = nullptr;
  16538. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  16539. !certs) {
  16540. if (certs) CFRelease(certs);
  16541. continue;
  16542. }
  16543. auto count = CFArrayGetCount(certs);
  16544. for (CFIndex i = 0; i < count; i++) {
  16545. auto cert = reinterpret_cast<SecCertificateRef>(
  16546. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  16547. CFDataRef der = SecCertificateCopyData(cert);
  16548. if (der) {
  16549. const unsigned char *data = CFDataGetBytePtr(der);
  16550. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  16551. if (x509) {
  16552. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  16553. X509_free(x509);
  16554. }
  16555. CFRelease(der);
  16556. }
  16557. }
  16558. CFRelease(certs);
  16559. }
  16560. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16561. #else
  16562. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16563. #endif
  16564. #else
  16565. // Other Unix: use default verify paths
  16566. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16567. #endif
  16568. }
  16569. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16570. const char *password) {
  16571. if (!ctx || !cert || !key) return false;
  16572. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16573. // Load certificate
  16574. auto cert_bio = BIO_new_mem_buf(cert, -1);
  16575. if (!cert_bio) return false;
  16576. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  16577. BIO_free(cert_bio);
  16578. if (!x509) return false;
  16579. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  16580. X509_free(x509);
  16581. if (!cert_ok) return false;
  16582. // Load private key
  16583. auto key_bio = BIO_new_mem_buf(key, -1);
  16584. if (!key_bio) return false;
  16585. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  16586. password ? const_cast<char *>(password)
  16587. : nullptr);
  16588. BIO_free(key_bio);
  16589. if (!pkey) return false;
  16590. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  16591. EVP_PKEY_free(pkey);
  16592. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  16593. }
  16594. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16595. const char *key_path, const char *password) {
  16596. if (!ctx || !cert_path || !key_path) return false;
  16597. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16598. if (password && password[0] != '\0') {
  16599. SSL_CTX_set_default_passwd_cb_userdata(
  16600. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  16601. }
  16602. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  16603. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  16604. }
  16605. inline ctx_t create_server_context() {
  16606. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16607. if (ctx) {
  16608. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  16609. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  16610. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  16611. }
  16612. return static_cast<ctx_t>(ctx);
  16613. }
  16614. inline void set_verify_client(ctx_t ctx, bool require) {
  16615. if (!ctx) return;
  16616. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  16617. require
  16618. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  16619. : SSL_VERIFY_NONE,
  16620. nullptr);
  16621. }
  16622. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16623. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  16624. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16625. SSL *ssl = SSL_new(ssl_ctx);
  16626. if (!ssl) return nullptr;
  16627. // Disable auto-retry for proper non-blocking I/O handling
  16628. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  16629. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  16630. if (!bio) {
  16631. SSL_free(ssl);
  16632. return nullptr;
  16633. }
  16634. SSL_set_bio(ssl, bio, bio);
  16635. return static_cast<session_t>(ssl);
  16636. }
  16637. inline void free_session(session_t session) {
  16638. if (session) { SSL_free(static_cast<SSL *>(session)); }
  16639. }
  16640. inline bool set_sni(session_t session, const char *hostname,
  16641. bool /*verify_hostname*/) {
  16642. if (!session || !hostname) return false;
  16643. auto ssl = static_cast<SSL *>(session);
  16644. // Set SNI (Server Name Indication) only - does not enable verification.
  16645. // OpenSSL never binds identity checking to SNI (that happens post-
  16646. // handshake in setup_client_tls_session()), so verify_hostname is unused.
  16647. #if defined(OPENSSL_IS_BORINGSSL)
  16648. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  16649. #else
  16650. // Direct call instead of macro to suppress -Wold-style-cast warning
  16651. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  16652. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  16653. #endif
  16654. }
  16655. inline TlsError connect(session_t session) {
  16656. if (!session) { return TlsError(); }
  16657. auto ssl = static_cast<SSL *>(session);
  16658. auto ret = SSL_connect(ssl);
  16659. TlsError err;
  16660. if (ret == 1) {
  16661. err.code = ErrorCode::Success;
  16662. } else {
  16663. auto ssl_err = SSL_get_error(ssl, ret);
  16664. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16665. err.backend_code = ERR_get_error();
  16666. }
  16667. return err;
  16668. }
  16669. inline TlsError accept(session_t session) {
  16670. if (!session) { return TlsError(); }
  16671. auto ssl = static_cast<SSL *>(session);
  16672. auto ret = SSL_accept(ssl);
  16673. TlsError err;
  16674. if (ret == 1) {
  16675. err.code = ErrorCode::Success;
  16676. } else {
  16677. auto ssl_err = SSL_get_error(ssl, ret);
  16678. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16679. err.backend_code = ERR_get_error();
  16680. }
  16681. return err;
  16682. }
  16683. inline bool connect_nonblocking(session_t session, socket_t sock,
  16684. time_t timeout_sec, time_t timeout_usec,
  16685. TlsError *err) {
  16686. if (!session) {
  16687. if (err) { err->code = ErrorCode::Fatal; }
  16688. return false;
  16689. }
  16690. auto ssl = static_cast<SSL *>(session);
  16691. auto bio = SSL_get_rbio(ssl);
  16692. // Set non-blocking mode for handshake
  16693. detail::set_nonblocking(sock, true);
  16694. if (bio) { BIO_set_nbio(bio, 1); }
  16695. auto cleanup = detail::scope_exit([&]() {
  16696. // Restore blocking mode after handshake
  16697. if (bio) { BIO_set_nbio(bio, 0); }
  16698. detail::set_nonblocking(sock, false);
  16699. });
  16700. auto res = 0;
  16701. while ((res = SSL_connect(ssl)) != 1) {
  16702. auto ssl_err = SSL_get_error(ssl, res);
  16703. switch (ssl_err) {
  16704. case SSL_ERROR_WANT_READ:
  16705. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16706. continue;
  16707. }
  16708. break;
  16709. case SSL_ERROR_WANT_WRITE:
  16710. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16711. continue;
  16712. }
  16713. break;
  16714. default: break;
  16715. }
  16716. if (err) {
  16717. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  16718. err->backend_code = ERR_get_error();
  16719. }
  16720. return false;
  16721. }
  16722. if (err) { err->code = ErrorCode::Success; }
  16723. return true;
  16724. }
  16725. inline bool accept_nonblocking(session_t session, socket_t sock,
  16726. time_t timeout_sec, time_t timeout_usec,
  16727. TlsError *err) {
  16728. if (!session) {
  16729. if (err) { err->code = ErrorCode::Fatal; }
  16730. return false;
  16731. }
  16732. auto ssl = static_cast<SSL *>(session);
  16733. auto bio = SSL_get_rbio(ssl);
  16734. // Set non-blocking mode for handshake
  16735. detail::set_nonblocking(sock, true);
  16736. if (bio) { BIO_set_nbio(bio, 1); }
  16737. auto cleanup = detail::scope_exit([&]() {
  16738. // Restore blocking mode after handshake
  16739. if (bio) { BIO_set_nbio(bio, 0); }
  16740. detail::set_nonblocking(sock, false);
  16741. });
  16742. auto res = 0;
  16743. while ((res = SSL_accept(ssl)) != 1) {
  16744. auto ssl_err = SSL_get_error(ssl, res);
  16745. switch (ssl_err) {
  16746. case SSL_ERROR_WANT_READ:
  16747. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16748. continue;
  16749. }
  16750. break;
  16751. case SSL_ERROR_WANT_WRITE:
  16752. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16753. continue;
  16754. }
  16755. break;
  16756. default: break;
  16757. }
  16758. if (err) {
  16759. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  16760. err->backend_code = ERR_get_error();
  16761. }
  16762. return false;
  16763. }
  16764. if (err) { err->code = ErrorCode::Success; }
  16765. return true;
  16766. }
  16767. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16768. if (!session || !buf) {
  16769. err.code = ErrorCode::Fatal;
  16770. return -1;
  16771. }
  16772. auto ssl = static_cast<SSL *>(session);
  16773. constexpr auto max_len =
  16774. static_cast<size_t>((std::numeric_limits<int>::max)());
  16775. if (len > max_len) { len = max_len; }
  16776. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  16777. if (ret > 0) {
  16778. err.code = ErrorCode::Success;
  16779. return ret;
  16780. }
  16781. auto ssl_err = SSL_get_error(ssl, ret);
  16782. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16783. if (err.code == ErrorCode::PeerClosed) {
  16784. return 0;
  16785. } // Gracefully handle the peer closed state.
  16786. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  16787. return -1;
  16788. }
  16789. inline ssize_t write(session_t session, const void *buf, size_t len,
  16790. TlsError &err) {
  16791. if (!session || !buf) {
  16792. err.code = ErrorCode::Fatal;
  16793. return -1;
  16794. }
  16795. auto ssl = static_cast<SSL *>(session);
  16796. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  16797. if (ret > 0) {
  16798. err.code = ErrorCode::Success;
  16799. return ret;
  16800. }
  16801. auto ssl_err = SSL_get_error(ssl, ret);
  16802. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16803. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  16804. return -1;
  16805. }
  16806. inline int pending(const_session_t session) {
  16807. if (!session) return 0;
  16808. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  16809. }
  16810. inline void shutdown(session_t session, bool graceful) {
  16811. if (!session) return;
  16812. auto ssl = static_cast<SSL *>(session);
  16813. if (graceful) {
  16814. // Send close_notify without waiting for the peer's. The connection is
  16815. // closed right after this, so a unidirectional shutdown is enough, and an
  16816. // idle peer that never answers would otherwise hold this thread until the
  16817. // read timeout. The other backends do not wait either.
  16818. SSL_shutdown(ssl);
  16819. }
  16820. }
  16821. inline bool is_peer_closed(session_t session, socket_t sock) {
  16822. if (!session) return true;
  16823. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  16824. detail::set_nonblocking(sock, true);
  16825. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16826. auto ssl = static_cast<SSL *>(session);
  16827. char buf;
  16828. auto ret = SSL_peek(ssl, &buf, 1);
  16829. if (ret > 0) return false;
  16830. auto err = SSL_get_error(ssl, ret);
  16831. return err == SSL_ERROR_ZERO_RETURN;
  16832. }
  16833. inline cert_t get_peer_cert(const_session_t session) {
  16834. if (!session) return nullptr;
  16835. return static_cast<cert_t>(SSL_get1_peer_certificate(
  16836. static_cast<SSL *>(const_cast<void *>(session))));
  16837. }
  16838. inline size_t get_peer_certs(const_session_t session,
  16839. std::vector<cert_t> &certs) {
  16840. certs.clear();
  16841. if (!session) { return 0; }
  16842. auto ssl = static_cast<const SSL *>(session);
  16843. // On the server side, the chain leaves out the peer's own certificate
  16844. if (SSL_is_server(ssl)) {
  16845. if (auto leaf = get_peer_cert(session)) { certs.push_back(leaf); }
  16846. }
  16847. auto sk = SSL_get_peer_cert_chain(ssl);
  16848. for (int i = 0; sk && i < sk_X509_num(sk); i++) {
  16849. auto x509 = sk_X509_value(sk, i);
  16850. X509_up_ref(x509);
  16851. certs.push_back(static_cast<cert_t>(x509));
  16852. }
  16853. return certs.size();
  16854. }
  16855. inline void free_cert(cert_t cert) {
  16856. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  16857. }
  16858. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16859. if (!cert || !hostname) return false;
  16860. auto x509 = static_cast<X509 *>(cert);
  16861. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  16862. if (detail::is_ip_address(hostname)) {
  16863. return X509_check_ip_asc(x509, hostname, 0) == 1;
  16864. }
  16865. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  16866. }
  16867. inline uint64_t hostname_mismatch_code() {
  16868. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  16869. }
  16870. inline long get_verify_result(const_session_t session) {
  16871. if (!session) return X509_V_ERR_UNSPECIFIED;
  16872. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  16873. }
  16874. inline std::string get_cert_subject_cn(cert_t cert) {
  16875. if (!cert) return "";
  16876. auto x509 = static_cast<X509 *>(cert);
  16877. auto subject_name = X509_get_subject_name(x509);
  16878. if (!subject_name) return "";
  16879. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  16880. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  16881. if (idx < 0) return "";
  16882. auto entry = X509_NAME_get_entry(subject_name, idx);
  16883. if (!entry) return "";
  16884. auto data = X509_NAME_ENTRY_get_data(entry);
  16885. if (!data) return "";
  16886. return std::string(
  16887. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  16888. static_cast<size_t>(ASN1_STRING_length(data)));
  16889. }
  16890. inline std::string get_cert_issuer_name(cert_t cert) {
  16891. if (!cert) return "";
  16892. auto x509 = static_cast<X509 *>(cert);
  16893. auto issuer_name = X509_get_issuer_name(x509);
  16894. if (!issuer_name) return "";
  16895. char buf[256];
  16896. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  16897. return std::string(buf);
  16898. }
  16899. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16900. sans.clear();
  16901. if (!cert) return false;
  16902. auto x509 = static_cast<X509 *>(cert);
  16903. auto names = static_cast<GENERAL_NAMES *>(
  16904. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16905. if (!names) return true; // No SANs is valid
  16906. auto count = sk_GENERAL_NAME_num(names);
  16907. for (decltype(count) i = 0; i < count; i++) {
  16908. auto gen = sk_GENERAL_NAME_value(names, i);
  16909. if (!gen) continue;
  16910. SanEntry entry;
  16911. switch (gen->type) {
  16912. case GEN_DNS:
  16913. entry.type = SanType::DNS;
  16914. if (gen->d.dNSName) {
  16915. entry.value = std::string(
  16916. reinterpret_cast<const char *>(
  16917. ASN1_STRING_get0_data(gen->d.dNSName)),
  16918. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  16919. }
  16920. break;
  16921. case GEN_IPADD:
  16922. entry.type = SanType::IP;
  16923. if (gen->d.iPAddress) {
  16924. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  16925. auto len = ASN1_STRING_length(gen->d.iPAddress);
  16926. if (len == 4) {
  16927. // IPv4
  16928. char buf[INET_ADDRSTRLEN];
  16929. inet_ntop(AF_INET, data, buf, sizeof(buf));
  16930. entry.value = buf;
  16931. } else if (len == 16) {
  16932. // IPv6
  16933. char buf[INET6_ADDRSTRLEN];
  16934. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  16935. entry.value = buf;
  16936. }
  16937. }
  16938. break;
  16939. case GEN_EMAIL:
  16940. entry.type = SanType::EMAIL;
  16941. if (gen->d.rfc822Name) {
  16942. entry.value = std::string(
  16943. reinterpret_cast<const char *>(
  16944. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  16945. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  16946. }
  16947. break;
  16948. case GEN_URI:
  16949. entry.type = SanType::URI;
  16950. if (gen->d.uniformResourceIdentifier) {
  16951. entry.value = std::string(
  16952. reinterpret_cast<const char *>(
  16953. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  16954. static_cast<size_t>(
  16955. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  16956. }
  16957. break;
  16958. default: entry.type = SanType::OTHER; break;
  16959. }
  16960. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16961. }
  16962. GENERAL_NAMES_free(names);
  16963. return true;
  16964. }
  16965. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16966. time_t &not_after) {
  16967. if (!cert) return false;
  16968. auto x509 = static_cast<X509 *>(cert);
  16969. auto nb = X509_get0_notBefore(x509);
  16970. auto na = X509_get0_notAfter(x509);
  16971. if (!nb || !na) return false;
  16972. ASN1_TIME *epoch = ASN1_TIME_new();
  16973. if (!epoch) return false;
  16974. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  16975. if (!ASN1_TIME_set(epoch, 0)) return false;
  16976. int pday, psec;
  16977. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  16978. not_before = 86400 * (time_t)pday + psec;
  16979. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  16980. not_after = 86400 * (time_t)pday + psec;
  16981. return true;
  16982. }
  16983. inline std::string get_cert_serial(cert_t cert) {
  16984. if (!cert) return "";
  16985. auto x509 = static_cast<X509 *>(cert);
  16986. auto serial = X509_get_serialNumber(x509);
  16987. if (!serial) return "";
  16988. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  16989. if (!bn) return "";
  16990. auto hex = BN_bn2hex(bn);
  16991. BN_free(bn);
  16992. if (!hex) return "";
  16993. std::string result(hex);
  16994. OPENSSL_free(hex);
  16995. return result;
  16996. }
  16997. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16998. if (!cert) return false;
  16999. auto x509 = static_cast<X509 *>(cert);
  17000. auto len = i2d_X509(x509, nullptr);
  17001. if (len < 0) return false;
  17002. der.resize(static_cast<size_t>(len));
  17003. auto p = der.data();
  17004. i2d_X509(x509, &p);
  17005. return true;
  17006. }
  17007. inline const char *get_sni(const_session_t session) {
  17008. if (!session) return nullptr;
  17009. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  17010. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  17011. }
  17012. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  17013. inline uint64_t get_error() { return ERR_get_error(); }
  17014. inline std::string error_string(uint64_t code) {
  17015. char buf[256];
  17016. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  17017. return std::string(buf);
  17018. }
  17019. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17020. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  17021. if (!mem) { return nullptr; }
  17022. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  17023. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  17024. if (!inf) { return nullptr; }
  17025. auto store = X509_STORE_new();
  17026. if (store) {
  17027. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  17028. auto itmp = sk_X509_INFO_value(inf, i);
  17029. if (!itmp) { continue; }
  17030. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  17031. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  17032. }
  17033. }
  17034. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  17035. return static_cast<ca_store_t>(store);
  17036. }
  17037. inline void free_ca_store(ca_store_t store) {
  17038. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  17039. }
  17040. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17041. if (!ctx || !store) { return false; }
  17042. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  17043. auto x509_store = static_cast<X509_STORE *>(store);
  17044. // Check if same store is already set
  17045. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  17046. // SSL_CTX_set_cert_store takes ownership and frees the old store
  17047. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  17048. return true;
  17049. }
  17050. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17051. certs.clear();
  17052. if (!ctx) { return 0; }
  17053. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  17054. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  17055. if (!store) { return 0; }
  17056. auto objs = impl::get_store_objects(store);
  17057. if (!objs) { return 0; }
  17058. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  17059. auto count = sk_X509_OBJECT_num(objs);
  17060. for (decltype(count) i = 0; i < count; i++) {
  17061. auto obj = sk_X509_OBJECT_value(objs, i);
  17062. if (!obj) { continue; }
  17063. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  17064. auto x509 = X509_OBJECT_get0_X509(obj);
  17065. if (x509) {
  17066. // Increment reference count so caller can free it
  17067. X509_up_ref(x509);
  17068. certs.push_back(static_cast<cert_t>(x509));
  17069. }
  17070. }
  17071. }
  17072. return certs.size();
  17073. }
  17074. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17075. std::vector<std::string> names;
  17076. if (!ctx) { return names; }
  17077. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  17078. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  17079. if (!store) { return names; }
  17080. auto objs = impl::get_store_objects(store);
  17081. if (!objs) { return names; }
  17082. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  17083. auto count = sk_X509_OBJECT_num(objs);
  17084. for (decltype(count) i = 0; i < count; i++) {
  17085. auto obj = sk_X509_OBJECT_value(objs, i);
  17086. if (!obj) { continue; }
  17087. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  17088. auto x509 = X509_OBJECT_get0_X509(obj);
  17089. if (x509) {
  17090. auto subject = X509_get_subject_name(x509);
  17091. if (subject) {
  17092. char buf[512];
  17093. X509_NAME_oneline(subject, buf, sizeof(buf));
  17094. names.push_back(buf);
  17095. }
  17096. }
  17097. }
  17098. }
  17099. return names;
  17100. }
  17101. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17102. const char *key_pem, const char *password) {
  17103. if (!ctx || !cert_pem || !key_pem) { return false; }
  17104. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  17105. // Load certificate from PEM
  17106. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  17107. if (!cert_bio) { return false; }
  17108. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  17109. BIO_free(cert_bio);
  17110. if (!cert) { return false; }
  17111. // Load private key from PEM
  17112. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  17113. if (!key_bio) {
  17114. X509_free(cert);
  17115. return false;
  17116. }
  17117. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  17118. password ? const_cast<char *>(password)
  17119. : nullptr);
  17120. BIO_free(key_bio);
  17121. if (!key) {
  17122. X509_free(cert);
  17123. return false;
  17124. }
  17125. // Update certificate and key
  17126. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  17127. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  17128. X509_free(cert);
  17129. EVP_PKEY_free(key);
  17130. return ret;
  17131. }
  17132. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17133. if (!ctx || !ca_pem) { return false; }
  17134. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  17135. // Create new X509_STORE from PEM
  17136. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  17137. if (!store) { return false; }
  17138. // SSL_CTX_set_cert_store takes ownership
  17139. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  17140. // Set client CA list for client certificate request
  17141. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  17142. if (ca_list) {
  17143. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  17144. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  17145. }
  17146. return true;
  17147. }
  17148. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17149. if (!ctx) { return false; }
  17150. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  17151. impl::get_verify_callback() = std::move(callback);
  17152. if (impl::get_verify_callback()) {
  17153. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  17154. } else {
  17155. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  17156. }
  17157. return true;
  17158. }
  17159. inline long get_verify_error(const_session_t session) {
  17160. if (!session) { return -1; }
  17161. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  17162. return SSL_get_verify_result(ssl);
  17163. }
  17164. inline std::string verify_error_string(long error_code) {
  17165. if (error_code == X509_V_OK) { return ""; }
  17166. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  17167. return str ? str : "unknown error";
  17168. }
  17169. } // namespace tls
  17170. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  17171. /*
  17172. * Group 9: TLS abstraction layer - Mbed TLS backend
  17173. */
  17174. /*
  17175. * Mbed TLS Backend Implementation
  17176. */
  17177. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17178. namespace tls {
  17179. namespace impl {
  17180. // Mbed TLS session wrapper
  17181. struct MbedTlsSession {
  17182. mbedtls_ssl_context ssl;
  17183. socket_t sock = INVALID_SOCKET;
  17184. std::string hostname; // For client: set via set_sni
  17185. std::string sni_hostname; // For server: received from client via SNI callback
  17186. // Mbed TLS has no SSL_peek() equivalent, so is_peer_closed() must probe with
  17187. // a real 1-byte mbedtls_ssl_read(). If that probe lands on application data
  17188. // (e.g. a response that arrived while this side was still in its post-write
  17189. // check), the byte is pushed back here and served by the next read().
  17190. unsigned char peeked_byte = 0;
  17191. bool has_peeked_byte = false;
  17192. // Set by set_sni() when the caller disabled hostname verification, so the
  17193. // verify callback can clear the CN/SAN mismatch flag while still enforcing
  17194. // the rest of the chain (Mbed TLS ties SNI and identity checking together;
  17195. // OpenSSL and wolfSSL keep them independent).
  17196. bool suppress_hostname_mismatch = false;
  17197. // Copied from the owning MbedTlsContext at creation. set_sni() uses this to
  17198. // decide which verify callback to install when hostname verification is
  17199. // disabled: mbedtls_verify_callback() when a user callback is genuinely
  17200. // wired for this context, or a self-contained one otherwise, so a session
  17201. // that never opted into a callback never consults the process-wide
  17202. // set_verify_callback() slot (which some other, unrelated client may have
  17203. // populated).
  17204. bool has_verify_callback = false;
  17205. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  17206. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  17207. MbedTlsSession(const MbedTlsSession &) = delete;
  17208. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  17209. };
  17210. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  17211. // queue)
  17212. inline int &mbedtls_last_error() {
  17213. static thread_local int err = 0;
  17214. return err;
  17215. }
  17216. // Helper to map Mbed TLS error to ErrorCode
  17217. inline ErrorCode map_mbedtls_error(int ret, int &out_errno,
  17218. uint32_t verify_flags) {
  17219. if (ret == 0) { return ErrorCode::Success; }
  17220. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  17221. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  17222. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  17223. return ErrorCode::PeerClosed;
  17224. }
  17225. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  17226. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  17227. out_errno = errno;
  17228. return ErrorCode::SyscallError;
  17229. }
  17230. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  17231. // Unlike OpenSSL/wolfSSL, Mbed TLS folds the CN/SAN identity check into
  17232. // the handshake's chain verification (see set_sni()); a mismatch there
  17233. // is reported the same way as any other verify_flags bit. Report it as
  17234. // HostnameMismatch, matching the other backends and the post-handshake
  17235. // identity check below, but only when naming is the sole problem -
  17236. // if the chain itself is also untrusted/expired/etc., that takes
  17237. // priority over the naming detail.
  17238. if (verify_flags == static_cast<uint32_t>(hostname_mismatch_code())) {
  17239. return ErrorCode::HostnameMismatch;
  17240. }
  17241. return ErrorCode::CertVerifyFailed;
  17242. }
  17243. return ErrorCode::Fatal;
  17244. }
  17245. // Populates a TlsError from a failed (non-zero) mbedtls_ssl_handshake()
  17246. // return value, including the verify-flags-dependent HostnameMismatch
  17247. // mapping; shared by connect() and connect_nonblocking() so the
  17248. // backend_code policy for that mapping only lives in one place.
  17249. inline void fill_mbedtls_tls_error(TlsError &err, mbedtls_ssl_context &ssl,
  17250. int ret) {
  17251. auto verify_flags = mbedtls_ssl_get_verify_result(&ssl);
  17252. err.code = map_mbedtls_error(ret, err.sys_errno, verify_flags);
  17253. err.backend_code = err.code == ErrorCode::HostnameMismatch
  17254. ? static_cast<uint64_t>(verify_flags)
  17255. : static_cast<uint64_t>(-ret);
  17256. }
  17257. // A TLS 1.3 NewSessionTicket (signaled by default on Mbed TLS 4.x) is a
  17258. // non-fatal notification delivered between records, not an error and not
  17259. // application data, so I/O calls that see it should just be retried. Kept in
  17260. // one helper so the retry loops keep an intact "do { } while (...)" instead of
  17261. // splitting the closing brace across an #if.
  17262. inline bool mbedtls_is_session_ticket(int ret) {
  17263. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  17264. return ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
  17265. #else
  17266. (void)ret;
  17267. return false;
  17268. #endif
  17269. }
  17270. // BIO-like send callback for Mbed TLS
  17271. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  17272. size_t len) {
  17273. auto sock = *static_cast<socket_t *>(ctx);
  17274. #ifdef _WIN32
  17275. auto ret =
  17276. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  17277. if (ret == SOCKET_ERROR) {
  17278. int err = WSAGetLastError();
  17279. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  17280. return MBEDTLS_ERR_NET_SEND_FAILED;
  17281. }
  17282. #else
  17283. auto ret = send(sock, buf, len, 0);
  17284. if (ret < 0) {
  17285. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  17286. return MBEDTLS_ERR_SSL_WANT_WRITE;
  17287. }
  17288. return MBEDTLS_ERR_NET_SEND_FAILED;
  17289. }
  17290. #endif
  17291. return static_cast<int>(ret);
  17292. }
  17293. // BIO-like recv callback for Mbed TLS
  17294. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  17295. auto sock = *static_cast<socket_t *>(ctx);
  17296. #ifdef _WIN32
  17297. auto ret =
  17298. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  17299. if (ret == SOCKET_ERROR) {
  17300. int err = WSAGetLastError();
  17301. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  17302. return MBEDTLS_ERR_NET_RECV_FAILED;
  17303. }
  17304. #else
  17305. auto ret = recv(sock, buf, len, 0);
  17306. if (ret < 0) {
  17307. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  17308. return MBEDTLS_ERR_SSL_WANT_READ;
  17309. }
  17310. return MBEDTLS_ERR_NET_RECV_FAILED;
  17311. }
  17312. #endif
  17313. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  17314. return static_cast<int>(ret);
  17315. }
  17316. // MbedTlsContext constructor/destructor implementations
  17317. inline MbedTlsContext::MbedTlsContext() {
  17318. mbedtls_ssl_config_init(&conf);
  17319. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17320. mbedtls_entropy_init(&entropy);
  17321. mbedtls_ctr_drbg_init(&ctr_drbg);
  17322. #endif
  17323. mbedtls_x509_crt_init(&ca_chain);
  17324. mbedtls_x509_crt_init(&own_cert);
  17325. mbedtls_pk_init(&own_key);
  17326. }
  17327. inline MbedTlsContext::~MbedTlsContext() {
  17328. mbedtls_pk_free(&own_key);
  17329. mbedtls_x509_crt_free(&own_cert);
  17330. mbedtls_x509_crt_free(&ca_chain);
  17331. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17332. mbedtls_ctr_drbg_free(&ctr_drbg);
  17333. mbedtls_entropy_free(&entropy);
  17334. #endif
  17335. mbedtls_ssl_config_free(&conf);
  17336. }
  17337. // Thread-local storage for SNI captured during handshake
  17338. // This is needed because the SNI callback doesn't have a way to pass
  17339. // session-specific data before the session is fully set up
  17340. inline std::string &mbedpending_sni() {
  17341. static thread_local std::string sni;
  17342. return sni;
  17343. }
  17344. // SNI callback for Mbed TLS server to capture client's SNI hostname
  17345. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  17346. const unsigned char *name, size_t name_len) {
  17347. (void)p_ctx;
  17348. (void)ssl;
  17349. // Store SNI name in thread-local storage
  17350. // It will be retrieved and stored in the session after handshake
  17351. if (name && name_len > 0) {
  17352. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  17353. } else {
  17354. mbedpending_sni().clear();
  17355. }
  17356. return 0; // Accept any SNI
  17357. }
  17358. inline void mbedtls_clear_cn_mismatch(uint32_t *flags) {
  17359. *flags &= ~static_cast<uint32_t>(hostname_mismatch_code());
  17360. }
  17361. // Verify callback used when hostname verification is disabled for a session
  17362. // that has no user-supplied verify callback of its own (MbedTlsSession::
  17363. // has_verify_callback is false). Deliberately does not consult
  17364. // get_verify_callback(): that slot is process-wide, so reading it here would
  17365. // pick up whatever another, unrelated client last installed there.
  17366. inline int mbedtls_mask_hostname_mismatch_callback(void *data,
  17367. mbedtls_x509_crt *, int,
  17368. uint32_t *flags) {
  17369. (void)data;
  17370. mbedtls_clear_cn_mismatch(flags);
  17371. return 0;
  17372. }
  17373. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  17374. int cert_depth, uint32_t *flags);
  17375. // MbedTLS verify callback wrapper
  17376. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  17377. int cert_depth, uint32_t *flags) {
  17378. // data points to the MbedTlsSession
  17379. auto *session = static_cast<MbedTlsSession *>(data);
  17380. // set_sni() disabled hostname verification for this session: drop the
  17381. // CN/SAN mismatch flag so it doesn't fail the chain check below, mirroring
  17382. // the OpenSSL/wolfSSL backends where identity checking is independent of
  17383. // SNI. The final pass/fail decision still comes from the remaining flags
  17384. // (or, below, from the user's own verify callback).
  17385. if (session && session->suppress_hostname_mismatch) {
  17386. mbedtls_clear_cn_mismatch(flags);
  17387. }
  17388. auto &callback = get_verify_callback();
  17389. if (!callback) { return 0; } // Continue with default verification
  17390. // Build context
  17391. VerifyContext verify_ctx;
  17392. verify_ctx.session = static_cast<session_t>(session);
  17393. verify_ctx.cert = static_cast<cert_t>(crt);
  17394. verify_ctx.depth = cert_depth;
  17395. verify_ctx.preverify_ok = (*flags == 0);
  17396. verify_ctx.error_code = static_cast<long>(*flags);
  17397. // Convert Mbed TLS flags to error string
  17398. static thread_local char error_buf[256];
  17399. if (*flags != 0) {
  17400. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  17401. verify_ctx.error_string = error_buf;
  17402. } else {
  17403. verify_ctx.error_string = nullptr;
  17404. }
  17405. bool accepted = callback(verify_ctx);
  17406. if (accepted) {
  17407. *flags = 0; // Clear all error flags
  17408. return 0;
  17409. }
  17410. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  17411. }
  17412. } // namespace impl
  17413. inline ctx_t create_client_context() {
  17414. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  17415. if (!ctx) { return nullptr; }
  17416. ctx->is_server = false;
  17417. #ifdef CPPHTTPLIB_MBEDTLS_V4
  17418. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  17419. if (!detail::ensure_mbedtls_psa_crypto()) {
  17420. delete ctx;
  17421. return nullptr;
  17422. }
  17423. int ret;
  17424. #else
  17425. // Seed the random number generator
  17426. const char *pers = "httplib_client";
  17427. int ret = mbedtls_ctr_drbg_seed(
  17428. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  17429. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  17430. if (ret != 0) {
  17431. impl::mbedtls_last_error() = ret;
  17432. delete ctx;
  17433. return nullptr;
  17434. }
  17435. #endif
  17436. // Set up SSL config for client
  17437. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  17438. MBEDTLS_SSL_TRANSPORT_STREAM,
  17439. MBEDTLS_SSL_PRESET_DEFAULT);
  17440. if (ret != 0) {
  17441. impl::mbedtls_last_error() = ret;
  17442. delete ctx;
  17443. return nullptr;
  17444. }
  17445. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17446. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  17447. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  17448. #endif
  17449. // Default: verify peer certificate
  17450. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17451. // Set minimum TLS version to 1.2
  17452. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17453. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17454. #else
  17455. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17456. MBEDTLS_SSL_MINOR_VERSION_3);
  17457. #endif
  17458. return static_cast<ctx_t>(ctx);
  17459. }
  17460. inline ctx_t create_server_context() {
  17461. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  17462. if (!ctx) { return nullptr; }
  17463. ctx->is_server = true;
  17464. #ifdef CPPHTTPLIB_MBEDTLS_V4
  17465. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  17466. if (!detail::ensure_mbedtls_psa_crypto()) {
  17467. delete ctx;
  17468. return nullptr;
  17469. }
  17470. int ret;
  17471. #else
  17472. // Seed the random number generator
  17473. const char *pers = "httplib_server";
  17474. int ret = mbedtls_ctr_drbg_seed(
  17475. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  17476. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  17477. if (ret != 0) {
  17478. impl::mbedtls_last_error() = ret;
  17479. delete ctx;
  17480. return nullptr;
  17481. }
  17482. #endif
  17483. // Set up SSL config for server
  17484. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  17485. MBEDTLS_SSL_TRANSPORT_STREAM,
  17486. MBEDTLS_SSL_PRESET_DEFAULT);
  17487. if (ret != 0) {
  17488. impl::mbedtls_last_error() = ret;
  17489. delete ctx;
  17490. return nullptr;
  17491. }
  17492. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17493. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  17494. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  17495. #endif
  17496. // Default: don't verify client
  17497. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  17498. // Set minimum TLS version to 1.2
  17499. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17500. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17501. #else
  17502. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17503. MBEDTLS_SSL_MINOR_VERSION_3);
  17504. #endif
  17505. // Set SNI callback to capture client's SNI hostname
  17506. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  17507. return static_cast<ctx_t>(ctx);
  17508. }
  17509. inline void free_context(ctx_t ctx) {
  17510. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  17511. }
  17512. inline bool set_min_version(ctx_t ctx, Version version) {
  17513. if (!ctx) { return false; }
  17514. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17515. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17516. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  17517. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  17518. if (version >= Version::TLS1_3) {
  17519. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  17520. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  17521. #endif
  17522. }
  17523. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  17524. #else
  17525. // Mbed TLS 2.x uses major/minor version numbers
  17526. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  17527. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  17528. if (version >= Version::TLS1_3) {
  17529. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  17530. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  17531. #else
  17532. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  17533. #endif
  17534. }
  17535. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  17536. #endif
  17537. return true;
  17538. }
  17539. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  17540. if (!ctx || !pem) { return false; }
  17541. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17542. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  17543. // Add null terminator if not present
  17544. std::string pem_str(pem, len);
  17545. int ret = mbedtls_x509_crt_parse(
  17546. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  17547. pem_str.size() + 1);
  17548. if (ret != 0) {
  17549. impl::mbedtls_last_error() = ret;
  17550. return false;
  17551. }
  17552. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17553. return true;
  17554. }
  17555. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  17556. if (!ctx || !file_path) { return false; }
  17557. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17558. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  17559. if (ret != 0) {
  17560. impl::mbedtls_last_error() = ret;
  17561. return false;
  17562. }
  17563. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17564. return true;
  17565. }
  17566. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  17567. if (!ctx || !dir_path) { return false; }
  17568. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17569. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  17570. if (ret < 0) { // Returns number of certs on success, negative on error
  17571. impl::mbedtls_last_error() = ret;
  17572. return false;
  17573. }
  17574. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17575. return true;
  17576. }
  17577. inline bool load_system_certs(ctx_t ctx) {
  17578. if (!ctx) { return false; }
  17579. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17580. bool loaded = false;
  17581. #ifdef _WIN32
  17582. loaded = impl::enumerate_windows_system_certs(
  17583. [&](const unsigned char *data, size_t len) {
  17584. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  17585. });
  17586. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  17587. loaded = impl::enumerate_macos_keychain_certs(
  17588. [&](const unsigned char *data, size_t len) {
  17589. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  17590. });
  17591. #else
  17592. for (auto path = impl::system_ca_paths(); *path; ++path) {
  17593. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  17594. loaded = true;
  17595. break;
  17596. }
  17597. }
  17598. if (!loaded) {
  17599. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  17600. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  17601. loaded = true;
  17602. break;
  17603. }
  17604. }
  17605. }
  17606. #endif
  17607. if (loaded) {
  17608. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17609. }
  17610. return loaded;
  17611. }
  17612. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  17613. const char *password) {
  17614. if (!ctx || !cert || !key) { return false; }
  17615. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17616. // Parse certificate
  17617. std::string cert_str(cert);
  17618. int ret = mbedtls_x509_crt_parse(
  17619. &mctx->own_cert,
  17620. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  17621. cert_str.size() + 1);
  17622. if (ret != 0) {
  17623. impl::mbedtls_last_error() = ret;
  17624. return false;
  17625. }
  17626. // Parse private key
  17627. std::string key_str(key);
  17628. const unsigned char *pwd =
  17629. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  17630. size_t pwd_len = password ? strlen(password) : 0;
  17631. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17632. ret = mbedtls_pk_parse_key(
  17633. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  17634. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  17635. &mctx->ctr_drbg);
  17636. #else
  17637. ret = mbedtls_pk_parse_key(
  17638. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  17639. key_str.size() + 1, pwd, pwd_len);
  17640. #endif
  17641. if (ret != 0) {
  17642. impl::mbedtls_last_error() = ret;
  17643. return false;
  17644. }
  17645. // Verify that the certificate and private key match.
  17646. // Mbed TLS 4.x: mbedtls_pk_check_pair() reports a spurious mismatch for
  17647. // PSA-backed keys, so skip it and let the handshake surface a real mismatch.
  17648. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17649. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17650. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  17651. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17652. #else
  17653. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  17654. #endif
  17655. if (ret != 0) {
  17656. impl::mbedtls_last_error() = ret;
  17657. return false;
  17658. }
  17659. #endif
  17660. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  17661. if (ret != 0) {
  17662. impl::mbedtls_last_error() = ret;
  17663. return false;
  17664. }
  17665. return true;
  17666. }
  17667. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  17668. const char *key_path, const char *password) {
  17669. if (!ctx || !cert_path || !key_path) { return false; }
  17670. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17671. // Parse certificate file
  17672. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  17673. if (ret != 0) {
  17674. impl::mbedtls_last_error() = ret;
  17675. return false;
  17676. }
  17677. // Parse private key file
  17678. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17679. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  17680. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17681. #else
  17682. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  17683. #endif
  17684. if (ret != 0) {
  17685. impl::mbedtls_last_error() = ret;
  17686. return false;
  17687. }
  17688. // Verify that the certificate and private key match.
  17689. // Mbed TLS 4.x: see set_client_cert() — skip the spurious check_pair.
  17690. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17691. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17692. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  17693. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17694. #else
  17695. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  17696. #endif
  17697. if (ret != 0) {
  17698. impl::mbedtls_last_error() = ret;
  17699. return false;
  17700. }
  17701. #endif
  17702. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  17703. if (ret != 0) {
  17704. impl::mbedtls_last_error() = ret;
  17705. return false;
  17706. }
  17707. return true;
  17708. }
  17709. inline void set_verify_client(ctx_t ctx, bool require) {
  17710. if (!ctx) { return; }
  17711. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17712. mctx->verify_client = require;
  17713. if (require) {
  17714. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17715. } else {
  17716. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  17717. // is called (matching OpenSSL behavior). Otherwise use NONE.
  17718. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  17719. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  17720. : MBEDTLS_SSL_VERIFY_NONE);
  17721. }
  17722. }
  17723. inline session_t create_session(ctx_t ctx, socket_t sock) {
  17724. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  17725. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17726. auto session = new (std::nothrow) impl::MbedTlsSession();
  17727. if (!session) { return nullptr; }
  17728. session->sock = sock;
  17729. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  17730. if (ret != 0) {
  17731. impl::mbedtls_last_error() = ret;
  17732. delete session;
  17733. return nullptr;
  17734. }
  17735. // Explicitly opt out of in-handshake hostname verification by default;
  17736. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  17737. // fails outright when no hostname was set. set_sni() installs the real
  17738. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  17739. // caller verifies the certificate identity post-handshake via
  17740. // verify_hostname().
  17741. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  17742. // Set BIO callbacks
  17743. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  17744. impl::mbedtls_net_recv_cb, nullptr);
  17745. // Set per-session verify callback with session pointer if callback is
  17746. // registered
  17747. session->has_verify_callback = mctx->has_verify_callback;
  17748. if (mctx->has_verify_callback) {
  17749. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  17750. session);
  17751. }
  17752. return static_cast<session_t>(session);
  17753. }
  17754. inline void free_session(session_t session) {
  17755. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  17756. }
  17757. inline bool set_sni(session_t session, const char *hostname,
  17758. bool verify_hostname) {
  17759. if (!session || !hostname) { return false; }
  17760. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17761. // mbedtls_ssl_set_hostname() both sends the SNI extension and binds the
  17762. // handshake-time CN/SAN check to `hostname`; the two can't be requested
  17763. // independently, so a disabled hostname check is handled below by masking
  17764. // the resulting mismatch flag instead of skipping this call.
  17765. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  17766. if (ret != 0) {
  17767. impl::mbedtls_last_error() = ret;
  17768. return false;
  17769. }
  17770. msession->hostname = hostname;
  17771. if (!verify_hostname) {
  17772. msession->suppress_hostname_mismatch = true;
  17773. // If a user verify callback is already wired for this session,
  17774. // mbedtls_verify_callback() masks the mismatch flag itself before
  17775. // consulting it (see suppress_hostname_mismatch above) - reinstalling it
  17776. // here would be redundant. Otherwise install the self-contained masking
  17777. // callback, which never touches the process-wide callback slot.
  17778. if (!msession->has_verify_callback) {
  17779. mbedtls_ssl_set_verify(&msession->ssl,
  17780. impl::mbedtls_mask_hostname_mismatch_callback,
  17781. msession);
  17782. }
  17783. }
  17784. return true;
  17785. }
  17786. inline TlsError connect(session_t session) {
  17787. TlsError err;
  17788. if (!session) {
  17789. err.code = ErrorCode::Fatal;
  17790. return err;
  17791. }
  17792. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17793. int ret;
  17794. do {
  17795. ret = mbedtls_ssl_handshake(&msession->ssl);
  17796. } while (impl::mbedtls_is_session_ticket(ret));
  17797. if (ret == 0) {
  17798. err.code = ErrorCode::Success;
  17799. } else {
  17800. impl::fill_mbedtls_tls_error(err, msession->ssl, ret);
  17801. impl::mbedtls_last_error() = ret;
  17802. }
  17803. return err;
  17804. }
  17805. inline TlsError accept(session_t session) {
  17806. // Same as connect for Mbed TLS - handshake works for both client and server
  17807. auto result = connect(session);
  17808. // After successful handshake, capture SNI from thread-local storage
  17809. if (result.code == ErrorCode::Success && session) {
  17810. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17811. msession->sni_hostname = std::move(impl::mbedpending_sni());
  17812. impl::mbedpending_sni().clear();
  17813. }
  17814. return result;
  17815. }
  17816. inline bool connect_nonblocking(session_t session, socket_t sock,
  17817. time_t timeout_sec, time_t timeout_usec,
  17818. TlsError *err) {
  17819. if (!session) {
  17820. if (err) { err->code = ErrorCode::Fatal; }
  17821. return false;
  17822. }
  17823. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17824. // Set socket to non-blocking mode
  17825. detail::set_nonblocking(sock, true);
  17826. auto cleanup =
  17827. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17828. int ret;
  17829. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  17830. // Non-fatal TLS 1.3 ticket; retry immediately.
  17831. if (impl::mbedtls_is_session_ticket(ret)) { continue; }
  17832. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  17833. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  17834. continue;
  17835. }
  17836. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  17837. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  17838. continue;
  17839. }
  17840. }
  17841. // TlsError or timeout
  17842. if (err) { impl::fill_mbedtls_tls_error(*err, msession->ssl, ret); }
  17843. impl::mbedtls_last_error() = ret;
  17844. return false;
  17845. }
  17846. if (err) { err->code = ErrorCode::Success; }
  17847. return true;
  17848. }
  17849. inline bool accept_nonblocking(session_t session, socket_t sock,
  17850. time_t timeout_sec, time_t timeout_usec,
  17851. TlsError *err) {
  17852. // Same implementation as connect for Mbed TLS
  17853. bool result =
  17854. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  17855. // After successful handshake, capture SNI from thread-local storage
  17856. if (result && session) {
  17857. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17858. msession->sni_hostname = std::move(impl::mbedpending_sni());
  17859. impl::mbedpending_sni().clear();
  17860. }
  17861. return result;
  17862. }
  17863. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  17864. if (!session || !buf) {
  17865. err.code = ErrorCode::Fatal;
  17866. return -1;
  17867. }
  17868. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17869. // Serve a byte consumed by the is_peer_closed() probe before reading more.
  17870. if (msession->has_peeked_byte) {
  17871. if (len == 0) { return 0; }
  17872. auto p = static_cast<unsigned char *>(buf);
  17873. p[0] = msession->peeked_byte;
  17874. msession->has_peeked_byte = false;
  17875. size_t n = 1;
  17876. // Top up with any already-decrypted bytes without risking a block.
  17877. if (len > 1 && mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17878. int extra = mbedtls_ssl_read(&msession->ssl, p + 1, len - 1);
  17879. if (extra > 0) { n += static_cast<size_t>(extra); }
  17880. }
  17881. err.code = ErrorCode::Success;
  17882. return static_cast<ssize_t>(n);
  17883. }
  17884. int ret;
  17885. do {
  17886. ret = mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf),
  17887. len);
  17888. } while (impl::mbedtls_is_session_ticket(ret));
  17889. if (ret > 0) {
  17890. err.code = ErrorCode::Success;
  17891. return static_cast<ssize_t>(ret);
  17892. }
  17893. if (ret == 0) {
  17894. err.code = ErrorCode::PeerClosed;
  17895. return 0;
  17896. }
  17897. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17898. err.backend_code = static_cast<uint64_t>(-ret);
  17899. impl::mbedtls_last_error() = ret;
  17900. // mbedTLS signals a clean close_notify via a negative error code rather
  17901. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  17902. if (err.code == ErrorCode::PeerClosed) { return 0; }
  17903. return -1;
  17904. }
  17905. inline ssize_t write(session_t session, const void *buf, size_t len,
  17906. TlsError &err) {
  17907. if (!session || !buf) {
  17908. err.code = ErrorCode::Fatal;
  17909. return -1;
  17910. }
  17911. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17912. int ret;
  17913. do {
  17914. ret = mbedtls_ssl_write(&msession->ssl,
  17915. static_cast<const unsigned char *>(buf), len);
  17916. } while (impl::mbedtls_is_session_ticket(ret));
  17917. if (ret > 0) {
  17918. err.code = ErrorCode::Success;
  17919. return static_cast<ssize_t>(ret);
  17920. }
  17921. if (ret == 0) {
  17922. err.code = ErrorCode::PeerClosed;
  17923. return 0;
  17924. }
  17925. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17926. err.backend_code = static_cast<uint64_t>(-ret);
  17927. impl::mbedtls_last_error() = ret;
  17928. return -1;
  17929. }
  17930. inline int pending(const_session_t session) {
  17931. if (!session) { return 0; }
  17932. auto msession =
  17933. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17934. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl)) +
  17935. (msession->has_peeked_byte ? 1 : 0);
  17936. }
  17937. inline void shutdown(session_t session, bool graceful) {
  17938. if (!session) { return; }
  17939. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17940. if (graceful) {
  17941. // Try to send close_notify, but don't block forever
  17942. int ret;
  17943. int attempts = 0;
  17944. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  17945. attempts < 3) {
  17946. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  17947. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  17948. break;
  17949. }
  17950. attempts++;
  17951. }
  17952. }
  17953. }
  17954. inline bool is_peer_closed(session_t session, socket_t sock) {
  17955. if (!session || sock == INVALID_SOCKET) { return true; }
  17956. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17957. // Check if there's already decrypted or pushed-back data available.
  17958. // If so, the connection is definitely alive.
  17959. if (msession->has_peeked_byte ||
  17960. mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17961. return false;
  17962. }
  17963. // Set socket to non-blocking to avoid blocking on read
  17964. detail::set_nonblocking(sock, true);
  17965. auto cleanup =
  17966. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17967. // Probe with a 1-byte read (Mbed TLS has no peek API). If the probe lands
  17968. // on application data — e.g. a response that already arrived — push the
  17969. // byte back so the next read() delivers it instead of losing it.
  17970. unsigned char buf;
  17971. int ret;
  17972. do {
  17973. ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  17974. } while (impl::mbedtls_is_session_ticket(ret));
  17975. // If we got data or WANT_READ (would block), connection is alive
  17976. if (ret > 0) {
  17977. msession->peeked_byte = buf;
  17978. msession->has_peeked_byte = true;
  17979. return false;
  17980. }
  17981. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  17982. // If we get a peer close notify or a connection reset, the peer is closed
  17983. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  17984. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  17985. }
  17986. inline cert_t get_peer_cert(const_session_t session) {
  17987. if (!session) { return nullptr; }
  17988. auto msession =
  17989. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17990. // Mbed TLS returns a pointer to the internal peer cert chain.
  17991. // WARNING: This pointer is only valid while the session is active.
  17992. // Do not use the certificate after calling free_session().
  17993. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  17994. return const_cast<mbedtls_x509_crt *>(cert);
  17995. }
  17996. inline size_t get_peer_certs(const_session_t session,
  17997. std::vector<cert_t> &certs) {
  17998. certs.clear();
  17999. // Mbed TLS parses the whole received chain into a list headed by the peer
  18000. // certificate, owned by the session like get_peer_cert()'s result
  18001. for (auto crt = static_cast<mbedtls_x509_crt *>(get_peer_cert(session));
  18002. crt && crt->raw.len > 0; crt = crt->next) {
  18003. certs.push_back(static_cast<cert_t>(crt));
  18004. }
  18005. return certs.size();
  18006. }
  18007. inline void free_cert(cert_t cert) {
  18008. // Mbed TLS: peer certificate is owned by the SSL context.
  18009. // No-op here, but callers should still call this for cross-backend
  18010. // portability.
  18011. (void)cert;
  18012. }
  18013. inline bool verify_hostname(cert_t cert, const char *hostname) {
  18014. if (!cert || !hostname) { return false; }
  18015. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  18016. std::string host_str(hostname);
  18017. // Check if hostname is an IP address (IPv4 or IPv6)
  18018. unsigned char ip_bytes[16];
  18019. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  18020. auto is_ip = ip_len > 0;
  18021. // Check Subject Alternative Names (SAN). Mbed TLS keeps the GeneralName type
  18022. // in buf.tag and the raw value in buf.p / buf.len.
  18023. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  18024. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  18025. const unsigned char *p = san->buf.p;
  18026. size_t len = san->buf.len;
  18027. auto san_type = san->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK;
  18028. if (is_ip) {
  18029. // For an IP host, only a matching iPAddress SAN of the same family
  18030. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  18031. if (san_type == MBEDTLS_X509_SAN_IP_ADDRESS && len == ip_len &&
  18032. memcmp(p, ip_bytes, ip_len) == 0) {
  18033. return true;
  18034. }
  18035. } else if (san_type == MBEDTLS_X509_SAN_DNS_NAME) {
  18036. std::string san_name(reinterpret_cast<const char *>(p), len);
  18037. if (detail::match_hostname(san_name, host_str)) { return true; }
  18038. }
  18039. san = san->next;
  18040. }
  18041. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  18042. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  18043. // the OpenSSL backend's X509_check_ip behaves the same way).
  18044. if (!is_ip) {
  18045. char cn[256];
  18046. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  18047. if (ret > 0) {
  18048. std::string cn_str(cn);
  18049. // Look for "CN=" in the DN string
  18050. size_t cn_pos = cn_str.find("CN=");
  18051. if (cn_pos != std::string::npos) {
  18052. size_t start = cn_pos + 3;
  18053. size_t end = cn_str.find(',', start);
  18054. std::string cn_value =
  18055. cn_str.substr(start, end == std::string::npos ? end : end - start);
  18056. if (detail::match_hostname(cn_value, host_str)) { return true; }
  18057. }
  18058. }
  18059. }
  18060. return false;
  18061. }
  18062. inline uint64_t hostname_mismatch_code() {
  18063. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  18064. }
  18065. inline long get_verify_result(const_session_t session) {
  18066. if (!session) { return -1; }
  18067. auto msession =
  18068. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  18069. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  18070. // Return 0 (X509_V_OK equivalent) if verification passed
  18071. return flags == 0 ? 0 : static_cast<long>(flags);
  18072. }
  18073. inline std::string get_cert_subject_cn(cert_t cert) {
  18074. if (!cert) return "";
  18075. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  18076. // Find the CN in the subject
  18077. const mbedtls_x509_name *name = &x509->subject;
  18078. while (name != nullptr) {
  18079. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  18080. return std::string(reinterpret_cast<const char *>(name->val.p),
  18081. name->val.len);
  18082. }
  18083. name = name->next;
  18084. }
  18085. return "";
  18086. }
  18087. inline std::string get_cert_issuer_name(cert_t cert) {
  18088. if (!cert) return "";
  18089. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  18090. // Build a human-readable issuer name string
  18091. char buf[512];
  18092. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  18093. if (ret < 0) return "";
  18094. return std::string(buf);
  18095. }
  18096. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  18097. sans.clear();
  18098. if (!cert) return false;
  18099. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  18100. // Parse the Subject Alternative Name extension
  18101. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  18102. while (cur != nullptr) {
  18103. if (cur->buf.len > 0) {
  18104. const unsigned char *p = cur->buf.p;
  18105. size_t value_len = cur->buf.len;
  18106. SanEntry entry;
  18107. switch (cur->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK) {
  18108. case MBEDTLS_X509_SAN_DNS_NAME:
  18109. entry.type = SanType::DNS;
  18110. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  18111. break;
  18112. case MBEDTLS_X509_SAN_IP_ADDRESS:
  18113. entry.type = SanType::IP;
  18114. if (value_len == 4) {
  18115. // IPv4
  18116. char buf[16];
  18117. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  18118. entry.value = buf;
  18119. } else if (value_len == 16) {
  18120. // IPv6
  18121. char buf[64];
  18122. snprintf(buf, sizeof(buf),
  18123. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  18124. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  18125. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9],
  18126. p[10], p[11], p[12], p[13], p[14], p[15]);
  18127. entry.value = buf;
  18128. }
  18129. break;
  18130. case MBEDTLS_X509_SAN_RFC822_NAME:
  18131. entry.type = SanType::EMAIL;
  18132. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  18133. break;
  18134. case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER:
  18135. entry.type = SanType::URI;
  18136. entry.value = std::string(reinterpret_cast<const char *>(p), value_len);
  18137. break;
  18138. default: entry.type = SanType::OTHER; break;
  18139. }
  18140. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  18141. }
  18142. cur = cur->next;
  18143. }
  18144. return true;
  18145. }
  18146. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  18147. time_t &not_after) {
  18148. if (!cert) return false;
  18149. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  18150. // Convert mbedtls_x509_time to time_t
  18151. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  18152. struct tm tm_time = {};
  18153. tm_time.tm_year = t.year - 1900;
  18154. tm_time.tm_mon = t.mon - 1;
  18155. tm_time.tm_mday = t.day;
  18156. tm_time.tm_hour = t.hour;
  18157. tm_time.tm_min = t.min;
  18158. tm_time.tm_sec = t.sec;
  18159. #ifdef _WIN32
  18160. return _mkgmtime(&tm_time);
  18161. #else
  18162. return timegm(&tm_time);
  18163. #endif
  18164. };
  18165. not_before = to_time_t(x509->valid_from);
  18166. not_after = to_time_t(x509->valid_to);
  18167. return true;
  18168. }
  18169. inline std::string get_cert_serial(cert_t cert) {
  18170. if (!cert) return "";
  18171. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  18172. // Convert serial number to hex string
  18173. std::string result;
  18174. result.reserve(x509->serial.len * 2);
  18175. for (size_t i = 0; i < x509->serial.len; i++) {
  18176. char hex[3];
  18177. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  18178. result += hex;
  18179. }
  18180. return result;
  18181. }
  18182. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  18183. if (!cert) return false;
  18184. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  18185. if (!crt->raw.p || crt->raw.len == 0) return false;
  18186. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  18187. return true;
  18188. }
  18189. inline const char *get_sni(const_session_t session) {
  18190. if (!session) return nullptr;
  18191. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  18192. // For server: return SNI received from client during handshake
  18193. if (!msession->sni_hostname.empty()) {
  18194. return msession->sni_hostname.c_str();
  18195. }
  18196. // For client: return the hostname set via set_sni
  18197. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  18198. return nullptr;
  18199. }
  18200. inline uint64_t peek_error() {
  18201. // Mbed TLS doesn't have an error queue, return the last error
  18202. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  18203. }
  18204. inline uint64_t get_error() {
  18205. // Mbed TLS doesn't have an error queue, return and clear the last error
  18206. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  18207. impl::mbedtls_last_error() = 0;
  18208. return err;
  18209. }
  18210. inline std::string error_string(uint64_t code) {
  18211. char buf[256];
  18212. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  18213. return std::string(buf);
  18214. }
  18215. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  18216. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  18217. if (!ca_chain) { return nullptr; }
  18218. mbedtls_x509_crt_init(ca_chain);
  18219. // mbedtls_x509_crt_parse expects null-terminated PEM
  18220. int ret = mbedtls_x509_crt_parse(ca_chain,
  18221. reinterpret_cast<const unsigned char *>(pem),
  18222. len + 1); // +1 for null terminator
  18223. if (ret != 0) {
  18224. // Try without +1 in case PEM is already null-terminated
  18225. ret = mbedtls_x509_crt_parse(
  18226. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  18227. if (ret != 0) {
  18228. mbedtls_x509_crt_free(ca_chain);
  18229. delete ca_chain;
  18230. return nullptr;
  18231. }
  18232. }
  18233. return static_cast<ca_store_t>(ca_chain);
  18234. }
  18235. inline void free_ca_store(ca_store_t store) {
  18236. if (store) {
  18237. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  18238. mbedtls_x509_crt_free(ca_chain);
  18239. delete ca_chain;
  18240. }
  18241. }
  18242. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  18243. if (!ctx || !store) { return false; }
  18244. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18245. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  18246. // Free existing CA chain
  18247. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  18248. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  18249. // Copy the CA chain (deep copy)
  18250. // Parse from the raw data of the source cert
  18251. mbedtls_x509_crt *src = ca_chain;
  18252. while (src != nullptr) {
  18253. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  18254. src->raw.len);
  18255. if (ret != 0) {
  18256. free_ca_store(store);
  18257. return false;
  18258. }
  18259. src = src->next;
  18260. }
  18261. // This function takes ownership of the store; the chain was deep-copied
  18262. // above, so release the source
  18263. free_ca_store(store);
  18264. // Update the SSL config to use the new CA chain
  18265. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  18266. return true;
  18267. }
  18268. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  18269. certs.clear();
  18270. if (!ctx) { return 0; }
  18271. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18272. // Iterate through the CA chain
  18273. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  18274. while (cert != nullptr && cert->raw.len > 0) {
  18275. // Create a copy of the certificate for the caller
  18276. auto *copy = new mbedtls_x509_crt;
  18277. mbedtls_x509_crt_init(copy);
  18278. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  18279. if (ret == 0) {
  18280. certs.push_back(static_cast<cert_t>(copy));
  18281. } else {
  18282. mbedtls_x509_crt_free(copy);
  18283. delete copy;
  18284. }
  18285. cert = cert->next;
  18286. }
  18287. return certs.size();
  18288. }
  18289. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  18290. std::vector<std::string> names;
  18291. if (!ctx) { return names; }
  18292. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18293. // Iterate through the CA chain
  18294. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  18295. while (cert != nullptr && cert->raw.len > 0) {
  18296. char buf[512];
  18297. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  18298. if (ret > 0) { names.push_back(buf); }
  18299. cert = cert->next;
  18300. }
  18301. return names;
  18302. }
  18303. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  18304. const char *key_pem, const char *password) {
  18305. if (!ctx || !cert_pem || !key_pem) { return false; }
  18306. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18307. // Free existing certificate and key
  18308. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  18309. mbedtls_pk_free(&mbed_ctx->own_key);
  18310. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  18311. mbedtls_pk_init(&mbed_ctx->own_key);
  18312. // Parse certificate PEM
  18313. int ret = mbedtls_x509_crt_parse(
  18314. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  18315. strlen(cert_pem) + 1);
  18316. if (ret != 0) {
  18317. impl::mbedtls_last_error() = ret;
  18318. return false;
  18319. }
  18320. // Parse private key PEM
  18321. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  18322. ret = mbedtls_pk_parse_key(
  18323. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  18324. strlen(key_pem) + 1,
  18325. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  18326. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  18327. &mbed_ctx->ctr_drbg);
  18328. #else
  18329. ret = mbedtls_pk_parse_key(
  18330. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  18331. strlen(key_pem) + 1,
  18332. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  18333. password ? strlen(password) : 0);
  18334. #endif
  18335. if (ret != 0) {
  18336. impl::mbedtls_last_error() = ret;
  18337. return false;
  18338. }
  18339. // Configure SSL to use the new certificate and key
  18340. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  18341. &mbed_ctx->own_key);
  18342. if (ret != 0) {
  18343. impl::mbedtls_last_error() = ret;
  18344. return false;
  18345. }
  18346. return true;
  18347. }
  18348. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  18349. if (!ctx || !ca_pem) { return false; }
  18350. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18351. // Free existing CA chain
  18352. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  18353. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  18354. // Parse CA PEM
  18355. int ret = mbedtls_x509_crt_parse(
  18356. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  18357. strlen(ca_pem) + 1);
  18358. if (ret != 0) {
  18359. impl::mbedtls_last_error() = ret;
  18360. return false;
  18361. }
  18362. // Update SSL config to use new CA chain
  18363. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  18364. return true;
  18365. }
  18366. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  18367. if (!ctx) { return false; }
  18368. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18369. impl::get_verify_callback() = std::move(callback);
  18370. mbed_ctx->has_verify_callback =
  18371. static_cast<bool>(impl::get_verify_callback());
  18372. if (mbed_ctx->has_verify_callback) {
  18373. // Set OPTIONAL mode to ensure callback is called even when verification
  18374. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  18375. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  18376. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  18377. nullptr);
  18378. } else {
  18379. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  18380. }
  18381. return true;
  18382. }
  18383. inline long get_verify_error(const_session_t session) {
  18384. if (!session) { return -1; }
  18385. auto *msession =
  18386. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  18387. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  18388. }
  18389. inline std::string verify_error_string(long error_code) {
  18390. if (error_code == 0) { return ""; }
  18391. char buf[256];
  18392. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  18393. static_cast<uint32_t>(error_code));
  18394. // Remove trailing newline if present
  18395. std::string result(buf);
  18396. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  18397. result.pop_back();
  18398. }
  18399. return result;
  18400. }
  18401. } // namespace tls
  18402. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  18403. /*
  18404. * Group 10: TLS abstraction layer - wolfSSL backend
  18405. */
  18406. /*
  18407. * wolfSSL Backend Implementation
  18408. */
  18409. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  18410. namespace tls {
  18411. namespace impl {
  18412. // wolfSSL session wrapper
  18413. struct WolfSSLSession {
  18414. WOLFSSL *ssl = nullptr;
  18415. socket_t sock = INVALID_SOCKET;
  18416. std::string hostname; // For client: set via set_sni
  18417. std::string sni_hostname; // For server: received from client via SNI callback
  18418. WolfSSLSession() = default;
  18419. ~WolfSSLSession() {
  18420. if (ssl) { wolfSSL_free(ssl); }
  18421. }
  18422. WolfSSLSession(const WolfSSLSession &) = delete;
  18423. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  18424. };
  18425. // Thread-local error code accessor for wolfSSL
  18426. inline uint64_t &wolfssl_last_error() {
  18427. static thread_local uint64_t err = 0;
  18428. return err;
  18429. }
  18430. // Helper to map wolfSSL error to ErrorCode.
  18431. // ssl_error is the value from wolfSSL_get_error().
  18432. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  18433. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  18434. int &out_errno) {
  18435. switch (ssl_error) {
  18436. case SSL_ERROR_NONE: return ErrorCode::Success;
  18437. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  18438. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  18439. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  18440. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  18441. default:
  18442. if (ssl) {
  18443. // wolfSSL stores the low-level error code as a negative value.
  18444. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  18445. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  18446. if (low_err == DOMAIN_NAME_MISMATCH) {
  18447. return ErrorCode::HostnameMismatch;
  18448. }
  18449. // Check verify result to distinguish cert verification from generic SSL
  18450. // errors.
  18451. long vr = wolfSSL_get_verify_result(ssl);
  18452. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  18453. }
  18454. return ErrorCode::Fatal;
  18455. }
  18456. }
  18457. // WolfSSLContext constructor/destructor implementations
  18458. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  18459. inline WolfSSLContext::~WolfSSLContext() {
  18460. if (ctx) { wolfSSL_CTX_free(ctx); }
  18461. }
  18462. // Thread-local storage for SNI captured during handshake
  18463. inline std::string &wolfssl_pending_sni() {
  18464. static thread_local std::string sni;
  18465. return sni;
  18466. }
  18467. // SNI callback for wolfSSL server to capture client's SNI hostname
  18468. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  18469. (void)ret;
  18470. (void)exArg;
  18471. void *name_data = nullptr;
  18472. unsigned short name_len =
  18473. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  18474. if (name_data && name_len > 0) {
  18475. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  18476. name_len);
  18477. } else {
  18478. wolfssl_pending_sni().clear();
  18479. }
  18480. return 0; // Continue regardless
  18481. }
  18482. // wolfSSL verify callback wrapper
  18483. inline int wolfssl_verify_callback(int preverify_ok,
  18484. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  18485. auto &callback = get_verify_callback();
  18486. if (!callback) { return preverify_ok; }
  18487. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  18488. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  18489. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  18490. // Get the WOLFSSL object from the X509_STORE_CTX
  18491. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  18492. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  18493. VerifyContext verify_ctx;
  18494. verify_ctx.session = static_cast<session_t>(ssl);
  18495. verify_ctx.cert = static_cast<cert_t>(cert);
  18496. verify_ctx.depth = depth;
  18497. verify_ctx.preverify_ok = (preverify_ok != 0);
  18498. verify_ctx.error_code = static_cast<long>(err);
  18499. if (err != 0) {
  18500. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  18501. } else {
  18502. verify_ctx.error_string = nullptr;
  18503. }
  18504. bool accepted = callback(verify_ctx);
  18505. return accepted ? 1 : 0;
  18506. }
  18507. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  18508. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  18509. wolfSSL_CTX_set_default_passwd_cb(
  18510. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  18511. auto *pwd = static_cast<const char *>(userdata);
  18512. if (!pwd) return 0;
  18513. auto len = static_cast<int>(strlen(pwd));
  18514. if (len > size) len = size;
  18515. memcpy(buf, pwd, static_cast<size_t>(len));
  18516. return len;
  18517. });
  18518. }
  18519. } // namespace impl
  18520. inline ctx_t create_client_context() {
  18521. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  18522. if (!ctx) { return nullptr; }
  18523. ctx->is_server = false;
  18524. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  18525. if (!method) {
  18526. delete ctx;
  18527. return nullptr;
  18528. }
  18529. ctx->ctx = wolfSSL_CTX_new(method);
  18530. if (!ctx->ctx) {
  18531. delete ctx;
  18532. return nullptr;
  18533. }
  18534. // Default: verify peer certificate
  18535. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  18536. return static_cast<ctx_t>(ctx);
  18537. }
  18538. inline ctx_t create_server_context() {
  18539. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  18540. if (!ctx) { return nullptr; }
  18541. ctx->is_server = true;
  18542. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  18543. if (!method) {
  18544. delete ctx;
  18545. return nullptr;
  18546. }
  18547. ctx->ctx = wolfSSL_CTX_new(method);
  18548. if (!ctx->ctx) {
  18549. delete ctx;
  18550. return nullptr;
  18551. }
  18552. // Default: don't verify client
  18553. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  18554. // Enable SNI on server
  18555. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  18556. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  18557. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  18558. return static_cast<ctx_t>(ctx);
  18559. }
  18560. inline void free_context(ctx_t ctx) {
  18561. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  18562. }
  18563. inline bool set_min_version(ctx_t ctx, Version version) {
  18564. if (!ctx) { return false; }
  18565. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18566. int min_ver = WOLFSSL_TLSV1_2;
  18567. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  18568. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  18569. }
  18570. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  18571. if (!ctx || !pem) { return false; }
  18572. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18573. int ret = wolfSSL_CTX_load_verify_buffer(
  18574. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  18575. static_cast<long>(len), SSL_FILETYPE_PEM);
  18576. if (ret != SSL_SUCCESS) {
  18577. impl::wolfssl_last_error() =
  18578. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18579. return false;
  18580. }
  18581. wctx->ca_pem_data_.append(pem, len);
  18582. return true;
  18583. }
  18584. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  18585. if (!ctx || !file_path) { return false; }
  18586. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18587. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  18588. if (ret != SSL_SUCCESS) {
  18589. impl::wolfssl_last_error() =
  18590. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18591. return false;
  18592. }
  18593. return true;
  18594. }
  18595. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  18596. if (!ctx || !dir_path) { return false; }
  18597. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18598. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  18599. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  18600. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  18601. // immediately. Return true even on failure since the CA file may have
  18602. // already been loaded, matching OpenSSL's lenient behavior.
  18603. (void)ret;
  18604. return true;
  18605. }
  18606. inline bool load_system_certs(ctx_t ctx) {
  18607. if (!ctx) { return false; }
  18608. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18609. bool loaded = false;
  18610. #ifdef _WIN32
  18611. loaded = impl::enumerate_windows_system_certs(
  18612. [&](const unsigned char *data, size_t len) {
  18613. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  18614. static_cast<long>(len),
  18615. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  18616. });
  18617. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  18618. loaded = impl::enumerate_macos_keychain_certs(
  18619. [&](const unsigned char *data, size_t len) {
  18620. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  18621. static_cast<long>(len),
  18622. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  18623. });
  18624. #else
  18625. for (auto path = impl::system_ca_paths(); *path; ++path) {
  18626. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  18627. SSL_SUCCESS) {
  18628. loaded = true;
  18629. break;
  18630. }
  18631. }
  18632. if (!loaded) {
  18633. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  18634. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  18635. SSL_SUCCESS) {
  18636. loaded = true;
  18637. break;
  18638. }
  18639. }
  18640. }
  18641. #endif
  18642. return loaded;
  18643. }
  18644. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  18645. const char *password) {
  18646. if (!ctx || !cert || !key) { return false; }
  18647. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18648. // Load certificate
  18649. int ret = wolfSSL_CTX_use_certificate_buffer(
  18650. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  18651. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  18652. if (ret != SSL_SUCCESS) {
  18653. impl::wolfssl_last_error() =
  18654. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18655. return false;
  18656. }
  18657. // Set password callback if password is provided
  18658. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18659. // Load private key
  18660. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  18661. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  18662. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  18663. if (ret != SSL_SUCCESS) {
  18664. impl::wolfssl_last_error() =
  18665. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18666. return false;
  18667. }
  18668. // Verify that the certificate and private key match
  18669. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  18670. }
  18671. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  18672. const char *key_path, const char *password) {
  18673. if (!ctx || !cert_path || !key_path) { return false; }
  18674. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18675. // Load certificate file
  18676. int ret =
  18677. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  18678. if (ret != SSL_SUCCESS) {
  18679. impl::wolfssl_last_error() =
  18680. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18681. return false;
  18682. }
  18683. // Set password callback if password is provided
  18684. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18685. // Load private key file
  18686. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  18687. if (ret != SSL_SUCCESS) {
  18688. impl::wolfssl_last_error() =
  18689. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18690. return false;
  18691. }
  18692. // Verify that the certificate and private key match
  18693. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  18694. }
  18695. inline void set_verify_client(ctx_t ctx, bool require) {
  18696. if (!ctx) { return; }
  18697. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18698. wctx->verify_client = require;
  18699. if (require) {
  18700. wolfSSL_CTX_set_verify(
  18701. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  18702. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  18703. } else {
  18704. if (wctx->has_verify_callback) {
  18705. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  18706. impl::wolfssl_verify_callback);
  18707. } else {
  18708. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  18709. }
  18710. }
  18711. }
  18712. inline session_t create_session(ctx_t ctx, socket_t sock) {
  18713. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  18714. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18715. auto session = new (std::nothrow) impl::WolfSSLSession();
  18716. if (!session) { return nullptr; }
  18717. session->sock = sock;
  18718. session->ssl = wolfSSL_new(wctx->ctx);
  18719. if (!session->ssl) {
  18720. impl::wolfssl_last_error() =
  18721. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18722. delete session;
  18723. return nullptr;
  18724. }
  18725. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  18726. return static_cast<session_t>(session);
  18727. }
  18728. inline void free_session(session_t session) {
  18729. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  18730. }
  18731. inline bool set_sni(session_t session, const char *hostname,
  18732. bool verify_hostname) {
  18733. if (!session || !hostname) { return false; }
  18734. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18735. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  18736. static_cast<word16>(strlen(hostname)));
  18737. if (ret != WOLFSSL_SUCCESS) {
  18738. impl::wolfssl_last_error() =
  18739. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18740. return false;
  18741. }
  18742. // wolfSSL_check_domain_name binds identity checking to the handshake,
  18743. // separately from the SNI extension sent above; skip it when hostname
  18744. // verification is disabled so only the chain is checked, matching OpenSSL.
  18745. if (verify_hostname) { wolfSSL_check_domain_name(wsession->ssl, hostname); }
  18746. wsession->hostname = hostname;
  18747. return true;
  18748. }
  18749. inline TlsError connect(session_t session) {
  18750. TlsError err;
  18751. if (!session) {
  18752. err.code = ErrorCode::Fatal;
  18753. return err;
  18754. }
  18755. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18756. int ret = wolfSSL_connect(wsession->ssl);
  18757. if (ret == SSL_SUCCESS) {
  18758. err.code = ErrorCode::Success;
  18759. } else {
  18760. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18761. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18762. err.backend_code = static_cast<uint64_t>(ssl_error);
  18763. impl::wolfssl_last_error() = err.backend_code;
  18764. }
  18765. return err;
  18766. }
  18767. inline TlsError accept(session_t session) {
  18768. TlsError err;
  18769. if (!session) {
  18770. err.code = ErrorCode::Fatal;
  18771. return err;
  18772. }
  18773. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18774. int ret = wolfSSL_accept(wsession->ssl);
  18775. if (ret == SSL_SUCCESS) {
  18776. err.code = ErrorCode::Success;
  18777. // Capture SNI from thread-local storage after successful handshake
  18778. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  18779. impl::wolfssl_pending_sni().clear();
  18780. } else {
  18781. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18782. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18783. err.backend_code = static_cast<uint64_t>(ssl_error);
  18784. impl::wolfssl_last_error() = err.backend_code;
  18785. }
  18786. return err;
  18787. }
  18788. inline bool connect_nonblocking(session_t session, socket_t sock,
  18789. time_t timeout_sec, time_t timeout_usec,
  18790. TlsError *err) {
  18791. if (!session) {
  18792. if (err) { err->code = ErrorCode::Fatal; }
  18793. return false;
  18794. }
  18795. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18796. // Set socket to non-blocking mode
  18797. detail::set_nonblocking(sock, true);
  18798. auto cleanup =
  18799. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18800. int ret;
  18801. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  18802. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18803. if (ssl_error == SSL_ERROR_WANT_READ) {
  18804. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  18805. continue;
  18806. }
  18807. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18808. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18809. continue;
  18810. }
  18811. }
  18812. // Error or timeout
  18813. if (err) {
  18814. err->code =
  18815. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18816. err->backend_code = static_cast<uint64_t>(ssl_error);
  18817. }
  18818. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18819. return false;
  18820. }
  18821. if (err) { err->code = ErrorCode::Success; }
  18822. return true;
  18823. }
  18824. inline bool accept_nonblocking(session_t session, socket_t sock,
  18825. time_t timeout_sec, time_t timeout_usec,
  18826. TlsError *err) {
  18827. if (!session) {
  18828. if (err) { err->code = ErrorCode::Fatal; }
  18829. return false;
  18830. }
  18831. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18832. // Set socket to non-blocking mode
  18833. detail::set_nonblocking(sock, true);
  18834. auto cleanup =
  18835. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18836. int ret;
  18837. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  18838. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18839. if (ssl_error == SSL_ERROR_WANT_READ) {
  18840. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  18841. continue;
  18842. }
  18843. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18844. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18845. continue;
  18846. }
  18847. }
  18848. // Error or timeout
  18849. if (err) {
  18850. err->code =
  18851. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18852. err->backend_code = static_cast<uint64_t>(ssl_error);
  18853. }
  18854. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18855. return false;
  18856. }
  18857. if (err) { err->code = ErrorCode::Success; }
  18858. // Capture SNI from thread-local storage after successful handshake
  18859. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  18860. impl::wolfssl_pending_sni().clear();
  18861. return true;
  18862. }
  18863. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  18864. if (!session || !buf) {
  18865. err.code = ErrorCode::Fatal;
  18866. return -1;
  18867. }
  18868. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18869. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  18870. if (ret > 0) {
  18871. err.code = ErrorCode::Success;
  18872. return static_cast<ssize_t>(ret);
  18873. }
  18874. if (ret == 0) {
  18875. err.code = ErrorCode::PeerClosed;
  18876. return 0;
  18877. }
  18878. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18879. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18880. err.backend_code = static_cast<uint64_t>(ssl_error);
  18881. impl::wolfssl_last_error() = err.backend_code;
  18882. return -1;
  18883. }
  18884. inline ssize_t write(session_t session, const void *buf, size_t len,
  18885. TlsError &err) {
  18886. if (!session || !buf) {
  18887. err.code = ErrorCode::Fatal;
  18888. return -1;
  18889. }
  18890. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18891. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  18892. if (ret > 0) {
  18893. err.code = ErrorCode::Success;
  18894. return static_cast<ssize_t>(ret);
  18895. }
  18896. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  18897. // Treat this as an error (return -1) so callers don't spin in a
  18898. // write loop adding zero to the offset.
  18899. if (ret == 0) {
  18900. err.code = ErrorCode::PeerClosed;
  18901. return -1;
  18902. }
  18903. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18904. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18905. err.backend_code = static_cast<uint64_t>(ssl_error);
  18906. impl::wolfssl_last_error() = err.backend_code;
  18907. return -1;
  18908. }
  18909. inline int pending(const_session_t session) {
  18910. if (!session) { return 0; }
  18911. auto wsession =
  18912. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18913. return wolfSSL_pending(wsession->ssl);
  18914. }
  18915. inline void shutdown(session_t session, bool graceful) {
  18916. if (!session) { return; }
  18917. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18918. if (graceful) {
  18919. int ret;
  18920. int attempts = 0;
  18921. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  18922. attempts < 3) {
  18923. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18924. if (ssl_error != SSL_ERROR_WANT_READ &&
  18925. ssl_error != SSL_ERROR_WANT_WRITE) {
  18926. break;
  18927. }
  18928. attempts++;
  18929. }
  18930. } else {
  18931. wolfSSL_shutdown(wsession->ssl);
  18932. }
  18933. }
  18934. inline bool is_peer_closed(session_t session, socket_t sock) {
  18935. if (!session || sock == INVALID_SOCKET) { return true; }
  18936. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18937. // Check if there's already decrypted data available
  18938. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  18939. // Set socket to non-blocking to avoid blocking on read
  18940. detail::set_nonblocking(sock, true);
  18941. auto cleanup =
  18942. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18943. // Peek 1 byte to check connection status without consuming data
  18944. unsigned char buf;
  18945. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  18946. // If we got data or WANT_READ (would block), connection is alive
  18947. if (ret > 0) { return false; }
  18948. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18949. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  18950. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  18951. ret == 0;
  18952. }
  18953. inline cert_t get_peer_cert(const_session_t session) {
  18954. if (!session) { return nullptr; }
  18955. auto wsession =
  18956. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18957. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  18958. return static_cast<cert_t>(cert);
  18959. }
  18960. inline size_t get_peer_certs(const_session_t session,
  18961. std::vector<cert_t> &certs) {
  18962. certs.clear();
  18963. if (!session) { return 0; }
  18964. // wolfSSL keeps the received chain only when built with SESSION_CERTS
  18965. #ifdef SESSION_CERTS
  18966. auto wsession =
  18967. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18968. auto chain = wolfSSL_get_peer_chain(wsession->ssl);
  18969. auto count = chain ? wolfSSL_get_chain_count(chain) : 0;
  18970. for (int i = 0; i < count; i++) {
  18971. auto x509 = wolfSSL_get_chain_X509(chain, i);
  18972. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  18973. }
  18974. #endif
  18975. return certs.size();
  18976. }
  18977. inline void free_cert(cert_t cert) {
  18978. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  18979. }
  18980. inline bool verify_hostname(cert_t cert, const char *hostname) {
  18981. if (!cert || !hostname) { return false; }
  18982. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18983. std::string host_str(hostname);
  18984. // Check if hostname is an IP address (IPv4 or IPv6)
  18985. unsigned char ip_bytes[16];
  18986. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  18987. auto is_ip = ip_len > 0;
  18988. // Check Subject Alternative Names
  18989. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  18990. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18991. if (san_names) {
  18992. int san_count = wolfSSL_sk_num(san_names);
  18993. for (int i = 0; i < san_count; i++) {
  18994. auto *names =
  18995. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  18996. if (!names) continue;
  18997. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  18998. // DNS name
  18999. unsigned char *dns_name = nullptr;
  19000. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  19001. if (dns_name && dns_len > 0) {
  19002. std::string san_name(reinterpret_cast<char *>(dns_name),
  19003. static_cast<size_t>(dns_len));
  19004. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  19005. if (detail::match_hostname(san_name, host_str)) {
  19006. wolfSSL_sk_free(san_names);
  19007. return true;
  19008. }
  19009. }
  19010. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  19011. // IP address: only an iPAddress SAN of the same family (4 bytes for
  19012. // IPv4, 16 bytes for IPv6) may authenticate the host.
  19013. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  19014. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  19015. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  19016. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  19017. wolfSSL_sk_free(san_names);
  19018. return true;
  19019. }
  19020. }
  19021. }
  19022. wolfSSL_sk_free(san_names);
  19023. }
  19024. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  19025. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  19026. // the OpenSSL backend's X509_check_ip behaves the same way).
  19027. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  19028. if (subject) {
  19029. char cn[256] = {};
  19030. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  19031. sizeof(cn));
  19032. if (cn_len > 0) {
  19033. std::string cn_str(cn, static_cast<size_t>(cn_len));
  19034. if (detail::match_hostname(cn_str, host_str)) { return true; }
  19035. }
  19036. }
  19037. return false;
  19038. }
  19039. inline uint64_t hostname_mismatch_code() {
  19040. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  19041. }
  19042. inline long get_verify_result(const_session_t session) {
  19043. if (!session) { return -1; }
  19044. auto wsession =
  19045. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  19046. long result = wolfSSL_get_verify_result(wsession->ssl);
  19047. return result;
  19048. }
  19049. inline std::string get_cert_subject_cn(cert_t cert) {
  19050. if (!cert) return "";
  19051. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  19052. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  19053. if (!subject) return "";
  19054. char cn[256] = {};
  19055. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  19056. sizeof(cn));
  19057. if (cn_len <= 0) return "";
  19058. return std::string(cn, static_cast<size_t>(cn_len));
  19059. }
  19060. inline std::string get_cert_issuer_name(cert_t cert) {
  19061. if (!cert) return "";
  19062. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  19063. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  19064. if (!issuer) return "";
  19065. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  19066. if (!name_str) return "";
  19067. std::string result(name_str);
  19068. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  19069. return result;
  19070. }
  19071. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  19072. sans.clear();
  19073. if (!cert) return false;
  19074. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  19075. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  19076. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  19077. if (!san_names) return true; // No SANs is not an error
  19078. int count = wolfSSL_sk_num(san_names);
  19079. for (int i = 0; i < count; i++) {
  19080. auto *name =
  19081. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  19082. if (!name) continue;
  19083. SanEntry entry;
  19084. switch (name->type) {
  19085. case WOLFSSL_GEN_DNS: {
  19086. entry.type = SanType::DNS;
  19087. unsigned char *dns_name = nullptr;
  19088. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  19089. if (dns_name && dns_len > 0) {
  19090. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  19091. static_cast<size_t>(dns_len));
  19092. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  19093. }
  19094. break;
  19095. }
  19096. case WOLFSSL_GEN_IPADD: {
  19097. entry.type = SanType::IP;
  19098. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  19099. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  19100. if (ip_data && ip_len == 4) {
  19101. char buf[16];
  19102. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  19103. ip_data[2], ip_data[3]);
  19104. entry.value = buf;
  19105. } else if (ip_data && ip_len == 16) {
  19106. char buf[64];
  19107. snprintf(buf, sizeof(buf),
  19108. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  19109. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  19110. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  19111. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  19112. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  19113. ip_data[14], ip_data[15]);
  19114. entry.value = buf;
  19115. }
  19116. break;
  19117. }
  19118. case WOLFSSL_GEN_EMAIL:
  19119. entry.type = SanType::EMAIL;
  19120. {
  19121. unsigned char *email = nullptr;
  19122. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  19123. if (email && email_len > 0) {
  19124. entry.value = std::string(reinterpret_cast<char *>(email),
  19125. static_cast<size_t>(email_len));
  19126. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  19127. }
  19128. }
  19129. break;
  19130. case WOLFSSL_GEN_URI:
  19131. entry.type = SanType::URI;
  19132. {
  19133. unsigned char *uri = nullptr;
  19134. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  19135. &uri, name->d.uniformResourceIdentifier);
  19136. if (uri && uri_len > 0) {
  19137. entry.value = std::string(reinterpret_cast<char *>(uri),
  19138. static_cast<size_t>(uri_len));
  19139. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  19140. }
  19141. }
  19142. break;
  19143. default: entry.type = SanType::OTHER; break;
  19144. }
  19145. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  19146. }
  19147. wolfSSL_sk_free(san_names);
  19148. return true;
  19149. }
  19150. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  19151. time_t &not_after) {
  19152. if (!cert) return false;
  19153. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  19154. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  19155. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  19156. if (!nb || !na) return false;
  19157. // wolfSSL_ASN1_TIME_to_tm is available
  19158. struct tm tm_nb = {}, tm_na = {};
  19159. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  19160. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  19161. #ifdef _WIN32
  19162. not_before = _mkgmtime(&tm_nb);
  19163. not_after = _mkgmtime(&tm_na);
  19164. #else
  19165. not_before = timegm(&tm_nb);
  19166. not_after = timegm(&tm_na);
  19167. #endif
  19168. return true;
  19169. }
  19170. inline std::string get_cert_serial(cert_t cert) {
  19171. if (!cert) return "";
  19172. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  19173. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  19174. if (!serial_asn1) return "";
  19175. // Get the serial number data
  19176. int len = serial_asn1->length;
  19177. unsigned char *data = serial_asn1->data;
  19178. if (!data || len <= 0) return "";
  19179. std::string result;
  19180. result.reserve(static_cast<size_t>(len) * 2);
  19181. for (int i = 0; i < len; i++) {
  19182. char hex[3];
  19183. snprintf(hex, sizeof(hex), "%02X", data[i]);
  19184. result += hex;
  19185. }
  19186. return result;
  19187. }
  19188. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  19189. if (!cert) return false;
  19190. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  19191. int der_len = 0;
  19192. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  19193. if (!der_data || der_len <= 0) return false;
  19194. der.assign(der_data, der_data + der_len);
  19195. return true;
  19196. }
  19197. inline const char *get_sni(const_session_t session) {
  19198. if (!session) return nullptr;
  19199. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  19200. // For server: return SNI received from client during handshake
  19201. if (!wsession->sni_hostname.empty()) {
  19202. return wsession->sni_hostname.c_str();
  19203. }
  19204. // For client: return the hostname set via set_sni
  19205. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  19206. return nullptr;
  19207. }
  19208. inline uint64_t peek_error() {
  19209. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  19210. }
  19211. inline uint64_t get_error() {
  19212. uint64_t err = impl::wolfssl_last_error();
  19213. impl::wolfssl_last_error() = 0;
  19214. return err;
  19215. }
  19216. inline std::string error_string(uint64_t code) {
  19217. char buf[256];
  19218. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  19219. return std::string(buf);
  19220. }
  19221. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  19222. if (!pem || len == 0) { return nullptr; }
  19223. // Validate by attempting to load into a temporary ctx
  19224. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  19225. if (!tmp_ctx) { return nullptr; }
  19226. int ret = wolfSSL_CTX_load_verify_buffer(
  19227. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  19228. static_cast<long>(len), SSL_FILETYPE_PEM);
  19229. wolfSSL_CTX_free(tmp_ctx);
  19230. if (ret != SSL_SUCCESS) { return nullptr; }
  19231. return static_cast<ca_store_t>(
  19232. new impl::WolfSSLCAStore{std::string(pem, len)});
  19233. }
  19234. inline void free_ca_store(ca_store_t store) {
  19235. delete static_cast<impl::WolfSSLCAStore *>(store);
  19236. }
  19237. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  19238. if (!ctx || !store) { return false; }
  19239. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19240. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  19241. int ret = wolfSSL_CTX_load_verify_buffer(
  19242. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  19243. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  19244. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  19245. // This function takes ownership of the store; the PEM data was copied into
  19246. // the context, so release the source
  19247. free_ca_store(store);
  19248. return ret == SSL_SUCCESS;
  19249. }
  19250. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  19251. certs.clear();
  19252. if (!ctx) { return 0; }
  19253. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19254. if (wctx->ca_pem_data_.empty()) { return 0; }
  19255. const std::string &pem = wctx->ca_pem_data_;
  19256. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  19257. const std::string end_marker = "-----END CERTIFICATE-----";
  19258. size_t pos = 0;
  19259. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  19260. size_t end_pos = pem.find(end_marker, pos);
  19261. if (end_pos == std::string::npos) { break; }
  19262. end_pos += end_marker.size();
  19263. std::string cert_pem = pem.substr(pos, end_pos - pos);
  19264. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  19265. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  19266. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  19267. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  19268. pos = end_pos;
  19269. }
  19270. return certs.size();
  19271. }
  19272. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  19273. std::vector<std::string> names;
  19274. if (!ctx) { return names; }
  19275. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19276. if (wctx->ca_pem_data_.empty()) { return names; }
  19277. const std::string &pem = wctx->ca_pem_data_;
  19278. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  19279. const std::string end_marker = "-----END CERTIFICATE-----";
  19280. size_t pos = 0;
  19281. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  19282. size_t end_pos = pem.find(end_marker, pos);
  19283. if (end_pos == std::string::npos) { break; }
  19284. end_pos += end_marker.size();
  19285. std::string cert_pem = pem.substr(pos, end_pos - pos);
  19286. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  19287. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  19288. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  19289. if (x509) {
  19290. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  19291. if (subject) {
  19292. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  19293. if (name_str) {
  19294. names.push_back(name_str);
  19295. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  19296. }
  19297. }
  19298. wolfSSL_X509_free(x509);
  19299. }
  19300. pos = end_pos;
  19301. }
  19302. return names;
  19303. }
  19304. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  19305. const char *key_pem, const char *password) {
  19306. if (!ctx || !cert_pem || !key_pem) { return false; }
  19307. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19308. // Load new certificate
  19309. int ret = wolfSSL_CTX_use_certificate_buffer(
  19310. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  19311. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  19312. if (ret != SSL_SUCCESS) {
  19313. impl::wolfssl_last_error() =
  19314. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  19315. return false;
  19316. }
  19317. // Set password if provided
  19318. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  19319. // Load new private key
  19320. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  19321. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  19322. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  19323. if (ret != SSL_SUCCESS) {
  19324. impl::wolfssl_last_error() =
  19325. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  19326. return false;
  19327. }
  19328. return true;
  19329. }
  19330. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  19331. if (!ctx || !ca_pem) { return false; }
  19332. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19333. int ret = wolfSSL_CTX_load_verify_buffer(
  19334. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  19335. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  19336. if (ret != SSL_SUCCESS) {
  19337. impl::wolfssl_last_error() =
  19338. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  19339. return false;
  19340. }
  19341. return true;
  19342. }
  19343. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  19344. if (!ctx) { return false; }
  19345. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19346. impl::get_verify_callback() = std::move(callback);
  19347. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  19348. if (wctx->has_verify_callback) {
  19349. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  19350. impl::wolfssl_verify_callback);
  19351. } else {
  19352. wolfSSL_CTX_set_verify(
  19353. wctx->ctx,
  19354. wctx->verify_client
  19355. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  19356. : SSL_VERIFY_NONE,
  19357. nullptr);
  19358. }
  19359. return true;
  19360. }
  19361. inline long get_verify_error(const_session_t session) {
  19362. if (!session) { return -1; }
  19363. auto *wsession =
  19364. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  19365. return wolfSSL_get_verify_result(wsession->ssl);
  19366. }
  19367. inline std::string verify_error_string(long error_code) {
  19368. if (error_code == 0) { return ""; }
  19369. const char *str =
  19370. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  19371. return str ? std::string(str) : std::string();
  19372. }
  19373. } // namespace tls
  19374. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  19375. // WebSocket implementation
  19376. namespace ws {
  19377. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  19378. bool fin) {
  19379. std::lock_guard<std::mutex> lock(write_mutex_);
  19380. if (closed_) { return false; }
  19381. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  19382. }
  19383. inline ReadResult WebSocket::read(std::string &msg) {
  19384. std::unique_lock<std::mutex> read_lock(read_mutex_);
  19385. while (!closed_) {
  19386. Opcode opcode;
  19387. std::string payload;
  19388. bool fin;
  19389. impl::FrameRead r =
  19390. impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  19391. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH);
  19392. // A timeout landed on a frame boundary: the connection is untouched and
  19393. // still usable, so hand control back without closing it. That is only
  19394. // useful to a caller who asked for the timeout; the compile-time default
  19395. // is a backstop against a peer gone quiet, and elapsing it closes the
  19396. // connection so a plain `while (ws.read(msg))` loop ends.
  19397. if (r == impl::FrameRead::Timeout && read_timeout_set_) { return Timeout; }
  19398. if (r != impl::FrameRead::Ok) {
  19399. closed_ = true;
  19400. return Fail;
  19401. }
  19402. switch (opcode) {
  19403. case Opcode::Ping: {
  19404. std::lock_guard<std::mutex> lock(write_mutex_);
  19405. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  19406. payload.size(), true, !is_server_);
  19407. continue;
  19408. }
  19409. case Opcode::Pong: {
  19410. std::lock_guard<std::mutex> lock(ping_mutex_);
  19411. unacked_pings_ = 0;
  19412. continue;
  19413. }
  19414. case Opcode::Close: {
  19415. if (!closed_.exchange(true)) {
  19416. // Echo close frame back
  19417. std::lock_guard<std::mutex> lock(write_mutex_);
  19418. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  19419. payload.size(), true, !is_server_);
  19420. }
  19421. return Fail;
  19422. }
  19423. case Opcode::Text:
  19424. case Opcode::Binary: {
  19425. auto result = opcode == Opcode::Text ? Text : Binary;
  19426. msg = std::move(payload);
  19427. // Handle fragmentation
  19428. if (!fin) {
  19429. while (true) {
  19430. Opcode cont_opcode;
  19431. std::string cont_payload;
  19432. bool cont_fin;
  19433. // A timeout is not reportable here: half of a fragmented message is
  19434. // already in `msg` and read() has no way to resume it, so it is a
  19435. // failure like any other. Timeouts are only ever seen on a message
  19436. // boundary.
  19437. if (impl::read_websocket_frame(
  19438. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  19439. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) !=
  19440. impl::FrameRead::Ok) {
  19441. closed_ = true;
  19442. return Fail;
  19443. }
  19444. if (cont_opcode == Opcode::Ping) {
  19445. std::lock_guard<std::mutex> lock(write_mutex_);
  19446. detail::write_websocket_frame(
  19447. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  19448. true, !is_server_);
  19449. continue;
  19450. }
  19451. if (cont_opcode == Opcode::Pong) {
  19452. std::lock_guard<std::mutex> lock(ping_mutex_);
  19453. unacked_pings_ = 0;
  19454. continue;
  19455. }
  19456. if (cont_opcode == Opcode::Close) {
  19457. if (!closed_.exchange(true)) {
  19458. std::lock_guard<std::mutex> lock(write_mutex_);
  19459. detail::write_websocket_frame(
  19460. strm_, Opcode::Close, cont_payload.data(),
  19461. cont_payload.size(), true, !is_server_);
  19462. }
  19463. return Fail;
  19464. }
  19465. // RFC 6455: continuation frames must use opcode 0x0
  19466. if (cont_opcode != Opcode::Continuation) {
  19467. closed_ = true;
  19468. return Fail;
  19469. }
  19470. msg += cont_payload;
  19471. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  19472. closed_ = true;
  19473. return Fail;
  19474. }
  19475. if (cont_fin) { break; }
  19476. }
  19477. }
  19478. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  19479. if (result == Text && !impl::is_valid_utf8(msg)) {
  19480. // close() takes the read lock to wait for the peer's Close reply, so
  19481. // it must not run while this thread still holds it.
  19482. read_lock.unlock();
  19483. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  19484. return Fail;
  19485. }
  19486. return result;
  19487. }
  19488. default: closed_ = true; return Fail;
  19489. }
  19490. }
  19491. return Fail;
  19492. }
  19493. inline bool WebSocket::send(const std::string &data) {
  19494. return send_frame(Opcode::Text, data.data(), data.size());
  19495. }
  19496. inline bool WebSocket::send(const char *data, size_t len) {
  19497. return send_frame(Opcode::Binary, data, len);
  19498. }
  19499. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  19500. if (closed_.exchange(true)) { return; }
  19501. ping_cv_.notify_all();
  19502. std::string payload;
  19503. auto code = static_cast<uint16_t>(status);
  19504. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  19505. payload.push_back(static_cast<char>(code & 0xFF));
  19506. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  19507. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  19508. payload += reason.substr(0, 123);
  19509. {
  19510. std::lock_guard<std::mutex> lock(write_mutex_);
  19511. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  19512. payload.size(), true, !is_server_);
  19513. }
  19514. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  19515. // Close response before closing the TCP connection.
  19516. //
  19517. // Wait only when no other thread is parsing frames. When one is, it is the
  19518. // thread positioned to see the peer's reply, and reading here would take
  19519. // bytes out of the message it is assembling. Bailing out also leaves the
  19520. // stream, including its read timeout, entirely to that thread.
  19521. std::unique_lock<std::mutex> read_lock(read_mutex_, std::try_to_lock);
  19522. if (!read_lock.owns_lock()) { return; }
  19523. // Use a short timeout to avoid hanging if the peer doesn't respond.
  19524. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  19525. Opcode op;
  19526. std::string resp;
  19527. bool fin;
  19528. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125) ==
  19529. impl::FrameRead::Ok) {
  19530. if (op == Opcode::Close) { break; }
  19531. }
  19532. }
  19533. inline WebSocket::~WebSocket() {
  19534. {
  19535. std::lock_guard<std::mutex> lock(ping_mutex_);
  19536. closed_ = true;
  19537. }
  19538. ping_cv_.notify_all();
  19539. if (ping_thread_.joinable()) { ping_thread_.join(); }
  19540. }
  19541. inline void WebSocket::start_heartbeat() {
  19542. if (ping_interval_sec_ == 0) { return; }
  19543. ping_thread_ = std::thread([this]() {
  19544. std::unique_lock<std::mutex> lock(ping_mutex_);
  19545. // The predicate keeps a spurious wakeup from sending a ping early
  19546. while (!ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_),
  19547. [this]() { return closed_.load(); })) {
  19548. // If the peer has failed to respond to the previous pings, give up.
  19549. // RFC 6455 does not define a pong-timeout mechanism; this is an
  19550. // opt-in liveness check controlled by max_missed_pongs_.
  19551. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  19552. lock.unlock();
  19553. close(CloseStatus::GoingAway, "pong timeout");
  19554. // Wake a read() blocked on the unresponsive peer. Only the read side
  19555. // is shut down: a TLS backend answers the EOF with an alert, and
  19556. // writing it to a socket closed for writing raises SIGPIPE.
  19557. #ifdef _WIN32
  19558. shutdown(strm_.socket(), SD_RECEIVE);
  19559. #else
  19560. shutdown(strm_.socket(), SHUT_RD);
  19561. #endif
  19562. return;
  19563. }
  19564. lock.unlock();
  19565. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  19566. lock.lock();
  19567. closed_ = true;
  19568. break;
  19569. }
  19570. lock.lock();
  19571. unacked_pings_++;
  19572. }
  19573. });
  19574. }
  19575. inline const Request &WebSocket::request() const { return req_; }
  19576. inline bool WebSocket::is_open() const { return !closed_; }
  19577. inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
  19578. // 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
  19579. // poll(), where 0 would instead mean "return immediately", so hand it the
  19580. // negative poll uses for an unbounded wait.
  19581. if (sec == 0 && usec == 0) { sec = -1; }
  19582. strm_.set_read_timeout(sec, usec);
  19583. read_timeout_set_ = true;
  19584. }
  19585. // WebSocketClient implementation
  19586. inline WebSocketClient::WebSocketClient(
  19587. const std::string &scheme_host_port_path, const Headers &headers)
  19588. : headers_(headers) {
  19589. detail::UrlComponents uc;
  19590. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  19591. !uc.host.empty() && !uc.path.empty()) {
  19592. auto &scheme = uc.scheme;
  19593. #ifdef CPPHTTPLIB_SSL_ENABLED
  19594. if (scheme != "ws" && scheme != "wss") {
  19595. #else
  19596. if (scheme != "ws") {
  19597. #endif
  19598. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  19599. std::string msg = "'" + scheme + "' scheme is not supported.";
  19600. throw std::invalid_argument(msg);
  19601. #endif
  19602. return;
  19603. }
  19604. auto is_ssl = scheme == "wss";
  19605. host_ = std::move(uc.host);
  19606. port_ = is_ssl ? 443 : 80;
  19607. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  19608. path_ = std::move(uc.path);
  19609. if (!uc.query.empty()) { path_ += uc.query; }
  19610. #ifdef CPPHTTPLIB_SSL_ENABLED
  19611. is_ssl_ = is_ssl;
  19612. if (is_ssl_) {
  19613. // The context lives as long as the client so that CA configuration
  19614. // survives reconnects; sessions are created per connection.
  19615. tls_ctx_ = tls::create_client_context();
  19616. if (!tls_ctx_) { return; }
  19617. }
  19618. #else
  19619. if (is_ssl) { return; }
  19620. #endif
  19621. is_valid_ = true;
  19622. }
  19623. }
  19624. #ifdef CPPHTTPLIB_SSL_ENABLED
  19625. inline WebSocketClient::WebSocketClient(
  19626. const std::string &scheme_host_port_path, const PemMemory &pem,
  19627. const Headers &headers)
  19628. : WebSocketClient(scheme_host_port_path, headers) {
  19629. // For ws:// URLs the client certificate is silently ignored, consistent
  19630. // with the TLS-only setters such as set_ca_cert_path().
  19631. if (is_valid_ && is_ssl_ && pem.cert_pem && pem.key_pem) {
  19632. if (!tls::set_client_cert_pem(tls_ctx_, pem.cert_pem, pem.key_pem,
  19633. pem.private_key_password)) {
  19634. tls::free_context(tls_ctx_);
  19635. tls_ctx_ = nullptr;
  19636. is_valid_ = false;
  19637. }
  19638. }
  19639. }
  19640. #endif
  19641. inline WebSocketClient::~WebSocketClient() {
  19642. shutdown_and_close();
  19643. #ifdef CPPHTTPLIB_SSL_ENABLED
  19644. if (tls_ctx_) {
  19645. tls::free_context(tls_ctx_);
  19646. tls_ctx_ = nullptr;
  19647. }
  19648. #endif
  19649. }
  19650. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  19651. inline void WebSocketClient::shutdown_and_close() {
  19652. // Send the close frame while the TLS session is still alive: ws_ holds an
  19653. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  19654. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  19655. if (ws_ && ws_->is_open()) { ws_->close(); }
  19656. ws_.reset();
  19657. #ifdef CPPHTTPLIB_SSL_ENABLED
  19658. if (is_ssl_) {
  19659. if (tls_session_) {
  19660. tls::shutdown(tls_session_, true);
  19661. tls::free_session(tls_session_);
  19662. tls_session_ = nullptr;
  19663. }
  19664. }
  19665. #endif
  19666. if (sock_ != INVALID_SOCKET) {
  19667. detail::shutdown_socket(sock_);
  19668. detail::close_socket(sock_);
  19669. sock_ = INVALID_SOCKET;
  19670. }
  19671. }
  19672. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm,
  19673. Error &error, int &ssl_error,
  19674. uint64_t &ssl_backend_error) {
  19675. // A read timeout of 0 means "wait forever", the way SO_RCVTIMEO reads it.
  19676. // The streams wait with poll(), where 0 instead means "return immediately",
  19677. // so they are given the negative poll uses for an unbounded wait.
  19678. auto unbounded = read_timeout_sec_ == 0 && read_timeout_usec_ == 0;
  19679. time_t strm_read_sec = unbounded ? -1 : read_timeout_sec_;
  19680. time_t strm_read_usec = unbounded ? 0 : read_timeout_usec_;
  19681. // The handshake belongs to establishing the connection, so an unset read
  19682. // timeout leaves it bounded by the connection timeout instead of forever.
  19683. time_t hs_sec = unbounded ? connection_timeout_sec_ : read_timeout_sec_;
  19684. time_t hs_usec = unbounded ? connection_timeout_usec_ : read_timeout_usec_;
  19685. #ifdef CPPHTTPLIB_SSL_ENABLED
  19686. if (is_ssl_) {
  19687. // A plain flag rather than SSLClient::load_certs()'s call_once: connect()
  19688. // is not safe to call concurrently on one client to begin with, since
  19689. // nothing else here is guarded either.
  19690. if (server_certificate_verification_ && !certs_loaded_) {
  19691. uint64_t backend_error = 0;
  19692. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_,
  19693. ca_cert_dir_path_, custom_ca_loaded_,
  19694. system_ca_mode_, backend_error);
  19695. certs_loaded_ = true;
  19696. }
  19697. detail::ClientTlsSessionOptions options;
  19698. options.server_hostname_verification = server_hostname_verification_;
  19699. detail::ClientTlsSessionError tls_error;
  19700. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  19701. server_certificate_verification_,
  19702. hs_sec, hs_usec, &tls_error,
  19703. options)) {
  19704. error = tls_error.error;
  19705. ssl_error = tls_error.ssl_error;
  19706. ssl_backend_error = tls_error.backend_error;
  19707. return false;
  19708. }
  19709. strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  19710. sock_, tls_session_, strm_read_sec, strm_read_usec, write_timeout_sec_,
  19711. write_timeout_usec_));
  19712. return true;
  19713. }
  19714. #else
  19715. (void)error;
  19716. (void)ssl_error;
  19717. (void)ssl_backend_error;
  19718. (void)hs_sec;
  19719. (void)hs_usec;
  19720. #endif
  19721. strm = std::unique_ptr<Stream>(
  19722. new detail::SocketStream(sock_, strm_read_sec, strm_read_usec,
  19723. write_timeout_sec_, write_timeout_usec_));
  19724. return true;
  19725. }
  19726. inline void WebSocketClient::prepare_default_headers(Request &req) {
  19727. #ifdef CPPHTTPLIB_SSL_ENABLED
  19728. auto is_ssl = is_ssl_;
  19729. #else
  19730. auto is_ssl = false;
  19731. #endif
  19732. if (!req.has_header("Host")) {
  19733. req.headers.emplace("Host", detail::make_default_host_header_value(
  19734. host_, port_, is_ssl, address_family_));
  19735. }
  19736. detail::add_default_user_agent_header(req);
  19737. }
  19738. inline Result WebSocketClient::connect() {
  19739. if (!is_valid_) { return Result{Error::Connection, -1, Headers{}}; }
  19740. shutdown_and_close();
  19741. // Check is custom IP or hostname specified for host_
  19742. std::string connect_host;
  19743. std::string ip;
  19744. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  19745. auto error = Error::Success;
  19746. sock_ = detail::create_client_socket(
  19747. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  19748. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  19749. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  19750. write_timeout_usec_, interface_, error);
  19751. if (sock_ == INVALID_SOCKET) {
  19752. if (error == Error::Success) { error = Error::Connection; }
  19753. return Result{error, -1, Headers{}};
  19754. }
  19755. std::unique_ptr<Stream> strm;
  19756. auto stream_error = Error::SSLConnection;
  19757. int ssl_error = 0;
  19758. uint64_t ssl_backend_error = 0;
  19759. if (!create_stream(strm, stream_error, ssl_error, ssl_backend_error)) {
  19760. shutdown_and_close();
  19761. #ifdef CPPHTTPLIB_SSL_ENABLED
  19762. return Result{stream_error, -1, Headers{}, ssl_error, ssl_backend_error};
  19763. #else
  19764. return Result{stream_error, -1, Headers{}};
  19765. #endif
  19766. }
  19767. Request req;
  19768. req.method = "GET";
  19769. req.path = path_;
  19770. req.headers = headers_;
  19771. prepare_default_headers(req);
  19772. detail::WebSocketUpgradeResponse upgrade;
  19773. if (!detail::perform_websocket_handshake(*strm, req, upgrade)) {
  19774. shutdown_and_close();
  19775. return Result{upgrade.error, upgrade.status, std::move(upgrade.headers)};
  19776. }
  19777. subprotocol_ = std::move(upgrade.selected_subprotocol);
  19778. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  19779. websocket_ping_interval_sec_,
  19780. websocket_max_missed_pongs_));
  19781. // The stream was created with the timeout already; tell the WebSocket
  19782. // whether it came from the caller, so read() knows to report it as Timeout.
  19783. ws_->read_timeout_set_ = read_timeout_set_;
  19784. return Result{Error::Success, upgrade.status, std::move(upgrade.headers)};
  19785. }
  19786. inline ReadResult WebSocketClient::read(std::string &msg) {
  19787. if (!ws_) { return Fail; }
  19788. return ws_->read(msg);
  19789. }
  19790. inline bool WebSocketClient::send(const std::string &data) {
  19791. if (!ws_) { return false; }
  19792. return ws_->send(data);
  19793. }
  19794. inline bool WebSocketClient::send(const char *data, size_t len) {
  19795. if (!ws_) { return false; }
  19796. return ws_->send(data, len);
  19797. }
  19798. inline void WebSocketClient::close(CloseStatus status,
  19799. const std::string &reason) {
  19800. if (ws_) { ws_->close(status, reason); }
  19801. }
  19802. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  19803. inline const std::string &WebSocketClient::subprotocol() const {
  19804. return subprotocol_;
  19805. }
  19806. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  19807. read_timeout_sec_ = sec;
  19808. read_timeout_usec_ = usec;
  19809. read_timeout_set_ = true;
  19810. // The members above only seed the next connect(); read() consults the
  19811. // stream, so an already-open connection has to be told directly.
  19812. if (ws_) { ws_->set_read_timeout(sec, usec); }
  19813. }
  19814. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  19815. write_timeout_sec_ = sec;
  19816. write_timeout_usec_ = usec;
  19817. }
  19818. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  19819. websocket_ping_interval_sec_ = sec;
  19820. }
  19821. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  19822. websocket_max_missed_pongs_ = count;
  19823. }
  19824. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  19825. inline void WebSocketClient::set_address_family(int family) {
  19826. address_family_ = family;
  19827. }
  19828. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  19829. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  19830. socket_options_ = std::move(socket_options);
  19831. }
  19832. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  19833. connection_timeout_sec_ = sec;
  19834. connection_timeout_usec_ = usec;
  19835. }
  19836. inline void WebSocketClient::set_interface(const std::string &intf) {
  19837. interface_ = intf;
  19838. }
  19839. inline void WebSocketClient::set_hostname_addr_map(
  19840. std::map<std::string, std::string> addr_map) {
  19841. addr_map_ = std::move(addr_map);
  19842. }
  19843. #ifdef CPPHTTPLIB_SSL_ENABLED
  19844. inline void
  19845. WebSocketClient::set_ca_cert_path(const std::string &ca_cert_file_path,
  19846. const std::string &ca_cert_dir_path) {
  19847. ca_cert_file_path_ = ca_cert_file_path;
  19848. ca_cert_dir_path_ = ca_cert_dir_path;
  19849. }
  19850. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  19851. if (store && tls_ctx_) {
  19852. // set_ca_store takes ownership of store
  19853. tls::set_ca_store(tls_ctx_, store);
  19854. custom_ca_loaded_ = true;
  19855. } else if (store) {
  19856. tls::free_ca_store(store);
  19857. }
  19858. }
  19859. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  19860. std::size_t size) {
  19861. if (tls_ctx_ && ca_cert && size > 0) {
  19862. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  19863. custom_ca_loaded_ = true;
  19864. }
  19865. }
  19866. inline void
  19867. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  19868. server_certificate_verification_ = enabled;
  19869. }
  19870. inline void WebSocketClient::enable_server_hostname_verification(bool enabled) {
  19871. server_hostname_verification_ = enabled;
  19872. }
  19873. inline void WebSocketClient::enable_system_ca(bool enabled) {
  19874. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  19875. }
  19876. #endif // CPPHTTPLIB_SSL_ENABLED
  19877. } // namespace ws
  19878. // ----------------------------------------------------------------------------
  19879. } // namespace httplib
  19880. #endif // CPPHTTPLIB_HTTPLIB_H