httplib.h 698 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049
  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.51.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003300"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. #ifndef CPPHTTPLIB_TCP_NODELAY
  109. #define CPPHTTPLIB_TCP_NODELAY false
  110. #endif
  111. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  112. #define CPPHTTPLIB_IPV6_V6ONLY false
  113. #endif
  114. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  115. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  116. #endif
  117. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  118. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  119. #endif
  120. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  121. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  124. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  125. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  126. ? std::thread::hardware_concurrency() - 1 \
  127. : 0))
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  131. #endif
  132. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  133. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 128
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  148. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  149. #endif
  150. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  151. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  152. #endif
  153. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  154. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  155. #endif
  156. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  157. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  158. #endif
  159. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  160. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  161. #endif
  162. /*
  163. * Headers
  164. */
  165. #ifdef _WIN32
  166. #ifndef _CRT_SECURE_NO_WARNINGS
  167. #define _CRT_SECURE_NO_WARNINGS
  168. #endif //_CRT_SECURE_NO_WARNINGS
  169. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  170. #define _CRT_NONSTDC_NO_DEPRECATE
  171. #endif //_CRT_NONSTDC_NO_DEPRECATE
  172. #if defined(_MSC_VER)
  173. #if _MSC_VER < 1900
  174. #error Sorry, Visual Studio versions prior to 2015 are not supported
  175. #endif
  176. #pragma comment(lib, "ws2_32.lib")
  177. #ifndef _SSIZE_T_DEFINED
  178. using ssize_t = __int64;
  179. #define _SSIZE_T_DEFINED
  180. #endif
  181. #endif // _MSC_VER
  182. #ifndef S_ISREG
  183. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  184. #endif // S_ISREG
  185. #ifndef S_ISDIR
  186. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  187. #endif // S_ISDIR
  188. #ifndef NOMINMAX
  189. #define NOMINMAX
  190. #endif // NOMINMAX
  191. #include <io.h>
  192. #include <winsock2.h>
  193. #include <ws2tcpip.h>
  194. #if defined(__has_include)
  195. #if __has_include(<afunix.h>)
  196. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  197. #include <afunix.h>
  198. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  199. #endif
  200. #endif
  201. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  202. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  203. #endif
  204. using nfds_t = unsigned long;
  205. using socket_t = SOCKET;
  206. using socklen_t = int;
  207. #else // not _WIN32
  208. #include <arpa/inet.h>
  209. #if !defined(_AIX) && !defined(__MVS__)
  210. #include <ifaddrs.h>
  211. #endif
  212. #ifdef __MVS__
  213. #include <strings.h>
  214. #ifndef NI_MAXHOST
  215. #define NI_MAXHOST 1025
  216. #endif
  217. #endif
  218. #include <net/if.h>
  219. #include <netdb.h>
  220. #include <netinet/in.h>
  221. #ifdef __linux__
  222. #include <resolv.h>
  223. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  224. #endif
  225. #include <csignal>
  226. #include <netinet/tcp.h>
  227. #include <poll.h>
  228. #include <pthread.h>
  229. #include <sys/mman.h>
  230. #include <sys/socket.h>
  231. #include <sys/un.h>
  232. #include <unistd.h>
  233. using socket_t = int;
  234. #ifndef INVALID_SOCKET
  235. #define INVALID_SOCKET (-1)
  236. #endif
  237. #endif //_WIN32
  238. #if defined(__APPLE__)
  239. #include <TargetConditionals.h>
  240. #endif
  241. #include <algorithm>
  242. #include <array>
  243. #include <atomic>
  244. #include <cassert>
  245. #include <chrono>
  246. #include <climits>
  247. #include <condition_variable>
  248. #include <cstdlib>
  249. #include <cstring>
  250. #include <errno.h>
  251. #include <exception>
  252. #include <fcntl.h>
  253. #include <fstream>
  254. #include <functional>
  255. #include <iomanip>
  256. #include <iostream>
  257. #include <list>
  258. #include <map>
  259. #include <memory>
  260. #include <mutex>
  261. #include <random>
  262. #include <regex>
  263. #include <set>
  264. #include <sstream>
  265. #include <string>
  266. #include <sys/stat.h>
  267. #include <system_error>
  268. #include <thread>
  269. #include <unordered_map>
  270. #include <unordered_set>
  271. #include <utility>
  272. // On macOS with a TLS backend, enable Keychain root certificates by default
  273. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  274. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  275. // only; on those platforms the user must provide a CA bundle explicitly.
  276. #if defined(__APPLE__) && defined(__clang__) && \
  277. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  278. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  279. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  280. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  281. #if TARGET_OS_OSX
  282. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  283. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  284. #endif
  285. #endif
  286. #endif
  287. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  288. defined(__APPLE__) && !TARGET_OS_OSX
  289. #error \
  290. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  291. #endif
  292. // On Windows, enable Schannel certificate verification by default
  293. // unless the user explicitly opts out.
  294. #if defined(_WIN32) && \
  295. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  296. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  297. #endif
  298. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  299. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  300. #if TARGET_OS_MAC && defined(__clang__)
  301. #include <CFNetwork/CFHost.h>
  302. #include <CoreFoundation/CoreFoundation.h>
  303. #endif
  304. #endif
  305. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  306. #ifdef _WIN32
  307. #include <wincrypt.h>
  308. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  309. // used
  310. #undef X509_NAME
  311. #undef X509_CERT_PAIR
  312. #undef X509_EXTENSIONS
  313. #undef PKCS7_SIGNER_INFO
  314. #ifdef _MSC_VER
  315. #pragma comment(lib, "crypt32.lib")
  316. #endif
  317. #endif // _WIN32
  318. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  319. #if TARGET_OS_OSX
  320. #include <Security/Security.h>
  321. #endif
  322. #endif
  323. #include <openssl/err.h>
  324. #include <openssl/evp.h>
  325. #include <openssl/ssl.h>
  326. #include <openssl/x509v3.h>
  327. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  328. #include <openssl/applink.c>
  329. #endif
  330. #include <iostream>
  331. #include <sstream>
  332. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  333. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  334. #error Please use OpenSSL or a current version of BoringSSL
  335. #endif
  336. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  337. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  338. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  339. #endif
  340. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  341. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  342. // version.h defines MBEDTLS_VERSION_MAJOR (on 2.x/3.x/4.x alike); it is pulled
  343. // in with this first include group so the version gating below can use it.
  344. #include <mbedtls/error.h>
  345. #include <mbedtls/net_sockets.h>
  346. #include <mbedtls/oid.h>
  347. #include <mbedtls/pk.h>
  348. #include <mbedtls/ssl.h>
  349. #include <mbedtls/version.h>
  350. #include <mbedtls/x509_crt.h>
  351. #if MBEDTLS_VERSION_MAJOR >= 4
  352. // Mbed TLS 4.x moved hashing/RNG to PSA Crypto and removed these headers.
  353. #include <psa/crypto.h>
  354. #else
  355. #include <mbedtls/ctr_drbg.h>
  356. #include <mbedtls/entropy.h>
  357. #include <mbedtls/md5.h>
  358. #include <mbedtls/sha1.h>
  359. #include <mbedtls/sha256.h>
  360. #include <mbedtls/sha512.h>
  361. #endif
  362. #ifdef _WIN32
  363. #include <wincrypt.h>
  364. #ifdef _MSC_VER
  365. #pragma comment(lib, "crypt32.lib")
  366. #endif
  367. #endif // _WIN32
  368. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  369. #if TARGET_OS_OSX
  370. #include <Security/Security.h>
  371. #endif
  372. #endif
  373. // Mbed TLS version API compatibility. Note: V4 implies V3 (both defined on
  374. // 4.x), so version-specific 3.x-only code must check V3 && !V4.
  375. #if MBEDTLS_VERSION_MAJOR >= 4
  376. #define CPPHTTPLIB_MBEDTLS_V4
  377. #endif
  378. #if MBEDTLS_VERSION_MAJOR >= 3
  379. #define CPPHTTPLIB_MBEDTLS_V3
  380. #endif
  381. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  382. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  383. #include <wolfssl/options.h>
  384. #include <wolfssl/openssl/x509v3.h>
  385. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  386. #ifndef WOLFSSL_GEN_EMAIL
  387. #define WOLFSSL_GEN_EMAIL 1
  388. #endif
  389. #ifndef WOLFSSL_GEN_DNS
  390. #define WOLFSSL_GEN_DNS 2
  391. #endif
  392. #ifndef WOLFSSL_GEN_URI
  393. #define WOLFSSL_GEN_URI 6
  394. #endif
  395. #ifndef WOLFSSL_GEN_IPADD
  396. #define WOLFSSL_GEN_IPADD 7
  397. #endif
  398. #include <wolfssl/ssl.h>
  399. #include <wolfssl/wolfcrypt/hash.h>
  400. #include <wolfssl/wolfcrypt/md5.h>
  401. #include <wolfssl/wolfcrypt/sha256.h>
  402. #include <wolfssl/wolfcrypt/sha512.h>
  403. #ifdef _WIN32
  404. #include <wincrypt.h>
  405. #ifdef _MSC_VER
  406. #pragma comment(lib, "crypt32.lib")
  407. #endif
  408. #endif // _WIN32
  409. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  410. #if TARGET_OS_OSX
  411. #include <Security/Security.h>
  412. #endif
  413. #endif
  414. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  415. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  416. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  417. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  418. #define CPPHTTPLIB_SSL_ENABLED
  419. #endif
  420. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  421. #include <zlib.h>
  422. #endif
  423. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  424. #include <brotli/decode.h>
  425. #include <brotli/encode.h>
  426. #endif
  427. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  428. #include <zstd.h>
  429. #endif
  430. /*
  431. * Declaration
  432. */
  433. namespace httplib {
  434. namespace ws {
  435. class WebSocket;
  436. } // namespace ws
  437. namespace detail {
  438. /*
  439. * Backport std::make_unique from C++14.
  440. *
  441. * NOTE: This code came up with the following stackoverflow post:
  442. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  443. *
  444. */
  445. template <class T, class... Args>
  446. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  447. make_unique(Args &&...args) {
  448. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  449. }
  450. template <class T>
  451. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  452. make_unique(std::size_t n) {
  453. typedef typename std::remove_extent<T>::type RT;
  454. return std::unique_ptr<T>(new RT[n]);
  455. }
  456. // Locale-independent ASCII character classification. The <cctype>
  457. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  458. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  459. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  460. // classified without regard to the locale.
  461. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  462. inline bool is_ascii_alpha(char c) {
  463. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  464. }
  465. inline bool is_ascii_alnum(char c) {
  466. return is_ascii_digit(c) || is_ascii_alpha(c);
  467. }
  468. namespace case_ignore {
  469. inline unsigned char to_lower(int c) {
  470. const static unsigned char table[256] = {
  471. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  472. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  473. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  474. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  475. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  476. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  477. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  478. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  479. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  480. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  481. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  482. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  483. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  484. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  485. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  486. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  487. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  488. 255,
  489. };
  490. return table[(unsigned char)(char)c];
  491. }
  492. inline std::string to_lower(const std::string &s) {
  493. std::string result = s;
  494. std::transform(
  495. result.begin(), result.end(), result.begin(),
  496. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  497. return result;
  498. }
  499. inline bool equal(const std::string &a, const std::string &b) {
  500. return a.size() == b.size() &&
  501. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  502. return to_lower(ca) == to_lower(cb);
  503. });
  504. }
  505. struct equal_to {
  506. bool operator()(const std::string &a, const std::string &b) const {
  507. return equal(a, b);
  508. }
  509. };
  510. struct hash {
  511. size_t operator()(const std::string &key) const {
  512. return hash_core(key.data(), key.size(), 0);
  513. }
  514. size_t hash_core(const char *s, size_t l, size_t h) const {
  515. return (l == 0) ? h
  516. : hash_core(s + 1, l - 1,
  517. // Unsets the 6 high bits of h, therefore no
  518. // overflow happens
  519. (((std::numeric_limits<size_t>::max)() >> 6) &
  520. h * 33) ^
  521. static_cast<unsigned char>(to_lower(*s)));
  522. }
  523. };
  524. template <typename T>
  525. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  526. detail::case_ignore::equal_to>;
  527. } // namespace case_ignore
  528. // This is based on
  529. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  530. struct scope_exit {
  531. explicit scope_exit(std::function<void(void)> &&f)
  532. : exit_function(std::move(f)), execute_on_destruction{true} {}
  533. scope_exit(scope_exit &&rhs) noexcept
  534. : exit_function(std::move(rhs.exit_function)),
  535. execute_on_destruction{rhs.execute_on_destruction} {
  536. rhs.release();
  537. }
  538. ~scope_exit() {
  539. if (execute_on_destruction) { this->exit_function(); }
  540. }
  541. void release() { this->execute_on_destruction = false; }
  542. private:
  543. scope_exit(const scope_exit &) = delete;
  544. void operator=(const scope_exit &) = delete;
  545. scope_exit &operator=(scope_exit &&) = delete;
  546. std::function<void(void)> exit_function;
  547. bool execute_on_destruction;
  548. };
  549. // Simple from_chars implementation for integer and double types (C++17
  550. // substitute)
  551. template <typename T> struct from_chars_result {
  552. const char *ptr;
  553. std::errc ec;
  554. };
  555. template <typename T>
  556. inline from_chars_result<T> from_chars(const char *first, const char *last,
  557. T &value, int base = 10) {
  558. value = 0;
  559. const char *p = first;
  560. bool negative = false;
  561. if (p != last && *p == '-') {
  562. negative = true;
  563. ++p;
  564. }
  565. if (p == last) { return {first, std::errc::invalid_argument}; }
  566. T result = 0;
  567. for (; p != last; ++p) {
  568. char c = *p;
  569. int digit = -1;
  570. if (is_ascii_digit(c)) {
  571. digit = c - '0';
  572. } else if ('a' <= c && c <= 'z') {
  573. digit = c - 'a' + 10;
  574. } else if ('A' <= c && c <= 'Z') {
  575. digit = c - 'A' + 10;
  576. } else {
  577. break;
  578. }
  579. if (digit < 0 || digit >= base) { break; }
  580. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  581. return {p, std::errc::result_out_of_range};
  582. }
  583. result = result * base + digit;
  584. }
  585. if (p == first || (negative && p == first + 1)) {
  586. return {first, std::errc::invalid_argument};
  587. }
  588. value = negative ? T(0) - result : result;
  589. return {p, std::errc{}};
  590. }
  591. // from_chars for double (hand-written, locale-independent)
  592. //
  593. // The only double consumed by this library is the HTTP quality value, whose
  594. // grammar is (RFC 9110 12.4.2):
  595. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  596. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  597. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  598. // '.' always the decimal separator (std::strtod would instead read it from the
  599. // global C locale, mis-parsing q-values once an embedder calls
  600. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  601. // the result to [0, 1], so inputs outside that range need not be distinguished
  602. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  603. // cases that exponent and wide-range handling would introduce.
  604. inline from_chars_result<double> from_chars(const char *first, const char *last,
  605. double &value) {
  606. value = 0.0;
  607. const char *p = first;
  608. // Each 1eN is exactly representable, so a single final division by the
  609. // matching entry yields a correctly-rounded result.
  610. static const double powers_of_ten[] = {
  611. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  612. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  613. const int max_frac_digits =
  614. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  615. // Accumulate digits into a 64-bit integer and remember how many were
  616. // fractional. Two independent caps keep this bounded and safe:
  617. // * accumulation saturates before mantissa could overflow uint64_t, and
  618. // * frac_digits is capped at max_frac_digits so it is always a valid index
  619. // into powers_of_ten (without this an input like "0.000...0" would never
  620. // grow mantissa, so the saturation cap alone would not bound it).
  621. // Both caps only drop digits far beyond the precision a q-value needs; any
  622. // value they would change is well outside [0, 1] and rejected by the caller.
  623. uint64_t mantissa = 0;
  624. int frac_digits = 0;
  625. bool seen_digit = false;
  626. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  627. auto accumulate = [&](char c) {
  628. if (mantissa <= limit) {
  629. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  630. return true;
  631. }
  632. return false;
  633. };
  634. for (; p != last && is_ascii_digit(*p); ++p) {
  635. seen_digit = true;
  636. accumulate(*p);
  637. }
  638. if (p != last && *p == '.') {
  639. ++p;
  640. for (; p != last && is_ascii_digit(*p); ++p) {
  641. seen_digit = true;
  642. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  643. }
  644. }
  645. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  646. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  647. return {p, std::errc{}};
  648. }
  649. inline bool parse_port(const char *s, size_t len, int &port) {
  650. int val = 0;
  651. auto r = from_chars(s, s + len, val);
  652. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  653. port = val;
  654. return true;
  655. }
  656. inline bool parse_port(const std::string &s, int &port) {
  657. return parse_port(s.data(), s.size(), port);
  658. }
  659. struct UrlComponents {
  660. std::string scheme;
  661. std::string host;
  662. std::string port;
  663. std::string path;
  664. std::string query;
  665. };
  666. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  667. uc = {};
  668. size_t pos = 0;
  669. auto sep = url.find("://");
  670. if (sep != std::string::npos) {
  671. uc.scheme = url.substr(0, sep);
  672. // Scheme must be [a-z]+ only
  673. if (uc.scheme.empty()) { return false; }
  674. for (auto c : uc.scheme) {
  675. if (c < 'a' || c > 'z') { return false; }
  676. }
  677. pos = sep + 3;
  678. } else if (url.compare(0, 2, "//") == 0) {
  679. pos = 2;
  680. }
  681. auto has_authority_prefix = pos > 0;
  682. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  683. url[0] != '?' && url[0] != '#');
  684. if (has_authority) {
  685. if (pos < url.size() && url[pos] == '[') {
  686. auto close = url.find(']', pos);
  687. if (close == std::string::npos) { return false; }
  688. uc.host = url.substr(pos + 1, close - pos - 1);
  689. // IPv6 host must be [a-fA-F0-9:]+ only
  690. if (uc.host.empty()) { return false; }
  691. for (auto c : uc.host) {
  692. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  693. (c >= 'A' && c <= 'F') || c == ':')) {
  694. return false;
  695. }
  696. }
  697. pos = close + 1;
  698. } else {
  699. auto end = url.find_first_of(":/?#", pos);
  700. if (end == std::string::npos) { end = url.size(); }
  701. uc.host = url.substr(pos, end - pos);
  702. pos = end;
  703. }
  704. if (pos < url.size() && url[pos] == ':') {
  705. ++pos;
  706. auto end = url.find_first_of("/?#", pos);
  707. if (end == std::string::npos) { end = url.size(); }
  708. uc.port = url.substr(pos, end - pos);
  709. pos = end;
  710. }
  711. // Without :// or //, the entire input must be consumed as host[:port].
  712. // If there is leftover (path, query, etc.), this is not a valid
  713. // host[:port] string — clear and reparse as a plain path.
  714. if (!has_authority_prefix && pos < url.size()) {
  715. uc.host.clear();
  716. uc.port.clear();
  717. pos = 0;
  718. }
  719. }
  720. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  721. auto end = url.find_first_of("?#", pos);
  722. if (end == std::string::npos) { end = url.size(); }
  723. uc.path = url.substr(pos, end - pos);
  724. pos = end;
  725. }
  726. if (pos < url.size() && url[pos] == '?') {
  727. auto end = url.find('#', pos);
  728. if (end == std::string::npos) { end = url.size(); }
  729. uc.query = url.substr(pos, end - pos);
  730. }
  731. return true;
  732. }
  733. } // namespace detail
  734. enum class SSLVerifierResponse {
  735. // no decision has been made, use the built-in certificate verifier
  736. NoDecisionMade,
  737. // connection certificate is verified and accepted
  738. CertificateAccepted,
  739. // connection certificate was processed but is rejected
  740. CertificateRejected
  741. };
  742. // System CA loading policy for SSL clients. Auto (the default) loads system
  743. // CA certs only when no custom CA is configured; enable_system_ca() switches
  744. // to an explicit policy.
  745. enum class SystemCAMode { Auto, Enabled, Disabled };
  746. enum StatusCode {
  747. // Information responses
  748. Continue_100 = 100,
  749. SwitchingProtocol_101 = 101,
  750. Processing_102 = 102,
  751. EarlyHints_103 = 103,
  752. // Successful responses
  753. OK_200 = 200,
  754. Created_201 = 201,
  755. Accepted_202 = 202,
  756. NonAuthoritativeInformation_203 = 203,
  757. NoContent_204 = 204,
  758. ResetContent_205 = 205,
  759. PartialContent_206 = 206,
  760. MultiStatus_207 = 207,
  761. AlreadyReported_208 = 208,
  762. IMUsed_226 = 226,
  763. // Redirection messages
  764. MultipleChoices_300 = 300,
  765. MovedPermanently_301 = 301,
  766. Found_302 = 302,
  767. SeeOther_303 = 303,
  768. NotModified_304 = 304,
  769. UseProxy_305 = 305,
  770. unused_306 = 306,
  771. TemporaryRedirect_307 = 307,
  772. PermanentRedirect_308 = 308,
  773. // Client error responses
  774. BadRequest_400 = 400,
  775. Unauthorized_401 = 401,
  776. PaymentRequired_402 = 402,
  777. Forbidden_403 = 403,
  778. NotFound_404 = 404,
  779. MethodNotAllowed_405 = 405,
  780. NotAcceptable_406 = 406,
  781. ProxyAuthenticationRequired_407 = 407,
  782. RequestTimeout_408 = 408,
  783. Conflict_409 = 409,
  784. Gone_410 = 410,
  785. LengthRequired_411 = 411,
  786. PreconditionFailed_412 = 412,
  787. PayloadTooLarge_413 = 413,
  788. UriTooLong_414 = 414,
  789. UnsupportedMediaType_415 = 415,
  790. RangeNotSatisfiable_416 = 416,
  791. ExpectationFailed_417 = 417,
  792. ImATeapot_418 = 418,
  793. MisdirectedRequest_421 = 421,
  794. UnprocessableContent_422 = 422,
  795. Locked_423 = 423,
  796. FailedDependency_424 = 424,
  797. TooEarly_425 = 425,
  798. UpgradeRequired_426 = 426,
  799. PreconditionRequired_428 = 428,
  800. TooManyRequests_429 = 429,
  801. RequestHeaderFieldsTooLarge_431 = 431,
  802. UnavailableForLegalReasons_451 = 451,
  803. // Server error responses
  804. InternalServerError_500 = 500,
  805. NotImplemented_501 = 501,
  806. BadGateway_502 = 502,
  807. ServiceUnavailable_503 = 503,
  808. GatewayTimeout_504 = 504,
  809. HttpVersionNotSupported_505 = 505,
  810. VariantAlsoNegotiates_506 = 506,
  811. InsufficientStorage_507 = 507,
  812. LoopDetected_508 = 508,
  813. NotExtended_510 = 510,
  814. NetworkAuthenticationRequired_511 = 511,
  815. };
  816. using Headers =
  817. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  818. detail::case_ignore::equal_to>;
  819. using Params = std::multimap<std::string, std::string>;
  820. using Match = std::smatch;
  821. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  822. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  823. /*
  824. * detail: type-erased storage used by UserData.
  825. * ABI-stable regardless of C++ standard — always uses this custom
  826. * implementation instead of std::any.
  827. */
  828. namespace detail {
  829. using any_type_id = const void *;
  830. template <typename T> any_type_id any_typeid() noexcept {
  831. static const char id = 0;
  832. return &id;
  833. }
  834. struct any_storage {
  835. virtual ~any_storage() = default;
  836. virtual std::unique_ptr<any_storage> clone() const = 0;
  837. virtual any_type_id type_id() const noexcept = 0;
  838. };
  839. template <typename T> struct any_value final : any_storage {
  840. T value;
  841. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  842. std::unique_ptr<any_storage> clone() const override {
  843. return std::unique_ptr<any_storage>(new any_value<T>(value));
  844. }
  845. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  846. };
  847. } // namespace detail
  848. class UserData {
  849. public:
  850. UserData() = default;
  851. UserData(UserData &&) noexcept = default;
  852. UserData &operator=(UserData &&) noexcept = default;
  853. UserData(const UserData &o) {
  854. for (const auto &e : o.entries_) {
  855. if (e.second) { entries_[e.first] = e.second->clone(); }
  856. }
  857. }
  858. UserData &operator=(const UserData &o) {
  859. if (this != &o) {
  860. entries_.clear();
  861. for (const auto &e : o.entries_) {
  862. if (e.second) { entries_[e.first] = e.second->clone(); }
  863. }
  864. }
  865. return *this;
  866. }
  867. template <typename T> void set(const std::string &key, T &&value) {
  868. using D = typename std::decay<T>::type;
  869. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  870. }
  871. template <typename T> T *get(const std::string &key) noexcept {
  872. auto it = entries_.find(key);
  873. if (it == entries_.end() || !it->second) { return nullptr; }
  874. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  875. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  876. }
  877. template <typename T> const T *get(const std::string &key) const noexcept {
  878. auto it = entries_.find(key);
  879. if (it == entries_.end() || !it->second) { return nullptr; }
  880. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  881. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  882. }
  883. bool has(const std::string &key) const noexcept {
  884. return entries_.find(key) != entries_.end();
  885. }
  886. void erase(const std::string &key) { entries_.erase(key); }
  887. void clear() noexcept { entries_.clear(); }
  888. private:
  889. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  890. entries_;
  891. };
  892. struct Response;
  893. using ResponseHandler = std::function<bool(const Response &response)>;
  894. struct FormData {
  895. std::string name;
  896. std::string content;
  897. std::string filename;
  898. std::string content_type;
  899. Headers headers;
  900. };
  901. struct FormField {
  902. std::string name;
  903. std::string content;
  904. Headers headers;
  905. };
  906. using FormFields = std::multimap<std::string, FormField>;
  907. using FormFiles = std::multimap<std::string, FormData>;
  908. struct MultipartFormData {
  909. FormFields fields; // Text fields from multipart
  910. FormFiles files; // Files from multipart
  911. // Text field access
  912. std::string get_field(const std::string &key, size_t id = 0) const;
  913. std::vector<std::string> get_fields(const std::string &key) const;
  914. bool has_field(const std::string &key) const;
  915. size_t get_field_count(const std::string &key) const;
  916. // File access
  917. FormData get_file(const std::string &key, size_t id = 0) const;
  918. std::vector<FormData> get_files(const std::string &key) const;
  919. bool has_file(const std::string &key) const;
  920. size_t get_file_count(const std::string &key) const;
  921. };
  922. struct UploadFormData {
  923. std::string name;
  924. std::string content;
  925. std::string filename;
  926. std::string content_type;
  927. };
  928. using UploadFormDataItems = std::vector<UploadFormData>;
  929. class DataSink {
  930. public:
  931. DataSink() : os(&sb_), sb_(*this) {}
  932. DataSink(const DataSink &) = delete;
  933. DataSink &operator=(const DataSink &) = delete;
  934. DataSink(DataSink &&) = delete;
  935. DataSink &operator=(DataSink &&) = delete;
  936. std::function<bool(const char *data, size_t data_len)> write;
  937. std::function<bool()> is_writable;
  938. std::function<void()> done;
  939. std::function<void(const Headers &trailer)> done_with_trailer;
  940. std::ostream os;
  941. private:
  942. class data_sink_streambuf final : public std::streambuf {
  943. public:
  944. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  945. protected:
  946. std::streamsize xsputn(const char *s, std::streamsize n) override {
  947. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  948. return 0;
  949. }
  950. private:
  951. DataSink &sink_;
  952. };
  953. data_sink_streambuf sb_;
  954. };
  955. using ContentProvider =
  956. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  957. using ContentProviderWithoutLength =
  958. std::function<bool(size_t offset, DataSink &sink)>;
  959. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  960. struct FormDataProvider {
  961. std::string name;
  962. ContentProviderWithoutLength provider;
  963. std::string filename;
  964. std::string content_type;
  965. };
  966. using FormDataProviderItems = std::vector<FormDataProvider>;
  967. inline FormDataProvider
  968. make_file_provider(const std::string &name, const std::string &filepath,
  969. const std::string &filename = std::string(),
  970. const std::string &content_type = std::string()) {
  971. FormDataProvider fdp;
  972. fdp.name = name;
  973. fdp.filename = filename.empty() ? filepath : filename;
  974. fdp.content_type = content_type;
  975. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  976. std::ifstream f(filepath, std::ios::binary);
  977. if (!f) { return false; }
  978. if (offset > 0) {
  979. f.seekg(static_cast<std::streamoff>(offset));
  980. if (!f.good()) {
  981. sink.done();
  982. return true;
  983. }
  984. }
  985. char buf[8192];
  986. f.read(buf, sizeof(buf));
  987. auto n = static_cast<size_t>(f.gcount());
  988. if (n > 0) { return sink.write(buf, n); }
  989. sink.done(); // EOF
  990. return true;
  991. };
  992. return fdp;
  993. }
  994. inline std::pair<size_t, ContentProvider>
  995. make_file_body(const std::string &filepath) {
  996. size_t size = 0;
  997. {
  998. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  999. if (!f) { return {0, ContentProvider{}}; }
  1000. size = static_cast<size_t>(f.tellg());
  1001. }
  1002. ContentProvider provider = [filepath](size_t offset, size_t length,
  1003. DataSink &sink) -> bool {
  1004. std::ifstream f(filepath, std::ios::binary);
  1005. if (!f) { return false; }
  1006. f.seekg(static_cast<std::streamoff>(offset));
  1007. if (!f.good()) { return false; }
  1008. char buf[8192];
  1009. while (length > 0) {
  1010. auto to_read = (std::min)(sizeof(buf), length);
  1011. f.read(buf, static_cast<std::streamsize>(to_read));
  1012. auto n = static_cast<size_t>(f.gcount());
  1013. if (n == 0) { break; }
  1014. if (!sink.write(buf, n)) { return false; }
  1015. length -= n;
  1016. }
  1017. return true;
  1018. };
  1019. return {size, std::move(provider)};
  1020. }
  1021. using ContentReceiverWithProgress = std::function<bool(
  1022. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1023. using ContentReceiver =
  1024. std::function<bool(const char *data, size_t data_length)>;
  1025. using FormDataHeader = std::function<bool(const FormData &file)>;
  1026. class ContentReader {
  1027. public:
  1028. using Reader = std::function<bool(ContentReceiver receiver)>;
  1029. using FormDataReader =
  1030. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1031. ContentReader(Reader reader, FormDataReader multipart_reader)
  1032. : reader_(std::move(reader)),
  1033. formdata_reader_(std::move(multipart_reader)) {}
  1034. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1035. return formdata_reader_(std::move(header), std::move(receiver));
  1036. }
  1037. bool operator()(ContentReceiver receiver) const {
  1038. return reader_(std::move(receiver));
  1039. }
  1040. Reader reader_;
  1041. FormDataReader formdata_reader_;
  1042. };
  1043. using Range = std::pair<ssize_t, ssize_t>;
  1044. using Ranges = std::vector<Range>;
  1045. #ifdef CPPHTTPLIB_SSL_ENABLED
  1046. // TLS abstraction layer - public type definitions and API
  1047. namespace tls {
  1048. // Opaque handles (defined as void* for abstraction)
  1049. using ctx_t = void *;
  1050. using session_t = void *;
  1051. using const_session_t = const void *; // For read-only session access
  1052. using cert_t = void *;
  1053. using ca_store_t = void *;
  1054. // TLS versions
  1055. enum class Version {
  1056. TLS1_2 = 0x0303,
  1057. TLS1_3 = 0x0304,
  1058. };
  1059. // Subject Alternative Names (SAN) entry types
  1060. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1061. // SAN entry structure
  1062. struct SanEntry {
  1063. SanType type;
  1064. std::string value;
  1065. };
  1066. // Verification context for certificate verification callback
  1067. struct VerifyContext {
  1068. session_t session; // TLS session handle
  1069. cert_t cert; // Current certificate being verified
  1070. int depth; // Certificate chain depth (0 = leaf)
  1071. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1072. long error_code; // Backend-specific error code (0 = no error)
  1073. const char *error_string; // Human-readable error description
  1074. // Certificate introspection methods
  1075. std::string subject_cn() const;
  1076. std::string issuer_name() const;
  1077. bool check_hostname(const char *hostname) const;
  1078. std::vector<SanEntry> sans() const;
  1079. bool validity(time_t &not_before, time_t &not_after) const;
  1080. std::string serial() const;
  1081. };
  1082. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1083. // TlsError codes for TLS operations (backend-independent)
  1084. enum class ErrorCode : int {
  1085. Success = 0,
  1086. WantRead, // Non-blocking: need to wait for read
  1087. WantWrite, // Non-blocking: need to wait for write
  1088. PeerClosed, // Peer closed the connection
  1089. Fatal, // Unrecoverable error
  1090. SyscallError, // System call error (check sys_errno)
  1091. CertVerifyFailed, // Certificate verification failed
  1092. HostnameMismatch, // Hostname verification failed
  1093. };
  1094. // TLS error information
  1095. struct TlsError {
  1096. ErrorCode code = ErrorCode::Fatal;
  1097. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1098. int sys_errno = 0; // errno when SyscallError
  1099. // Convert verification error code to human-readable string
  1100. static std::string verify_error_to_string(long error_code);
  1101. };
  1102. // RAII wrapper for peer certificate
  1103. class PeerCert {
  1104. public:
  1105. PeerCert();
  1106. PeerCert(PeerCert &&other) noexcept;
  1107. PeerCert &operator=(PeerCert &&other) noexcept;
  1108. ~PeerCert();
  1109. PeerCert(const PeerCert &) = delete;
  1110. PeerCert &operator=(const PeerCert &) = delete;
  1111. explicit operator bool() const;
  1112. std::string subject_cn() const;
  1113. std::string issuer_name() const;
  1114. bool check_hostname(const char *hostname) const;
  1115. std::vector<SanEntry> sans() const;
  1116. bool validity(time_t &not_before, time_t &not_after) const;
  1117. std::string serial() const;
  1118. private:
  1119. explicit PeerCert(cert_t cert);
  1120. cert_t cert_ = nullptr;
  1121. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1122. };
  1123. // Callback for TLS context setup (used by SSLServer constructor)
  1124. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1125. } // namespace tls
  1126. #endif
  1127. struct Request {
  1128. std::string method;
  1129. std::string path;
  1130. std::string matched_route;
  1131. Params params;
  1132. Headers headers;
  1133. Headers trailers;
  1134. std::string body;
  1135. std::string remote_addr;
  1136. int remote_port = -1;
  1137. std::string local_addr;
  1138. int local_port = -1;
  1139. // for server
  1140. std::string version;
  1141. std::string target;
  1142. MultipartFormData form;
  1143. Ranges ranges;
  1144. Match matches;
  1145. std::unordered_map<std::string, std::string> path_params;
  1146. std::function<bool()> is_connection_closed = []() { return true; };
  1147. // for client
  1148. std::vector<std::string> accept_content_types;
  1149. ResponseHandler response_handler;
  1150. ContentReceiverWithProgress content_receiver;
  1151. DownloadProgress download_progress;
  1152. UploadProgress upload_progress;
  1153. bool has_header(const std::string &key) const;
  1154. std::string get_header_value(const std::string &key, const char *def = "",
  1155. size_t id = 0) const;
  1156. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1157. size_t id = 0) const;
  1158. size_t get_header_value_count(const std::string &key) const;
  1159. void set_header(const std::string &key, const std::string &val);
  1160. bool has_trailer(const std::string &key) const;
  1161. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1162. size_t get_trailer_value_count(const std::string &key) const;
  1163. bool has_param(const std::string &key) const;
  1164. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1165. std::vector<std::string> get_param_values(const std::string &key) const;
  1166. size_t get_param_value_count(const std::string &key) const;
  1167. bool is_multipart_form_data() const;
  1168. // private members...
  1169. bool body_consumed_ = false;
  1170. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1171. size_t content_length_ = 0;
  1172. ContentProvider content_provider_;
  1173. bool is_chunked_content_provider_ = false;
  1174. size_t authorization_count_ = 0;
  1175. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1176. (std::chrono::steady_clock::time_point::min)();
  1177. #ifdef CPPHTTPLIB_SSL_ENABLED
  1178. tls::const_session_t ssl = nullptr;
  1179. tls::PeerCert peer_cert() const;
  1180. std::string sni() const;
  1181. #endif
  1182. };
  1183. struct Response {
  1184. std::string version;
  1185. int status = -1;
  1186. std::string reason;
  1187. Headers headers;
  1188. Headers trailers;
  1189. std::string body;
  1190. std::string location; // Redirect location
  1191. // User-defined context — set by pre-routing/pre-request handlers and read
  1192. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1193. UserData user_data;
  1194. bool has_header(const std::string &key) const;
  1195. std::string get_header_value(const std::string &key, const char *def = "",
  1196. size_t id = 0) const;
  1197. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1198. size_t id = 0) const;
  1199. size_t get_header_value_count(const std::string &key) const;
  1200. void set_header(const std::string &key, const std::string &val);
  1201. bool has_trailer(const std::string &key) const;
  1202. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1203. size_t get_trailer_value_count(const std::string &key) const;
  1204. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1205. void set_content(const char *s, size_t n, const std::string &content_type);
  1206. void set_content(const std::string &s, const std::string &content_type);
  1207. void set_content(std::string &&s, const std::string &content_type);
  1208. void set_content_provider(
  1209. size_t length, const std::string &content_type, ContentProvider provider,
  1210. ContentProviderResourceReleaser resource_releaser = nullptr);
  1211. void set_content_provider(
  1212. const std::string &content_type, ContentProviderWithoutLength provider,
  1213. ContentProviderResourceReleaser resource_releaser = nullptr);
  1214. void set_chunked_content_provider(
  1215. const std::string &content_type, ContentProviderWithoutLength provider,
  1216. ContentProviderResourceReleaser resource_releaser = nullptr);
  1217. void set_file_content(const std::string &path,
  1218. const std::string &content_type);
  1219. void set_file_content(const std::string &path);
  1220. Response() = default;
  1221. Response(const Response &) = default;
  1222. Response &operator=(const Response &) = default;
  1223. Response(Response &&) = default;
  1224. Response &operator=(Response &&) = default;
  1225. ~Response() {
  1226. if (content_provider_resource_releaser_) {
  1227. content_provider_resource_releaser_(content_provider_success_);
  1228. }
  1229. }
  1230. // private members...
  1231. size_t content_length_ = 0;
  1232. ContentProvider content_provider_;
  1233. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1234. bool is_chunked_content_provider_ = false;
  1235. bool content_provider_success_ = false;
  1236. std::string file_content_path_;
  1237. std::string file_content_content_type_;
  1238. };
  1239. enum class Error {
  1240. Success = 0,
  1241. Unknown,
  1242. Connection,
  1243. BindIPAddress,
  1244. Read,
  1245. Write,
  1246. ExceedRedirectCount,
  1247. Canceled,
  1248. SSLConnection,
  1249. SSLLoadingCerts,
  1250. SSLServerVerification,
  1251. SSLServerHostnameVerification,
  1252. UnsupportedMultipartBoundaryChars,
  1253. Compression,
  1254. ConnectionTimeout,
  1255. ProxyConnection,
  1256. ConnectionClosed,
  1257. Timeout,
  1258. ResourceExhaustion,
  1259. TooManyFormDataFiles,
  1260. ExceedMaxPayloadSize,
  1261. ExceedUriMaxLength,
  1262. ExceedMaxSocketDescriptorCount,
  1263. InvalidRequestLine,
  1264. InvalidHTTPMethod,
  1265. InvalidHTTPVersion,
  1266. InvalidHeaders,
  1267. MultipartParsing,
  1268. OpenFile,
  1269. Listen,
  1270. GetSockName,
  1271. UnsupportedAddressFamily,
  1272. HTTPParsing,
  1273. InvalidRangeHeader,
  1274. // For internal use only
  1275. SSLPeerCouldBeClosed_,
  1276. };
  1277. std::string to_string(Error error);
  1278. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1279. class Stream {
  1280. public:
  1281. virtual ~Stream() = default;
  1282. virtual bool is_readable() const = 0;
  1283. virtual bool wait_readable() const = 0;
  1284. virtual bool wait_writable() const = 0;
  1285. virtual bool is_peer_alive() const { return wait_writable(); }
  1286. virtual ssize_t read(char *ptr, size_t size) = 0;
  1287. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1288. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1289. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1290. virtual socket_t socket() const = 0;
  1291. virtual time_t duration() const = 0;
  1292. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1293. (void)sec;
  1294. (void)usec;
  1295. }
  1296. ssize_t write(const char *ptr);
  1297. ssize_t write(const std::string &s);
  1298. Error get_error() const { return error_; }
  1299. protected:
  1300. Error error_ = Error::Success;
  1301. };
  1302. class TaskQueue {
  1303. public:
  1304. TaskQueue() = default;
  1305. virtual ~TaskQueue() = default;
  1306. virtual bool enqueue(std::function<void()> fn) = 0;
  1307. virtual void shutdown() = 0;
  1308. virtual void on_idle() {}
  1309. };
  1310. class ThreadPool final : public TaskQueue {
  1311. public:
  1312. explicit ThreadPool(
  1313. size_t n, size_t max_n = 0, size_t mqr = 0,
  1314. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1315. ThreadPool(const ThreadPool &) = delete;
  1316. ~ThreadPool() override = default;
  1317. bool enqueue(std::function<void()> fn) override;
  1318. void shutdown() override;
  1319. private:
  1320. void worker(bool is_dynamic);
  1321. void move_to_finished(std::thread::id id);
  1322. void cleanup_finished_threads();
  1323. size_t base_thread_count_;
  1324. size_t max_thread_count_;
  1325. size_t max_queued_requests_;
  1326. time_t idle_timeout_sec_;
  1327. size_t idle_thread_count_;
  1328. bool shutdown_;
  1329. std::list<std::function<void()>> jobs_;
  1330. std::vector<std::thread> threads_; // base threads
  1331. std::list<std::thread> dynamic_threads_; // dynamic threads
  1332. std::vector<std::thread>
  1333. finished_threads_; // exited dynamic threads awaiting join
  1334. std::condition_variable cond_;
  1335. std::mutex mutex_;
  1336. };
  1337. using Logger = std::function<void(const Request &, const Response &)>;
  1338. // Forward declaration for Error type
  1339. enum class Error;
  1340. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1341. using SocketOptions = std::function<void(socket_t sock)>;
  1342. void default_socket_options(socket_t sock);
  1343. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1344. const char *status_message(int status);
  1345. std::string to_string(Error error);
  1346. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1347. std::string get_bearer_token_auth(const Request &req);
  1348. namespace detail {
  1349. class MatcherBase {
  1350. public:
  1351. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1352. virtual ~MatcherBase() = default;
  1353. const std::string &pattern() const { return pattern_; }
  1354. // Match request path and populate its matches and
  1355. virtual bool match(Request &request) const = 0;
  1356. private:
  1357. std::string pattern_;
  1358. };
  1359. /**
  1360. * Captures parameters in request path and stores them in Request::path_params
  1361. *
  1362. * Capture name is a substring of a pattern from : to /.
  1363. * The rest of the pattern is matched against the request path directly
  1364. * Parameters are captured starting from the next character after
  1365. * the end of the last matched static pattern fragment until the next /.
  1366. *
  1367. * Example pattern:
  1368. * "/path/fragments/:capture/more/fragments/:second_capture"
  1369. * Static fragments:
  1370. * "/path/fragments/", "more/fragments/"
  1371. *
  1372. * Given the following request path:
  1373. * "/path/fragments/:1/more/fragments/:2"
  1374. * the resulting capture will be
  1375. * {{"capture", "1"}, {"second_capture", "2"}}
  1376. */
  1377. class PathParamsMatcher final : public MatcherBase {
  1378. public:
  1379. PathParamsMatcher(const std::string &pattern);
  1380. bool match(Request &request) const override;
  1381. private:
  1382. // Treat segment separators as the end of path parameter capture
  1383. // Does not need to handle query parameters as they are parsed before path
  1384. // matching
  1385. static constexpr char separator = '/';
  1386. // Contains static path fragments to match against, excluding the '/' after
  1387. // path params
  1388. // Fragments are separated by path params
  1389. std::vector<std::string> static_fragments_;
  1390. // Stores the names of the path parameters to be used as keys in the
  1391. // Request::path_params map
  1392. std::vector<std::string> param_names_;
  1393. };
  1394. /**
  1395. * Performs std::regex_match on request path
  1396. * and stores the result in Request::matches
  1397. *
  1398. * Note that regex match is performed directly on the whole request.
  1399. * This means that wildcard patterns may match multiple path segments with /:
  1400. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1401. */
  1402. class RegexMatcher final : public MatcherBase {
  1403. public:
  1404. RegexMatcher(const std::string &pattern)
  1405. : MatcherBase(pattern), regex_(pattern) {}
  1406. bool match(Request &request) const override;
  1407. private:
  1408. std::regex regex_;
  1409. };
  1410. int close_socket(socket_t sock) noexcept;
  1411. ssize_t write_headers(Stream &strm, const Headers &headers);
  1412. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1413. time_t usec);
  1414. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1415. const std::string &boundary);
  1416. ContentProvider
  1417. make_multipart_content_provider(const UploadFormDataItems &items,
  1418. const std::string &boundary);
  1419. } // namespace detail
  1420. bool is_valid_multipart_boundary(const std::string &boundary);
  1421. // Serializer for multipart/form-data request bodies. The boundary is owned
  1422. // by the writer so that per-part framing and the final terminator always
  1423. // agree. Field names and filenames are escaped following the WHATWG HTML
  1424. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1425. // in content types.
  1426. class MultipartFormDataWriter {
  1427. public:
  1428. MultipartFormDataWriter();
  1429. // precondition: is_valid_multipart_boundary(boundary)
  1430. explicit MultipartFormDataWriter(std::string boundary);
  1431. const std::string &boundary() const;
  1432. std::string content_type() const;
  1433. // In-memory items -> whole body (known length)
  1434. std::string serialize(const UploadFormDataItems &items) const;
  1435. size_t content_length(const UploadFormDataItems &items) const;
  1436. // Per-part framing for streaming via a content provider
  1437. std::string item_begin(const UploadFormData &item) const;
  1438. static std::string item_end();
  1439. std::string finish() const;
  1440. private:
  1441. std::string boundary_;
  1442. };
  1443. class Server {
  1444. public:
  1445. using Handler = std::function<void(const Request &, Response &)>;
  1446. using ExceptionHandler =
  1447. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1448. enum class HandlerResponse {
  1449. Handled,
  1450. Unhandled,
  1451. };
  1452. using HandlerWithResponse =
  1453. std::function<HandlerResponse(const Request &, Response &)>;
  1454. using HandlerWithContentReader = std::function<void(
  1455. const Request &, Response &, const ContentReader &content_reader)>;
  1456. using Expect100ContinueHandler =
  1457. std::function<int(const Request &, Response &)>;
  1458. using StartHandler = std::function<void()>;
  1459. using WebSocketHandler =
  1460. std::function<void(const Request &, ws::WebSocket &)>;
  1461. using SubProtocolSelector =
  1462. std::function<std::string(const std::vector<std::string> &protocols)>;
  1463. Server();
  1464. virtual ~Server();
  1465. virtual bool is_valid() const;
  1466. Server &Get(const std::string &pattern, Handler handler);
  1467. Server &Post(const std::string &pattern, Handler handler);
  1468. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1469. Server &Put(const std::string &pattern, Handler handler);
  1470. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1471. Server &Patch(const std::string &pattern, Handler handler);
  1472. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1473. Server &Delete(const std::string &pattern, Handler handler);
  1474. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1475. Server &Options(const std::string &pattern, Handler handler);
  1476. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1477. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1478. SubProtocolSelector sub_protocol_selector);
  1479. bool set_base_dir(const std::string &dir,
  1480. const std::string &mount_point = std::string());
  1481. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1482. Headers headers = Headers());
  1483. bool remove_mount_point(const std::string &mount_point);
  1484. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1485. const std::string &mime);
  1486. Server &set_default_file_mimetype(const std::string &mime);
  1487. Server &set_file_request_handler(Handler handler);
  1488. template <class ErrorHandlerFunc>
  1489. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1490. return set_error_handler_core(
  1491. std::forward<ErrorHandlerFunc>(handler),
  1492. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1493. }
  1494. Server &set_exception_handler(ExceptionHandler handler);
  1495. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1496. Server &set_post_routing_handler(Handler handler);
  1497. Server &set_pre_request_handler(HandlerWithResponse handler);
  1498. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1499. Server &set_start_handler(StartHandler handler);
  1500. Server &set_logger(Logger logger);
  1501. Server &set_pre_compression_logger(Logger logger);
  1502. Server &set_error_logger(ErrorLogger error_logger);
  1503. Server &set_address_family(int family);
  1504. Server &set_tcp_nodelay(bool on);
  1505. Server &set_ipv6_v6only(bool on);
  1506. Server &set_socket_options(SocketOptions socket_options);
  1507. Server &set_default_headers(Headers headers);
  1508. Server &
  1509. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1510. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1511. Server &set_keep_alive_max_count(size_t count);
  1512. Server &set_keep_alive_timeout(time_t sec);
  1513. template <class Rep, class Period>
  1514. Server &
  1515. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1516. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1517. template <class Rep, class Period>
  1518. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1519. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1520. template <class Rep, class Period>
  1521. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1522. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1523. template <class Rep, class Period>
  1524. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1525. Server &set_payload_max_length(size_t length);
  1526. Server &set_websocket_ping_interval(time_t sec);
  1527. template <class Rep, class Period>
  1528. Server &set_websocket_ping_interval(
  1529. const std::chrono::duration<Rep, Period> &duration);
  1530. Server &set_websocket_max_missed_pongs(int count);
  1531. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1532. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1533. bool listen_after_bind();
  1534. bool listen(const std::string &host, int port, int socket_flags = 0);
  1535. bool is_running() const;
  1536. void wait_until_ready() const;
  1537. void stop() noexcept;
  1538. void decommission();
  1539. std::function<TaskQueue *(void)> new_task_queue;
  1540. protected:
  1541. bool process_request(Stream &strm, const std::string &remote_addr,
  1542. int remote_port, const std::string &local_addr,
  1543. int local_port, bool close_connection,
  1544. bool &connection_closed,
  1545. const std::function<void(Request &)> &setup_request,
  1546. bool *websocket_upgraded = nullptr);
  1547. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1548. std::vector<std::string> trusted_proxies_;
  1549. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1550. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1551. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1552. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1553. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1554. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1555. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1556. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1557. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1558. time_t websocket_ping_interval_sec_ =
  1559. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1560. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1561. private:
  1562. using Handlers =
  1563. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1564. using HandlersForContentReader =
  1565. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1566. HandlerWithContentReader>>;
  1567. static std::unique_ptr<detail::MatcherBase>
  1568. make_matcher(const std::string &pattern);
  1569. template <typename H>
  1570. Server &add_handler(
  1571. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1572. const std::string &pattern, H handler) {
  1573. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1574. return *this;
  1575. }
  1576. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1577. Server &set_error_handler_core(Handler handler, std::false_type);
  1578. socket_t create_server_socket(const std::string &host, int port,
  1579. int socket_flags,
  1580. SocketOptions socket_options) const;
  1581. int bind_internal(const std::string &host, int port, int socket_flags);
  1582. bool listen_internal();
  1583. bool routing(Request &req, Response &res, Stream &strm);
  1584. bool handle_file_request(Request &req, Response &res);
  1585. bool check_if_not_modified(const Request &req, Response &res,
  1586. const std::string &etag, time_t mtime) const;
  1587. bool check_if_range(Request &req, const std::string &etag,
  1588. time_t mtime) const;
  1589. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1590. Stream &strm);
  1591. bool dispatch_request_for_content_reader(
  1592. Request &req, Response &res, ContentReader content_reader,
  1593. const HandlersForContentReader &handlers) const;
  1594. bool parse_request_line(const char *s, Request &req) const;
  1595. void apply_ranges(const Request &req, Response &res,
  1596. std::string &content_type, std::string &boundary) const;
  1597. bool write_response(Stream &strm, bool close_connection, Request &req,
  1598. Response &res);
  1599. bool write_response_with_content(Stream &strm, bool close_connection,
  1600. const Request &req, Response &res);
  1601. bool write_response_core(Stream &strm, bool close_connection,
  1602. const Request &req, Response &res,
  1603. bool need_apply_ranges);
  1604. bool write_content_with_provider(Stream &strm, const Request &req,
  1605. Response &res, const std::string &boundary,
  1606. const std::string &content_type);
  1607. bool read_content(Stream &strm, Request &req, Response &res);
  1608. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1609. Response &res,
  1610. ContentReceiver receiver,
  1611. FormDataHeader multipart_header,
  1612. ContentReceiver multipart_receiver);
  1613. bool read_content_core(Stream &strm, Request &req, Response &res,
  1614. ContentReceiver receiver,
  1615. FormDataHeader multipart_header,
  1616. ContentReceiver multipart_receiver) const;
  1617. virtual bool process_and_close_socket(socket_t sock);
  1618. void output_log(const Request &req, const Response &res) const;
  1619. void output_pre_compression_log(const Request &req,
  1620. const Response &res) const;
  1621. void output_error_log(const Error &err, const Request *req) const;
  1622. std::atomic<bool> is_running_{false};
  1623. std::atomic<bool> is_decommissioned{false};
  1624. struct MountPointEntry {
  1625. std::string mount_point;
  1626. std::string base_dir;
  1627. std::string resolved_base_dir;
  1628. Headers headers;
  1629. };
  1630. std::vector<MountPointEntry> base_dirs_;
  1631. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1632. std::string default_file_mimetype_ = "application/octet-stream";
  1633. Handler file_request_handler_;
  1634. Handlers get_handlers_;
  1635. Handlers post_handlers_;
  1636. HandlersForContentReader post_handlers_for_content_reader_;
  1637. Handlers put_handlers_;
  1638. HandlersForContentReader put_handlers_for_content_reader_;
  1639. Handlers patch_handlers_;
  1640. HandlersForContentReader patch_handlers_for_content_reader_;
  1641. Handlers delete_handlers_;
  1642. HandlersForContentReader delete_handlers_for_content_reader_;
  1643. Handlers options_handlers_;
  1644. struct WebSocketHandlerEntry {
  1645. std::unique_ptr<detail::MatcherBase> matcher;
  1646. WebSocketHandler handler;
  1647. SubProtocolSelector sub_protocol_selector;
  1648. };
  1649. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1650. WebSocketHandlers websocket_handlers_;
  1651. HandlerWithResponse error_handler_;
  1652. ExceptionHandler exception_handler_;
  1653. HandlerWithResponse pre_routing_handler_;
  1654. Handler post_routing_handler_;
  1655. HandlerWithResponse pre_request_handler_;
  1656. Expect100ContinueHandler expect_100_continue_handler_;
  1657. StartHandler start_handler_;
  1658. mutable std::mutex logger_mutex_;
  1659. Logger logger_;
  1660. Logger pre_compression_logger_;
  1661. ErrorLogger error_logger_;
  1662. int address_family_ = AF_UNSPEC;
  1663. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1664. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1665. SocketOptions socket_options_ = default_socket_options;
  1666. Headers default_headers_;
  1667. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1668. detail::write_headers;
  1669. };
  1670. class Result {
  1671. public:
  1672. Result() = default;
  1673. Result(std::unique_ptr<Response> &&res, Error err,
  1674. Headers &&request_headers = Headers{})
  1675. : res_(std::move(res)), err_(err),
  1676. request_headers_(std::move(request_headers)) {}
  1677. // Response
  1678. operator bool() const { return res_ != nullptr; }
  1679. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1680. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1681. const Response &value() const { return *res_; }
  1682. Response &value() { return *res_; }
  1683. const Response &operator*() const { return *res_; }
  1684. Response &operator*() { return *res_; }
  1685. const Response *operator->() const { return res_.get(); }
  1686. Response *operator->() { return res_.get(); }
  1687. // Error
  1688. Error error() const { return err_; }
  1689. // Request Headers
  1690. bool has_request_header(const std::string &key) const;
  1691. std::string get_request_header_value(const std::string &key,
  1692. const char *def = "",
  1693. size_t id = 0) const;
  1694. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1695. size_t id = 0) const;
  1696. size_t get_request_header_value_count(const std::string &key) const;
  1697. private:
  1698. std::unique_ptr<Response> res_;
  1699. Error err_ = Error::Unknown;
  1700. Headers request_headers_;
  1701. #ifdef CPPHTTPLIB_SSL_ENABLED
  1702. public:
  1703. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1704. int ssl_error)
  1705. : res_(std::move(res)), err_(err),
  1706. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1707. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1708. int ssl_error, uint64_t ssl_backend_error)
  1709. : res_(std::move(res)), err_(err),
  1710. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1711. ssl_backend_error_(ssl_backend_error) {}
  1712. int ssl_error() const { return ssl_error_; }
  1713. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1714. private:
  1715. int ssl_error_ = 0;
  1716. uint64_t ssl_backend_error_ = 0;
  1717. #endif
  1718. };
  1719. struct ClientConnection {
  1720. socket_t sock = INVALID_SOCKET;
  1721. bool is_open() const { return sock != INVALID_SOCKET; }
  1722. ClientConnection() = default;
  1723. ~ClientConnection();
  1724. ClientConnection(const ClientConnection &) = delete;
  1725. ClientConnection &operator=(const ClientConnection &) = delete;
  1726. ClientConnection(ClientConnection &&other) noexcept
  1727. : sock(other.sock)
  1728. #ifdef CPPHTTPLIB_SSL_ENABLED
  1729. ,
  1730. session(other.session)
  1731. #endif
  1732. {
  1733. other.sock = INVALID_SOCKET;
  1734. #ifdef CPPHTTPLIB_SSL_ENABLED
  1735. other.session = nullptr;
  1736. #endif
  1737. }
  1738. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1739. if (this != &other) {
  1740. sock = other.sock;
  1741. other.sock = INVALID_SOCKET;
  1742. #ifdef CPPHTTPLIB_SSL_ENABLED
  1743. session = other.session;
  1744. other.session = nullptr;
  1745. #endif
  1746. }
  1747. return *this;
  1748. }
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. tls::session_t session = nullptr;
  1751. #endif
  1752. };
  1753. namespace detail {
  1754. struct ChunkedDecoder;
  1755. struct BodyReader {
  1756. Stream *stream = nullptr;
  1757. bool has_content_length = false;
  1758. size_t content_length = 0;
  1759. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1760. size_t bytes_read = 0;
  1761. bool chunked = false;
  1762. bool eof = false;
  1763. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1764. Error last_error = Error::Success;
  1765. ssize_t read(char *buf, size_t len);
  1766. bool has_error() const { return last_error != Error::Success; }
  1767. };
  1768. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1769. size_t len) {
  1770. (void)stream;
  1771. return br.read(buf, len);
  1772. }
  1773. class decompressor;
  1774. enum class NoProxyKind {
  1775. Wildcard, // "*"
  1776. HostnameSuffix, // "example.com" or ".example.com"
  1777. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1778. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1779. };
  1780. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1781. // Lets one CIDR matcher cover both families.
  1782. using IPBytes = std::array<uint8_t, 16>;
  1783. struct NoProxyEntry {
  1784. NoProxyKind kind = NoProxyKind::Wildcard;
  1785. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1786. IPBytes net{};
  1787. int prefix_bits = 0;
  1788. };
  1789. struct NormalizedTarget {
  1790. std::string hostname; // lowercase; brackets and trailing dot removed
  1791. bool is_ipv4 = false;
  1792. bool is_ipv6 = false;
  1793. IPBytes ip{};
  1794. };
  1795. } // namespace detail
  1796. class ClientImpl {
  1797. public:
  1798. explicit ClientImpl(const std::string &host);
  1799. explicit ClientImpl(const std::string &host, int port);
  1800. explicit ClientImpl(const std::string &host, int port,
  1801. const std::string &client_cert_path,
  1802. const std::string &client_key_path);
  1803. virtual ~ClientImpl();
  1804. virtual bool is_valid() const;
  1805. struct StreamHandle {
  1806. std::unique_ptr<Response> response;
  1807. Error error = Error::Success;
  1808. StreamHandle() = default;
  1809. StreamHandle(const StreamHandle &) = delete;
  1810. StreamHandle &operator=(const StreamHandle &) = delete;
  1811. StreamHandle(StreamHandle &&) = default;
  1812. StreamHandle &operator=(StreamHandle &&) = default;
  1813. ~StreamHandle() = default;
  1814. bool is_valid() const {
  1815. return response != nullptr && error == Error::Success;
  1816. }
  1817. ssize_t read(char *buf, size_t len);
  1818. void parse_trailers_if_needed();
  1819. Error get_read_error() const { return body_reader_.last_error; }
  1820. bool has_read_error() const { return body_reader_.has_error(); }
  1821. bool trailers_parsed_ = false;
  1822. private:
  1823. friend class ClientImpl;
  1824. ssize_t read_with_decompression(char *buf, size_t len);
  1825. std::unique_ptr<ClientConnection> connection_;
  1826. std::unique_ptr<Stream> socket_stream_;
  1827. Stream *stream_ = nullptr;
  1828. detail::BodyReader body_reader_;
  1829. std::unique_ptr<detail::decompressor> decompressor_;
  1830. std::string decompress_buffer_;
  1831. size_t decompress_offset_ = 0;
  1832. size_t decompressed_bytes_read_ = 0;
  1833. };
  1834. // clang-format off
  1835. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1836. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1837. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1838. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1839. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1840. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1841. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1842. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1843. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1844. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1845. Result Head(const std::string &path);
  1846. Result Head(const std::string &path, const Headers &headers);
  1847. Result Post(const std::string &path);
  1848. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1849. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1850. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1851. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1852. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1853. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1854. Result Post(const std::string &path, const Params &params);
  1855. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1856. Result Post(const std::string &path, const Headers &headers);
  1857. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1858. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1859. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1860. 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);
  1861. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1862. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1863. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1864. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1865. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1866. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1867. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1868. Result Put(const std::string &path);
  1869. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1870. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1871. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1872. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1873. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1874. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1875. Result Put(const std::string &path, const Params &params);
  1876. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1877. Result Put(const std::string &path, const Headers &headers);
  1878. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1879. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1880. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1881. 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);
  1882. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1883. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1884. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1885. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1886. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1887. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1888. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1889. Result Patch(const std::string &path);
  1890. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1891. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1892. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1893. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1894. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1895. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1896. Result Patch(const std::string &path, const Params &params);
  1897. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1898. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1899. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1900. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1901. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1902. 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);
  1903. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1904. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1905. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1906. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1907. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1908. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1909. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1910. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1911. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1912. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1913. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1914. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1915. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1916. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1917. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1918. Result Options(const std::string &path);
  1919. Result Options(const std::string &path, const Headers &headers);
  1920. // clang-format on
  1921. // Streaming API: Open a stream for reading response body incrementally
  1922. // Socket ownership is transferred to StreamHandle for true streaming
  1923. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1924. StreamHandle open_stream(const std::string &method, const std::string &path,
  1925. const Params &params = {},
  1926. const Headers &headers = {},
  1927. const std::string &body = {},
  1928. const std::string &content_type = {});
  1929. bool send(Request &req, Response &res, Error &error);
  1930. Result send(const Request &req);
  1931. void stop();
  1932. std::string host() const;
  1933. int port() const;
  1934. size_t is_socket_open() const;
  1935. socket_t socket() const;
  1936. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1937. void set_default_headers(Headers headers);
  1938. void
  1939. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1940. void set_address_family(int family);
  1941. void set_tcp_nodelay(bool on);
  1942. void set_ipv6_v6only(bool on);
  1943. void set_socket_options(SocketOptions socket_options);
  1944. void set_connection_timeout(time_t sec, time_t usec = 0);
  1945. template <class Rep, class Period>
  1946. void
  1947. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1948. void set_read_timeout(time_t sec, time_t usec = 0);
  1949. template <class Rep, class Period>
  1950. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1951. void set_write_timeout(time_t sec, time_t usec = 0);
  1952. template <class Rep, class Period>
  1953. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1954. void set_max_timeout(time_t msec);
  1955. template <class Rep, class Period>
  1956. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1957. void set_basic_auth(const std::string &username, const std::string &password);
  1958. void set_bearer_token_auth(const std::string &token);
  1959. void set_keep_alive(bool on);
  1960. void set_follow_location(bool on);
  1961. void set_path_encode(bool on);
  1962. void set_compress(bool on);
  1963. void set_decompress(bool on);
  1964. void set_payload_max_length(size_t length);
  1965. void set_interface(const std::string &intf);
  1966. void set_proxy(const std::string &host, int port);
  1967. void set_proxy_basic_auth(const std::string &username,
  1968. const std::string &password);
  1969. void set_proxy_bearer_token_auth(const std::string &token);
  1970. void set_no_proxy(const std::vector<std::string> &patterns);
  1971. void set_logger(Logger logger);
  1972. void set_error_logger(ErrorLogger error_logger);
  1973. protected:
  1974. struct Socket {
  1975. socket_t sock = INVALID_SOCKET;
  1976. // For Mbed TLS compatibility: start_time for request timeout tracking
  1977. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1978. bool is_open() const { return sock != INVALID_SOCKET; }
  1979. #ifdef CPPHTTPLIB_SSL_ENABLED
  1980. tls::session_t ssl = nullptr;
  1981. #endif
  1982. };
  1983. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1984. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1985. virtual bool setup_proxy_connection(
  1986. Socket &socket,
  1987. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1988. Response &res, bool &success, Error &error);
  1989. bool is_proxy_enabled_for_host(const std::string &host) const;
  1990. // All of:
  1991. // shutdown_ssl
  1992. // shutdown_socket
  1993. // close_socket
  1994. // disconnect
  1995. // should ONLY be called when socket_mutex_ is locked, and only when
  1996. // no other thread is using the socket.
  1997. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1998. void shutdown_socket(Socket &socket) const;
  1999. void close_socket(Socket &socket);
  2000. void disconnect(bool gracefully);
  2001. bool process_request(Stream &strm, Request &req, Response &res,
  2002. bool close_connection, Error &error);
  2003. bool write_content_with_provider(Stream &strm, const Request &req,
  2004. Error &error) const;
  2005. void copy_settings(const ClientImpl &rhs);
  2006. void output_log(const Request &req, const Response &res) const;
  2007. void output_error_log(const Error &err, const Request *req) const;
  2008. // Socket endpoint information
  2009. const std::string host_;
  2010. const int port_;
  2011. // Current open socket
  2012. Socket socket_;
  2013. mutable std::mutex socket_mutex_;
  2014. std::recursive_mutex request_mutex_;
  2015. // These are all protected under socket_mutex
  2016. size_t socket_requests_in_flight_ = 0;
  2017. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2018. bool socket_should_be_closed_when_request_is_done_ = false;
  2019. // Hostname to connection target map. The value is an IP literal or another
  2020. // hostname; only the connection target changes, never the identity.
  2021. std::map<std::string, std::string> addr_map_;
  2022. // Default headers
  2023. Headers default_headers_;
  2024. // Header writer
  2025. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2026. detail::write_headers;
  2027. // Settings
  2028. std::string client_cert_path_;
  2029. std::string client_key_path_;
  2030. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2031. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2032. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2033. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2034. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2035. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2036. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2037. std::string basic_auth_username_;
  2038. std::string basic_auth_password_;
  2039. std::string bearer_token_auth_token_;
  2040. bool keep_alive_ = false;
  2041. bool follow_location_ = false;
  2042. bool path_encode_ = true;
  2043. int address_family_ = AF_UNSPEC;
  2044. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2045. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2046. SocketOptions socket_options_ = nullptr;
  2047. bool compress_ = false;
  2048. bool decompress_ = true;
  2049. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2050. bool has_payload_max_length_ = false;
  2051. std::string interface_;
  2052. std::string proxy_host_;
  2053. int proxy_port_ = -1;
  2054. std::string proxy_basic_auth_username_;
  2055. std::string proxy_basic_auth_password_;
  2056. std::string proxy_bearer_token_auth_token_;
  2057. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2058. mutable detail::NormalizedTarget host_normalized_;
  2059. mutable bool host_normalized_valid_ = false;
  2060. mutable std::mutex logger_mutex_;
  2061. Logger logger_;
  2062. ErrorLogger error_logger_;
  2063. private:
  2064. bool send_(Request &req, Response &res, Error &error);
  2065. Result send_(Request &&req);
  2066. socket_t create_client_socket(Error &error) const;
  2067. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2068. bool skip_100_continue = true) const;
  2069. bool write_request(Stream &strm, Request &req, bool close_connection,
  2070. Error &error, bool skip_body = false);
  2071. bool write_request_body(Stream &strm, Request &req, Error &error);
  2072. void prepare_default_headers(Request &r, bool for_stream,
  2073. const std::string &ct);
  2074. bool redirect(Request &req, Response &res, Error &error);
  2075. bool create_redirect_client(const std::string &scheme,
  2076. const std::string &host, int port, Request &req,
  2077. Response &res, const std::string &path,
  2078. const std::string &location, Error &error);
  2079. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2080. bool handle_request(Stream &strm, Request &req, Response &res,
  2081. bool close_connection, Error &error);
  2082. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2083. Request &req, const char *body, size_t content_length,
  2084. ContentProvider content_provider,
  2085. ContentProviderWithoutLength content_provider_without_length,
  2086. const std::string &content_type, ContentReceiver content_receiver,
  2087. Error &error);
  2088. Result send_with_content_provider_and_receiver(
  2089. const std::string &method, const std::string &path,
  2090. const Headers &headers, const char *body, size_t content_length,
  2091. ContentProvider content_provider,
  2092. ContentProviderWithoutLength content_provider_without_length,
  2093. const std::string &content_type, ContentReceiver content_receiver,
  2094. UploadProgress progress);
  2095. ContentProviderWithoutLength get_multipart_content_provider(
  2096. const std::string &boundary, const UploadFormDataItems &items,
  2097. const FormDataProviderItems &provider_items) const;
  2098. virtual bool
  2099. process_socket(const Socket &socket,
  2100. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2101. std::function<bool(Stream &strm)> callback);
  2102. virtual bool is_ssl() const;
  2103. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2104. #ifdef CPPHTTPLIB_SSL_ENABLED
  2105. public:
  2106. void set_digest_auth(const std::string &username,
  2107. const std::string &password);
  2108. void set_proxy_digest_auth(const std::string &username,
  2109. const std::string &password);
  2110. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2111. const std::string &ca_cert_dir_path = std::string());
  2112. void enable_server_certificate_verification(bool enabled);
  2113. void enable_server_hostname_verification(bool enabled);
  2114. void enable_system_ca(bool enabled);
  2115. protected:
  2116. std::string digest_auth_username_;
  2117. std::string digest_auth_password_;
  2118. std::string proxy_digest_auth_username_;
  2119. std::string proxy_digest_auth_password_;
  2120. std::string ca_cert_file_path_;
  2121. std::string ca_cert_dir_path_;
  2122. bool server_certificate_verification_ = true;
  2123. bool server_hostname_verification_ = true;
  2124. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2125. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2126. int last_ssl_error_ = 0;
  2127. uint64_t last_backend_error_ = 0;
  2128. #endif
  2129. };
  2130. class Client {
  2131. public:
  2132. // Universal interface
  2133. explicit Client(const std::string &scheme_host_port);
  2134. explicit Client(const std::string &scheme_host_port,
  2135. const std::string &client_cert_path,
  2136. const std::string &client_key_path);
  2137. // HTTP only interface
  2138. explicit Client(const std::string &host, int port);
  2139. explicit Client(const std::string &host, int port,
  2140. const std::string &client_cert_path,
  2141. const std::string &client_key_path);
  2142. Client(Client &&) = default;
  2143. Client &operator=(Client &&) = default;
  2144. ~Client();
  2145. bool is_valid() const;
  2146. // clang-format off
  2147. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2148. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2149. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2150. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2151. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2152. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2153. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2154. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2155. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2156. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2157. Result Head(const std::string &path);
  2158. Result Head(const std::string &path, const Headers &headers);
  2159. Result Post(const std::string &path);
  2160. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2161. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2162. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2163. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2164. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2165. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2166. Result Post(const std::string &path, const Params &params);
  2167. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2168. Result Post(const std::string &path, const Headers &headers);
  2169. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2170. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2171. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2172. 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);
  2173. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2174. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2175. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2176. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2177. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2178. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2179. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2180. Result Put(const std::string &path);
  2181. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2182. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2184. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2185. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2186. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2187. Result Put(const std::string &path, const Params &params);
  2188. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2189. Result Put(const std::string &path, const Headers &headers);
  2190. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2191. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2192. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2193. 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);
  2194. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2195. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2196. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2197. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2198. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2199. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2200. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2201. Result Patch(const std::string &path);
  2202. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2203. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2205. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2206. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2207. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2208. Result Patch(const std::string &path, const Params &params);
  2209. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2210. Result Patch(const std::string &path, const Headers &headers);
  2211. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2212. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2213. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2214. 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);
  2215. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2216. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2217. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2218. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2219. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2220. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2221. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2222. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2223. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2224. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2225. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2226. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2227. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2228. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2229. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2230. Result Options(const std::string &path);
  2231. Result Options(const std::string &path, const Headers &headers);
  2232. // clang-format on
  2233. // Streaming API: Open a stream for reading response body incrementally
  2234. // Socket ownership is transferred to StreamHandle for true streaming
  2235. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2236. ClientImpl::StreamHandle open_stream(const std::string &method,
  2237. const std::string &path,
  2238. const Params &params = {},
  2239. const Headers &headers = {},
  2240. const std::string &body = {},
  2241. const std::string &content_type = {});
  2242. bool send(Request &req, Response &res, Error &error);
  2243. Result send(const Request &req);
  2244. void stop();
  2245. std::string host() const;
  2246. int port() const;
  2247. size_t is_socket_open() const;
  2248. socket_t socket() const;
  2249. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2250. void set_default_headers(Headers headers);
  2251. void
  2252. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2253. void set_address_family(int family);
  2254. void set_tcp_nodelay(bool on);
  2255. void set_socket_options(SocketOptions socket_options);
  2256. void set_connection_timeout(time_t sec, time_t usec = 0);
  2257. template <class Rep, class Period>
  2258. void
  2259. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2260. void set_read_timeout(time_t sec, time_t usec = 0);
  2261. template <class Rep, class Period>
  2262. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2263. void set_write_timeout(time_t sec, time_t usec = 0);
  2264. template <class Rep, class Period>
  2265. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2266. void set_max_timeout(time_t msec);
  2267. template <class Rep, class Period>
  2268. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2269. void set_basic_auth(const std::string &username, const std::string &password);
  2270. void set_bearer_token_auth(const std::string &token);
  2271. void set_keep_alive(bool on);
  2272. void set_follow_location(bool on);
  2273. void set_path_encode(bool on);
  2274. void set_compress(bool on);
  2275. void set_decompress(bool on);
  2276. void set_payload_max_length(size_t length);
  2277. void set_interface(const std::string &intf);
  2278. void set_proxy(const std::string &host, int port);
  2279. void set_proxy_basic_auth(const std::string &username,
  2280. const std::string &password);
  2281. void set_proxy_bearer_token_auth(const std::string &token);
  2282. void set_no_proxy(const std::vector<std::string> &patterns);
  2283. void set_logger(Logger logger);
  2284. void set_error_logger(ErrorLogger error_logger);
  2285. private:
  2286. std::unique_ptr<ClientImpl> cli_;
  2287. #ifdef CPPHTTPLIB_SSL_ENABLED
  2288. public:
  2289. void set_digest_auth(const std::string &username,
  2290. const std::string &password);
  2291. void set_proxy_digest_auth(const std::string &username,
  2292. const std::string &password);
  2293. void enable_server_certificate_verification(bool enabled);
  2294. void enable_server_hostname_verification(bool enabled);
  2295. void enable_system_ca(bool enabled);
  2296. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2297. const std::string &ca_cert_dir_path = std::string());
  2298. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2299. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2300. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2301. void set_session_verifier(
  2302. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2303. tls::ctx_t tls_context() const;
  2304. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2305. void enable_windows_certificate_verification(bool enabled);
  2306. #endif
  2307. private:
  2308. bool is_ssl_ = false;
  2309. #endif
  2310. };
  2311. #ifdef CPPHTTPLIB_SSL_ENABLED
  2312. class SSLServer : public Server {
  2313. public:
  2314. SSLServer(const char *cert_path, const char *private_key_path,
  2315. const char *client_ca_cert_file_path = nullptr,
  2316. const char *client_ca_cert_dir_path = nullptr,
  2317. const char *private_key_password = nullptr);
  2318. struct PemMemory {
  2319. const char *cert_pem;
  2320. size_t cert_pem_len;
  2321. const char *key_pem;
  2322. size_t key_pem_len;
  2323. const char *client_ca_pem;
  2324. size_t client_ca_pem_len;
  2325. const char *private_key_password;
  2326. };
  2327. explicit SSLServer(const PemMemory &pem);
  2328. // The callback receives the ctx_t handle which can be cast to the
  2329. // appropriate backend type (SSL_CTX* for OpenSSL,
  2330. // tls::impl::MbedTlsContext* for Mbed TLS)
  2331. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2332. ~SSLServer() override;
  2333. bool is_valid() const override;
  2334. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2335. const char *client_ca_pem = nullptr,
  2336. const char *password = nullptr);
  2337. tls::ctx_t tls_context() const { return ctx_; }
  2338. int ssl_last_error() const { return last_ssl_error_; }
  2339. private:
  2340. bool process_and_close_socket(socket_t sock) override;
  2341. tls::ctx_t ctx_ = nullptr;
  2342. std::mutex ctx_mutex_;
  2343. int last_ssl_error_ = 0;
  2344. };
  2345. class SSLClient final : public ClientImpl {
  2346. public:
  2347. explicit SSLClient(const std::string &host);
  2348. explicit SSLClient(const std::string &host, int port);
  2349. explicit SSLClient(const std::string &host, int port,
  2350. const std::string &client_cert_path,
  2351. const std::string &client_key_path,
  2352. const std::string &private_key_password = std::string());
  2353. struct PemMemory {
  2354. const char *cert_pem;
  2355. size_t cert_pem_len;
  2356. const char *key_pem;
  2357. size_t key_pem_len;
  2358. const char *private_key_password;
  2359. };
  2360. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2361. ~SSLClient() override;
  2362. bool is_valid() const override;
  2363. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2364. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2365. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2366. // Post-handshake session verifier (backend-independent)
  2367. void set_session_verifier(
  2368. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2369. tls::ctx_t tls_context() const { return ctx_; }
  2370. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2371. void enable_windows_certificate_verification(bool enabled);
  2372. #endif
  2373. private:
  2374. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2375. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2376. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2377. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2378. bool
  2379. process_socket(const Socket &socket,
  2380. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2381. std::function<bool(Stream &strm)> callback) override;
  2382. bool is_ssl() const override;
  2383. bool setup_proxy_connection(
  2384. Socket &socket,
  2385. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2386. Response &res, bool &success, Error &error) override;
  2387. bool connect_with_proxy(
  2388. Socket &sock,
  2389. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2390. Response &res, bool &success, Error &error);
  2391. bool initialize_ssl(Socket &socket, Error &error);
  2392. void init_ctx();
  2393. void reset_ctx_on_error();
  2394. bool load_certs();
  2395. tls::ctx_t ctx_ = nullptr;
  2396. std::mutex ctx_mutex_;
  2397. std::once_flag initialize_cert_;
  2398. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2399. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2400. // Used to keep custom CA configuration exclusive with system CA loading.
  2401. bool ca_cert_store_set_ = false;
  2402. long verify_result_ = 0;
  2403. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2404. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2405. bool enable_windows_cert_verification_ = true;
  2406. #endif
  2407. friend class ClientImpl;
  2408. };
  2409. #endif // CPPHTTPLIB_SSL_ENABLED
  2410. namespace detail {
  2411. template <typename T, typename U>
  2412. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2413. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2414. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2415. duration - std::chrono::seconds(sec))
  2416. .count();
  2417. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2418. }
  2419. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2420. return N - 1;
  2421. }
  2422. inline bool is_numeric(const std::string &str) {
  2423. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2424. }
  2425. inline size_t get_header_value_u64(const Headers &headers,
  2426. const std::string &key, size_t def,
  2427. size_t id, bool &is_invalid_value) {
  2428. is_invalid_value = false;
  2429. auto rng = headers.equal_range(key);
  2430. auto it = rng.first;
  2431. std::advance(it, static_cast<ssize_t>(id));
  2432. if (it != rng.second) {
  2433. if (is_numeric(it->second)) {
  2434. // Parse at size_t width so an out-of-range Content-Length is reported
  2435. // rather than silently saturated/truncated (a value above 2^32 would
  2436. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  2437. // and return SIZE_MAX so the existing oversized-value guards reject it.
  2438. size_t val = 0;
  2439. const auto &s = it->second;
  2440. auto r = from_chars(s.data(), s.data() + s.size(), val);
  2441. if (r.ec == std::errc::result_out_of_range) {
  2442. is_invalid_value = true;
  2443. return (std::numeric_limits<size_t>::max)();
  2444. }
  2445. return val;
  2446. } else {
  2447. is_invalid_value = true;
  2448. }
  2449. }
  2450. return def;
  2451. }
  2452. inline size_t get_header_value_u64(const Headers &headers,
  2453. const std::string &key, size_t def,
  2454. size_t id) {
  2455. auto dummy = false;
  2456. return get_header_value_u64(headers, key, def, id, dummy);
  2457. }
  2458. } // namespace detail
  2459. template <class Rep, class Period>
  2460. inline Server &
  2461. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2462. detail::duration_to_sec_and_usec(
  2463. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2464. return *this;
  2465. }
  2466. template <class Rep, class Period>
  2467. inline Server &
  2468. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2469. detail::duration_to_sec_and_usec(
  2470. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2471. return *this;
  2472. }
  2473. template <class Rep, class Period>
  2474. inline Server &
  2475. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2476. detail::duration_to_sec_and_usec(
  2477. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2478. return *this;
  2479. }
  2480. template <class Rep, class Period>
  2481. inline void ClientImpl::set_connection_timeout(
  2482. const std::chrono::duration<Rep, Period> &duration) {
  2483. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2484. set_connection_timeout(sec, usec);
  2485. });
  2486. }
  2487. template <class Rep, class Period>
  2488. inline void ClientImpl::set_read_timeout(
  2489. const std::chrono::duration<Rep, Period> &duration) {
  2490. detail::duration_to_sec_and_usec(
  2491. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2492. }
  2493. template <class Rep, class Period>
  2494. inline void ClientImpl::set_write_timeout(
  2495. const std::chrono::duration<Rep, Period> &duration) {
  2496. detail::duration_to_sec_and_usec(
  2497. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2498. }
  2499. template <class Rep, class Period>
  2500. inline void ClientImpl::set_max_timeout(
  2501. const std::chrono::duration<Rep, Period> &duration) {
  2502. auto msec =
  2503. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2504. set_max_timeout(msec);
  2505. }
  2506. template <class Rep, class Period>
  2507. inline void Client::set_connection_timeout(
  2508. const std::chrono::duration<Rep, Period> &duration) {
  2509. cli_->set_connection_timeout(duration);
  2510. }
  2511. template <class Rep, class Period>
  2512. inline void
  2513. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2514. cli_->set_read_timeout(duration);
  2515. }
  2516. template <class Rep, class Period>
  2517. inline void
  2518. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2519. cli_->set_write_timeout(duration);
  2520. }
  2521. inline void Client::set_max_timeout(time_t msec) {
  2522. cli_->set_max_timeout(msec);
  2523. }
  2524. template <class Rep, class Period>
  2525. inline void
  2526. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2527. cli_->set_max_timeout(duration);
  2528. }
  2529. /*
  2530. * Forward declarations and types that will be part of the .h file if split into
  2531. * .h + .cc.
  2532. */
  2533. std::string hosted_at(const std::string &hostname);
  2534. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2535. // JavaScript-style URL encoding/decoding functions
  2536. std::string encode_uri_component(const std::string &value);
  2537. std::string encode_uri(const std::string &value);
  2538. std::string decode_uri_component(const std::string &value);
  2539. std::string decode_uri(const std::string &value);
  2540. // RFC 3986 compliant URL component encoding/decoding functions
  2541. std::string encode_path_component(const std::string &component);
  2542. std::string decode_path_component(const std::string &component);
  2543. std::string encode_query_component(const std::string &component,
  2544. bool space_as_plus = true);
  2545. std::string decode_query_component(const std::string &component,
  2546. bool plus_as_space = true);
  2547. std::string sanitize_filename(const std::string &filename);
  2548. std::string append_query_params(const std::string &path, const Params &params);
  2549. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2550. std::pair<std::string, std::string>
  2551. make_basic_authentication_header(const std::string &username,
  2552. const std::string &password,
  2553. bool is_proxy = false);
  2554. namespace detail {
  2555. #if defined(_WIN32)
  2556. inline std::wstring u8string_to_wstring(const char *s) {
  2557. if (!s) { return std::wstring(); }
  2558. auto len = static_cast<int>(strlen(s));
  2559. if (!len) { return std::wstring(); }
  2560. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2561. if (!wlen) { return std::wstring(); }
  2562. std::wstring ws;
  2563. ws.resize(wlen);
  2564. wlen = ::MultiByteToWideChar(
  2565. CP_UTF8, 0, s, len,
  2566. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2567. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2568. return ws;
  2569. }
  2570. #endif
  2571. struct FileStat {
  2572. FileStat(const std::string &path);
  2573. bool is_file() const;
  2574. bool is_dir() const;
  2575. time_t mtime() const;
  2576. size_t size() const;
  2577. private:
  2578. #if defined(_WIN32)
  2579. struct _stat st_;
  2580. #else
  2581. struct stat st_;
  2582. #endif
  2583. int ret_ = -1;
  2584. };
  2585. std::string make_host_and_port_string(const std::string &host, int port,
  2586. bool is_ssl);
  2587. template <typename T>
  2588. bool check_and_write_headers(Stream &strm, Headers &headers, T header_writer,
  2589. Error &error);
  2590. std::string trim_copy(const std::string &s);
  2591. void divide(
  2592. const char *data, std::size_t size, char d,
  2593. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2594. fn);
  2595. void divide(
  2596. const std::string &str, char d,
  2597. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2598. fn);
  2599. void split(const char *b, const char *e, char d,
  2600. std::function<void(const char *, const char *)> fn);
  2601. void split(const char *b, const char *e, char d, size_t m,
  2602. std::function<void(const char *, const char *)> fn);
  2603. bool process_client_socket(
  2604. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2605. time_t write_timeout_sec, time_t write_timeout_usec,
  2606. time_t max_timeout_msec,
  2607. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2608. std::function<bool(Stream &)> callback);
  2609. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2610. int port, int address_family, bool tcp_nodelay,
  2611. bool ipv6_v6only, SocketOptions socket_options,
  2612. time_t connection_timeout_sec,
  2613. time_t connection_timeout_usec,
  2614. time_t read_timeout_sec, time_t read_timeout_usec,
  2615. time_t write_timeout_sec,
  2616. time_t write_timeout_usec,
  2617. const std::string &intf, Error &error);
  2618. const char *get_header_value(const Headers &headers, const std::string &key,
  2619. const char *def, size_t id);
  2620. std::string params_to_query_str(const Params &params);
  2621. void parse_query_text(const char *data, std::size_t size, Params &params);
  2622. void parse_query_text(const std::string &s, Params &params);
  2623. bool parse_multipart_boundary(const std::string &content_type,
  2624. std::string &boundary);
  2625. bool parse_range_header(const std::string &s, Ranges &ranges);
  2626. bool parse_accept_header(const std::string &s,
  2627. std::vector<std::string> &content_types);
  2628. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2629. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2630. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2631. EncodingType encoding_type(const Request &req, const Response &res);
  2632. class BufferStream final : public Stream {
  2633. public:
  2634. BufferStream() = default;
  2635. ~BufferStream() override = default;
  2636. bool is_readable() const override;
  2637. bool wait_readable() const override;
  2638. bool wait_writable() const override;
  2639. ssize_t read(char *ptr, size_t size) override;
  2640. ssize_t write(const char *ptr, size_t size) override;
  2641. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2642. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2643. socket_t socket() const override;
  2644. time_t duration() const override;
  2645. const std::string &get_buffer() const;
  2646. private:
  2647. std::string buffer;
  2648. size_t position = 0;
  2649. };
  2650. class compressor {
  2651. public:
  2652. virtual ~compressor() = default;
  2653. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2654. virtual bool compress(const char *data, size_t data_length, bool last,
  2655. Callback callback) = 0;
  2656. };
  2657. class decompressor {
  2658. public:
  2659. virtual ~decompressor() = default;
  2660. virtual bool is_valid() const = 0;
  2661. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2662. virtual bool decompress(const char *data, size_t data_length,
  2663. Callback callback) = 0;
  2664. };
  2665. class nocompressor final : public compressor {
  2666. public:
  2667. ~nocompressor() override = default;
  2668. bool compress(const char *data, size_t data_length, bool /*last*/,
  2669. Callback callback) override;
  2670. };
  2671. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2672. class gzip_compressor final : public compressor {
  2673. public:
  2674. gzip_compressor();
  2675. ~gzip_compressor() override;
  2676. bool compress(const char *data, size_t data_length, bool last,
  2677. Callback callback) override;
  2678. private:
  2679. bool is_valid_ = false;
  2680. z_stream strm_;
  2681. };
  2682. class gzip_decompressor final : public decompressor {
  2683. public:
  2684. gzip_decompressor();
  2685. ~gzip_decompressor() override;
  2686. bool is_valid() const override;
  2687. bool decompress(const char *data, size_t data_length,
  2688. Callback callback) override;
  2689. private:
  2690. bool is_valid_ = false;
  2691. z_stream strm_;
  2692. };
  2693. #endif
  2694. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2695. class brotli_compressor final : public compressor {
  2696. public:
  2697. brotli_compressor();
  2698. ~brotli_compressor();
  2699. bool compress(const char *data, size_t data_length, bool last,
  2700. Callback callback) override;
  2701. private:
  2702. BrotliEncoderState *state_ = nullptr;
  2703. };
  2704. class brotli_decompressor final : public decompressor {
  2705. public:
  2706. brotli_decompressor();
  2707. ~brotli_decompressor();
  2708. bool is_valid() const override;
  2709. bool decompress(const char *data, size_t data_length,
  2710. Callback callback) override;
  2711. private:
  2712. BrotliDecoderResult decoder_r;
  2713. BrotliDecoderState *decoder_s = nullptr;
  2714. };
  2715. #endif
  2716. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2717. class zstd_compressor : public compressor {
  2718. public:
  2719. zstd_compressor();
  2720. ~zstd_compressor();
  2721. bool compress(const char *data, size_t data_length, bool last,
  2722. Callback callback) override;
  2723. private:
  2724. ZSTD_CCtx *ctx_ = nullptr;
  2725. };
  2726. class zstd_decompressor : public decompressor {
  2727. public:
  2728. zstd_decompressor();
  2729. ~zstd_decompressor();
  2730. bool is_valid() const override;
  2731. bool decompress(const char *data, size_t data_length,
  2732. Callback callback) override;
  2733. private:
  2734. ZSTD_DCtx *ctx_ = nullptr;
  2735. };
  2736. #endif
  2737. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2738. // to store data. The call can set memory on stack for performance.
  2739. class stream_line_reader {
  2740. public:
  2741. stream_line_reader(Stream &strm, char *fixed_buffer,
  2742. size_t fixed_buffer_size);
  2743. const char *ptr() const;
  2744. size_t size() const;
  2745. bool end_with_crlf() const;
  2746. bool getline();
  2747. private:
  2748. void append(char c);
  2749. Stream &strm_;
  2750. char *fixed_buffer_;
  2751. const size_t fixed_buffer_size_;
  2752. size_t fixed_buffer_used_size_ = 0;
  2753. std::string growable_buffer_;
  2754. };
  2755. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2756. const Headers &src_headers);
  2757. struct ChunkedDecoder {
  2758. Stream &strm;
  2759. size_t chunk_remaining = 0;
  2760. bool finished = false;
  2761. char line_buf[64];
  2762. size_t last_chunk_total = 0;
  2763. size_t last_chunk_offset = 0;
  2764. explicit ChunkedDecoder(Stream &s);
  2765. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2766. size_t &out_chunk_total);
  2767. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2768. };
  2769. class mmap {
  2770. public:
  2771. mmap(const char *path);
  2772. ~mmap();
  2773. bool open(const char *path);
  2774. void close();
  2775. bool is_open() const;
  2776. size_t size() const;
  2777. const char *data() const;
  2778. private:
  2779. #if defined(_WIN32)
  2780. HANDLE hFile_ = NULL;
  2781. HANDLE hMapping_ = NULL;
  2782. #else
  2783. int fd_ = -1;
  2784. #endif
  2785. size_t size_ = 0;
  2786. void *addr_ = nullptr;
  2787. bool is_open_empty_file = false;
  2788. };
  2789. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2790. namespace fields {
  2791. bool is_token_char(char c);
  2792. bool is_token(const std::string &s);
  2793. bool is_field_name(const std::string &s);
  2794. bool is_vchar(char c);
  2795. bool is_obs_text(char c);
  2796. bool is_field_vchar(char c);
  2797. bool is_field_content(const std::string &s);
  2798. bool is_field_value(const std::string &s);
  2799. bool is_field_valid(const std::string &name, const std::string &value);
  2800. } // namespace fields
  2801. } // namespace detail
  2802. /*
  2803. * TLS Abstraction Layer Declarations
  2804. */
  2805. #ifdef CPPHTTPLIB_SSL_ENABLED
  2806. // TLS abstraction layer - backend-specific type declarations
  2807. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2808. namespace tls {
  2809. namespace impl {
  2810. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2811. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2812. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2813. struct MbedTlsContext {
  2814. mbedtls_ssl_config conf;
  2815. #ifndef CPPHTTPLIB_MBEDTLS_V4
  2816. // Mbed TLS 4.x uses PSA Crypto's internal RNG; no explicit entropy/DRBG.
  2817. mbedtls_entropy_context entropy;
  2818. mbedtls_ctr_drbg_context ctr_drbg;
  2819. #endif
  2820. mbedtls_x509_crt ca_chain;
  2821. mbedtls_x509_crt own_cert;
  2822. mbedtls_pk_context own_key;
  2823. bool is_server = false;
  2824. bool verify_client = false;
  2825. bool has_verify_callback = false;
  2826. MbedTlsContext();
  2827. ~MbedTlsContext();
  2828. MbedTlsContext(const MbedTlsContext &) = delete;
  2829. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2830. };
  2831. } // namespace impl
  2832. } // namespace tls
  2833. #endif
  2834. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2835. namespace tls {
  2836. namespace impl {
  2837. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2838. // This struct is accessible via tls::impl for use in SSL context
  2839. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2840. struct WolfSSLContext {
  2841. WOLFSSL_CTX *ctx = nullptr;
  2842. bool is_server = false;
  2843. bool verify_client = false;
  2844. bool has_verify_callback = false;
  2845. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2846. WolfSSLContext();
  2847. ~WolfSSLContext();
  2848. WolfSSLContext(const WolfSSLContext &) = delete;
  2849. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2850. };
  2851. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2852. struct WolfSSLCAStore {
  2853. std::string pem_data;
  2854. };
  2855. } // namespace impl
  2856. } // namespace tls
  2857. #endif
  2858. #endif // CPPHTTPLIB_SSL_ENABLED
  2859. namespace stream {
  2860. class Result {
  2861. public:
  2862. Result();
  2863. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2864. Result(Result &&other) noexcept;
  2865. Result &operator=(Result &&other) noexcept;
  2866. Result(const Result &) = delete;
  2867. Result &operator=(const Result &) = delete;
  2868. // Response info
  2869. bool is_valid() const;
  2870. explicit operator bool() const;
  2871. int status() const;
  2872. const Headers &headers() const;
  2873. std::string get_header_value(const std::string &key,
  2874. const char *def = "") const;
  2875. bool has_header(const std::string &key) const;
  2876. Error error() const;
  2877. Error read_error() const;
  2878. bool has_read_error() const;
  2879. // Stream reading
  2880. bool next();
  2881. const char *data() const;
  2882. size_t size() const;
  2883. std::string read_all();
  2884. private:
  2885. ClientImpl::StreamHandle handle_;
  2886. std::string buffer_;
  2887. size_t current_size_ = 0;
  2888. size_t chunk_size_;
  2889. bool finished_ = false;
  2890. };
  2891. // GET
  2892. template <typename ClientType>
  2893. inline Result Get(ClientType &cli, const std::string &path,
  2894. size_t chunk_size = 8192) {
  2895. return Result{cli.open_stream("GET", path), chunk_size};
  2896. }
  2897. template <typename ClientType>
  2898. inline Result Get(ClientType &cli, const std::string &path,
  2899. const Headers &headers, size_t chunk_size = 8192) {
  2900. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2901. }
  2902. template <typename ClientType>
  2903. inline Result Get(ClientType &cli, const std::string &path,
  2904. const Params &params, size_t chunk_size = 8192) {
  2905. return Result{cli.open_stream("GET", path, params), chunk_size};
  2906. }
  2907. template <typename ClientType>
  2908. inline Result Get(ClientType &cli, const std::string &path,
  2909. const Params &params, const Headers &headers,
  2910. size_t chunk_size = 8192) {
  2911. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2912. }
  2913. // POST
  2914. template <typename ClientType>
  2915. inline Result Post(ClientType &cli, const std::string &path,
  2916. const std::string &body, const std::string &content_type,
  2917. size_t chunk_size = 8192) {
  2918. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2919. chunk_size};
  2920. }
  2921. template <typename ClientType>
  2922. inline Result Post(ClientType &cli, const std::string &path,
  2923. const Headers &headers, const std::string &body,
  2924. const std::string &content_type, size_t chunk_size = 8192) {
  2925. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2926. chunk_size};
  2927. }
  2928. template <typename ClientType>
  2929. inline Result Post(ClientType &cli, const std::string &path,
  2930. const Params &params, const std::string &body,
  2931. const std::string &content_type, size_t chunk_size = 8192) {
  2932. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2933. chunk_size};
  2934. }
  2935. template <typename ClientType>
  2936. inline Result Post(ClientType &cli, const std::string &path,
  2937. const Params &params, const Headers &headers,
  2938. const std::string &body, const std::string &content_type,
  2939. size_t chunk_size = 8192) {
  2940. return Result{
  2941. cli.open_stream("POST", path, params, headers, body, content_type),
  2942. chunk_size};
  2943. }
  2944. // PUT
  2945. template <typename ClientType>
  2946. inline Result Put(ClientType &cli, const std::string &path,
  2947. const std::string &body, const std::string &content_type,
  2948. size_t chunk_size = 8192) {
  2949. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2950. chunk_size};
  2951. }
  2952. template <typename ClientType>
  2953. inline Result Put(ClientType &cli, const std::string &path,
  2954. const Headers &headers, const std::string &body,
  2955. const std::string &content_type, size_t chunk_size = 8192) {
  2956. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2957. chunk_size};
  2958. }
  2959. template <typename ClientType>
  2960. inline Result Put(ClientType &cli, const std::string &path,
  2961. const Params &params, const std::string &body,
  2962. const std::string &content_type, size_t chunk_size = 8192) {
  2963. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2964. chunk_size};
  2965. }
  2966. template <typename ClientType>
  2967. inline Result Put(ClientType &cli, const std::string &path,
  2968. const Params &params, const Headers &headers,
  2969. const std::string &body, const std::string &content_type,
  2970. size_t chunk_size = 8192) {
  2971. return Result{
  2972. cli.open_stream("PUT", path, params, headers, body, content_type),
  2973. chunk_size};
  2974. }
  2975. // PATCH
  2976. template <typename ClientType>
  2977. inline Result Patch(ClientType &cli, const std::string &path,
  2978. const std::string &body, const std::string &content_type,
  2979. size_t chunk_size = 8192) {
  2980. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2981. chunk_size};
  2982. }
  2983. template <typename ClientType>
  2984. inline Result Patch(ClientType &cli, const std::string &path,
  2985. const Headers &headers, const std::string &body,
  2986. const std::string &content_type, size_t chunk_size = 8192) {
  2987. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2988. chunk_size};
  2989. }
  2990. template <typename ClientType>
  2991. inline Result Patch(ClientType &cli, const std::string &path,
  2992. const Params &params, const std::string &body,
  2993. const std::string &content_type, size_t chunk_size = 8192) {
  2994. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2995. chunk_size};
  2996. }
  2997. template <typename ClientType>
  2998. inline Result Patch(ClientType &cli, const std::string &path,
  2999. const Params &params, const Headers &headers,
  3000. const std::string &body, const std::string &content_type,
  3001. size_t chunk_size = 8192) {
  3002. return Result{
  3003. cli.open_stream("PATCH", path, params, headers, body, content_type),
  3004. chunk_size};
  3005. }
  3006. // DELETE
  3007. template <typename ClientType>
  3008. inline Result Delete(ClientType &cli, const std::string &path,
  3009. size_t chunk_size = 8192) {
  3010. return Result{cli.open_stream("DELETE", path), chunk_size};
  3011. }
  3012. template <typename ClientType>
  3013. inline Result Delete(ClientType &cli, const std::string &path,
  3014. const Headers &headers, size_t chunk_size = 8192) {
  3015. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  3016. }
  3017. template <typename ClientType>
  3018. inline Result Delete(ClientType &cli, const std::string &path,
  3019. const std::string &body, const std::string &content_type,
  3020. size_t chunk_size = 8192) {
  3021. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3022. chunk_size};
  3023. }
  3024. template <typename ClientType>
  3025. inline Result Delete(ClientType &cli, const std::string &path,
  3026. const Headers &headers, const std::string &body,
  3027. const std::string &content_type,
  3028. size_t chunk_size = 8192) {
  3029. return Result{
  3030. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3031. chunk_size};
  3032. }
  3033. template <typename ClientType>
  3034. inline Result Delete(ClientType &cli, const std::string &path,
  3035. const Params &params, size_t chunk_size = 8192) {
  3036. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3037. }
  3038. template <typename ClientType>
  3039. inline Result Delete(ClientType &cli, const std::string &path,
  3040. const Params &params, const Headers &headers,
  3041. size_t chunk_size = 8192) {
  3042. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3043. }
  3044. template <typename ClientType>
  3045. inline Result Delete(ClientType &cli, const std::string &path,
  3046. const Params &params, const std::string &body,
  3047. const std::string &content_type,
  3048. size_t chunk_size = 8192) {
  3049. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3050. chunk_size};
  3051. }
  3052. template <typename ClientType>
  3053. inline Result Delete(ClientType &cli, const std::string &path,
  3054. const Params &params, const Headers &headers,
  3055. const std::string &body, const std::string &content_type,
  3056. size_t chunk_size = 8192) {
  3057. return Result{
  3058. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3059. chunk_size};
  3060. }
  3061. // HEAD
  3062. template <typename ClientType>
  3063. inline Result Head(ClientType &cli, const std::string &path,
  3064. size_t chunk_size = 8192) {
  3065. return Result{cli.open_stream("HEAD", path), chunk_size};
  3066. }
  3067. template <typename ClientType>
  3068. inline Result Head(ClientType &cli, const std::string &path,
  3069. const Headers &headers, size_t chunk_size = 8192) {
  3070. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3071. }
  3072. template <typename ClientType>
  3073. inline Result Head(ClientType &cli, const std::string &path,
  3074. const Params &params, size_t chunk_size = 8192) {
  3075. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3076. }
  3077. template <typename ClientType>
  3078. inline Result Head(ClientType &cli, const std::string &path,
  3079. const Params &params, const Headers &headers,
  3080. size_t chunk_size = 8192) {
  3081. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3082. }
  3083. // OPTIONS
  3084. template <typename ClientType>
  3085. inline Result Options(ClientType &cli, const std::string &path,
  3086. size_t chunk_size = 8192) {
  3087. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3088. }
  3089. template <typename ClientType>
  3090. inline Result Options(ClientType &cli, const std::string &path,
  3091. const Headers &headers, size_t chunk_size = 8192) {
  3092. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3093. }
  3094. template <typename ClientType>
  3095. inline Result Options(ClientType &cli, const std::string &path,
  3096. const Params &params, size_t chunk_size = 8192) {
  3097. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3098. }
  3099. template <typename ClientType>
  3100. inline Result Options(ClientType &cli, const std::string &path,
  3101. const Params &params, const Headers &headers,
  3102. size_t chunk_size = 8192) {
  3103. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3104. }
  3105. } // namespace stream
  3106. namespace sse {
  3107. struct SSEMessage {
  3108. std::string event; // Event type (default: "message")
  3109. std::string data; // Event payload
  3110. std::string id; // Event ID for Last-Event-ID header
  3111. SSEMessage();
  3112. void clear();
  3113. };
  3114. class SSEClient {
  3115. public:
  3116. using MessageHandler = std::function<void(const SSEMessage &)>;
  3117. using ErrorHandler = std::function<void(Error)>;
  3118. using OpenHandler = std::function<void()>;
  3119. SSEClient(Client &client, const std::string &path);
  3120. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3121. ~SSEClient();
  3122. SSEClient(const SSEClient &) = delete;
  3123. SSEClient &operator=(const SSEClient &) = delete;
  3124. // Event handlers
  3125. SSEClient &on_message(MessageHandler handler);
  3126. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3127. SSEClient &on_open(OpenHandler handler);
  3128. SSEClient &on_error(ErrorHandler handler);
  3129. SSEClient &set_reconnect_interval(int ms);
  3130. SSEClient &set_max_reconnect_attempts(int n);
  3131. // Update headers (thread-safe)
  3132. SSEClient &set_headers(const Headers &headers);
  3133. // State accessors
  3134. bool is_connected() const;
  3135. const std::string &last_event_id() const;
  3136. // Blocking start - runs event loop with auto-reconnect
  3137. void start();
  3138. // Non-blocking start - runs in background thread
  3139. void start_async();
  3140. // Stop the client (thread-safe)
  3141. void stop();
  3142. private:
  3143. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3144. void run_event_loop();
  3145. void dispatch_event(const SSEMessage &msg);
  3146. bool should_reconnect(int count) const;
  3147. void wait_for_reconnect();
  3148. // Client and path
  3149. Client &client_;
  3150. std::string path_;
  3151. Headers headers_;
  3152. mutable std::mutex headers_mutex_;
  3153. // Callbacks
  3154. MessageHandler on_message_;
  3155. std::map<std::string, MessageHandler> event_handlers_;
  3156. OpenHandler on_open_;
  3157. ErrorHandler on_error_;
  3158. // Configuration
  3159. int reconnect_interval_ms_ = 3000;
  3160. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3161. // State
  3162. std::atomic<bool> running_{false};
  3163. std::atomic<bool> connected_{false};
  3164. std::string last_event_id_;
  3165. // Async support
  3166. std::thread async_thread_;
  3167. };
  3168. } // namespace sse
  3169. namespace ws {
  3170. enum class Opcode : uint8_t {
  3171. Continuation = 0x0,
  3172. Text = 0x1,
  3173. Binary = 0x2,
  3174. Close = 0x8,
  3175. Ping = 0x9,
  3176. Pong = 0xA,
  3177. };
  3178. enum class CloseStatus : uint16_t {
  3179. Normal = 1000,
  3180. GoingAway = 1001,
  3181. ProtocolError = 1002,
  3182. UnsupportedData = 1003,
  3183. NoStatus = 1005,
  3184. Abnormal = 1006,
  3185. InvalidPayload = 1007,
  3186. PolicyViolation = 1008,
  3187. MessageTooBig = 1009,
  3188. MandatoryExtension = 1010,
  3189. InternalError = 1011,
  3190. };
  3191. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3192. class WebSocket {
  3193. public:
  3194. WebSocket(const WebSocket &) = delete;
  3195. WebSocket &operator=(const WebSocket &) = delete;
  3196. ~WebSocket();
  3197. ReadResult read(std::string &msg);
  3198. bool send(const std::string &data);
  3199. bool send(const char *data, size_t len);
  3200. void close(CloseStatus status = CloseStatus::Normal,
  3201. const std::string &reason = "");
  3202. const Request &request() const;
  3203. bool is_open() const;
  3204. private:
  3205. friend class httplib::Server;
  3206. friend class WebSocketClient;
  3207. WebSocket(
  3208. Stream &strm, const Request &req, bool is_server,
  3209. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3210. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3211. : strm_(strm), req_(req), is_server_(is_server),
  3212. ping_interval_sec_(ping_interval_sec),
  3213. max_missed_pongs_(max_missed_pongs) {
  3214. start_heartbeat();
  3215. }
  3216. WebSocket(
  3217. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3218. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3219. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3220. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3221. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3222. max_missed_pongs_(max_missed_pongs) {
  3223. start_heartbeat();
  3224. }
  3225. void start_heartbeat();
  3226. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3227. Stream &strm_;
  3228. std::unique_ptr<Stream> owned_strm_;
  3229. Request req_;
  3230. bool is_server_;
  3231. time_t ping_interval_sec_;
  3232. int max_missed_pongs_;
  3233. int unacked_pings_ = 0;
  3234. std::atomic<bool> closed_{false};
  3235. std::mutex write_mutex_;
  3236. std::thread ping_thread_;
  3237. std::mutex ping_mutex_;
  3238. std::condition_variable ping_cv_;
  3239. };
  3240. class WebSocketClient {
  3241. public:
  3242. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3243. const Headers &headers = {});
  3244. ~WebSocketClient();
  3245. WebSocketClient(const WebSocketClient &) = delete;
  3246. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3247. bool is_valid() const;
  3248. bool connect();
  3249. ReadResult read(std::string &msg);
  3250. bool send(const std::string &data);
  3251. bool send(const char *data, size_t len);
  3252. void close(CloseStatus status = CloseStatus::Normal,
  3253. const std::string &reason = "");
  3254. bool is_open() const;
  3255. const std::string &subprotocol() const;
  3256. void set_read_timeout(time_t sec, time_t usec = 0);
  3257. void set_write_timeout(time_t sec, time_t usec = 0);
  3258. void set_websocket_ping_interval(time_t sec);
  3259. void set_websocket_max_missed_pongs(int count);
  3260. void set_tcp_nodelay(bool on);
  3261. void set_address_family(int family);
  3262. void set_ipv6_v6only(bool on);
  3263. void set_socket_options(SocketOptions socket_options);
  3264. void set_connection_timeout(time_t sec, time_t usec = 0);
  3265. void set_interface(const std::string &intf);
  3266. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3267. #ifdef CPPHTTPLIB_SSL_ENABLED
  3268. void set_ca_cert_path(const std::string &path);
  3269. void set_ca_cert_store(tls::ca_store_t store);
  3270. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3271. void enable_server_certificate_verification(bool enabled);
  3272. void enable_system_ca(bool enabled);
  3273. #endif
  3274. private:
  3275. void shutdown_and_close();
  3276. bool create_stream(std::unique_ptr<Stream> &strm);
  3277. void prepare_default_headers(Request &req);
  3278. std::string host_;
  3279. int port_;
  3280. std::string path_;
  3281. Headers headers_;
  3282. std::string subprotocol_;
  3283. bool is_valid_ = false;
  3284. socket_t sock_ = INVALID_SOCKET;
  3285. std::unique_ptr<WebSocket> ws_;
  3286. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3287. time_t read_timeout_usec_ = 0;
  3288. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3289. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3290. time_t websocket_ping_interval_sec_ =
  3291. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3292. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3293. int address_family_ = AF_UNSPEC;
  3294. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3295. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3296. SocketOptions socket_options_ = nullptr;
  3297. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3298. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3299. std::string interface_;
  3300. // Hostname to connection target map. The value is an IP literal or another
  3301. // hostname; only the connection target changes, never the identity.
  3302. std::map<std::string, std::string> addr_map_;
  3303. #ifdef CPPHTTPLIB_SSL_ENABLED
  3304. bool is_ssl_ = false;
  3305. tls::ctx_t tls_ctx_ = nullptr;
  3306. tls::session_t tls_session_ = nullptr;
  3307. std::string ca_cert_file_path_;
  3308. bool custom_ca_loaded_ = false;
  3309. bool certs_loaded_ = false;
  3310. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3311. bool server_certificate_verification_ = true;
  3312. #endif
  3313. };
  3314. namespace impl {
  3315. bool is_valid_utf8(const std::string &s);
  3316. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3317. bool &fin, bool expect_masked, size_t max_len);
  3318. } // namespace impl
  3319. } // namespace ws
  3320. // ----------------------------------------------------------------------------
  3321. /*
  3322. * Implementation that will be part of the .cc file if split into .h + .cc.
  3323. */
  3324. namespace stream {
  3325. // stream::Result implementations
  3326. inline Result::Result() : chunk_size_(8192) {}
  3327. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3328. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3329. inline Result::Result(Result &&other) noexcept
  3330. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3331. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3332. finished_(other.finished_) {
  3333. other.current_size_ = 0;
  3334. other.finished_ = true;
  3335. }
  3336. inline Result &Result::operator=(Result &&other) noexcept {
  3337. if (this != &other) {
  3338. handle_ = std::move(other.handle_);
  3339. buffer_ = std::move(other.buffer_);
  3340. current_size_ = other.current_size_;
  3341. chunk_size_ = other.chunk_size_;
  3342. finished_ = other.finished_;
  3343. other.current_size_ = 0;
  3344. other.finished_ = true;
  3345. }
  3346. return *this;
  3347. }
  3348. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3349. inline Result::operator bool() const { return is_valid(); }
  3350. inline int Result::status() const {
  3351. return handle_.response ? handle_.response->status : -1;
  3352. }
  3353. inline const Headers &Result::headers() const {
  3354. static const Headers empty_headers;
  3355. return handle_.response ? handle_.response->headers : empty_headers;
  3356. }
  3357. inline std::string Result::get_header_value(const std::string &key,
  3358. const char *def) const {
  3359. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3360. }
  3361. inline bool Result::has_header(const std::string &key) const {
  3362. return handle_.response ? handle_.response->has_header(key) : false;
  3363. }
  3364. inline Error Result::error() const { return handle_.error; }
  3365. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3366. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3367. inline bool Result::next() {
  3368. if (!handle_.is_valid() || finished_) { return false; }
  3369. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3370. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3371. if (n > 0) {
  3372. current_size_ = static_cast<size_t>(n);
  3373. return true;
  3374. }
  3375. current_size_ = 0;
  3376. finished_ = true;
  3377. return false;
  3378. }
  3379. inline const char *Result::data() const { return buffer_.data(); }
  3380. inline size_t Result::size() const { return current_size_; }
  3381. inline std::string Result::read_all() {
  3382. std::string result;
  3383. while (next()) {
  3384. result.append(data(), size());
  3385. }
  3386. return result;
  3387. }
  3388. } // namespace stream
  3389. namespace sse {
  3390. // SSEMessage implementations
  3391. inline SSEMessage::SSEMessage() : event("message") {}
  3392. inline void SSEMessage::clear() {
  3393. event = "message";
  3394. data.clear();
  3395. id.clear();
  3396. }
  3397. // SSEClient implementations
  3398. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3399. : client_(client), path_(path) {}
  3400. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3401. const Headers &headers)
  3402. : client_(client), path_(path), headers_(headers) {}
  3403. inline SSEClient::~SSEClient() { stop(); }
  3404. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3405. on_message_ = std::move(handler);
  3406. return *this;
  3407. }
  3408. inline SSEClient &SSEClient::on_event(const std::string &type,
  3409. MessageHandler handler) {
  3410. event_handlers_[type] = std::move(handler);
  3411. return *this;
  3412. }
  3413. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3414. on_open_ = std::move(handler);
  3415. return *this;
  3416. }
  3417. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3418. on_error_ = std::move(handler);
  3419. return *this;
  3420. }
  3421. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3422. reconnect_interval_ms_ = ms;
  3423. return *this;
  3424. }
  3425. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3426. max_reconnect_attempts_ = n;
  3427. return *this;
  3428. }
  3429. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3430. std::lock_guard<std::mutex> lock(headers_mutex_);
  3431. headers_ = headers;
  3432. return *this;
  3433. }
  3434. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3435. inline const std::string &SSEClient::last_event_id() const {
  3436. return last_event_id_;
  3437. }
  3438. inline void SSEClient::start() {
  3439. running_.store(true);
  3440. run_event_loop();
  3441. }
  3442. inline void SSEClient::start_async() {
  3443. running_.store(true);
  3444. async_thread_ = std::thread([this]() { run_event_loop(); });
  3445. }
  3446. inline void SSEClient::stop() {
  3447. running_.store(false);
  3448. client_.stop(); // Cancel any pending operations
  3449. if (async_thread_.joinable()) { async_thread_.join(); }
  3450. }
  3451. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3452. int &retry_ms) {
  3453. // Blank line signals end of event
  3454. if (line.empty() || line == "\r") { return true; }
  3455. // Lines starting with ':' are comments (ignored)
  3456. if (!line.empty() && line[0] == ':') { return false; }
  3457. // Find the colon separator
  3458. auto colon_pos = line.find(':');
  3459. if (colon_pos == std::string::npos) {
  3460. // Line with no colon is treated as field name with empty value
  3461. return false;
  3462. }
  3463. auto field = line.substr(0, colon_pos);
  3464. std::string value;
  3465. // Value starts after colon, skip optional single space
  3466. if (colon_pos + 1 < line.size()) {
  3467. auto value_start = colon_pos + 1;
  3468. if (line[value_start] == ' ') { value_start++; }
  3469. value = line.substr(value_start);
  3470. // Remove trailing \r if present
  3471. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3472. }
  3473. // Handle known fields
  3474. if (field == "event") {
  3475. msg.event = value;
  3476. } else if (field == "data") {
  3477. // Multiple data lines are concatenated with newlines
  3478. if (!msg.data.empty()) { msg.data += "\n"; }
  3479. msg.data += value;
  3480. } else if (field == "id") {
  3481. // Empty id is valid (clears the last event ID)
  3482. msg.id = value;
  3483. } else if (field == "retry") {
  3484. // Parse retry interval in milliseconds
  3485. {
  3486. int v = 0;
  3487. auto res =
  3488. detail::from_chars(value.data(), value.data() + value.size(), v);
  3489. if (res.ec == std::errc{}) { retry_ms = v; }
  3490. }
  3491. }
  3492. // Unknown fields are ignored per SSE spec
  3493. return false;
  3494. }
  3495. inline void SSEClient::run_event_loop() {
  3496. auto reconnect_count = 0;
  3497. while (running_.load()) {
  3498. // Build headers, including Last-Event-ID if we have one
  3499. Headers request_headers;
  3500. {
  3501. std::lock_guard<std::mutex> lock(headers_mutex_);
  3502. request_headers = headers_;
  3503. }
  3504. if (!last_event_id_.empty()) {
  3505. request_headers.emplace("Last-Event-ID", last_event_id_);
  3506. }
  3507. // Open streaming connection
  3508. auto result = stream::Get(client_, path_, request_headers);
  3509. // Connection error handling
  3510. if (!result) {
  3511. connected_.store(false);
  3512. if (on_error_) { on_error_(result.error()); }
  3513. if (!should_reconnect(reconnect_count)) { break; }
  3514. wait_for_reconnect();
  3515. reconnect_count++;
  3516. continue;
  3517. }
  3518. if (result.status() != StatusCode::OK_200) {
  3519. connected_.store(false);
  3520. if (on_error_) { on_error_(Error::Connection); }
  3521. // For certain errors, don't reconnect.
  3522. // Note: 401 is intentionally absent so that handlers can refresh
  3523. // credentials via set_headers() and let the client reconnect.
  3524. if (result.status() == StatusCode::NoContent_204 ||
  3525. result.status() == StatusCode::NotFound_404 ||
  3526. result.status() == StatusCode::Forbidden_403) {
  3527. break;
  3528. }
  3529. if (!should_reconnect(reconnect_count)) { break; }
  3530. wait_for_reconnect();
  3531. reconnect_count++;
  3532. continue;
  3533. }
  3534. // Connection successful
  3535. connected_.store(true);
  3536. reconnect_count = 0;
  3537. if (on_open_) { on_open_(); }
  3538. // Event receiving loop
  3539. std::string buffer;
  3540. SSEMessage current_msg;
  3541. while (running_.load() && result.next()) {
  3542. buffer.append(result.data(), result.size());
  3543. // Process complete lines in the buffer
  3544. size_t line_start = 0;
  3545. size_t newline_pos;
  3546. while ((newline_pos = buffer.find('\n', line_start)) !=
  3547. std::string::npos) {
  3548. auto line = buffer.substr(line_start, newline_pos - line_start);
  3549. line_start = newline_pos + 1;
  3550. // Parse the line and check if event is complete
  3551. auto event_complete =
  3552. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3553. if (event_complete && !current_msg.data.empty()) {
  3554. // Update last_event_id for reconnection
  3555. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3556. // Dispatch event to appropriate handler
  3557. dispatch_event(current_msg);
  3558. current_msg.clear();
  3559. }
  3560. }
  3561. // Keep unprocessed data in buffer
  3562. buffer.erase(0, line_start);
  3563. }
  3564. // Connection ended
  3565. connected_.store(false);
  3566. if (!running_.load()) { break; }
  3567. // Check for read errors
  3568. if (result.has_read_error()) {
  3569. if (on_error_) { on_error_(result.read_error()); }
  3570. }
  3571. if (!should_reconnect(reconnect_count)) { break; }
  3572. wait_for_reconnect();
  3573. reconnect_count++;
  3574. }
  3575. connected_.store(false);
  3576. }
  3577. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3578. // Check for specific event type handler first
  3579. auto it = event_handlers_.find(msg.event);
  3580. if (it != event_handlers_.end()) {
  3581. it->second(msg);
  3582. return;
  3583. }
  3584. // Fall back to generic message handler
  3585. if (on_message_) { on_message_(msg); }
  3586. }
  3587. inline bool SSEClient::should_reconnect(int count) const {
  3588. if (!running_.load()) { return false; }
  3589. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3590. return count < max_reconnect_attempts_;
  3591. }
  3592. inline void SSEClient::wait_for_reconnect() {
  3593. // Use small increments to check running_ flag frequently
  3594. auto waited = 0;
  3595. while (running_.load() && waited < reconnect_interval_ms_) {
  3596. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3597. waited += 100;
  3598. }
  3599. }
  3600. } // namespace sse
  3601. #ifdef CPPHTTPLIB_SSL_ENABLED
  3602. /*
  3603. * TLS abstraction layer - internal function declarations
  3604. * These are implementation details and not part of the public API.
  3605. */
  3606. namespace tls {
  3607. // Client context
  3608. ctx_t create_client_context();
  3609. void free_context(ctx_t ctx);
  3610. bool set_min_version(ctx_t ctx, Version version);
  3611. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3612. bool load_ca_file(ctx_t ctx, const char *file_path);
  3613. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3614. bool load_system_certs(ctx_t ctx);
  3615. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3616. const char *password);
  3617. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3618. const char *key_path, const char *password);
  3619. // Server context
  3620. ctx_t create_server_context();
  3621. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3622. const char *password);
  3623. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3624. const char *key_path, const char *password);
  3625. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3626. void set_verify_client(ctx_t ctx, bool require);
  3627. // Session management
  3628. session_t create_session(ctx_t ctx, socket_t sock);
  3629. void free_session(session_t session);
  3630. bool set_sni(session_t session, const char *hostname);
  3631. bool set_hostname(session_t session, const char *hostname);
  3632. // Handshake (non-blocking capable)
  3633. TlsError connect(session_t session);
  3634. TlsError accept(session_t session);
  3635. // Handshake with timeout (blocking until timeout)
  3636. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3637. time_t timeout_usec, TlsError *err);
  3638. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3639. time_t timeout_usec, TlsError *err);
  3640. // I/O (non-blocking capable)
  3641. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3642. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3643. int pending(const_session_t session);
  3644. void shutdown(session_t session, bool graceful);
  3645. // Connection state
  3646. bool is_peer_closed(session_t session, socket_t sock);
  3647. // Certificate verification
  3648. cert_t get_peer_cert(const_session_t session);
  3649. void free_cert(cert_t cert);
  3650. bool verify_hostname(cert_t cert, const char *hostname);
  3651. uint64_t hostname_mismatch_code();
  3652. long get_verify_result(const_session_t session);
  3653. // Certificate introspection
  3654. std::string get_cert_subject_cn(cert_t cert);
  3655. std::string get_cert_issuer_name(cert_t cert);
  3656. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3657. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3658. std::string get_cert_serial(cert_t cert);
  3659. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3660. const char *get_sni(const_session_t session);
  3661. // CA store management
  3662. ca_store_t create_ca_store(const char *pem, size_t len);
  3663. void free_ca_store(ca_store_t store);
  3664. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3665. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3666. std::vector<std::string> get_ca_names(ctx_t ctx);
  3667. // Dynamic certificate update (for servers)
  3668. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3669. const char *password);
  3670. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3671. // Certificate verification callback
  3672. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3673. long get_verify_error(const_session_t session);
  3674. std::string verify_error_string(long error_code);
  3675. // TlsError information
  3676. uint64_t peek_error();
  3677. uint64_t get_error();
  3678. std::string error_string(uint64_t code);
  3679. } // namespace tls
  3680. #endif // CPPHTTPLIB_SSL_ENABLED
  3681. /*
  3682. * Group 1: detail namespace - Non-SSL utilities
  3683. */
  3684. namespace detail {
  3685. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3686. const void *optval, socklen_t optlen) {
  3687. return setsockopt(sock, level, optname,
  3688. #ifdef _WIN32
  3689. reinterpret_cast<const char *>(optval),
  3690. #else
  3691. optval,
  3692. #endif
  3693. optlen) == 0;
  3694. }
  3695. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3696. time_t sec, time_t usec) {
  3697. #ifdef _WIN32
  3698. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3699. #else
  3700. timeval timeout;
  3701. timeout.tv_sec = static_cast<long>(sec);
  3702. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3703. #endif
  3704. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3705. }
  3706. inline bool is_hex(char c, int &v) {
  3707. if (is_ascii_digit(c)) {
  3708. v = c - '0';
  3709. return true;
  3710. } else if ('A' <= c && c <= 'F') {
  3711. v = c - 'A' + 10;
  3712. return true;
  3713. } else if ('a' <= c && c <= 'f') {
  3714. v = c - 'a' + 10;
  3715. return true;
  3716. }
  3717. return false;
  3718. }
  3719. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3720. int &val) {
  3721. if (i >= s.size()) { return false; }
  3722. val = 0;
  3723. for (; cnt; i++, cnt--) {
  3724. if (!s[i]) { return false; }
  3725. auto v = 0;
  3726. if (is_hex(s[i], v)) {
  3727. val = val * 16 + v;
  3728. } else {
  3729. return false;
  3730. }
  3731. }
  3732. return true;
  3733. }
  3734. inline std::string from_i_to_hex(size_t n) {
  3735. static const auto charset = "0123456789abcdef";
  3736. std::string ret;
  3737. do {
  3738. ret = charset[n & 15] + ret;
  3739. n >>= 4;
  3740. } while (n > 0);
  3741. return ret;
  3742. }
  3743. inline std::string compute_etag(const FileStat &fs) {
  3744. if (!fs.is_file()) { return std::string(); }
  3745. // If mtime cannot be determined (negative value indicates an error
  3746. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3747. // value like 0 could collide with a real file that legitimately has
  3748. // mtime == 0 (epoch) and lead to misleading validators.
  3749. auto mtime_raw = fs.mtime();
  3750. if (mtime_raw < 0) { return std::string(); }
  3751. auto mtime = static_cast<size_t>(mtime_raw);
  3752. auto size = fs.size();
  3753. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3754. from_i_to_hex(size) + "\"";
  3755. }
  3756. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3757. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3758. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3759. inline std::string file_mtime_to_http_date(time_t mtime) {
  3760. if (mtime < 0) { return std::string(); }
  3761. struct tm tm_buf;
  3762. #ifdef _WIN32
  3763. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3764. #else
  3765. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3766. #endif
  3767. char buf[64];
  3768. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3769. return std::string();
  3770. }
  3771. return std::string(buf);
  3772. }
  3773. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3774. inline time_t parse_http_date(const std::string &date_str) {
  3775. struct tm tm_buf;
  3776. // Create a classic locale object once for all parsing attempts
  3777. const std::locale classic_locale = std::locale::classic();
  3778. // Try to parse using std::get_time (C++11, cross-platform)
  3779. auto try_parse = [&](const char *fmt) -> bool {
  3780. std::istringstream ss(date_str);
  3781. ss.imbue(classic_locale);
  3782. memset(&tm_buf, 0, sizeof(tm_buf));
  3783. ss >> std::get_time(&tm_buf, fmt);
  3784. return !ss.fail();
  3785. };
  3786. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3787. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3788. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3789. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3790. // asctime format: "Sun Nov 6 08:49:37 1994"
  3791. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3792. return static_cast<time_t>(-1);
  3793. }
  3794. }
  3795. }
  3796. #ifdef _WIN32
  3797. return _mkgmtime(&tm_buf);
  3798. #elif defined _AIX
  3799. return mktime(&tm_buf);
  3800. #else
  3801. return timegm(&tm_buf);
  3802. #endif
  3803. }
  3804. inline bool is_weak_etag(const std::string &s) {
  3805. // Check if the string is a weak ETag (starts with 'W/"')
  3806. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3807. }
  3808. inline bool is_strong_etag(const std::string &s) {
  3809. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3810. // chars)
  3811. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3812. }
  3813. inline size_t to_utf8(int code, char *buff) {
  3814. if (code < 0x0080) {
  3815. buff[0] = static_cast<char>(code & 0x7F);
  3816. return 1;
  3817. } else if (code < 0x0800) {
  3818. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3819. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3820. return 2;
  3821. } else if (code < 0xD800) {
  3822. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3823. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3824. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3825. return 3;
  3826. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3827. return 0;
  3828. } else if (code < 0x10000) {
  3829. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3830. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3831. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3832. return 3;
  3833. } else if (code < 0x110000) {
  3834. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3835. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3836. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3837. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3838. return 4;
  3839. }
  3840. // NOTREACHED
  3841. return 0;
  3842. }
  3843. } // namespace detail
  3844. namespace ws {
  3845. namespace impl {
  3846. inline bool is_valid_utf8(const std::string &s) {
  3847. size_t i = 0;
  3848. auto n = s.size();
  3849. while (i < n) {
  3850. auto c = static_cast<unsigned char>(s[i]);
  3851. size_t len;
  3852. uint32_t cp;
  3853. if (c < 0x80) {
  3854. i++;
  3855. continue;
  3856. } else if ((c & 0xE0) == 0xC0) {
  3857. len = 2;
  3858. cp = c & 0x1F;
  3859. } else if ((c & 0xF0) == 0xE0) {
  3860. len = 3;
  3861. cp = c & 0x0F;
  3862. } else if ((c & 0xF8) == 0xF0) {
  3863. len = 4;
  3864. cp = c & 0x07;
  3865. } else {
  3866. return false;
  3867. }
  3868. if (i + len > n) { return false; }
  3869. for (size_t j = 1; j < len; j++) {
  3870. auto b = static_cast<unsigned char>(s[i + j]);
  3871. if ((b & 0xC0) != 0x80) { return false; }
  3872. cp = (cp << 6) | (b & 0x3F);
  3873. }
  3874. // Overlong encoding check
  3875. if (len == 2 && cp < 0x80) { return false; }
  3876. if (len == 3 && cp < 0x800) { return false; }
  3877. if (len == 4 && cp < 0x10000) { return false; }
  3878. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3879. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3880. if (cp > 0x10FFFF) { return false; }
  3881. i += len;
  3882. }
  3883. return true;
  3884. }
  3885. } // namespace impl
  3886. } // namespace ws
  3887. namespace detail {
  3888. // NOTE: This code came up with the following stackoverflow post:
  3889. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3890. inline std::string base64_encode(const std::string &in) {
  3891. static const auto lookup =
  3892. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3893. std::string out;
  3894. out.reserve(in.size());
  3895. // Unsigned: the accumulator is never masked, so with a signed int the
  3896. // `val << 8` below overflows once enough bytes are folded in (undefined
  3897. // behaviour before C++20). Only the low bits are ever emitted, so the
  3898. // wrap-around of an unsigned accumulator does not affect the output.
  3899. uint32_t val = 0;
  3900. auto valb = -6;
  3901. for (auto c : in) {
  3902. val = (val << 8) + static_cast<uint8_t>(c);
  3903. valb += 8;
  3904. while (valb >= 0) {
  3905. out.push_back(lookup[(val >> valb) & 0x3F]);
  3906. valb -= 6;
  3907. }
  3908. }
  3909. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3910. while (out.size() % 4) {
  3911. out.push_back('=');
  3912. }
  3913. return out;
  3914. }
  3915. inline std::string sha1(const std::string &input) {
  3916. // RFC 3174 SHA-1 implementation
  3917. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3918. return (x << n) | (x >> (32 - n));
  3919. };
  3920. uint32_t h0 = 0x67452301;
  3921. uint32_t h1 = 0xEFCDAB89;
  3922. uint32_t h2 = 0x98BADCFE;
  3923. uint32_t h3 = 0x10325476;
  3924. uint32_t h4 = 0xC3D2E1F0;
  3925. // Pre-processing: adding padding bits
  3926. std::string msg = input;
  3927. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3928. msg.push_back(static_cast<char>(0x80u));
  3929. while (msg.size() % 64 != 56) {
  3930. msg.push_back(0);
  3931. }
  3932. // Append original length in bits as 64-bit big-endian
  3933. for (int i = 56; i >= 0; i -= 8) {
  3934. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3935. }
  3936. // Process each 512-bit chunk
  3937. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3938. uint32_t w[80];
  3939. for (size_t i = 0; i < 16; i++) {
  3940. w[i] =
  3941. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3942. << 24) |
  3943. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3944. << 16) |
  3945. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3946. << 8) |
  3947. (static_cast<uint32_t>(
  3948. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3949. }
  3950. for (int i = 16; i < 80; i++) {
  3951. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3952. }
  3953. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3954. for (int i = 0; i < 80; i++) {
  3955. uint32_t f, k;
  3956. if (i < 20) {
  3957. f = (b & c) | ((~b) & d);
  3958. k = 0x5A827999;
  3959. } else if (i < 40) {
  3960. f = b ^ c ^ d;
  3961. k = 0x6ED9EBA1;
  3962. } else if (i < 60) {
  3963. f = (b & c) | (b & d) | (c & d);
  3964. k = 0x8F1BBCDC;
  3965. } else {
  3966. f = b ^ c ^ d;
  3967. k = 0xCA62C1D6;
  3968. }
  3969. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3970. e = d;
  3971. d = c;
  3972. c = left_rotate(b, 30);
  3973. b = a;
  3974. a = temp;
  3975. }
  3976. h0 += a;
  3977. h1 += b;
  3978. h2 += c;
  3979. h3 += d;
  3980. h4 += e;
  3981. }
  3982. // Produce the final hash as a 20-byte binary string
  3983. std::string hash(20, '\0');
  3984. for (size_t i = 0; i < 4; i++) {
  3985. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3986. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3987. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3988. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3989. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3990. }
  3991. return hash;
  3992. }
  3993. inline std::string websocket_accept_key(const std::string &client_key) {
  3994. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3995. return base64_encode(sha1(client_key + magic));
  3996. }
  3997. inline bool is_websocket_upgrade(const Request &req) {
  3998. if (req.method != "GET") { return false; }
  3999. // Check Upgrade: websocket (case-insensitive)
  4000. auto upgrade_it = req.headers.find("Upgrade");
  4001. if (upgrade_it == req.headers.end()) { return false; }
  4002. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  4003. if (upgrade_val != "websocket") { return false; }
  4004. // Check Connection header contains "Upgrade"
  4005. auto connection_it = req.headers.find("Connection");
  4006. if (connection_it == req.headers.end()) { return false; }
  4007. auto connection_val = case_ignore::to_lower(connection_it->second);
  4008. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  4009. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  4010. // RFC 6455 Section 4.2.1
  4011. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  4012. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  4013. return false;
  4014. }
  4015. static const std::string b64chars =
  4016. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4017. for (size_t i = 0; i < 22; i++) {
  4018. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  4019. }
  4020. // Check Sec-WebSocket-Version: 13
  4021. auto version = req.get_header_value("Sec-WebSocket-Version");
  4022. if (version != "13") { return false; }
  4023. return true;
  4024. }
  4025. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  4026. const char *data, size_t len, bool fin,
  4027. bool mask) {
  4028. // First byte: FIN + opcode
  4029. uint8_t header[2];
  4030. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  4031. (static_cast<uint8_t>(opcode) & 0x0F));
  4032. // Second byte: MASK + payload length
  4033. if (len < 126) {
  4034. header[1] = static_cast<uint8_t>(len);
  4035. if (mask) { header[1] |= 0x80; }
  4036. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4037. } else if (len <= 0xFFFF) {
  4038. header[1] = 126;
  4039. if (mask) { header[1] |= 0x80; }
  4040. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4041. uint8_t ext[2];
  4042. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4043. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4044. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4045. } else {
  4046. header[1] = 127;
  4047. if (mask) { header[1] |= 0x80; }
  4048. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4049. uint8_t ext[8];
  4050. for (int i = 7; i >= 0; i--) {
  4051. ext[7 - i] =
  4052. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4053. }
  4054. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4055. }
  4056. if (mask) {
  4057. // Generate random mask key
  4058. thread_local std::mt19937 rng(std::random_device{}());
  4059. uint8_t mask_key[4];
  4060. auto r = rng();
  4061. std::memcpy(mask_key, &r, 4);
  4062. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4063. // Write masked payload in chunks
  4064. const size_t chunk_size = 4096;
  4065. std::vector<char> buf((std::min)(len, chunk_size));
  4066. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4067. size_t n = (std::min)(chunk_size, len - offset);
  4068. for (size_t i = 0; i < n; i++) {
  4069. buf[i] =
  4070. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4071. }
  4072. if (strm.write(buf.data(), n) < 0) { return false; }
  4073. }
  4074. } else {
  4075. if (len > 0) {
  4076. if (strm.write(data, len) < 0) { return false; }
  4077. }
  4078. }
  4079. return true;
  4080. }
  4081. } // namespace detail
  4082. namespace ws {
  4083. namespace impl {
  4084. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4085. std::string &payload, bool &fin,
  4086. bool expect_masked, size_t max_len) {
  4087. // Read first 2 bytes
  4088. uint8_t header[2];
  4089. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4090. fin = (header[0] & 0x80) != 0;
  4091. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4092. if (header[0] & 0x70) { return false; }
  4093. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4094. bool masked = (header[1] & 0x80) != 0;
  4095. uint64_t payload_len = header[1] & 0x7F;
  4096. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4097. // MUST have a payload length of 125 bytes or less
  4098. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4099. if (is_control) {
  4100. if (!fin) { return false; }
  4101. if (payload_len > 125) { return false; }
  4102. }
  4103. if (masked != expect_masked) { return false; }
  4104. // Extended payload length
  4105. if (payload_len == 126) {
  4106. uint8_t ext[2];
  4107. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4108. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4109. } else if (payload_len == 127) {
  4110. uint8_t ext[8];
  4111. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4112. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4113. if (ext[0] & 0x80) { return false; }
  4114. payload_len = 0;
  4115. for (int i = 0; i < 8; i++) {
  4116. payload_len = (payload_len << 8) | ext[i];
  4117. }
  4118. }
  4119. if (payload_len > max_len) { return false; }
  4120. // Read mask key if present
  4121. uint8_t mask_key[4] = {0};
  4122. if (masked) {
  4123. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4124. }
  4125. // Read payload
  4126. payload.resize(static_cast<size_t>(payload_len));
  4127. if (payload_len > 0) {
  4128. size_t total_read = 0;
  4129. while (total_read < payload_len) {
  4130. auto n = strm.read(&payload[total_read],
  4131. static_cast<size_t>(payload_len - total_read));
  4132. if (n <= 0) { return false; }
  4133. total_read += static_cast<size_t>(n);
  4134. }
  4135. }
  4136. // Unmask if needed
  4137. if (masked) {
  4138. for (size_t i = 0; i < payload.size(); i++) {
  4139. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4140. }
  4141. }
  4142. return true;
  4143. }
  4144. } // namespace impl
  4145. } // namespace ws
  4146. namespace detail {
  4147. inline bool is_valid_path(const std::string &path) {
  4148. size_t level = 0;
  4149. size_t i = 0;
  4150. // Skip slash
  4151. while (i < path.size() && path[i] == '/') {
  4152. i++;
  4153. }
  4154. while (i < path.size()) {
  4155. // Read component
  4156. auto beg = i;
  4157. while (i < path.size() && path[i] != '/') {
  4158. if (path[i] == '\0') {
  4159. return false;
  4160. } else if (path[i] == '\\') {
  4161. return false;
  4162. }
  4163. i++;
  4164. }
  4165. auto len = i - beg;
  4166. assert(len > 0);
  4167. if (!path.compare(beg, len, ".")) {
  4168. ;
  4169. } else if (!path.compare(beg, len, "..")) {
  4170. if (level == 0) { return false; }
  4171. level--;
  4172. } else {
  4173. level++;
  4174. }
  4175. // Skip slash
  4176. while (i < path.size() && path[i] == '/') {
  4177. i++;
  4178. }
  4179. }
  4180. return true;
  4181. }
  4182. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4183. #if defined(_WIN32)
  4184. char buf[_MAX_PATH];
  4185. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4186. resolved = buf;
  4187. #elif defined(PATH_MAX)
  4188. char buf[PATH_MAX];
  4189. if (realpath(path, buf) == nullptr) { return false; }
  4190. resolved = buf;
  4191. #else
  4192. auto buf = realpath(path, nullptr);
  4193. auto guard = scope_exit([&]() { std::free(buf); });
  4194. if (buf == nullptr) { return false; }
  4195. resolved = buf;
  4196. #endif
  4197. return true;
  4198. }
  4199. inline bool is_path_within_base(const std::string &resolved_path,
  4200. const std::string &resolved_base) {
  4201. #if defined(_WIN32)
  4202. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4203. resolved_base.size()) == 0;
  4204. #else
  4205. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4206. resolved_base.size()) == 0;
  4207. #endif
  4208. }
  4209. inline FileStat::FileStat(const std::string &path) {
  4210. #if defined(_WIN32)
  4211. auto wpath = u8string_to_wstring(path.c_str());
  4212. ret_ = _wstat(wpath.c_str(), &st_);
  4213. #else
  4214. ret_ = stat(path.c_str(), &st_);
  4215. #endif
  4216. }
  4217. inline bool FileStat::is_file() const {
  4218. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4219. }
  4220. inline bool FileStat::is_dir() const {
  4221. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4222. }
  4223. inline time_t FileStat::mtime() const {
  4224. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4225. : static_cast<time_t>(-1);
  4226. }
  4227. inline size_t FileStat::size() const {
  4228. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4229. }
  4230. inline std::string encode_path(const std::string &s) {
  4231. std::string result;
  4232. result.reserve(s.size());
  4233. for (size_t i = 0; s[i]; i++) {
  4234. switch (s[i]) {
  4235. case ' ': result += "%20"; break;
  4236. case '+': result += "%2B"; break;
  4237. case '\r': result += "%0D"; break;
  4238. case '\n': result += "%0A"; break;
  4239. case '\'': result += "%27"; break;
  4240. case ',': result += "%2C"; break;
  4241. // case ':': result += "%3A"; break; // ok? probably...
  4242. case ';': result += "%3B"; break;
  4243. default:
  4244. auto c = static_cast<uint8_t>(s[i]);
  4245. if (c >= 0x80) {
  4246. result += '%';
  4247. char hex[4];
  4248. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4249. assert(len == 2);
  4250. result.append(hex, static_cast<size_t>(len));
  4251. } else {
  4252. result += s[i];
  4253. }
  4254. break;
  4255. }
  4256. }
  4257. return result;
  4258. }
  4259. inline std::string file_extension(const std::string &path) {
  4260. std::smatch m;
  4261. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4262. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4263. return std::string();
  4264. }
  4265. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4266. template <typename T>
  4267. inline bool parse_header(const char *beg, const char *end, T fn);
  4268. template <typename T>
  4269. inline bool parse_header(const char *beg, const char *end, T fn) {
  4270. // Skip trailing spaces and tabs.
  4271. while (beg < end && is_space_or_tab(end[-1])) {
  4272. end--;
  4273. }
  4274. auto p = beg;
  4275. while (p < end && *p != ':') {
  4276. p++;
  4277. }
  4278. auto name = std::string(beg, p);
  4279. if (!detail::fields::is_field_name(name)) { return false; }
  4280. if (p == end) { return false; }
  4281. auto key_end = p;
  4282. if (*p++ != ':') { return false; }
  4283. while (p < end && is_space_or_tab(*p)) {
  4284. p++;
  4285. }
  4286. if (p <= end) {
  4287. auto key_len = key_end - beg;
  4288. if (!key_len) { return false; }
  4289. auto key = std::string(beg, key_end);
  4290. auto val = std::string(p, end);
  4291. if (!detail::fields::is_field_value(val)) { return false; }
  4292. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4293. // percent-decoded by the recipient. Applications that need to interpret a
  4294. // value as a URI component should call httplib::decode_uri_component()
  4295. // (or decode_path_component()) explicitly.
  4296. fn(key, val);
  4297. return true;
  4298. }
  4299. return false;
  4300. }
  4301. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4302. const Headers &src_headers) {
  4303. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4304. // transfer coding is complete when a chunk with a chunk-size of zero is
  4305. // received, possibly followed by a trailer section, and finally terminated by
  4306. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4307. //
  4308. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4309. // doesn't care for the existence of the final CRLF. In other words, it seems
  4310. // to be ok whether the final CRLF exists or not in the chunked data.
  4311. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4312. //
  4313. // According to the reference code in RFC 9112, cpp-httplib now allows
  4314. // chunked transfer coding data without the final CRLF.
  4315. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4316. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4317. "transfer-encoding",
  4318. "content-length",
  4319. "host",
  4320. "authorization",
  4321. "www-authenticate",
  4322. "proxy-authenticate",
  4323. "proxy-authorization",
  4324. "cookie",
  4325. "set-cookie",
  4326. "cache-control",
  4327. "expect",
  4328. "max-forwards",
  4329. "pragma",
  4330. "range",
  4331. "te",
  4332. "age",
  4333. "expires",
  4334. "date",
  4335. "location",
  4336. "retry-after",
  4337. "vary",
  4338. "warning",
  4339. "content-encoding",
  4340. "content-type",
  4341. "content-range",
  4342. "trailer"};
  4343. case_ignore::unordered_set<std::string> declared_trailers;
  4344. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4345. if (trailer_header && std::strlen(trailer_header)) {
  4346. auto len = std::strlen(trailer_header);
  4347. split(trailer_header, trailer_header + len, ',',
  4348. [&](const char *b, const char *e) {
  4349. const char *kbeg = b;
  4350. const char *kend = e;
  4351. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4352. ++kbeg;
  4353. }
  4354. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4355. --kend;
  4356. }
  4357. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4358. if (!key.empty() &&
  4359. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4360. declared_trailers.insert(key);
  4361. }
  4362. });
  4363. }
  4364. size_t trailer_header_count = 0;
  4365. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4366. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4367. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4368. constexpr auto line_terminator_len = 2;
  4369. auto line_beg = line_reader.ptr();
  4370. auto line_end =
  4371. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4372. if (!parse_header(line_beg, line_end,
  4373. [&](const std::string &key, const std::string &val) {
  4374. if (declared_trailers.find(key) !=
  4375. declared_trailers.end()) {
  4376. dest.emplace(key, val);
  4377. trailer_header_count++;
  4378. }
  4379. })) {
  4380. return false;
  4381. }
  4382. if (!line_reader.getline()) { return false; }
  4383. }
  4384. return true;
  4385. }
  4386. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4387. size_t right) {
  4388. while (b + left < e && is_space_or_tab(b[left])) {
  4389. left++;
  4390. }
  4391. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4392. right--;
  4393. }
  4394. return std::make_pair(left, right);
  4395. }
  4396. inline std::string trim_copy(const std::string &s) {
  4397. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4398. return s.substr(r.first, r.second - r.first);
  4399. }
  4400. inline std::string trim_double_quotes_copy(const std::string &s) {
  4401. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4402. return s.substr(1, s.size() - 2);
  4403. }
  4404. return s;
  4405. }
  4406. inline void
  4407. divide(const char *data, std::size_t size, char d,
  4408. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4409. fn) {
  4410. const auto it = std::find(data, data + size, d);
  4411. const auto found = static_cast<std::size_t>(it != data + size);
  4412. const auto lhs_data = data;
  4413. const auto lhs_size = static_cast<std::size_t>(it - data);
  4414. const auto rhs_data = it + found;
  4415. const auto rhs_size = size - lhs_size - found;
  4416. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4417. }
  4418. inline void
  4419. divide(const std::string &str, char d,
  4420. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4421. fn) {
  4422. divide(str.data(), str.size(), d, std::move(fn));
  4423. }
  4424. inline void split(const char *b, const char *e, char d,
  4425. std::function<void(const char *, const char *)> fn) {
  4426. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4427. }
  4428. inline void split(const char *b, const char *e, char d, size_t m,
  4429. std::function<void(const char *, const char *)> fn) {
  4430. size_t i = 0;
  4431. size_t beg = 0;
  4432. size_t count = 1;
  4433. while (e ? (b + i < e) : (b[i] != '\0')) {
  4434. if (b[i] == d && count < m) {
  4435. auto r = trim(b, e, beg, i);
  4436. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4437. beg = i + 1;
  4438. count++;
  4439. }
  4440. i++;
  4441. }
  4442. if (i) {
  4443. auto r = trim(b, e, beg, i);
  4444. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4445. }
  4446. }
  4447. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4448. std::function<bool(const char *, const char *)> fn) {
  4449. size_t i = 0;
  4450. size_t beg = 0;
  4451. size_t count = 1;
  4452. while (e ? (b + i < e) : (b[i] != '\0')) {
  4453. if (b[i] == d && count < m) {
  4454. auto r = trim(b, e, beg, i);
  4455. if (r.first < r.second) {
  4456. auto found = fn(&b[r.first], &b[r.second]);
  4457. if (found) { return true; }
  4458. }
  4459. beg = i + 1;
  4460. count++;
  4461. }
  4462. i++;
  4463. }
  4464. if (i) {
  4465. auto r = trim(b, e, beg, i);
  4466. if (r.first < r.second) {
  4467. auto found = fn(&b[r.first], &b[r.second]);
  4468. if (found) { return true; }
  4469. }
  4470. }
  4471. return false;
  4472. }
  4473. inline bool split_find(const char *b, const char *e, char d,
  4474. std::function<bool(const char *, const char *)> fn) {
  4475. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4476. std::move(fn));
  4477. }
  4478. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4479. size_t fixed_buffer_size)
  4480. : strm_(strm), fixed_buffer_(fixed_buffer),
  4481. fixed_buffer_size_(fixed_buffer_size) {}
  4482. inline const char *stream_line_reader::ptr() const {
  4483. if (growable_buffer_.empty()) {
  4484. return fixed_buffer_;
  4485. } else {
  4486. return growable_buffer_.data();
  4487. }
  4488. }
  4489. inline size_t stream_line_reader::size() const {
  4490. if (growable_buffer_.empty()) {
  4491. return fixed_buffer_used_size_;
  4492. } else {
  4493. return growable_buffer_.size();
  4494. }
  4495. }
  4496. inline bool stream_line_reader::end_with_crlf() const {
  4497. auto end = ptr() + size();
  4498. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4499. }
  4500. inline bool stream_line_reader::getline() {
  4501. fixed_buffer_used_size_ = 0;
  4502. growable_buffer_.clear();
  4503. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4504. char prev_byte = 0;
  4505. #endif
  4506. for (size_t i = 0;; i++) {
  4507. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4508. // Treat exceptionally long lines as an error to
  4509. // prevent infinite loops/memory exhaustion
  4510. return false;
  4511. }
  4512. char byte;
  4513. auto n = strm_.read(&byte, 1);
  4514. if (n < 0) {
  4515. return false;
  4516. } else if (n == 0) {
  4517. if (i == 0) {
  4518. return false;
  4519. } else {
  4520. break;
  4521. }
  4522. }
  4523. append(byte);
  4524. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4525. if (byte == '\n') { break; }
  4526. #else
  4527. if (prev_byte == '\r' && byte == '\n') { break; }
  4528. prev_byte = byte;
  4529. #endif
  4530. }
  4531. return true;
  4532. }
  4533. inline void stream_line_reader::append(char c) {
  4534. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4535. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4536. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4537. } else {
  4538. if (growable_buffer_.empty()) {
  4539. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4540. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4541. }
  4542. growable_buffer_ += c;
  4543. }
  4544. }
  4545. inline mmap::mmap(const char *path) { open(path); }
  4546. inline mmap::~mmap() { close(); }
  4547. inline bool mmap::open(const char *path) {
  4548. close();
  4549. #if defined(_WIN32)
  4550. auto wpath = u8string_to_wstring(path);
  4551. if (wpath.empty()) { return false; }
  4552. hFile_ =
  4553. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4554. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4555. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4556. LARGE_INTEGER size{};
  4557. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4558. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4559. // See:
  4560. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4561. if (static_cast<ULONGLONG>(size.QuadPart) >
  4562. (std::numeric_limits<decltype(size_)>::max)()) {
  4563. // `size_t` might be 32-bits, on 32-bits Windows.
  4564. return false;
  4565. }
  4566. size_ = static_cast<size_t>(size.QuadPart);
  4567. hMapping_ =
  4568. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4569. // Special treatment for an empty file...
  4570. if (hMapping_ == NULL && size_ == 0) {
  4571. close();
  4572. is_open_empty_file = true;
  4573. return true;
  4574. }
  4575. if (hMapping_ == NULL) {
  4576. close();
  4577. return false;
  4578. }
  4579. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4580. if (addr_ == nullptr) {
  4581. close();
  4582. return false;
  4583. }
  4584. #else
  4585. fd_ = ::open(path, O_RDONLY);
  4586. if (fd_ == -1) { return false; }
  4587. struct stat sb;
  4588. if (fstat(fd_, &sb) == -1) {
  4589. close();
  4590. return false;
  4591. }
  4592. size_ = static_cast<size_t>(sb.st_size);
  4593. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4594. // Special treatment for an empty file...
  4595. if (addr_ == MAP_FAILED && size_ == 0) {
  4596. close();
  4597. is_open_empty_file = true;
  4598. return false;
  4599. }
  4600. #endif
  4601. return true;
  4602. }
  4603. inline bool mmap::is_open() const {
  4604. return is_open_empty_file ? true : addr_ != nullptr;
  4605. }
  4606. inline size_t mmap::size() const { return size_; }
  4607. inline const char *mmap::data() const {
  4608. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4609. }
  4610. inline void mmap::close() {
  4611. #if defined(_WIN32)
  4612. if (addr_) {
  4613. ::UnmapViewOfFile(addr_);
  4614. addr_ = nullptr;
  4615. }
  4616. if (hMapping_) {
  4617. ::CloseHandle(hMapping_);
  4618. hMapping_ = NULL;
  4619. }
  4620. if (hFile_ != INVALID_HANDLE_VALUE) {
  4621. ::CloseHandle(hFile_);
  4622. hFile_ = INVALID_HANDLE_VALUE;
  4623. }
  4624. is_open_empty_file = false;
  4625. #else
  4626. if (addr_ != nullptr) {
  4627. munmap(addr_, size_);
  4628. addr_ = nullptr;
  4629. }
  4630. if (fd_ != -1) {
  4631. ::close(fd_);
  4632. fd_ = -1;
  4633. }
  4634. #endif
  4635. size_ = 0;
  4636. }
  4637. inline int close_socket(socket_t sock) noexcept {
  4638. #ifdef _WIN32
  4639. return closesocket(sock);
  4640. #else
  4641. return close(sock);
  4642. #endif
  4643. }
  4644. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4645. ssize_t res = 0;
  4646. while (true) {
  4647. res = fn();
  4648. if (res < 0 && errno == EINTR) {
  4649. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4650. continue;
  4651. }
  4652. break;
  4653. }
  4654. return res;
  4655. }
  4656. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4657. return handle_EINTR([&]() {
  4658. return recv(sock,
  4659. #ifdef _WIN32
  4660. static_cast<char *>(ptr), static_cast<int>(size),
  4661. #else
  4662. ptr, size,
  4663. #endif
  4664. flags);
  4665. });
  4666. }
  4667. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4668. int flags) {
  4669. return handle_EINTR([&]() {
  4670. return send(sock,
  4671. #ifdef _WIN32
  4672. static_cast<const char *>(ptr), static_cast<int>(size),
  4673. #else
  4674. ptr, size,
  4675. #endif
  4676. flags);
  4677. });
  4678. }
  4679. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4680. #ifdef _WIN32
  4681. return ::WSAPoll(fds, nfds, timeout);
  4682. #else
  4683. return ::poll(fds, nfds, timeout);
  4684. #endif
  4685. }
  4686. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4687. time_t usec) {
  4688. struct pollfd pfd;
  4689. pfd.fd = sock;
  4690. pfd.events = events;
  4691. pfd.revents = 0;
  4692. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4693. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4694. }
  4695. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4696. return select_impl(sock, POLLIN, sec, usec);
  4697. }
  4698. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4699. return select_impl(sock, POLLOUT, sec, usec);
  4700. }
  4701. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4702. time_t usec) {
  4703. struct pollfd pfd_read;
  4704. pfd_read.fd = sock;
  4705. pfd_read.events = POLLIN | POLLOUT;
  4706. pfd_read.revents = 0;
  4707. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4708. auto poll_res =
  4709. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4710. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4711. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4712. auto error = 0;
  4713. socklen_t len = sizeof(error);
  4714. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4715. reinterpret_cast<char *>(&error), &len);
  4716. auto successful = res >= 0 && !error;
  4717. return successful ? Error::Success : Error::Connection;
  4718. }
  4719. return Error::Connection;
  4720. }
  4721. inline bool is_socket_alive(socket_t sock) {
  4722. const auto val = detail::select_read(sock, 0, 0);
  4723. if (val == 0) {
  4724. return true;
  4725. } else if (val < 0 && errno == EBADF) {
  4726. return false;
  4727. }
  4728. char buf[1];
  4729. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4730. }
  4731. class SocketStream final : public Stream {
  4732. public:
  4733. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4734. time_t write_timeout_sec, time_t write_timeout_usec,
  4735. time_t max_timeout_msec = 0,
  4736. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4737. (std::chrono::steady_clock::time_point::min)());
  4738. ~SocketStream() override;
  4739. bool is_readable() const override;
  4740. bool wait_readable() const override;
  4741. bool wait_writable() const override;
  4742. bool is_peer_alive() const override;
  4743. ssize_t read(char *ptr, size_t size) override;
  4744. ssize_t write(const char *ptr, size_t size) override;
  4745. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4746. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4747. socket_t socket() const override;
  4748. time_t duration() const override;
  4749. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4750. private:
  4751. socket_t sock_;
  4752. time_t read_timeout_sec_;
  4753. time_t read_timeout_usec_;
  4754. time_t write_timeout_sec_;
  4755. time_t write_timeout_usec_;
  4756. time_t max_timeout_msec_;
  4757. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4758. std::vector<char> read_buff_;
  4759. size_t read_buff_off_ = 0;
  4760. size_t read_buff_content_size_ = 0;
  4761. static const size_t read_buff_size_ = 1024l * 4;
  4762. };
  4763. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4764. time_t keep_alive_timeout_sec) {
  4765. using namespace std::chrono;
  4766. const auto interval_usec =
  4767. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4768. // Avoid expensive `steady_clock::now()` call for the first time
  4769. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4770. const auto start = steady_clock::now() - microseconds{interval_usec};
  4771. const auto timeout = seconds{keep_alive_timeout_sec};
  4772. while (true) {
  4773. if (svr_sock == INVALID_SOCKET) {
  4774. break; // Server socket is closed
  4775. }
  4776. auto val = select_read(sock, 0, interval_usec);
  4777. if (val < 0) {
  4778. break; // Ssocket error
  4779. } else if (val == 0) {
  4780. if (steady_clock::now() - start > timeout) {
  4781. break; // Timeout
  4782. }
  4783. } else {
  4784. return true; // Ready for read
  4785. }
  4786. }
  4787. return false;
  4788. }
  4789. template <typename T>
  4790. inline bool
  4791. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4792. size_t keep_alive_max_count,
  4793. time_t keep_alive_timeout_sec, T callback) {
  4794. assert(keep_alive_max_count > 0);
  4795. auto ret = false;
  4796. auto count = keep_alive_max_count;
  4797. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4798. auto close_connection = count == 1;
  4799. auto connection_closed = false;
  4800. ret = callback(close_connection, connection_closed);
  4801. if (!ret || connection_closed) { break; }
  4802. count--;
  4803. }
  4804. return ret;
  4805. }
  4806. template <typename T>
  4807. inline bool
  4808. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4809. size_t keep_alive_max_count,
  4810. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4811. time_t read_timeout_usec, time_t write_timeout_sec,
  4812. time_t write_timeout_usec, T callback) {
  4813. return process_server_socket_core(
  4814. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4815. [&](bool close_connection, bool &connection_closed) {
  4816. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4817. write_timeout_sec, write_timeout_usec);
  4818. return callback(strm, close_connection, connection_closed);
  4819. });
  4820. }
  4821. inline bool process_client_socket(
  4822. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4823. time_t write_timeout_sec, time_t write_timeout_usec,
  4824. time_t max_timeout_msec,
  4825. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4826. std::function<bool(Stream &)> callback) {
  4827. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4828. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4829. start_time);
  4830. return callback(strm);
  4831. }
  4832. inline int shutdown_socket(socket_t sock) noexcept {
  4833. #ifdef _WIN32
  4834. return shutdown(sock, SD_BOTH);
  4835. #else
  4836. return shutdown(sock, SHUT_RDWR);
  4837. #endif
  4838. }
  4839. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4840. if (s.size() > 1 && s[0] == '\0') {
  4841. auto ret = s;
  4842. ret[0] = '@';
  4843. return ret;
  4844. }
  4845. return s;
  4846. }
  4847. inline std::string
  4848. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4849. if (s.size() > 1 && s[0] == '@') {
  4850. auto ret = s;
  4851. ret[0] = '\0';
  4852. return ret;
  4853. }
  4854. return s;
  4855. }
  4856. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4857. const struct addrinfo *hints,
  4858. struct addrinfo **res, time_t timeout_sec) {
  4859. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4860. if (timeout_sec <= 0) {
  4861. // No timeout specified, use standard getaddrinfo
  4862. return getaddrinfo(node, service, hints, res);
  4863. }
  4864. #ifdef _WIN32
  4865. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4866. OVERLAPPED overlapped = {};
  4867. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4868. if (!event) { return EAI_FAIL; }
  4869. overlapped.hEvent = event;
  4870. PADDRINFOEXW result_addrinfo = nullptr;
  4871. HANDLE cancel_handle = nullptr;
  4872. ADDRINFOEXW hints_ex = {};
  4873. if (hints) {
  4874. hints_ex.ai_flags = hints->ai_flags;
  4875. hints_ex.ai_family = hints->ai_family;
  4876. hints_ex.ai_socktype = hints->ai_socktype;
  4877. hints_ex.ai_protocol = hints->ai_protocol;
  4878. }
  4879. auto wnode = u8string_to_wstring(node);
  4880. auto wservice = u8string_to_wstring(service);
  4881. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4882. hints ? &hints_ex : nullptr, &result_addrinfo,
  4883. nullptr, &overlapped, nullptr, &cancel_handle);
  4884. if (ret == WSA_IO_PENDING) {
  4885. auto wait_result =
  4886. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4887. if (wait_result == WAIT_TIMEOUT) {
  4888. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4889. ::CloseHandle(event);
  4890. return EAI_AGAIN;
  4891. }
  4892. DWORD bytes_returned;
  4893. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4894. &bytes_returned, FALSE)) {
  4895. ::CloseHandle(event);
  4896. return ::WSAGetLastError();
  4897. }
  4898. }
  4899. ::CloseHandle(event);
  4900. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4901. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4902. return 0;
  4903. }
  4904. return ret;
  4905. #elif TARGET_OS_MAC && defined(__clang__)
  4906. if (!node) { return EAI_NONAME; }
  4907. // macOS implementation using CFHost API for asynchronous DNS resolution
  4908. CFStringRef hostname_ref = CFStringCreateWithCString(
  4909. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4910. if (!hostname_ref) { return EAI_MEMORY; }
  4911. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4912. CFRelease(hostname_ref);
  4913. if (!host_ref) { return EAI_MEMORY; }
  4914. // Set up context for callback
  4915. struct CFHostContext {
  4916. bool completed = false;
  4917. bool success = false;
  4918. CFArrayRef addresses = nullptr;
  4919. std::mutex mutex;
  4920. std::condition_variable cv;
  4921. } context;
  4922. CFHostClientContext client_context;
  4923. memset(&client_context, 0, sizeof(client_context));
  4924. client_context.info = &context;
  4925. // Set callback
  4926. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4927. const CFStreamError *error, void *info) {
  4928. auto ctx = static_cast<CFHostContext *>(info);
  4929. std::lock_guard<std::mutex> lock(ctx->mutex);
  4930. if (error && error->error != 0) {
  4931. ctx->success = false;
  4932. } else {
  4933. Boolean hasBeenResolved;
  4934. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4935. if (ctx->addresses && hasBeenResolved) {
  4936. CFRetain(ctx->addresses);
  4937. ctx->success = true;
  4938. } else {
  4939. ctx->success = false;
  4940. }
  4941. }
  4942. ctx->completed = true;
  4943. ctx->cv.notify_one();
  4944. };
  4945. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4946. CFRelease(host_ref);
  4947. return EAI_SYSTEM;
  4948. }
  4949. // Schedule on run loop
  4950. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4951. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4952. // Start resolution
  4953. CFStreamError stream_error;
  4954. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4955. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4956. CFRelease(host_ref);
  4957. return EAI_FAIL;
  4958. }
  4959. // Wait for completion with timeout
  4960. auto timeout_time =
  4961. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4962. bool timed_out = false;
  4963. {
  4964. std::unique_lock<std::mutex> lock(context.mutex);
  4965. while (!context.completed) {
  4966. auto now = std::chrono::steady_clock::now();
  4967. if (now >= timeout_time) {
  4968. timed_out = true;
  4969. break;
  4970. }
  4971. // Run the runloop for a short time
  4972. lock.unlock();
  4973. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4974. lock.lock();
  4975. }
  4976. }
  4977. // Clean up
  4978. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4979. CFHostSetClient(host_ref, nullptr, nullptr);
  4980. if (timed_out || !context.completed) {
  4981. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4982. CFRelease(host_ref);
  4983. return EAI_AGAIN;
  4984. }
  4985. if (!context.success || !context.addresses) {
  4986. CFRelease(host_ref);
  4987. return EAI_NODATA;
  4988. }
  4989. // Convert CFArray to addrinfo
  4990. CFIndex count = CFArrayGetCount(context.addresses);
  4991. if (count == 0) {
  4992. CFRelease(context.addresses);
  4993. CFRelease(host_ref);
  4994. return EAI_NODATA;
  4995. }
  4996. struct addrinfo *result_addrinfo = nullptr;
  4997. struct addrinfo **current = &result_addrinfo;
  4998. for (CFIndex i = 0; i < count; i++) {
  4999. CFDataRef addr_data =
  5000. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  5001. if (!addr_data) continue;
  5002. const struct sockaddr *sockaddr_ptr =
  5003. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  5004. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  5005. // Allocate addrinfo structure
  5006. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  5007. if (!*current) {
  5008. freeaddrinfo(result_addrinfo);
  5009. CFRelease(context.addresses);
  5010. CFRelease(host_ref);
  5011. return EAI_MEMORY;
  5012. }
  5013. memset(*current, 0, sizeof(struct addrinfo));
  5014. // Set up addrinfo fields
  5015. (*current)->ai_family = sockaddr_ptr->sa_family;
  5016. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  5017. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  5018. (*current)->ai_addrlen = sockaddr_len;
  5019. // Copy sockaddr
  5020. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  5021. if (!(*current)->ai_addr) {
  5022. freeaddrinfo(result_addrinfo);
  5023. CFRelease(context.addresses);
  5024. CFRelease(host_ref);
  5025. return EAI_MEMORY;
  5026. }
  5027. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  5028. // Set port if service is specified
  5029. if (service && *service) {
  5030. int port = 0;
  5031. if (parse_port(service, strlen(service), port)) {
  5032. if (sockaddr_ptr->sa_family == AF_INET) {
  5033. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5034. ->sin_port = htons(static_cast<uint16_t>(port));
  5035. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5036. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5037. ->sin6_port = htons(static_cast<uint16_t>(port));
  5038. }
  5039. }
  5040. }
  5041. current = &((*current)->ai_next);
  5042. }
  5043. CFRelease(context.addresses);
  5044. CFRelease(host_ref);
  5045. *res = result_addrinfo;
  5046. return 0;
  5047. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5048. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5049. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5050. // the resolver worker still references the stack-local gaicb. The cancel
  5051. // path therefore waits (gai_suspend with no timeout) for the worker to
  5052. // actually finish before letting the stack frame go. The trade-off is that
  5053. // a wedged DNS server can hold this thread for the system resolver timeout
  5054. // (~30s by default) past the caller's connection timeout.
  5055. struct gaicb request {};
  5056. struct gaicb *requests[1] = {&request};
  5057. struct sigevent sevp {};
  5058. struct timespec timeout {
  5059. timeout_sec, 0
  5060. };
  5061. request.ar_name = node;
  5062. request.ar_service = service;
  5063. request.ar_request = hints;
  5064. sevp.sigev_notify = SIGEV_NONE;
  5065. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5066. if (rc != 0) { return rc; }
  5067. auto cleanup = scope_exit([&] {
  5068. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5069. });
  5070. int wait_result = gai_suspend(requests, 1, &timeout);
  5071. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5072. int gai_result = gai_error(&request);
  5073. if (gai_result == 0) {
  5074. *res = request.ar_result;
  5075. request.ar_result = nullptr;
  5076. return 0;
  5077. }
  5078. return gai_result;
  5079. }
  5080. gai_cancel(&request);
  5081. while (gai_error(&request) == EAI_INPROGRESS) {
  5082. gai_suspend(requests, 1, nullptr);
  5083. }
  5084. return wait_result;
  5085. #else
  5086. // Fallback implementation using thread-based timeout for other Unix systems.
  5087. struct GetAddrInfoState {
  5088. ~GetAddrInfoState() {
  5089. if (info) { freeaddrinfo(info); }
  5090. }
  5091. std::mutex mutex;
  5092. std::condition_variable result_cv;
  5093. bool completed = false;
  5094. int result = EAI_SYSTEM;
  5095. std::string node;
  5096. std::string service;
  5097. struct addrinfo hints;
  5098. struct addrinfo *info = nullptr;
  5099. };
  5100. // Allocate on the heap, so the resolver thread can keep using the data.
  5101. auto state = std::make_shared<GetAddrInfoState>();
  5102. if (node) { state->node = node; }
  5103. state->service = service;
  5104. state->hints = *hints;
  5105. std::thread resolve_thread([state]() {
  5106. auto thread_result =
  5107. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5108. &state->info);
  5109. std::lock_guard<std::mutex> lock(state->mutex);
  5110. state->result = thread_result;
  5111. state->completed = true;
  5112. state->result_cv.notify_one();
  5113. });
  5114. // Wait for completion or timeout
  5115. std::unique_lock<std::mutex> lock(state->mutex);
  5116. auto finished =
  5117. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5118. [&] { return state->completed; });
  5119. if (finished) {
  5120. // Operation completed within timeout
  5121. resolve_thread.join();
  5122. *res = state->info;
  5123. state->info = nullptr; // Pass ownership to caller
  5124. return state->result;
  5125. } else {
  5126. // Timeout occurred
  5127. resolve_thread.detach(); // Let the thread finish in background
  5128. return EAI_AGAIN; // Return timeout error
  5129. }
  5130. #endif
  5131. #else
  5132. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5133. return getaddrinfo(node, service, hints, res);
  5134. #endif
  5135. }
  5136. template <typename BindOrConnect>
  5137. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5138. int address_family, int socket_flags, bool tcp_nodelay,
  5139. bool ipv6_v6only, SocketOptions socket_options,
  5140. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5141. // Get address info
  5142. const char *node = nullptr;
  5143. struct addrinfo hints;
  5144. struct addrinfo *result;
  5145. memset(&hints, 0, sizeof(struct addrinfo));
  5146. hints.ai_socktype = SOCK_STREAM;
  5147. hints.ai_protocol = IPPROTO_IP;
  5148. if (!ip.empty()) {
  5149. node = ip.c_str();
  5150. // Ask getaddrinfo to convert IP in c-string to address
  5151. hints.ai_family = AF_UNSPEC;
  5152. hints.ai_flags = AI_NUMERICHOST;
  5153. } else {
  5154. if (!host.empty()) { node = host.c_str(); }
  5155. hints.ai_family = address_family;
  5156. hints.ai_flags = socket_flags;
  5157. }
  5158. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5159. if (hints.ai_family == AF_UNIX) {
  5160. const auto addrlen = host.length();
  5161. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5162. #ifdef SOCK_CLOEXEC
  5163. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5164. hints.ai_protocol);
  5165. #else
  5166. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5167. #endif
  5168. if (sock != INVALID_SOCKET) {
  5169. sockaddr_un addr{};
  5170. addr.sun_family = AF_UNIX;
  5171. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5172. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5173. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5174. hints.ai_addrlen = static_cast<socklen_t>(
  5175. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5176. #ifndef SOCK_CLOEXEC
  5177. #ifndef _WIN32
  5178. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5179. #endif
  5180. #endif
  5181. if (socket_options) { socket_options(sock); }
  5182. #ifdef _WIN32
  5183. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5184. // remove the option.
  5185. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5186. #endif
  5187. bool dummy;
  5188. if (!bind_or_connect(sock, hints, dummy)) {
  5189. close_socket(sock);
  5190. sock = INVALID_SOCKET;
  5191. }
  5192. }
  5193. return sock;
  5194. }
  5195. #endif
  5196. auto service = std::to_string(port);
  5197. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5198. timeout_sec)) {
  5199. #if defined __linux__ && !defined __ANDROID__
  5200. res_init();
  5201. #endif
  5202. return INVALID_SOCKET;
  5203. }
  5204. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5205. for (auto rp = result; rp; rp = rp->ai_next) {
  5206. // Create a socket
  5207. #ifdef _WIN32
  5208. auto sock =
  5209. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5210. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5211. /**
  5212. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5213. * and above the socket creation fails on older Windows Systems.
  5214. *
  5215. * Let's try to create a socket the old way in this case.
  5216. *
  5217. * Reference:
  5218. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5219. *
  5220. * WSA_FLAG_NO_HANDLE_INHERIT:
  5221. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5222. * SP1, and later
  5223. *
  5224. */
  5225. if (sock == INVALID_SOCKET) {
  5226. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5227. }
  5228. #else
  5229. #ifdef SOCK_CLOEXEC
  5230. auto sock =
  5231. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5232. #else
  5233. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5234. #endif
  5235. #endif
  5236. if (sock == INVALID_SOCKET) { continue; }
  5237. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5238. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5239. close_socket(sock);
  5240. continue;
  5241. }
  5242. #endif
  5243. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5244. if (rp->ai_family == AF_INET6) {
  5245. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5246. }
  5247. if (socket_options) { socket_options(sock); }
  5248. // bind or connect
  5249. auto quit = false;
  5250. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5251. close_socket(sock);
  5252. if (quit) { break; }
  5253. }
  5254. return INVALID_SOCKET;
  5255. }
  5256. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5257. #ifdef _WIN32
  5258. auto flags = nonblocking ? 1UL : 0UL;
  5259. ioctlsocket(sock, FIONBIO, &flags);
  5260. #else
  5261. auto flags = fcntl(sock, F_GETFL, 0);
  5262. fcntl(sock, F_SETFL,
  5263. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5264. #endif
  5265. }
  5266. inline bool is_connection_error() {
  5267. #ifdef _WIN32
  5268. return WSAGetLastError() != WSAEWOULDBLOCK;
  5269. #else
  5270. return errno != EINPROGRESS;
  5271. #endif
  5272. }
  5273. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5274. struct addrinfo hints;
  5275. struct addrinfo *result;
  5276. memset(&hints, 0, sizeof(struct addrinfo));
  5277. hints.ai_family = AF_UNSPEC;
  5278. hints.ai_socktype = SOCK_STREAM;
  5279. hints.ai_protocol = 0;
  5280. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5281. return false;
  5282. }
  5283. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5284. auto ret = false;
  5285. for (auto rp = result; rp; rp = rp->ai_next) {
  5286. const auto &ai = *rp;
  5287. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5288. ret = true;
  5289. break;
  5290. }
  5291. }
  5292. return ret;
  5293. }
  5294. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5295. #define USE_IF2IP
  5296. #endif
  5297. #ifdef USE_IF2IP
  5298. inline std::string if2ip(int address_family, const std::string &ifn) {
  5299. struct ifaddrs *ifap;
  5300. getifaddrs(&ifap);
  5301. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5302. std::string addr_candidate;
  5303. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5304. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5305. (AF_UNSPEC == address_family ||
  5306. ifa->ifa_addr->sa_family == address_family)) {
  5307. if (ifa->ifa_addr->sa_family == AF_INET) {
  5308. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5309. char buf[INET_ADDRSTRLEN];
  5310. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5311. return std::string(buf, INET_ADDRSTRLEN);
  5312. }
  5313. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5314. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5315. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5316. char buf[INET6_ADDRSTRLEN] = {};
  5317. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5318. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5319. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5320. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5321. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5322. } else {
  5323. return std::string(buf, INET6_ADDRSTRLEN);
  5324. }
  5325. }
  5326. }
  5327. }
  5328. }
  5329. }
  5330. return addr_candidate;
  5331. }
  5332. #endif
  5333. inline socket_t create_client_socket(
  5334. const std::string &host, const std::string &ip, int port,
  5335. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5336. SocketOptions socket_options, time_t connection_timeout_sec,
  5337. time_t connection_timeout_usec, time_t read_timeout_sec,
  5338. time_t read_timeout_usec, time_t write_timeout_sec,
  5339. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5340. auto sock = create_socket(
  5341. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5342. std::move(socket_options),
  5343. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5344. if (!intf.empty()) {
  5345. #ifdef USE_IF2IP
  5346. auto ip_from_if = if2ip(address_family, intf);
  5347. if (ip_from_if.empty()) { ip_from_if = intf; }
  5348. if (!bind_ip_address(sock2, ip_from_if)) {
  5349. error = Error::BindIPAddress;
  5350. return false;
  5351. }
  5352. #endif
  5353. }
  5354. set_nonblocking(sock2, true);
  5355. auto ret =
  5356. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5357. if (ret < 0) {
  5358. if (is_connection_error()) {
  5359. error = Error::Connection;
  5360. return false;
  5361. }
  5362. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5363. connection_timeout_usec);
  5364. if (error != Error::Success) {
  5365. if (error == Error::ConnectionTimeout) { quit = true; }
  5366. return false;
  5367. }
  5368. }
  5369. set_nonblocking(sock2, false);
  5370. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5371. read_timeout_usec);
  5372. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5373. write_timeout_usec);
  5374. error = Error::Success;
  5375. return true;
  5376. },
  5377. connection_timeout_sec); // Pass DNS timeout
  5378. if (sock != INVALID_SOCKET) {
  5379. error = Error::Success;
  5380. } else {
  5381. if (error == Error::Success) { error = Error::Connection; }
  5382. }
  5383. return sock;
  5384. }
  5385. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5386. socklen_t addr_len, std::string &ip, int &port) {
  5387. if (addr.ss_family == AF_INET) {
  5388. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5389. } else if (addr.ss_family == AF_INET6) {
  5390. port =
  5391. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5392. } else {
  5393. return false;
  5394. }
  5395. std::array<char, NI_MAXHOST> ipstr{};
  5396. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5397. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5398. 0, NI_NUMERICHOST)) {
  5399. return false;
  5400. }
  5401. ip = ipstr.data();
  5402. return true;
  5403. }
  5404. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5405. struct sockaddr_storage addr;
  5406. socklen_t addr_len = sizeof(addr);
  5407. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5408. &addr_len)) {
  5409. get_ip_and_port(addr, addr_len, ip, port);
  5410. }
  5411. }
  5412. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5413. struct sockaddr_storage addr;
  5414. socklen_t addr_len = sizeof(addr);
  5415. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5416. &addr_len)) {
  5417. #ifndef _WIN32
  5418. if (addr.ss_family == AF_UNIX) {
  5419. #if defined(__linux__)
  5420. struct ucred ucred;
  5421. socklen_t len = sizeof(ucred);
  5422. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5423. port = ucred.pid;
  5424. }
  5425. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5426. pid_t pid;
  5427. socklen_t len = sizeof(pid);
  5428. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5429. port = pid;
  5430. }
  5431. #endif
  5432. return;
  5433. }
  5434. #endif
  5435. get_ip_and_port(addr, addr_len, ip, port);
  5436. }
  5437. }
  5438. // Recursive form retained so operator""_t below can compute hashes for
  5439. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5440. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5441. // instead, which is iterative and stack-safe.
  5442. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5443. unsigned int h) {
  5444. return (l == 0)
  5445. ? h
  5446. : str2tag_core(
  5447. s + 1, l - 1,
  5448. // Unsets the 6 high bits of h, therefore no overflow happens
  5449. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5450. h * 33) ^
  5451. static_cast<unsigned char>(*s));
  5452. }
  5453. inline unsigned int str2tag(const std::string &s) {
  5454. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5455. // for compile-time UDL evaluation of short string literals, but at runtime
  5456. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5457. // would blow the stack with one frame per character.
  5458. unsigned int h = 0;
  5459. for (auto c : s) {
  5460. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5461. static_cast<unsigned char>(c);
  5462. }
  5463. return h;
  5464. }
  5465. namespace udl {
  5466. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5467. return str2tag_core(s, l, 0);
  5468. }
  5469. } // namespace udl
  5470. inline std::string
  5471. find_content_type(const std::string &path,
  5472. const std::map<std::string, std::string> &user_data,
  5473. const std::string &default_content_type) {
  5474. auto ext = file_extension(path);
  5475. auto it = user_data.find(ext);
  5476. if (it != user_data.end()) { return it->second; }
  5477. using udl::operator""_t;
  5478. switch (str2tag(ext)) {
  5479. default: return default_content_type;
  5480. case "css"_t: return "text/css";
  5481. case "csv"_t: return "text/csv";
  5482. case "htm"_t:
  5483. case "html"_t: return "text/html";
  5484. case "js"_t:
  5485. case "mjs"_t: return "text/javascript";
  5486. case "txt"_t: return "text/plain";
  5487. case "vtt"_t: return "text/vtt";
  5488. case "apng"_t: return "image/apng";
  5489. case "avif"_t: return "image/avif";
  5490. case "bmp"_t: return "image/bmp";
  5491. case "gif"_t: return "image/gif";
  5492. case "png"_t: return "image/png";
  5493. case "svg"_t: return "image/svg+xml";
  5494. case "webp"_t: return "image/webp";
  5495. case "ico"_t: return "image/x-icon";
  5496. case "tif"_t: return "image/tiff";
  5497. case "tiff"_t: return "image/tiff";
  5498. case "jpg"_t:
  5499. case "jpeg"_t: return "image/jpeg";
  5500. case "mp4"_t: return "video/mp4";
  5501. case "mpeg"_t: return "video/mpeg";
  5502. case "webm"_t: return "video/webm";
  5503. case "mp3"_t: return "audio/mp3";
  5504. case "mpga"_t: return "audio/mpeg";
  5505. case "weba"_t: return "audio/webm";
  5506. case "wav"_t: return "audio/wave";
  5507. case "otf"_t: return "font/otf";
  5508. case "ttf"_t: return "font/ttf";
  5509. case "woff"_t: return "font/woff";
  5510. case "woff2"_t: return "font/woff2";
  5511. case "7z"_t: return "application/x-7z-compressed";
  5512. case "atom"_t: return "application/atom+xml";
  5513. case "pdf"_t: return "application/pdf";
  5514. case "json"_t: return "application/json";
  5515. case "rss"_t: return "application/rss+xml";
  5516. case "tar"_t: return "application/x-tar";
  5517. case "xht"_t:
  5518. case "xhtml"_t: return "application/xhtml+xml";
  5519. case "xslt"_t: return "application/xslt+xml";
  5520. case "xml"_t: return "application/xml";
  5521. case "gz"_t: return "application/gzip";
  5522. case "zip"_t: return "application/zip";
  5523. case "wasm"_t: return "application/wasm";
  5524. }
  5525. }
  5526. inline std::string
  5527. extract_media_type(const std::string &content_type,
  5528. std::map<std::string, std::string> *params = nullptr) {
  5529. // Extract type/subtype from Content-Type value (RFC 2045)
  5530. // e.g. "application/json; charset=utf-8" -> "application/json"
  5531. auto media_type = content_type;
  5532. auto semicolon_pos = media_type.find(';');
  5533. if (semicolon_pos != std::string::npos) {
  5534. auto param_str = media_type.substr(semicolon_pos + 1);
  5535. media_type = media_type.substr(0, semicolon_pos);
  5536. if (params) {
  5537. // Parse parameters: key=value pairs separated by ';'
  5538. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5539. [&](const char *b, const char *e) {
  5540. std::string key;
  5541. std::string val;
  5542. split(b, e, '=', [&](const char *b2, const char *e2) {
  5543. if (key.empty()) {
  5544. key.assign(b2, e2);
  5545. } else {
  5546. val.assign(b2, e2);
  5547. }
  5548. });
  5549. if (!key.empty()) {
  5550. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5551. }
  5552. });
  5553. }
  5554. }
  5555. // Trim whitespace from media type
  5556. return trim_copy(media_type);
  5557. }
  5558. inline bool can_compress_content_type(const std::string &content_type) {
  5559. using udl::operator""_t;
  5560. auto mime_type = extract_media_type(content_type);
  5561. auto tag = str2tag(mime_type);
  5562. switch (tag) {
  5563. case "image/svg+xml"_t:
  5564. case "application/javascript"_t:
  5565. case "application/x-javascript"_t:
  5566. case "application/json"_t:
  5567. case "application/ld+json"_t:
  5568. case "application/xml"_t:
  5569. case "application/xhtml+xml"_t:
  5570. case "application/rss+xml"_t:
  5571. case "application/atom+xml"_t:
  5572. case "application/xslt+xml"_t:
  5573. case "application/protobuf"_t: return true;
  5574. case "text/event-stream"_t: return false;
  5575. default: return !mime_type.rfind("text/", 0);
  5576. }
  5577. }
  5578. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5579. double &quality) {
  5580. quality = 1.0;
  5581. token.clear();
  5582. // Split on first ';': left = token name, right = parameters
  5583. const char *params_b = nullptr;
  5584. std::size_t params_len = 0;
  5585. divide(
  5586. b, static_cast<std::size_t>(e - b), ';',
  5587. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5588. auto r = trim(lb, lb + llen, 0, llen);
  5589. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5590. params_b = rb;
  5591. params_len = rlen;
  5592. });
  5593. if (token.empty()) { return false; }
  5594. if (params_len == 0) { return true; }
  5595. // Scan parameters for q= (stops on first match)
  5596. bool invalid = false;
  5597. split_find(params_b, params_b + params_len, ';',
  5598. (std::numeric_limits<size_t>::max)(),
  5599. [&](const char *pb, const char *pe) -> bool {
  5600. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5601. auto len = static_cast<size_t>(pe - pb);
  5602. if (len < 2) { return false; }
  5603. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5604. return false;
  5605. }
  5606. // Trim the value portion
  5607. auto r = trim(pb, pe, 2, len);
  5608. if (r.first >= r.second) {
  5609. invalid = true;
  5610. return true;
  5611. }
  5612. double v = 0.0;
  5613. auto res = from_chars(pb + r.first, pb + r.second, v);
  5614. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5615. invalid = true;
  5616. return true;
  5617. }
  5618. quality = v;
  5619. return true;
  5620. });
  5621. return !invalid;
  5622. }
  5623. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5624. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5625. return EncodingType::None;
  5626. }
  5627. const auto &s = req.get_header_value("Accept-Encoding");
  5628. if (s.empty()) { return EncodingType::None; }
  5629. // Single-pass: iterate tokens and track the best supported encoding.
  5630. // Server preference breaks ties (br > gzip > zstd).
  5631. EncodingType best = EncodingType::None;
  5632. double best_q = 0.0; // q=0 means "not acceptable"
  5633. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5634. auto priority = [](EncodingType t) -> int {
  5635. switch (t) {
  5636. case EncodingType::Brotli: return 0;
  5637. case EncodingType::Gzip: return 1;
  5638. case EncodingType::Zstd: return 2;
  5639. default: return 3;
  5640. }
  5641. };
  5642. std::string name;
  5643. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5644. double quality = 1.0;
  5645. if (!parse_quality(b, e, name, quality)) { return; }
  5646. if (quality <= 0.0) { return; }
  5647. EncodingType type = EncodingType::None;
  5648. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5649. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5650. #endif
  5651. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5652. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5653. type = EncodingType::Gzip;
  5654. }
  5655. #endif
  5656. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5657. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5658. type = EncodingType::Zstd;
  5659. }
  5660. #endif
  5661. if (type == EncodingType::None) { return; }
  5662. // Higher q-value wins; for equal q, server preference breaks ties
  5663. if (quality > best_q ||
  5664. (quality == best_q && priority(type) < priority(best))) {
  5665. best_q = quality;
  5666. best = type;
  5667. }
  5668. });
  5669. return best;
  5670. }
  5671. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5672. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5673. if (type == EncodingType::Gzip) {
  5674. return detail::make_unique<gzip_compressor>();
  5675. }
  5676. #endif
  5677. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5678. if (type == EncodingType::Brotli) {
  5679. return detail::make_unique<brotli_compressor>();
  5680. }
  5681. #endif
  5682. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5683. if (type == EncodingType::Zstd) {
  5684. return detail::make_unique<zstd_compressor>();
  5685. }
  5686. #endif
  5687. (void)type;
  5688. return nullptr;
  5689. }
  5690. inline const char *encoding_name(EncodingType type) {
  5691. switch (type) {
  5692. case EncodingType::Gzip: return "gzip";
  5693. case EncodingType::Brotli: return "br";
  5694. case EncodingType::Zstd: return "zstd";
  5695. default: return "";
  5696. }
  5697. }
  5698. inline bool nocompressor::compress(const char *data, size_t data_length,
  5699. bool /*last*/, Callback callback) {
  5700. if (!data_length) { return true; }
  5701. return callback(data, data_length);
  5702. }
  5703. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5704. inline gzip_compressor::gzip_compressor() {
  5705. std::memset(&strm_, 0, sizeof(strm_));
  5706. strm_.zalloc = Z_NULL;
  5707. strm_.zfree = Z_NULL;
  5708. strm_.opaque = Z_NULL;
  5709. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5710. Z_DEFAULT_STRATEGY) == Z_OK;
  5711. }
  5712. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5713. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5714. bool last, Callback callback) {
  5715. assert(is_valid_);
  5716. do {
  5717. constexpr size_t max_avail_in =
  5718. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5719. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5720. (std::min)(data_length, max_avail_in));
  5721. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5722. data_length -= strm_.avail_in;
  5723. data += strm_.avail_in;
  5724. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5725. auto ret = Z_OK;
  5726. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5727. do {
  5728. strm_.avail_out = static_cast<uInt>(buff.size());
  5729. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5730. ret = deflate(&strm_, flush);
  5731. if (ret == Z_STREAM_ERROR) { return false; }
  5732. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5733. return false;
  5734. }
  5735. } while (strm_.avail_out == 0);
  5736. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5737. (flush == Z_NO_FLUSH && ret == Z_OK));
  5738. assert(strm_.avail_in == 0);
  5739. } while (data_length > 0);
  5740. return true;
  5741. }
  5742. inline gzip_decompressor::gzip_decompressor() {
  5743. std::memset(&strm_, 0, sizeof(strm_));
  5744. strm_.zalloc = Z_NULL;
  5745. strm_.zfree = Z_NULL;
  5746. strm_.opaque = Z_NULL;
  5747. // 15 is the value of wbits, which should be at the maximum possible value
  5748. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5749. // that the stream type should be automatically detected either gzip or
  5750. // deflate.
  5751. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5752. }
  5753. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5754. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5755. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5756. Callback callback) {
  5757. assert(is_valid_);
  5758. auto ret = Z_OK;
  5759. do {
  5760. constexpr size_t max_avail_in =
  5761. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5762. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5763. (std::min)(data_length, max_avail_in));
  5764. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5765. data_length -= strm_.avail_in;
  5766. data += strm_.avail_in;
  5767. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5768. while (strm_.avail_in > 0 && ret == Z_OK) {
  5769. strm_.avail_out = static_cast<uInt>(buff.size());
  5770. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5771. ret = inflate(&strm_, Z_NO_FLUSH);
  5772. assert(ret != Z_STREAM_ERROR);
  5773. switch (ret) {
  5774. case Z_NEED_DICT:
  5775. case Z_DATA_ERROR:
  5776. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5777. }
  5778. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5779. return false;
  5780. }
  5781. }
  5782. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5783. } while (data_length > 0);
  5784. return true;
  5785. }
  5786. #endif
  5787. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5788. inline brotli_compressor::brotli_compressor() {
  5789. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5790. }
  5791. inline brotli_compressor::~brotli_compressor() {
  5792. BrotliEncoderDestroyInstance(state_);
  5793. }
  5794. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5795. bool last, Callback callback) {
  5796. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5797. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5798. auto available_in = data_length;
  5799. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5800. for (;;) {
  5801. if (last) {
  5802. if (BrotliEncoderIsFinished(state_)) { break; }
  5803. } else {
  5804. if (!available_in) { break; }
  5805. }
  5806. auto available_out = buff.size();
  5807. auto next_out = buff.data();
  5808. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5809. &available_out, &next_out, nullptr)) {
  5810. return false;
  5811. }
  5812. auto output_bytes = buff.size() - available_out;
  5813. if (output_bytes) {
  5814. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5815. }
  5816. }
  5817. return true;
  5818. }
  5819. inline brotli_decompressor::brotli_decompressor() {
  5820. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5821. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5822. : BROTLI_DECODER_RESULT_ERROR;
  5823. }
  5824. inline brotli_decompressor::~brotli_decompressor() {
  5825. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5826. }
  5827. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5828. inline bool brotli_decompressor::decompress(const char *data,
  5829. size_t data_length,
  5830. Callback callback) {
  5831. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5832. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5833. return 0;
  5834. }
  5835. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5836. size_t avail_in = data_length;
  5837. size_t total_out;
  5838. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5839. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5840. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5841. char *next_out = buff.data();
  5842. size_t avail_out = buff.size();
  5843. decoder_r = BrotliDecoderDecompressStream(
  5844. decoder_s, &avail_in, &next_in, &avail_out,
  5845. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5846. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5847. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5848. }
  5849. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5850. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5851. }
  5852. #endif
  5853. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5854. inline zstd_compressor::zstd_compressor() {
  5855. ctx_ = ZSTD_createCCtx();
  5856. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5857. }
  5858. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5859. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5860. bool last, Callback callback) {
  5861. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5862. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5863. ZSTD_inBuffer input = {data, data_length, 0};
  5864. bool finished;
  5865. do {
  5866. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5867. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5868. if (ZSTD_isError(remaining)) { return false; }
  5869. if (!callback(buff.data(), output.pos)) { return false; }
  5870. finished = last ? (remaining == 0) : (input.pos == input.size);
  5871. } while (!finished);
  5872. return true;
  5873. }
  5874. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5875. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5876. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5877. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5878. Callback callback) {
  5879. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5880. ZSTD_inBuffer input = {data, data_length, 0};
  5881. while (input.pos < input.size) {
  5882. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5883. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5884. if (ZSTD_isError(remaining)) { return false; }
  5885. if (!callback(buff.data(), output.pos)) { return false; }
  5886. }
  5887. return true;
  5888. }
  5889. #endif
  5890. inline std::unique_ptr<decompressor>
  5891. create_decompressor(const std::string &encoding) {
  5892. std::unique_ptr<decompressor> decompressor;
  5893. if (encoding == "gzip" || encoding == "deflate") {
  5894. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5895. decompressor = detail::make_unique<gzip_decompressor>();
  5896. #endif
  5897. } else if (encoding.find("br") != std::string::npos) {
  5898. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5899. decompressor = detail::make_unique<brotli_decompressor>();
  5900. #endif
  5901. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5902. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5903. decompressor = detail::make_unique<zstd_decompressor>();
  5904. #endif
  5905. }
  5906. return decompressor;
  5907. }
  5908. // Returns the best available compressor and its Content-Encoding name.
  5909. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5910. inline std::pair<std::unique_ptr<compressor>, const char *>
  5911. create_compressor() {
  5912. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5913. return {detail::make_unique<brotli_compressor>(), "br"};
  5914. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5915. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5916. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5917. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5918. #else
  5919. return {nullptr, nullptr};
  5920. #endif
  5921. }
  5922. inline bool is_prohibited_header_name(const std::string &name) {
  5923. using udl::operator""_t;
  5924. switch (str2tag(name)) {
  5925. case "REMOTE_ADDR"_t:
  5926. case "REMOTE_PORT"_t:
  5927. case "LOCAL_ADDR"_t:
  5928. case "LOCAL_PORT"_t: return true;
  5929. default: return false;
  5930. }
  5931. }
  5932. inline bool has_header(const Headers &headers, const std::string &key) {
  5933. if (is_prohibited_header_name(key)) { return false; }
  5934. return headers.find(key) != headers.end();
  5935. }
  5936. inline const char *get_header_value(const Headers &headers,
  5937. const std::string &key, const char *def,
  5938. size_t id) {
  5939. if (is_prohibited_header_name(key)) {
  5940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5941. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5942. throw std::invalid_argument(msg);
  5943. #else
  5944. return "";
  5945. #endif
  5946. }
  5947. auto rng = headers.equal_range(key);
  5948. auto it = rng.first;
  5949. std::advance(it, static_cast<ssize_t>(id));
  5950. if (it != rng.second) { return it->second.c_str(); }
  5951. return def;
  5952. }
  5953. inline size_t get_header_value_count(const Headers &headers,
  5954. const std::string &key) {
  5955. auto r = headers.equal_range(key);
  5956. return static_cast<size_t>(std::distance(r.first, r.second));
  5957. }
  5958. template <typename Map>
  5959. inline typename Map::mapped_type
  5960. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5961. auto rng = m.equal_range(key);
  5962. auto it = rng.first;
  5963. std::advance(it, static_cast<ssize_t>(id));
  5964. if (it != rng.second) { return it->second; }
  5965. return typename Map::mapped_type();
  5966. }
  5967. inline void set_header(Headers &headers, const std::string &key,
  5968. const std::string &val) {
  5969. if (fields::is_field_valid(key, val)) { headers.emplace(key, val); }
  5970. }
  5971. inline bool read_headers(Stream &strm, Headers &headers) {
  5972. const auto bufsiz = 2048;
  5973. char buf[bufsiz];
  5974. stream_line_reader line_reader(strm, buf, bufsiz);
  5975. size_t header_count = 0;
  5976. for (;;) {
  5977. if (!line_reader.getline()) { return false; }
  5978. // Check if the line ends with CRLF.
  5979. auto line_terminator_len = 2;
  5980. if (line_reader.end_with_crlf()) {
  5981. // Blank line indicates end of headers.
  5982. if (line_reader.size() == 2) { break; }
  5983. } else {
  5984. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5985. // Blank line indicates end of headers.
  5986. if (line_reader.size() == 1) { break; }
  5987. line_terminator_len = 1;
  5988. #else
  5989. continue; // Skip invalid line.
  5990. #endif
  5991. }
  5992. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5993. // Check header count limit
  5994. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5995. // Exclude line terminator
  5996. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5997. if (!parse_header(line_reader.ptr(), end,
  5998. [&](const std::string &key, const std::string &val) {
  5999. headers.emplace(key, val);
  6000. })) {
  6001. return false;
  6002. }
  6003. header_count++;
  6004. }
  6005. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  6006. // headers that have different values to prevent request smuggling.
  6007. auto cl_range = headers.equal_range("Content-Length");
  6008. if (cl_range.first != cl_range.second) {
  6009. const auto &first_val = cl_range.first->second;
  6010. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  6011. if (it->second != first_val) { return false; }
  6012. }
  6013. }
  6014. return true;
  6015. }
  6016. inline bool read_websocket_upgrade_response(Stream &strm,
  6017. const std::string &expected_accept,
  6018. std::string &selected_subprotocol) {
  6019. // Read status line
  6020. const auto bufsiz = 2048;
  6021. char buf[bufsiz];
  6022. stream_line_reader line_reader(strm, buf, bufsiz);
  6023. if (!line_reader.getline()) { return false; }
  6024. // Check for "HTTP/1.1 101"
  6025. auto line = std::string(line_reader.ptr(), line_reader.size());
  6026. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  6027. // Parse headers using existing read_headers
  6028. Headers headers;
  6029. if (!read_headers(strm, headers)) { return false; }
  6030. // Verify Upgrade: websocket (case-insensitive)
  6031. auto upgrade_it = headers.find("Upgrade");
  6032. if (upgrade_it == headers.end()) { return false; }
  6033. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  6034. if (upgrade_val != "websocket") { return false; }
  6035. // Verify Connection header contains "Upgrade" (case-insensitive)
  6036. auto connection_it = headers.find("Connection");
  6037. if (connection_it == headers.end()) { return false; }
  6038. auto connection_val = case_ignore::to_lower(connection_it->second);
  6039. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  6040. // Verify Sec-WebSocket-Accept header value
  6041. auto it = headers.find("Sec-WebSocket-Accept");
  6042. if (it == headers.end() || it->second != expected_accept) { return false; }
  6043. // Extract negotiated subprotocol
  6044. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6045. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6046. return true;
  6047. }
  6048. enum class ReadContentResult {
  6049. Success, // Successfully read the content
  6050. PayloadTooLarge, // The content exceeds the specified payload limit
  6051. Error // An error occurred while reading the content
  6052. };
  6053. inline ReadContentResult read_content_with_length(
  6054. Stream &strm, size_t len, DownloadProgress progress,
  6055. ContentReceiverWithProgress out,
  6056. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6057. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6058. detail::BodyReader br;
  6059. br.stream = &strm;
  6060. br.has_content_length = true;
  6061. br.content_length = len;
  6062. br.payload_max_length = payload_max_length;
  6063. br.chunked = false;
  6064. br.bytes_read = 0;
  6065. br.last_error = Error::Success;
  6066. size_t r = 0;
  6067. while (r < len) {
  6068. auto read_len = static_cast<size_t>(len - r);
  6069. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6070. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6071. if (n <= 0) {
  6072. // Check if it was a payload size error
  6073. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6074. return ReadContentResult::PayloadTooLarge;
  6075. }
  6076. return ReadContentResult::Error;
  6077. }
  6078. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6079. return ReadContentResult::Error;
  6080. }
  6081. r += static_cast<size_t>(n);
  6082. if (progress) {
  6083. if (!progress(r, len)) { return ReadContentResult::Error; }
  6084. }
  6085. }
  6086. return ReadContentResult::Success;
  6087. }
  6088. inline ReadContentResult
  6089. read_content_without_length(Stream &strm, size_t payload_max_length,
  6090. ContentReceiverWithProgress out) {
  6091. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6092. size_t r = 0;
  6093. for (;;) {
  6094. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6095. if (n == 0) { return ReadContentResult::Success; }
  6096. if (n < 0) { return ReadContentResult::Error; }
  6097. // Check if adding this data would exceed the payload limit
  6098. if (r > payload_max_length ||
  6099. payload_max_length - r < static_cast<size_t>(n)) {
  6100. return ReadContentResult::PayloadTooLarge;
  6101. }
  6102. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6103. return ReadContentResult::Error;
  6104. }
  6105. r += static_cast<size_t>(n);
  6106. }
  6107. return ReadContentResult::Success;
  6108. }
  6109. template <typename T>
  6110. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6111. size_t payload_max_length,
  6112. ContentReceiverWithProgress out) {
  6113. detail::ChunkedDecoder dec(strm);
  6114. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6115. size_t total_len = 0;
  6116. for (;;) {
  6117. size_t chunk_offset = 0;
  6118. size_t chunk_total = 0;
  6119. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6120. if (n < 0) { return ReadContentResult::Error; }
  6121. if (n == 0) {
  6122. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6123. return ReadContentResult::Error;
  6124. }
  6125. return ReadContentResult::Success;
  6126. }
  6127. if (total_len > payload_max_length ||
  6128. payload_max_length - total_len < static_cast<size_t>(n)) {
  6129. return ReadContentResult::PayloadTooLarge;
  6130. }
  6131. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6132. return ReadContentResult::Error;
  6133. }
  6134. total_len += static_cast<size_t>(n);
  6135. }
  6136. }
  6137. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6138. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  6139. // is the final transfer coding. A single field value may list several
  6140. // codings ("gzip, chunked"), and the list may be split across multiple
  6141. // Transfer-Encoding header lines (RFC 9110 5.3). Match the last coding token
  6142. // case-insensitively rather than comparing the whole value against "chunked".
  6143. //
  6144. // Security: reading a chunked message as unframed leaves its body in the
  6145. // socket, where a keep-alive connection parses it as a smuggled request.
  6146. // Headers is an unordered_multimap whose iteration order for duplicate keys
  6147. // is not portable, so when there is more than one Transfer-Encoding line we
  6148. // cannot tell which coding is truly final. In that ambiguous case we fail
  6149. // safe by treating the message as chunked (a mis-parse just closes the
  6150. // connection, whereas the opposite error enables smuggling).
  6151. auto rng = headers.equal_range("Transfer-Encoding");
  6152. size_t line_count = 0;
  6153. bool chunked_present = false;
  6154. bool last_line_ends_with_chunked = false;
  6155. for (auto it = rng.first; it != rng.second; ++it) {
  6156. line_count++;
  6157. const auto &value = it->second;
  6158. std::string last_coding;
  6159. bool line_has_chunked = false;
  6160. split(value.data(), value.data() + value.size(), ',',
  6161. [&](const char *b, const char *e) {
  6162. last_coding.assign(b, e);
  6163. if (case_ignore::equal(last_coding, "chunked")) {
  6164. line_has_chunked = true;
  6165. }
  6166. });
  6167. if (line_has_chunked) { chunked_present = true; }
  6168. last_line_ends_with_chunked = case_ignore::equal(last_coding, "chunked");
  6169. }
  6170. if (line_count == 0) { return false; }
  6171. if (line_count == 1) { return last_line_ends_with_chunked; }
  6172. return chunked_present;
  6173. }
  6174. template <typename T, typename U>
  6175. bool prepare_content_receiver(T &x, int &status,
  6176. ContentReceiverWithProgress receiver,
  6177. bool decompress, size_t payload_max_length,
  6178. bool &exceed_payload_max_length, U callback) {
  6179. if (decompress) {
  6180. std::string encoding = x.get_header_value("Content-Encoding");
  6181. std::unique_ptr<decompressor> decompressor;
  6182. if (!encoding.empty()) {
  6183. decompressor = detail::create_decompressor(encoding);
  6184. if (!decompressor) {
  6185. // Unsupported encoding or no support compiled in
  6186. status = StatusCode::UnsupportedMediaType_415;
  6187. return false;
  6188. }
  6189. }
  6190. if (decompressor) {
  6191. if (decompressor->is_valid()) {
  6192. size_t decompressed_size = 0;
  6193. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6194. size_t off, size_t len) {
  6195. return decompressor->decompress(
  6196. buf, n, [&](const char *buf2, size_t n2) {
  6197. // Guard against zip-bomb: check
  6198. // decompressed size against limit.
  6199. if (payload_max_length > 0 &&
  6200. (decompressed_size >= payload_max_length ||
  6201. n2 > payload_max_length - decompressed_size)) {
  6202. exceed_payload_max_length = true;
  6203. return false;
  6204. }
  6205. decompressed_size += n2;
  6206. return receiver(buf2, n2, off, len);
  6207. });
  6208. };
  6209. return callback(std::move(out));
  6210. } else {
  6211. status = StatusCode::InternalServerError_500;
  6212. return false;
  6213. }
  6214. }
  6215. }
  6216. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6217. size_t len) {
  6218. return receiver(buf, n, off, len);
  6219. };
  6220. return callback(std::move(out));
  6221. }
  6222. template <typename T>
  6223. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6224. DownloadProgress progress,
  6225. ContentReceiverWithProgress receiver, bool decompress) {
  6226. bool exceed_payload_max_length = false;
  6227. return prepare_content_receiver(
  6228. x, status, std::move(receiver), decompress, payload_max_length,
  6229. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6230. auto ret = true;
  6231. // Note: exceed_payload_max_length may also be set by the decompressor
  6232. // wrapper in prepare_content_receiver when the decompressed payload
  6233. // size exceeds the limit.
  6234. if (is_chunked_transfer_encoding(x.headers)) {
  6235. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6236. if (result == ReadContentResult::Success) {
  6237. ret = true;
  6238. } else if (result == ReadContentResult::PayloadTooLarge) {
  6239. exceed_payload_max_length = true;
  6240. ret = false;
  6241. } else {
  6242. ret = false;
  6243. }
  6244. } else if (!has_header(x.headers, "Content-Length")) {
  6245. auto result =
  6246. read_content_without_length(strm, payload_max_length, out);
  6247. if (result == ReadContentResult::Success) {
  6248. ret = true;
  6249. } else if (result == ReadContentResult::PayloadTooLarge) {
  6250. exceed_payload_max_length = true;
  6251. ret = false;
  6252. } else {
  6253. ret = false;
  6254. }
  6255. } else {
  6256. auto is_invalid_value = false;
  6257. auto len = get_header_value_u64(x.headers, "Content-Length",
  6258. (std::numeric_limits<size_t>::max)(),
  6259. 0, is_invalid_value);
  6260. if (is_invalid_value) {
  6261. ret = false;
  6262. } else if (len > 0) {
  6263. auto result = read_content_with_length(
  6264. strm, len, std::move(progress), out, payload_max_length);
  6265. ret = (result == ReadContentResult::Success);
  6266. if (result == ReadContentResult::PayloadTooLarge) {
  6267. exceed_payload_max_length = true;
  6268. }
  6269. }
  6270. }
  6271. if (!ret) {
  6272. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6273. : StatusCode::BadRequest_400;
  6274. }
  6275. return ret;
  6276. });
  6277. }
  6278. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6279. const std::string &path) {
  6280. // A request target must not carry CR/LF (or other control octets); otherwise
  6281. // a value smuggled into it splits the request line and injects headers or a
  6282. // whole request. The same field-value check already guards header values in
  6283. // check_and_write_headers and the request target in
  6284. // perform_websocket_handshake; apply it here too.
  6285. if (!fields::is_field_value(path)) { return -1; }
  6286. std::string s = method;
  6287. s += ' ';
  6288. s += path;
  6289. s += " HTTP/1.1\r\n";
  6290. return strm.write(s.data(), s.size());
  6291. }
  6292. inline ssize_t write_response_line(Stream &strm, int status) {
  6293. std::string s = "HTTP/1.1 ";
  6294. s += std::to_string(status);
  6295. s += ' ';
  6296. s += httplib::status_message(status);
  6297. s += "\r\n";
  6298. return strm.write(s.data(), s.size());
  6299. }
  6300. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6301. ssize_t write_len = 0;
  6302. for (const auto &x : headers) {
  6303. // Skip fields with invalid names or values to prevent response splitting
  6304. // via CR/LF injection, matching set_header(). The client validates request
  6305. // headers up front in check_and_write_headers, but the server passes
  6306. // res.headers straight to this writer, and res.headers is a public field
  6307. // an application can populate directly with request-derived values.
  6308. if (!fields::is_field_valid(x.first, x.second)) { continue; }
  6309. std::string s;
  6310. s = x.first;
  6311. s += ": ";
  6312. s += x.second;
  6313. s += "\r\n";
  6314. auto len = strm.write(s.data(), s.size());
  6315. if (len < 0) { return len; }
  6316. write_len += len;
  6317. }
  6318. auto len = strm.write("\r\n");
  6319. if (len < 0) { return len; }
  6320. write_len += len;
  6321. return write_len;
  6322. }
  6323. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6324. size_t offset = 0;
  6325. while (offset < l) {
  6326. auto length = strm.write(d + offset, l - offset);
  6327. if (length < 0) { return false; }
  6328. offset += static_cast<size_t>(length);
  6329. }
  6330. return true;
  6331. }
  6332. template <typename T>
  6333. inline bool write_content_with_progress(Stream &strm,
  6334. const ContentProvider &content_provider,
  6335. size_t offset, size_t length,
  6336. T is_shutting_down,
  6337. const UploadProgress &upload_progress,
  6338. Error &error) {
  6339. size_t end_offset = offset + length;
  6340. size_t start_offset = offset;
  6341. auto ok = true;
  6342. DataSink data_sink;
  6343. data_sink.write = [&](const char *d, size_t l) -> bool {
  6344. if (ok) {
  6345. if (write_data(strm, d, l)) {
  6346. offset += l;
  6347. if (upload_progress && length > 0) {
  6348. size_t current_written = offset - start_offset;
  6349. if (!upload_progress(current_written, length)) {
  6350. ok = false;
  6351. return false;
  6352. }
  6353. }
  6354. } else {
  6355. ok = false;
  6356. }
  6357. }
  6358. return ok;
  6359. };
  6360. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6361. while (offset < end_offset && !is_shutting_down()) {
  6362. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6363. error = Error::Write;
  6364. return false;
  6365. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6366. error = Error::Canceled;
  6367. return false;
  6368. } else if (!ok) {
  6369. error = Error::Write;
  6370. return false;
  6371. }
  6372. }
  6373. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6374. error = Error::Write;
  6375. return false;
  6376. }
  6377. error = Error::Success;
  6378. return true;
  6379. }
  6380. template <typename T>
  6381. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6382. size_t offset, size_t length, T is_shutting_down,
  6383. Error &error) {
  6384. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6385. is_shutting_down, nullptr, error);
  6386. }
  6387. template <typename T>
  6388. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6389. size_t offset, size_t length,
  6390. const T &is_shutting_down) {
  6391. auto error = Error::Success;
  6392. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6393. error);
  6394. }
  6395. template <typename T>
  6396. inline bool
  6397. write_content_without_length(Stream &strm,
  6398. const ContentProvider &content_provider,
  6399. const T &is_shutting_down) {
  6400. size_t offset = 0;
  6401. auto data_available = true;
  6402. auto ok = true;
  6403. DataSink data_sink;
  6404. data_sink.write = [&](const char *d, size_t l) -> bool {
  6405. if (ok) {
  6406. offset += l;
  6407. if (!write_data(strm, d, l)) { ok = false; }
  6408. }
  6409. return ok;
  6410. };
  6411. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6412. data_sink.done = [&](void) { data_available = false; };
  6413. while (data_available && !is_shutting_down()) {
  6414. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6415. return false;
  6416. } else if (!content_provider(offset, 0, data_sink)) {
  6417. return false;
  6418. } else if (!ok) {
  6419. return false;
  6420. }
  6421. }
  6422. return !data_available; // true only if done() was called, false if shutting
  6423. // down
  6424. }
  6425. template <typename T, typename U>
  6426. inline bool
  6427. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6428. const T &is_shutting_down, U &compressor, Error &error) {
  6429. size_t offset = 0;
  6430. auto data_available = true;
  6431. auto ok = true;
  6432. DataSink data_sink;
  6433. data_sink.write = [&](const char *d, size_t l) -> bool {
  6434. if (ok) {
  6435. data_available = l > 0;
  6436. offset += l;
  6437. std::string payload;
  6438. if (compressor.compress(d, l, false,
  6439. [&](const char *data, size_t data_len) {
  6440. payload.append(data, data_len);
  6441. return true;
  6442. })) {
  6443. if (!payload.empty()) {
  6444. // Emit chunked response header and footer for each chunk
  6445. auto chunk =
  6446. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6447. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6448. }
  6449. } else {
  6450. ok = false;
  6451. }
  6452. }
  6453. return ok;
  6454. };
  6455. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6456. auto done_with_trailer = [&](const Headers *trailer) {
  6457. if (!ok) { return; }
  6458. data_available = false;
  6459. std::string payload;
  6460. if (!compressor.compress(nullptr, 0, true,
  6461. [&](const char *data, size_t data_len) {
  6462. payload.append(data, data_len);
  6463. return true;
  6464. })) {
  6465. ok = false;
  6466. return;
  6467. }
  6468. if (!payload.empty()) {
  6469. // Emit chunked response header and footer for each chunk
  6470. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6471. if (!write_data(strm, chunk.data(), chunk.size())) {
  6472. ok = false;
  6473. return;
  6474. }
  6475. }
  6476. constexpr const char done_marker[] = "0\r\n";
  6477. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6478. // Trailer
  6479. if (trailer) {
  6480. for (const auto &kv : *trailer) {
  6481. // Skip fields with invalid names or values to prevent response
  6482. // splitting via CR/LF injection, matching set_header().
  6483. if (!fields::is_field_valid(kv.first, kv.second)) { continue; }
  6484. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6485. if (!write_data(strm, field_line.data(), field_line.size())) {
  6486. ok = false;
  6487. }
  6488. }
  6489. }
  6490. constexpr const char crlf[] = "\r\n";
  6491. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6492. };
  6493. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6494. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6495. done_with_trailer(&trailer);
  6496. };
  6497. while (data_available && !is_shutting_down()) {
  6498. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6499. error = Error::Write;
  6500. return false;
  6501. } else if (!content_provider(offset, 0, data_sink)) {
  6502. error = Error::Canceled;
  6503. return false;
  6504. } else if (!ok) {
  6505. error = Error::Write;
  6506. return false;
  6507. }
  6508. }
  6509. if (data_available) { // exited due to is_shutting_down(), not done()
  6510. error = Error::Write;
  6511. return false;
  6512. }
  6513. error = Error::Success;
  6514. return true;
  6515. }
  6516. template <typename T, typename U>
  6517. inline bool write_content_chunked(Stream &strm,
  6518. const ContentProvider &content_provider,
  6519. const T &is_shutting_down, U &compressor) {
  6520. auto error = Error::Success;
  6521. return write_content_chunked(strm, content_provider, is_shutting_down,
  6522. compressor, error);
  6523. }
  6524. template <typename T>
  6525. inline bool redirect(T &cli, Request &req, Response &res,
  6526. const std::string &path, const std::string &location,
  6527. Error &error) {
  6528. Request new_req = req;
  6529. new_req.path = path;
  6530. new_req.redirect_count_ -= 1;
  6531. if (res.status == StatusCode::SeeOther_303 &&
  6532. (req.method != "GET" && req.method != "HEAD")) {
  6533. new_req.method = "GET";
  6534. new_req.body.clear();
  6535. new_req.headers.clear();
  6536. }
  6537. Response new_res;
  6538. auto ret = cli.send(new_req, new_res, error);
  6539. if (ret) {
  6540. req = std::move(new_req);
  6541. res = std::move(new_res);
  6542. if (res.location.empty()) { res.location = location; }
  6543. }
  6544. return ret;
  6545. }
  6546. inline std::string params_to_query_str(const Params &params) {
  6547. std::string query;
  6548. for (auto it = params.begin(); it != params.end(); ++it) {
  6549. if (it != params.begin()) { query += '&'; }
  6550. query += encode_query_component(it->first);
  6551. query += '=';
  6552. query += encode_query_component(it->second);
  6553. }
  6554. return query;
  6555. }
  6556. inline void parse_query_text(const char *data, std::size_t size,
  6557. Params &params) {
  6558. std::set<std::string> cache;
  6559. split(data, data + size, '&', [&](const char *b, const char *e) {
  6560. std::string kv(b, e);
  6561. if (cache.find(kv) != cache.end()) { return; }
  6562. cache.insert(std::move(kv));
  6563. std::string key;
  6564. std::string val;
  6565. divide(b, static_cast<std::size_t>(e - b), '=',
  6566. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6567. std::size_t rhs_size) {
  6568. key.assign(lhs_data, lhs_size);
  6569. val.assign(rhs_data, rhs_size);
  6570. });
  6571. if (!key.empty()) {
  6572. params.emplace(decode_query_component(key), decode_query_component(val));
  6573. }
  6574. });
  6575. }
  6576. inline void parse_query_text(const std::string &s, Params &params) {
  6577. parse_query_text(s.data(), s.size(), params);
  6578. }
  6579. // Normalize a query string by decoding and re-encoding each key/value pair
  6580. // while preserving the original parameter order. This avoids double-encoding
  6581. // and ensures consistent encoding without reordering (unlike Params which
  6582. // uses std::multimap and sorts keys).
  6583. inline std::string normalize_query_string(const std::string &query) {
  6584. std::string result;
  6585. split(query.data(), query.data() + query.size(), '&',
  6586. [&](const char *b, const char *e) {
  6587. std::string key;
  6588. std::string val;
  6589. divide(b, static_cast<std::size_t>(e - b), '=',
  6590. [&](const char *lhs_data, std::size_t lhs_size,
  6591. const char *rhs_data, std::size_t rhs_size) {
  6592. key.assign(lhs_data, lhs_size);
  6593. val.assign(rhs_data, rhs_size);
  6594. });
  6595. if (!key.empty()) {
  6596. auto dec_key = decode_query_component(key);
  6597. auto dec_val = decode_query_component(val);
  6598. if (!result.empty()) { result += '&'; }
  6599. result += encode_query_component(dec_key);
  6600. if (!val.empty() || std::find(b, e, '=') != e) {
  6601. result += '=';
  6602. result += encode_query_component(dec_val);
  6603. }
  6604. }
  6605. });
  6606. return result;
  6607. }
  6608. // Build the request target that goes on the wire from a caller-supplied path.
  6609. // Shared by the buffered send path and the streaming API so that both put the
  6610. // same bytes in the request line for the same input.
  6611. inline std::string encode_request_target(const std::string &target,
  6612. bool path_encode) {
  6613. // `substr(0, npos)` yields the whole string, which is what the no-query
  6614. // case needs.
  6615. auto query_pos = target.find('?');
  6616. auto path_part = target.substr(0, query_pos);
  6617. std::string query_part;
  6618. if (query_pos != std::string::npos) {
  6619. query_part = target.substr(query_pos + 1);
  6620. }
  6621. auto result = path_encode ? encode_path(path_part) : std::move(path_part);
  6622. if (!query_part.empty()) {
  6623. // When path encoding is disabled the caller has supplied an already-encoded
  6624. // target and expects the exact bytes to be sent on the wire, so skip
  6625. // normalization for the query too. Normalizing would decode-then-re-encode
  6626. // it and corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  6627. // which a strict RFC 3986 server decodes back as `+`, not a space).
  6628. if (path_encode) {
  6629. auto normalized = normalize_query_string(query_part);
  6630. if (!normalized.empty()) {
  6631. result += '?';
  6632. result += normalized;
  6633. }
  6634. } else {
  6635. result += '?';
  6636. result += query_part;
  6637. }
  6638. }
  6639. return result;
  6640. }
  6641. inline bool parse_multipart_boundary(const std::string &content_type,
  6642. std::string &boundary) {
  6643. std::map<std::string, std::string> params;
  6644. extract_media_type(content_type, &params);
  6645. auto it = params.find("boundary");
  6646. if (it == params.end()) { return false; }
  6647. boundary = it->second;
  6648. return !boundary.empty();
  6649. }
  6650. inline void parse_disposition_params(const std::string &s, Params &params) {
  6651. std::set<std::string> cache;
  6652. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6653. std::string kv(b, e);
  6654. if (cache.find(kv) != cache.end()) { return; }
  6655. cache.insert(kv);
  6656. std::string key;
  6657. std::string val;
  6658. split(b, e, '=', [&](const char *b2, const char *e2) {
  6659. if (key.empty()) {
  6660. key.assign(b2, e2);
  6661. } else {
  6662. val.assign(b2, e2);
  6663. }
  6664. });
  6665. if (!key.empty()) {
  6666. params.emplace(trim_double_quotes_copy((key)),
  6667. trim_double_quotes_copy((val)));
  6668. }
  6669. });
  6670. }
  6671. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6672. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6673. #else
  6674. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6675. #endif
  6676. auto is_valid = [](const std::string &str) {
  6677. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6678. };
  6679. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6680. const auto pos = static_cast<size_t>(6);
  6681. const auto len = static_cast<size_t>(s.size() - 6);
  6682. auto all_valid_ranges = true;
  6683. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6684. if (!all_valid_ranges) { return; }
  6685. const auto it = std::find(b, e, '-');
  6686. if (it == e) {
  6687. all_valid_ranges = false;
  6688. return;
  6689. }
  6690. const auto lhs = std::string(b, it);
  6691. const auto rhs = std::string(it + 1, e);
  6692. if (!is_valid(lhs) || !is_valid(rhs)) {
  6693. all_valid_ranges = false;
  6694. return;
  6695. }
  6696. ssize_t first = -1;
  6697. if (!lhs.empty()) {
  6698. ssize_t v;
  6699. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6700. if (res.ec == std::errc{}) { first = v; }
  6701. }
  6702. ssize_t last = -1;
  6703. if (!rhs.empty()) {
  6704. ssize_t v;
  6705. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6706. if (res.ec == std::errc{}) { last = v; }
  6707. }
  6708. if ((first == -1 && last == -1) ||
  6709. (first != -1 && last != -1 && first > last)) {
  6710. all_valid_ranges = false;
  6711. return;
  6712. }
  6713. ranges.emplace_back(first, last);
  6714. });
  6715. return all_valid_ranges && !ranges.empty();
  6716. }
  6717. return false;
  6718. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6719. }
  6720. #else
  6721. } catch (...) { return false; }
  6722. #endif
  6723. inline bool parse_accept_header(const std::string &s,
  6724. std::vector<std::string> &content_types) {
  6725. content_types.clear();
  6726. // Empty string is considered valid (no preference)
  6727. if (s.empty()) { return true; }
  6728. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6729. if (s.front() == ',' || s.back() == ',' ||
  6730. s.find(",,") != std::string::npos) {
  6731. return false;
  6732. }
  6733. struct AcceptEntry {
  6734. std::string media_type;
  6735. double quality;
  6736. int order;
  6737. };
  6738. std::vector<AcceptEntry> entries;
  6739. int order = 0;
  6740. bool has_invalid_entry = false;
  6741. // Split by comma and parse each entry
  6742. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6743. std::string entry(b, e);
  6744. entry = trim_copy(entry);
  6745. if (entry.empty()) {
  6746. has_invalid_entry = true;
  6747. return;
  6748. }
  6749. AcceptEntry accept_entry;
  6750. accept_entry.order = order++;
  6751. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6752. accept_entry.media_type, accept_entry.quality)) {
  6753. has_invalid_entry = true;
  6754. return;
  6755. }
  6756. // Remove additional parameters from media type
  6757. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6758. // Basic validation of media type format
  6759. if (accept_entry.media_type.empty()) {
  6760. has_invalid_entry = true;
  6761. return;
  6762. }
  6763. // Check for basic media type format (should contain '/' or be '*')
  6764. if (accept_entry.media_type != "*" &&
  6765. accept_entry.media_type.find('/') == std::string::npos) {
  6766. has_invalid_entry = true;
  6767. return;
  6768. }
  6769. entries.push_back(std::move(accept_entry));
  6770. });
  6771. // Return false if any invalid entry was found
  6772. if (has_invalid_entry) { return false; }
  6773. // Sort by quality (descending), then by original order (ascending)
  6774. std::sort(entries.begin(), entries.end(),
  6775. [](const AcceptEntry &a, const AcceptEntry &b) {
  6776. if (a.quality != b.quality) {
  6777. return a.quality > b.quality; // Higher quality first
  6778. }
  6779. return a.order < b.order; // Earlier order first for same quality
  6780. });
  6781. // Extract sorted media types
  6782. content_types.reserve(entries.size());
  6783. for (auto &entry : entries) {
  6784. content_types.push_back(std::move(entry.media_type));
  6785. }
  6786. return true;
  6787. }
  6788. class FormDataParser {
  6789. public:
  6790. FormDataParser() = default;
  6791. void set_boundary(std::string &&boundary) {
  6792. boundary_ = std::move(boundary);
  6793. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6794. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6795. }
  6796. bool is_valid() const { return is_valid_; }
  6797. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6798. const ContentReceiver &content_callback) {
  6799. buf_append(buf, n);
  6800. while (buf_size() > 0) {
  6801. switch (state_) {
  6802. case 0: { // Initial boundary
  6803. auto pos = buf_find(dash_boundary_crlf_);
  6804. if (pos == buf_size()) { return true; }
  6805. buf_erase(pos + dash_boundary_crlf_.size());
  6806. state_ = 1;
  6807. break;
  6808. }
  6809. case 1: { // New entry
  6810. clear_file_info();
  6811. state_ = 2;
  6812. break;
  6813. }
  6814. case 2: { // Headers
  6815. auto pos = buf_find(crlf_);
  6816. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6817. while (pos < buf_size()) {
  6818. // Empty line
  6819. if (pos == 0) {
  6820. if (!header_callback(file_)) {
  6821. is_valid_ = false;
  6822. return false;
  6823. }
  6824. buf_erase(crlf_.size());
  6825. state_ = 3;
  6826. break;
  6827. }
  6828. // Check header count limit
  6829. if (header_count_ >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  6830. is_valid_ = false;
  6831. return false;
  6832. }
  6833. header_count_++;
  6834. const auto header = buf_head(pos);
  6835. if (!parse_header(header.data(), header.data() + header.size(),
  6836. [&](const std::string &, const std::string &) {})) {
  6837. is_valid_ = false;
  6838. return false;
  6839. }
  6840. // Parse and emplace space trimmed headers into a map
  6841. if (!parse_header(
  6842. header.data(), header.data() + header.size(),
  6843. [&](const std::string &key, const std::string &val) {
  6844. file_.headers.emplace(key, val);
  6845. })) {
  6846. is_valid_ = false;
  6847. return false;
  6848. }
  6849. constexpr const char header_content_type[] = "Content-Type:";
  6850. if (start_with_case_ignore(header, header_content_type)) {
  6851. file_.content_type =
  6852. trim_copy(header.substr(str_len(header_content_type)));
  6853. } else {
  6854. std::string disposition_params;
  6855. if (parse_content_disposition(header, disposition_params)) {
  6856. Params params;
  6857. parse_disposition_params(disposition_params, params);
  6858. auto it = params.find("name");
  6859. if (it != params.end()) {
  6860. file_.name = it->second;
  6861. } else {
  6862. is_valid_ = false;
  6863. return false;
  6864. }
  6865. it = params.find("filename");
  6866. if (it != params.end()) { file_.filename = it->second; }
  6867. it = params.find("filename*");
  6868. if (it != params.end()) {
  6869. // RFC 5987: only UTF-8 encoding is allowed
  6870. const auto &val = it->second;
  6871. constexpr const char utf8_prefix[] = "UTF-8''";
  6872. constexpr size_t prefix_len = str_len(utf8_prefix);
  6873. if (val.size() > prefix_len &&
  6874. start_with_case_ignore(val, utf8_prefix)) {
  6875. file_.filename = decode_path_component(
  6876. val.substr(prefix_len)); // override...
  6877. } else {
  6878. is_valid_ = false;
  6879. return false;
  6880. }
  6881. }
  6882. }
  6883. }
  6884. buf_erase(pos + crlf_.size());
  6885. pos = buf_find(crlf_);
  6886. }
  6887. if (state_ != 3) { return true; }
  6888. break;
  6889. }
  6890. case 3: { // Body
  6891. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6892. auto pos = buf_find(crlf_dash_boundary_);
  6893. if (pos < buf_size()) {
  6894. if (!content_callback(buf_data(), pos)) {
  6895. is_valid_ = false;
  6896. return false;
  6897. }
  6898. buf_erase(pos + crlf_dash_boundary_.size());
  6899. state_ = 4;
  6900. } else {
  6901. auto len = buf_size() - crlf_dash_boundary_.size();
  6902. if (len > 0) {
  6903. if (!content_callback(buf_data(), len)) {
  6904. is_valid_ = false;
  6905. return false;
  6906. }
  6907. buf_erase(len);
  6908. }
  6909. return true;
  6910. }
  6911. break;
  6912. }
  6913. case 4: { // Boundary
  6914. if (crlf_.size() > buf_size()) { return true; }
  6915. if (buf_start_with(crlf_)) {
  6916. buf_erase(crlf_.size());
  6917. state_ = 1;
  6918. } else {
  6919. if (dash_.size() > buf_size()) { return true; }
  6920. if (buf_start_with(dash_)) {
  6921. buf_erase(dash_.size());
  6922. is_valid_ = true;
  6923. buf_erase(buf_size()); // Remove epilogue
  6924. } else {
  6925. return true;
  6926. }
  6927. }
  6928. break;
  6929. }
  6930. }
  6931. }
  6932. return true;
  6933. }
  6934. private:
  6935. void clear_file_info() {
  6936. file_.name.clear();
  6937. file_.filename.clear();
  6938. file_.content_type.clear();
  6939. file_.headers.clear();
  6940. header_count_ = 0;
  6941. }
  6942. bool start_with_case_ignore(const std::string &a, const char *b,
  6943. size_t offset = 0) const {
  6944. const auto b_len = strlen(b);
  6945. if (a.size() < offset + b_len) { return false; }
  6946. for (size_t i = 0; i < b_len; i++) {
  6947. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6948. return false;
  6949. }
  6950. }
  6951. return true;
  6952. }
  6953. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6954. // Returns true if header matches, with the params portion in `params_out`.
  6955. bool parse_content_disposition(const std::string &header,
  6956. std::string &params_out) const {
  6957. constexpr const char prefix[] = "Content-Disposition:";
  6958. constexpr size_t prefix_len = str_len(prefix);
  6959. if (!start_with_case_ignore(header, prefix)) { return false; }
  6960. // Skip whitespace after "Content-Disposition:"
  6961. auto pos = prefix_len;
  6962. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6963. pos++;
  6964. }
  6965. // Match "form-data;" (case-insensitive)
  6966. constexpr const char form_data[] = "form-data;";
  6967. constexpr size_t form_data_len = str_len(form_data);
  6968. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6969. pos += form_data_len;
  6970. // Skip whitespace after "form-data;"
  6971. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6972. pos++;
  6973. }
  6974. params_out = header.substr(pos);
  6975. return true;
  6976. }
  6977. const std::string dash_ = "--";
  6978. const std::string crlf_ = "\r\n";
  6979. std::string boundary_;
  6980. std::string dash_boundary_crlf_;
  6981. std::string crlf_dash_boundary_;
  6982. size_t state_ = 0;
  6983. bool is_valid_ = false;
  6984. FormData file_;
  6985. size_t header_count_ = 0;
  6986. // Buffer
  6987. bool start_with(const std::string &a, size_t spos, size_t epos,
  6988. const std::string &b) const {
  6989. if (epos - spos < b.size()) { return false; }
  6990. for (size_t i = 0; i < b.size(); i++) {
  6991. if (a[i + spos] != b[i]) { return false; }
  6992. }
  6993. return true;
  6994. }
  6995. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6996. const char *buf_data() const { return &buf_[buf_spos_]; }
  6997. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6998. bool buf_start_with(const std::string &s) const {
  6999. return start_with(buf_, buf_spos_, buf_epos_, s);
  7000. }
  7001. size_t buf_find(const std::string &s) const {
  7002. auto c = s.front();
  7003. size_t off = buf_spos_;
  7004. while (off < buf_epos_) {
  7005. auto pos = off;
  7006. while (true) {
  7007. if (pos == buf_epos_) { return buf_size(); }
  7008. if (buf_[pos] == c) { break; }
  7009. pos++;
  7010. }
  7011. auto remaining_size = buf_epos_ - pos;
  7012. if (s.size() > remaining_size) { return buf_size(); }
  7013. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  7014. off = pos + 1;
  7015. }
  7016. return buf_size();
  7017. }
  7018. void buf_append(const char *data, size_t n) {
  7019. auto remaining_size = buf_size();
  7020. if (remaining_size > 0 && buf_spos_ > 0) {
  7021. for (size_t i = 0; i < remaining_size; i++) {
  7022. buf_[i] = buf_[buf_spos_ + i];
  7023. }
  7024. }
  7025. buf_spos_ = 0;
  7026. buf_epos_ = remaining_size;
  7027. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  7028. for (size_t i = 0; i < n; i++) {
  7029. buf_[buf_epos_ + i] = data[i];
  7030. }
  7031. buf_epos_ += n;
  7032. }
  7033. void buf_erase(size_t size) { buf_spos_ += size; }
  7034. std::string buf_;
  7035. size_t buf_spos_ = 0;
  7036. size_t buf_epos_ = 0;
  7037. };
  7038. inline std::string random_string(size_t length) {
  7039. constexpr const char data[] =
  7040. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  7041. thread_local auto engine([]() {
  7042. // std::random_device might actually be deterministic on some
  7043. // platforms, but due to lack of support in the c++ standard library,
  7044. // doing better requires either some ugly hacks or breaking portability.
  7045. std::random_device seed_gen;
  7046. // Request 128 bits of entropy for initialization
  7047. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  7048. return std::mt19937(seed_sequence);
  7049. }());
  7050. std::string result;
  7051. for (size_t i = 0; i < length; i++) {
  7052. result += data[engine() % (sizeof(data) - 1)];
  7053. }
  7054. return result;
  7055. }
  7056. inline std::string make_multipart_data_boundary() {
  7057. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  7058. }
  7059. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  7060. auto valid = true;
  7061. for (size_t i = 0; i < boundary.size(); i++) {
  7062. auto c = boundary[i];
  7063. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  7064. valid = false;
  7065. break;
  7066. }
  7067. }
  7068. return valid;
  7069. }
  7070. // Escape a multipart field name/filename following the WHATWG HTML standard
  7071. // ("escape a multipart form-data name"), which is what browsers send:
  7072. // '"' -> %22, CR -> %0D, LF -> %0A
  7073. // With escape_quote = false, only CR and LF are escaped; this is for header
  7074. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  7075. inline std::string escape_multipart_field(const std::string &s,
  7076. bool escape_quote = true) {
  7077. std::string result;
  7078. result.reserve(s.size());
  7079. for (auto c : s) {
  7080. switch (c) {
  7081. case '"':
  7082. if (escape_quote) {
  7083. result += "%22";
  7084. } else {
  7085. result += c;
  7086. }
  7087. break;
  7088. case '\r': result += "%0D"; break;
  7089. case '\n': result += "%0A"; break;
  7090. default: result += c; break;
  7091. }
  7092. }
  7093. return result;
  7094. }
  7095. template <typename T>
  7096. inline std::string
  7097. serialize_multipart_formdata_item_begin(const T &item,
  7098. const std::string &boundary) {
  7099. std::string body = "--" + boundary + "\r\n";
  7100. body += "Content-Disposition: form-data; name=\"" +
  7101. escape_multipart_field(item.name) + "\"";
  7102. if (!item.filename.empty()) {
  7103. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  7104. }
  7105. body += "\r\n";
  7106. if (!item.content_type.empty()) {
  7107. body +=
  7108. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  7109. "\r\n";
  7110. }
  7111. body += "\r\n";
  7112. return body;
  7113. }
  7114. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  7115. inline std::string
  7116. serialize_multipart_formdata_finish(const std::string &boundary) {
  7117. return "--" + boundary + "--\r\n";
  7118. }
  7119. inline std::string
  7120. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7121. return "multipart/form-data; boundary=" + boundary;
  7122. }
  7123. inline std::string
  7124. serialize_multipart_formdata(const UploadFormDataItems &items,
  7125. const std::string &boundary, bool finish = true) {
  7126. std::string body;
  7127. for (const auto &item : items) {
  7128. body += serialize_multipart_formdata_item_begin(item, boundary);
  7129. body += item.content + serialize_multipart_formdata_item_end();
  7130. }
  7131. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7132. return body;
  7133. }
  7134. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7135. const std::string &boundary) {
  7136. size_t total = 0;
  7137. for (const auto &item : items) {
  7138. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7139. total += item.content.size();
  7140. total += serialize_multipart_formdata_item_end().size();
  7141. }
  7142. total += serialize_multipart_formdata_finish(boundary).size();
  7143. return total;
  7144. }
  7145. struct MultipartSegment {
  7146. const char *data;
  7147. size_t size;
  7148. };
  7149. // NOTE: items must outlive the returned ContentProvider
  7150. // (safe for synchronous use inside Post/Put/Patch)
  7151. inline ContentProvider
  7152. make_multipart_content_provider(const UploadFormDataItems &items,
  7153. const std::string &boundary) {
  7154. // Own the per-item header strings and the finish string
  7155. std::vector<std::string> owned;
  7156. owned.reserve(items.size() + 1);
  7157. for (const auto &item : items)
  7158. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7159. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7160. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7161. std::vector<MultipartSegment> segs;
  7162. segs.reserve(items.size() * 3 + 1);
  7163. static const char crlf[] = "\r\n";
  7164. for (size_t i = 0; i < items.size(); i++) {
  7165. segs.push_back({owned[i].data(), owned[i].size()});
  7166. segs.push_back({items[i].content.data(), items[i].content.size()});
  7167. segs.push_back({crlf, 2});
  7168. }
  7169. segs.push_back({owned.back().data(), owned.back().size()});
  7170. struct MultipartState {
  7171. std::vector<std::string> owned;
  7172. std::vector<MultipartSegment> segs;
  7173. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7174. };
  7175. auto state = std::make_shared<MultipartState>();
  7176. state->owned = std::move(owned);
  7177. // `segs` holds raw pointers into owned strings; std::string move preserves
  7178. // the data pointer, so these pointers remain valid after the move above.
  7179. state->segs = std::move(segs);
  7180. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7181. // Buffer multiple small segments into fewer, larger writes to avoid
  7182. // excessive TCP packets when there are many form data items (#2410)
  7183. auto &buf = state->buf;
  7184. auto buf_size = buf.size();
  7185. size_t buf_len = 0;
  7186. size_t remaining = length;
  7187. // Find the first segment containing 'offset'
  7188. size_t pos = 0;
  7189. size_t seg_idx = 0;
  7190. for (; seg_idx < state->segs.size(); seg_idx++) {
  7191. const auto &seg = state->segs[seg_idx];
  7192. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7193. pos += seg.size;
  7194. }
  7195. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7196. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7197. const auto &seg = state->segs[seg_idx];
  7198. size_t available = seg.size - seg_offset;
  7199. size_t to_copy = (std::min)(available, remaining);
  7200. const char *src = seg.data + seg_offset;
  7201. seg_offset = 0; // only the first segment has a non-zero offset
  7202. while (to_copy > 0) {
  7203. size_t space = buf_size - buf_len;
  7204. size_t chunk = (std::min)(to_copy, space);
  7205. std::memcpy(buf.data() + buf_len, src, chunk);
  7206. buf_len += chunk;
  7207. src += chunk;
  7208. to_copy -= chunk;
  7209. remaining -= chunk;
  7210. if (buf_len == buf_size) {
  7211. if (!sink.write(buf.data(), buf_len)) { return false; }
  7212. buf_len = 0;
  7213. }
  7214. }
  7215. }
  7216. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7217. return true;
  7218. };
  7219. }
  7220. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7221. if (ranges.size() <= 1) return;
  7222. // Sort ranges by start position
  7223. std::sort(ranges.begin(), ranges.end(),
  7224. [](const Range &a, const Range &b) { return a.first < b.first; });
  7225. Ranges coalesced;
  7226. coalesced.reserve(ranges.size());
  7227. for (auto &r : ranges) {
  7228. auto first_pos = r.first;
  7229. auto last_pos = r.second;
  7230. // Handle special cases like in range_error
  7231. if (first_pos == -1 && last_pos == -1) {
  7232. first_pos = 0;
  7233. last_pos = static_cast<ssize_t>(content_length);
  7234. }
  7235. if (first_pos == -1) {
  7236. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7237. last_pos = static_cast<ssize_t>(content_length) - 1;
  7238. }
  7239. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7240. last_pos = static_cast<ssize_t>(content_length) - 1;
  7241. }
  7242. // Skip invalid ranges
  7243. if (!(0 <= first_pos && first_pos <= last_pos &&
  7244. last_pos < static_cast<ssize_t>(content_length))) {
  7245. continue;
  7246. }
  7247. // Coalesce with previous range if overlapping or adjacent (but not
  7248. // identical)
  7249. if (!coalesced.empty()) {
  7250. auto &prev = coalesced.back();
  7251. // Check if current range overlaps or is adjacent to previous range
  7252. // but don't coalesce identical ranges (allow duplicates)
  7253. if (first_pos <= prev.second + 1 &&
  7254. !(first_pos == prev.first && last_pos == prev.second)) {
  7255. // Extend the previous range
  7256. prev.second = (std::max)(prev.second, last_pos);
  7257. continue;
  7258. }
  7259. }
  7260. // Add new range
  7261. coalesced.emplace_back(first_pos, last_pos);
  7262. }
  7263. ranges = std::move(coalesced);
  7264. }
  7265. inline bool range_error(Request &req, Response &res) {
  7266. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7267. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7268. req.ranges.clear();
  7269. if (res.status == StatusCode::PartialContent_206) {
  7270. res.status = StatusCode::OK_200;
  7271. }
  7272. return false;
  7273. }
  7274. ssize_t content_len = static_cast<ssize_t>(
  7275. res.content_length_ ? res.content_length_ : res.body.size());
  7276. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7277. size_t overwrapping_count = 0;
  7278. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7279. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7280. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7281. // Too many ranges
  7282. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7283. for (auto &r : req.ranges) {
  7284. auto &first_pos = r.first;
  7285. auto &last_pos = r.second;
  7286. if (first_pos == -1 && last_pos == -1) {
  7287. first_pos = 0;
  7288. last_pos = content_len;
  7289. }
  7290. if (first_pos == -1) {
  7291. first_pos = content_len - last_pos;
  7292. last_pos = content_len - 1;
  7293. }
  7294. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7295. // A client can limit the number of bytes requested without knowing the
  7296. // size of the selected representation. If the last-pos value is absent,
  7297. // or if the value is greater than or equal to the current length of the
  7298. // representation data, the byte range is interpreted as the remainder of
  7299. // the representation (i.e., the server replaces the value of last-pos
  7300. // with a value that is one less than the current length of the selected
  7301. // representation).
  7302. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7303. if (last_pos == -1 || last_pos >= content_len) {
  7304. last_pos = content_len - 1;
  7305. }
  7306. // Range must be within content length
  7307. if (!(0 <= first_pos && first_pos <= last_pos &&
  7308. last_pos <= content_len - 1)) {
  7309. return true;
  7310. }
  7311. // Request must not have more than two overlapping ranges
  7312. for (const auto &processed_range : processed_ranges) {
  7313. if (!(last_pos < processed_range.first ||
  7314. first_pos > processed_range.second)) {
  7315. overwrapping_count++;
  7316. if (overwrapping_count > 2) { return true; }
  7317. break; // Only count once per range
  7318. }
  7319. }
  7320. processed_ranges.emplace_back(first_pos, last_pos);
  7321. }
  7322. // After validation, coalesce overlapping ranges as per RFC 9110
  7323. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7324. }
  7325. return false;
  7326. }
  7327. inline std::pair<size_t, size_t>
  7328. get_range_offset_and_length(Range r, size_t content_length) {
  7329. assert(r.first != -1 && r.second != -1);
  7330. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7331. assert(r.first <= r.second &&
  7332. r.second < static_cast<ssize_t>(content_length));
  7333. (void)(content_length);
  7334. return std::make_pair(static_cast<size_t>(r.first),
  7335. static_cast<size_t>(r.second - r.first) + 1);
  7336. }
  7337. inline std::string make_content_range_header_field(
  7338. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7339. auto st = offset_and_length.first;
  7340. auto ed = st + offset_and_length.second - 1;
  7341. std::string field = "bytes ";
  7342. field += std::to_string(st);
  7343. field += '-';
  7344. field += std::to_string(ed);
  7345. field += '/';
  7346. field += std::to_string(content_length);
  7347. return field;
  7348. }
  7349. template <typename SToken, typename CToken, typename Content>
  7350. bool process_multipart_ranges_data(const Request &req,
  7351. const std::string &boundary,
  7352. const std::string &content_type,
  7353. size_t content_length, SToken stoken,
  7354. CToken ctoken, Content content) {
  7355. for (size_t i = 0; i < req.ranges.size(); i++) {
  7356. ctoken("--");
  7357. stoken(boundary);
  7358. ctoken("\r\n");
  7359. if (!content_type.empty()) {
  7360. ctoken("Content-Type: ");
  7361. stoken(content_type);
  7362. ctoken("\r\n");
  7363. }
  7364. auto offset_and_length =
  7365. get_range_offset_and_length(req.ranges[i], content_length);
  7366. ctoken("Content-Range: ");
  7367. stoken(make_content_range_header_field(offset_and_length, content_length));
  7368. ctoken("\r\n");
  7369. ctoken("\r\n");
  7370. if (!content(offset_and_length.first, offset_and_length.second)) {
  7371. return false;
  7372. }
  7373. ctoken("\r\n");
  7374. }
  7375. ctoken("--");
  7376. stoken(boundary);
  7377. ctoken("--");
  7378. return true;
  7379. }
  7380. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7381. const std::string &boundary,
  7382. const std::string &content_type,
  7383. size_t content_length,
  7384. std::string &data) {
  7385. process_multipart_ranges_data(
  7386. req, boundary, content_type, content_length,
  7387. [&](const std::string &token) { data += token; },
  7388. [&](const std::string &token) { data += token; },
  7389. [&](size_t offset, size_t length) {
  7390. assert(offset + length <= content_length);
  7391. data += res.body.substr(offset, length);
  7392. return true;
  7393. });
  7394. }
  7395. inline size_t get_multipart_ranges_data_length(const Request &req,
  7396. const std::string &boundary,
  7397. const std::string &content_type,
  7398. size_t content_length) {
  7399. size_t data_length = 0;
  7400. process_multipart_ranges_data(
  7401. req, boundary, content_type, content_length,
  7402. [&](const std::string &token) { data_length += token.size(); },
  7403. [&](const std::string &token) { data_length += token.size(); },
  7404. [&](size_t /*offset*/, size_t length) {
  7405. data_length += length;
  7406. return true;
  7407. });
  7408. return data_length;
  7409. }
  7410. template <typename T>
  7411. inline bool
  7412. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7413. const std::string &boundary,
  7414. const std::string &content_type,
  7415. size_t content_length, const T &is_shutting_down) {
  7416. return process_multipart_ranges_data(
  7417. req, boundary, content_type, content_length,
  7418. [&](const std::string &token) { strm.write(token); },
  7419. [&](const std::string &token) { strm.write(token); },
  7420. [&](size_t offset, size_t length) {
  7421. return write_content(strm, res.content_provider_, offset, length,
  7422. is_shutting_down);
  7423. });
  7424. }
  7425. inline bool has_framed_body(const Request &req) {
  7426. return is_chunked_transfer_encoding(req.headers) ||
  7427. req.get_header_value_u64("Content-Length") > 0;
  7428. }
  7429. inline bool is_connection_persistent(const Request &req) {
  7430. auto conn = req.get_header_value("Connection");
  7431. if (conn == "close") { return false; }
  7432. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7433. return true;
  7434. }
  7435. inline bool expect_content(const Request &req) {
  7436. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7437. req.method == "DELETE") {
  7438. return true;
  7439. }
  7440. return has_framed_body(req);
  7441. }
  7442. #ifdef _WIN32
  7443. class WSInit {
  7444. public:
  7445. WSInit() {
  7446. WSADATA wsaData;
  7447. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7448. }
  7449. ~WSInit() {
  7450. if (is_valid_) WSACleanup();
  7451. }
  7452. bool is_valid_ = false;
  7453. };
  7454. static WSInit wsinit_;
  7455. #endif
  7456. inline bool parse_www_authenticate(const Response &res,
  7457. std::map<std::string, std::string> &auth,
  7458. bool is_proxy) {
  7459. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7460. if (res.has_header(auth_key)) {
  7461. thread_local auto re =
  7462. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7463. auto s = res.get_header_value(auth_key);
  7464. auto pos = s.find(' ');
  7465. if (pos != std::string::npos) {
  7466. auto type = s.substr(0, pos);
  7467. if (type == "Basic") {
  7468. return false;
  7469. } else if (type == "Digest") {
  7470. s = s.substr(pos + 1);
  7471. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7472. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7473. const auto &m = *i;
  7474. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7475. static_cast<size_t>(m.length(1)));
  7476. auto val = m.length(2) > 0
  7477. ? s.substr(static_cast<size_t>(m.position(2)),
  7478. static_cast<size_t>(m.length(2)))
  7479. : s.substr(static_cast<size_t>(m.position(3)),
  7480. static_cast<size_t>(m.length(3)));
  7481. auth[std::move(key)] = std::move(val);
  7482. }
  7483. return true;
  7484. }
  7485. }
  7486. }
  7487. return false;
  7488. }
  7489. class ContentProviderAdapter {
  7490. public:
  7491. explicit ContentProviderAdapter(
  7492. ContentProviderWithoutLength &&content_provider)
  7493. : content_provider_(std::move(content_provider)) {}
  7494. bool operator()(size_t offset, size_t, DataSink &sink) {
  7495. return content_provider_(offset, sink);
  7496. }
  7497. private:
  7498. ContentProviderWithoutLength content_provider_;
  7499. };
  7500. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7501. namespace fields {
  7502. inline bool is_token_char(char c) {
  7503. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7504. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7505. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7506. }
  7507. inline bool is_token(const std::string &s) {
  7508. if (s.empty()) { return false; }
  7509. for (auto c : s) {
  7510. if (!is_token_char(c)) { return false; }
  7511. }
  7512. return true;
  7513. }
  7514. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7515. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7516. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7517. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7518. inline bool is_field_content(const std::string &s) {
  7519. if (s.empty()) { return true; }
  7520. if (s.size() == 1) {
  7521. return is_field_vchar(s[0]);
  7522. } else if (s.size() == 2) {
  7523. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7524. } else {
  7525. size_t i = 0;
  7526. if (!is_field_vchar(s[i])) { return false; }
  7527. i++;
  7528. while (i < s.size() - 1) {
  7529. auto c = s[i++];
  7530. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7531. } else {
  7532. return false;
  7533. }
  7534. }
  7535. return is_field_vchar(s[i]);
  7536. }
  7537. }
  7538. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7539. inline bool is_field_valid(const std::string &name, const std::string &value) {
  7540. return is_field_name(name) && is_field_value(value);
  7541. }
  7542. } // namespace fields
  7543. inline bool perform_websocket_handshake(Stream &strm, Request &req,
  7544. std::string &selected_subprotocol) {
  7545. // Generate random Sec-WebSocket-Key
  7546. thread_local std::mt19937 rng(std::random_device{}());
  7547. std::string key_bytes(16, '\0');
  7548. for (size_t i = 0; i < 16; i += 4) {
  7549. auto r = rng();
  7550. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7551. }
  7552. auto client_key = base64_encode(key_bytes);
  7553. req.headers.erase("Upgrade");
  7554. req.headers.erase("Connection");
  7555. req.headers.erase("Sec-WebSocket-Key");
  7556. req.headers.erase("Sec-WebSocket-Version");
  7557. req.headers.emplace("Upgrade", "websocket");
  7558. req.headers.emplace("Connection", "Upgrade");
  7559. req.headers.emplace("Sec-WebSocket-Key", client_key);
  7560. req.headers.emplace("Sec-WebSocket-Version", "13");
  7561. // Build the request in memory first, like ClientImpl::write_request does.
  7562. // Writing straight to the socket would leak a request line onto the wire
  7563. // before check_and_write_headers gets a chance to reject an invalid header,
  7564. // and would emit one small write per header.
  7565. BufferStream bstrm;
  7566. if (write_request_line(bstrm, req.method, req.path) < 0) { return false; }
  7567. auto error = Error::Success;
  7568. if (!check_and_write_headers(bstrm, req.headers, write_headers, error)) {
  7569. return false;
  7570. }
  7571. const auto &data = bstrm.get_buffer();
  7572. if (!write_data(strm, data.data(), data.size())) { return false; }
  7573. // Verify 101 response and Sec-WebSocket-Accept header
  7574. auto expected_accept = websocket_accept_key(client_key);
  7575. return read_websocket_upgrade_response(strm, expected_accept,
  7576. selected_subprotocol);
  7577. }
  7578. inline bool is_ip_address(const std::string &host) {
  7579. struct in_addr addr4;
  7580. struct in6_addr addr6;
  7581. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7582. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7583. }
  7584. // Resolve where a client should connect for `host`, honoring a user-supplied
  7585. // hostname-to-address map. `host` itself is never rewritten, so it keeps
  7586. // supplying the Host header and SNI; only the connection target changes.
  7587. //
  7588. // A mapped IP literal goes to `ip`, which keeps create_socket's AI_NUMERICHOST
  7589. // path. Anything else goes to `connect_host`, which create_socket resolves as
  7590. // a name, or uses as the socket path when the address family is AF_UNIX. An
  7591. // absent or empty mapping leaves `host` as the connection target; without the
  7592. // empty check the value would reach getaddrinfo as a null node and silently
  7593. // resolve to loopback.
  7594. inline void apply_addr_map(const std::map<std::string, std::string> &addr_map,
  7595. const std::string &host, std::string &connect_host,
  7596. std::string &ip) {
  7597. connect_host = host;
  7598. ip.clear();
  7599. auto it = addr_map.find(host);
  7600. if (it == addr_map.end() || it->second.empty()) { return; }
  7601. if (is_ip_address(it->second)) {
  7602. ip = it->second;
  7603. } else {
  7604. connect_host = it->second;
  7605. }
  7606. }
  7607. } // namespace detail
  7608. /*
  7609. * Group 2: detail namespace - SSL common utilities
  7610. */
  7611. #ifdef CPPHTTPLIB_SSL_ENABLED
  7612. namespace detail {
  7613. class SSLSocketStream final : public Stream {
  7614. public:
  7615. SSLSocketStream(
  7616. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7617. time_t read_timeout_usec, time_t write_timeout_sec,
  7618. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7619. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7620. (std::chrono::steady_clock::time_point::min)());
  7621. ~SSLSocketStream() override;
  7622. bool is_readable() const override;
  7623. bool wait_readable() const override;
  7624. bool wait_writable() const override;
  7625. bool is_peer_alive() const override;
  7626. ssize_t read(char *ptr, size_t size) override;
  7627. ssize_t write(const char *ptr, size_t size) override;
  7628. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7629. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7630. socket_t socket() const override;
  7631. time_t duration() const override;
  7632. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7633. private:
  7634. socket_t sock_;
  7635. tls::session_t session_;
  7636. time_t read_timeout_sec_;
  7637. time_t read_timeout_usec_;
  7638. time_t write_timeout_sec_;
  7639. time_t write_timeout_usec_;
  7640. time_t max_timeout_msec_;
  7641. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7642. };
  7643. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7644. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7645. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7646. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7647. unsigned int hash_length = 0;
  7648. unsigned char hash[EVP_MAX_MD_SIZE];
  7649. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7650. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7651. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7652. std::stringstream ss;
  7653. for (auto i = 0u; i < hash_length; ++i) {
  7654. ss << std::hex << std::setw(2) << std::setfill('0')
  7655. << static_cast<unsigned int>(hash[i]);
  7656. }
  7657. return ss.str();
  7658. }
  7659. inline std::string MD5(const std::string &s) {
  7660. return message_digest(s, EVP_md5());
  7661. }
  7662. inline std::string SHA_256(const std::string &s) {
  7663. return message_digest(s, EVP_sha256());
  7664. }
  7665. inline std::string SHA_512(const std::string &s) {
  7666. return message_digest(s, EVP_sha512());
  7667. }
  7668. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7669. namespace {
  7670. template <size_t N>
  7671. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7672. std::stringstream ss;
  7673. for (size_t i = 0; i < N; ++i) {
  7674. ss << std::hex << std::setw(2) << std::setfill('0')
  7675. << static_cast<unsigned int>(hash[i]);
  7676. }
  7677. return ss.str();
  7678. }
  7679. } // namespace
  7680. #ifdef CPPHTTPLIB_MBEDTLS_V4
  7681. // Mbed TLS 4.x provides hashing (and TLS RNG) via PSA Crypto, which must be
  7682. // initialized once. PSA state is process-global; do not free it.
  7683. inline bool ensure_mbedtls_psa_crypto() {
  7684. static std::once_flag once;
  7685. static bool ok = false;
  7686. std::call_once(once, []() { ok = (psa_crypto_init() == PSA_SUCCESS); });
  7687. return ok;
  7688. }
  7689. inline bool psa_hash(psa_algorithm_t alg, const std::string &s,
  7690. unsigned char *out, size_t out_size) {
  7691. if (!ensure_mbedtls_psa_crypto()) { return false; }
  7692. size_t olen = 0;
  7693. return psa_hash_compute(alg, reinterpret_cast<const uint8_t *>(s.data()),
  7694. s.size(), out, out_size, &olen) == PSA_SUCCESS &&
  7695. olen == out_size;
  7696. }
  7697. #endif
  7698. inline std::string MD5(const std::string &s) {
  7699. unsigned char hash[16];
  7700. #ifdef CPPHTTPLIB_MBEDTLS_V4
  7701. if (!psa_hash(PSA_ALG_MD5, s, hash, sizeof(hash))) { return {}; }
  7702. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  7703. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7704. hash);
  7705. #else
  7706. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7707. hash);
  7708. #endif
  7709. return hash_to_hex(hash);
  7710. }
  7711. inline std::string SHA_256(const std::string &s) {
  7712. unsigned char hash[32];
  7713. #ifdef CPPHTTPLIB_MBEDTLS_V4
  7714. if (!psa_hash(PSA_ALG_SHA_256, s, hash, sizeof(hash))) { return {}; }
  7715. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  7716. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7717. hash, 0);
  7718. #else
  7719. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7720. s.size(), hash, 0);
  7721. #endif
  7722. return hash_to_hex(hash);
  7723. }
  7724. inline std::string SHA_512(const std::string &s) {
  7725. unsigned char hash[64];
  7726. #ifdef CPPHTTPLIB_MBEDTLS_V4
  7727. if (!psa_hash(PSA_ALG_SHA_512, s, hash, sizeof(hash))) { return {}; }
  7728. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  7729. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7730. hash, 0);
  7731. #else
  7732. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7733. s.size(), hash, 0);
  7734. #endif
  7735. return hash_to_hex(hash);
  7736. }
  7737. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7738. namespace {
  7739. template <size_t N>
  7740. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7741. std::stringstream ss;
  7742. for (size_t i = 0; i < N; ++i) {
  7743. ss << std::hex << std::setw(2) << std::setfill('0')
  7744. << static_cast<unsigned int>(hash[i]);
  7745. }
  7746. return ss.str();
  7747. }
  7748. } // namespace
  7749. inline std::string MD5(const std::string &s) {
  7750. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7751. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7752. static_cast<word32>(s.size()), hash);
  7753. return hash_to_hex(hash);
  7754. }
  7755. inline std::string SHA_256(const std::string &s) {
  7756. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7757. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7758. static_cast<word32>(s.size()), hash);
  7759. return hash_to_hex(hash);
  7760. }
  7761. inline std::string SHA_512(const std::string &s) {
  7762. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7763. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7764. static_cast<word32>(s.size()), hash);
  7765. return hash_to_hex(hash);
  7766. }
  7767. #endif
  7768. template <typename T>
  7769. inline bool process_server_socket_ssl(
  7770. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7771. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7772. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7773. time_t write_timeout_usec, T callback) {
  7774. return process_server_socket_core(
  7775. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7776. [&](bool close_connection, bool &connection_closed) {
  7777. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7778. write_timeout_sec, write_timeout_usec);
  7779. return callback(strm, close_connection, connection_closed);
  7780. });
  7781. }
  7782. template <typename T>
  7783. inline bool process_client_socket_ssl(
  7784. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7785. time_t read_timeout_usec, time_t write_timeout_sec,
  7786. time_t write_timeout_usec, time_t max_timeout_msec,
  7787. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7788. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7789. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7790. start_time);
  7791. return callback(strm);
  7792. }
  7793. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7794. const Request &req, const std::map<std::string, std::string> &auth,
  7795. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7796. const std::string &password, bool is_proxy = false) {
  7797. std::string nc;
  7798. {
  7799. std::stringstream ss;
  7800. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7801. nc = ss.str();
  7802. }
  7803. std::string qop;
  7804. if (auth.find("qop") != auth.end()) {
  7805. qop = auth.at("qop");
  7806. if (qop.find("auth-int") != std::string::npos) {
  7807. qop = "auth-int";
  7808. } else if (qop.find("auth") != std::string::npos) {
  7809. qop = "auth";
  7810. } else {
  7811. qop.clear();
  7812. }
  7813. }
  7814. std::string algo = "MD5";
  7815. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7816. std::string response;
  7817. {
  7818. auto H = algo == "SHA-256" ? detail::SHA_256
  7819. : algo == "SHA-512" ? detail::SHA_512
  7820. : detail::MD5;
  7821. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7822. auto A2 = req.method + ":" + req.path;
  7823. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7824. if (qop.empty()) {
  7825. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7826. } else {
  7827. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7828. ":" + qop + ":" + H(A2));
  7829. }
  7830. }
  7831. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7832. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7833. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7834. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7835. (qop.empty() ? ", response=\""
  7836. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7837. cnonce + "\", response=\"") +
  7838. response + "\"" +
  7839. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7840. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7841. return std::make_pair(key, field);
  7842. }
  7843. inline bool match_hostname(const std::string &pattern,
  7844. const std::string &hostname) {
  7845. // Exact match (case-insensitive)
  7846. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7847. // Split both pattern and hostname into components by '.'
  7848. std::vector<std::string> pattern_components;
  7849. if (!pattern.empty()) {
  7850. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7851. [&](const char *b, const char *e) {
  7852. pattern_components.emplace_back(b, e);
  7853. });
  7854. }
  7855. std::vector<std::string> host_components;
  7856. if (!hostname.empty()) {
  7857. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7858. [&](const char *b, const char *e) {
  7859. host_components.emplace_back(b, e);
  7860. });
  7861. }
  7862. // Component count must match
  7863. if (host_components.size() != pattern_components.size()) { return false; }
  7864. // Compare each component with wildcard support
  7865. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7866. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7867. auto itr = pattern_components.begin();
  7868. for (const auto &h : host_components) {
  7869. auto &p = *itr;
  7870. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7871. bool partial_match = false;
  7872. if (!p.empty() && p[p.size() - 1] == '*') {
  7873. const auto prefix_length = p.size() - 1;
  7874. if (prefix_length == 0) {
  7875. partial_match = true;
  7876. } else if (h.size() >= prefix_length) {
  7877. partial_match =
  7878. std::equal(p.begin(),
  7879. p.begin() + static_cast<std::string::difference_type>(
  7880. prefix_length),
  7881. h.begin(), [](const char ca, const char cb) {
  7882. return detail::case_ignore::to_lower(ca) ==
  7883. detail::case_ignore::to_lower(cb);
  7884. });
  7885. }
  7886. }
  7887. if (!partial_match) { return false; }
  7888. }
  7889. ++itr;
  7890. }
  7891. return true;
  7892. }
  7893. #ifdef _WIN32
  7894. // Verify certificate using Windows CertGetCertificateChain API.
  7895. // This provides real-time certificate validation with Windows Update
  7896. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7897. inline bool
  7898. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7899. const std::string &hostname,
  7900. bool verify_hostname, uint64_t &out_error) {
  7901. if (der_cert.empty()) { return false; }
  7902. out_error = 0;
  7903. // Create Windows certificate context from DER data
  7904. auto cert_context = CertCreateCertificateContext(
  7905. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7906. static_cast<DWORD>(der_cert.size()));
  7907. if (!cert_context) {
  7908. out_error = GetLastError();
  7909. return false;
  7910. }
  7911. auto cert_guard =
  7912. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7913. // Setup chain parameters
  7914. CERT_CHAIN_PARA chain_para = {};
  7915. chain_para.cbSize = sizeof(chain_para);
  7916. // Build certificate chain with revocation checking
  7917. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7918. auto chain_result = CertGetCertificateChain(
  7919. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7920. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7921. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7922. nullptr, &chain_context);
  7923. if (!chain_result || !chain_context) {
  7924. out_error = GetLastError();
  7925. return false;
  7926. }
  7927. auto chain_guard =
  7928. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7929. // Check if chain has errors
  7930. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7931. out_error = chain_context->TrustStatus.dwErrorStatus;
  7932. return false;
  7933. }
  7934. // Verify SSL policy
  7935. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7936. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7937. #ifdef AUTHTYPE_SERVER
  7938. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7939. #endif
  7940. std::wstring whost;
  7941. if (verify_hostname) {
  7942. whost = u8string_to_wstring(hostname.c_str());
  7943. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7944. }
  7945. CERT_CHAIN_POLICY_PARA policy_para = {};
  7946. policy_para.cbSize = sizeof(policy_para);
  7947. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7948. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7949. #else
  7950. policy_para.dwFlags = 0;
  7951. #endif
  7952. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7953. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7954. policy_status.cbSize = sizeof(policy_status);
  7955. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7956. &policy_para, &policy_status)) {
  7957. out_error = GetLastError();
  7958. return false;
  7959. }
  7960. if (policy_status.dwError != 0) {
  7961. out_error = policy_status.dwError;
  7962. return false;
  7963. }
  7964. return true;
  7965. }
  7966. #endif // _WIN32
  7967. // Loads CA file/dir configuration and applies the system CA policy to a
  7968. // client TLS context. PEM data and native stores are applied to the context
  7969. // directly at set time; has_custom_store reflects them for the Auto policy
  7970. // decision.
  7971. inline bool load_client_ca_config(tls::ctx_t ctx,
  7972. const std::string &ca_cert_file_path,
  7973. const std::string &ca_cert_dir_path,
  7974. bool has_custom_store, SystemCAMode mode,
  7975. uint64_t &backend_error) {
  7976. auto ret = true;
  7977. if (!ca_cert_file_path.empty()) {
  7978. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7979. backend_error = tls::get_error();
  7980. ret = false;
  7981. }
  7982. } else if (!ca_cert_dir_path.empty()) {
  7983. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7984. backend_error = tls::get_error();
  7985. ret = false;
  7986. }
  7987. }
  7988. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7989. !ca_cert_dir_path.empty() || has_custom_store;
  7990. if (mode == SystemCAMode::Enabled ||
  7991. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7992. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7993. }
  7994. return ret;
  7995. }
  7996. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7997. tls::session_t &session, socket_t sock,
  7998. bool server_certificate_verification,
  7999. time_t timeout_sec, time_t timeout_usec) {
  8000. using namespace tls;
  8001. if (!ctx) { return false; }
  8002. bool is_ip = is_ip_address(host);
  8003. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  8004. // Chain verification happens during the handshake even for IP hosts; the
  8005. // certificate identity is verified post-handshake via verify_hostname()
  8006. set_verify_client(ctx, server_certificate_verification);
  8007. #endif
  8008. session = create_session(ctx, sock);
  8009. if (!session) { return false; }
  8010. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  8011. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  8012. // their identity is checked post-handshake below instead.
  8013. if (!is_ip) {
  8014. if (server_certificate_verification) {
  8015. set_hostname(session, host.c_str());
  8016. } else {
  8017. set_sni(session, host.c_str());
  8018. }
  8019. }
  8020. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  8021. return false;
  8022. }
  8023. if (server_certificate_verification) {
  8024. if (get_verify_result(session) != 0) { return false; }
  8025. // Identity check against the peer certificate, post-handshake for all
  8026. // backends (same as SSLClient). For IP hosts this is the only identity
  8027. // verification since no hostname is bound during the handshake.
  8028. auto server_cert = get_peer_cert(session);
  8029. if (!server_cert) { return false; }
  8030. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  8031. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  8032. }
  8033. return true;
  8034. }
  8035. } // namespace detail
  8036. #endif // CPPHTTPLIB_SSL_ENABLED
  8037. /*
  8038. * Group 3: httplib namespace - Non-SSL public API implementations
  8039. */
  8040. inline void default_socket_options(socket_t sock) {
  8041. set_socket_opt(sock, SOL_SOCKET,
  8042. #ifdef SO_REUSEPORT
  8043. SO_REUSEPORT,
  8044. #else
  8045. SO_REUSEADDR,
  8046. #endif
  8047. 1);
  8048. }
  8049. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  8050. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  8051. sizeof(optval));
  8052. }
  8053. inline std::string get_bearer_token_auth(const Request &req) {
  8054. if (req.has_header("Authorization")) {
  8055. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  8056. return req.get_header_value("Authorization")
  8057. .substr(bearer_header_prefix_len);
  8058. }
  8059. return "";
  8060. }
  8061. inline const char *status_message(int status) {
  8062. switch (status) {
  8063. case StatusCode::Continue_100: return "Continue";
  8064. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  8065. case StatusCode::Processing_102: return "Processing";
  8066. case StatusCode::EarlyHints_103: return "Early Hints";
  8067. case StatusCode::OK_200: return "OK";
  8068. case StatusCode::Created_201: return "Created";
  8069. case StatusCode::Accepted_202: return "Accepted";
  8070. case StatusCode::NonAuthoritativeInformation_203:
  8071. return "Non-Authoritative Information";
  8072. case StatusCode::NoContent_204: return "No Content";
  8073. case StatusCode::ResetContent_205: return "Reset Content";
  8074. case StatusCode::PartialContent_206: return "Partial Content";
  8075. case StatusCode::MultiStatus_207: return "Multi-Status";
  8076. case StatusCode::AlreadyReported_208: return "Already Reported";
  8077. case StatusCode::IMUsed_226: return "IM Used";
  8078. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  8079. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  8080. case StatusCode::Found_302: return "Found";
  8081. case StatusCode::SeeOther_303: return "See Other";
  8082. case StatusCode::NotModified_304: return "Not Modified";
  8083. case StatusCode::UseProxy_305: return "Use Proxy";
  8084. case StatusCode::unused_306: return "unused";
  8085. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  8086. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  8087. case StatusCode::BadRequest_400: return "Bad Request";
  8088. case StatusCode::Unauthorized_401: return "Unauthorized";
  8089. case StatusCode::PaymentRequired_402: return "Payment Required";
  8090. case StatusCode::Forbidden_403: return "Forbidden";
  8091. case StatusCode::NotFound_404: return "Not Found";
  8092. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  8093. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  8094. case StatusCode::ProxyAuthenticationRequired_407:
  8095. return "Proxy Authentication Required";
  8096. case StatusCode::RequestTimeout_408: return "Request Timeout";
  8097. case StatusCode::Conflict_409: return "Conflict";
  8098. case StatusCode::Gone_410: return "Gone";
  8099. case StatusCode::LengthRequired_411: return "Length Required";
  8100. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  8101. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  8102. case StatusCode::UriTooLong_414: return "URI Too Long";
  8103. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  8104. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  8105. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  8106. case StatusCode::ImATeapot_418: return "I'm a teapot";
  8107. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  8108. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  8109. case StatusCode::Locked_423: return "Locked";
  8110. case StatusCode::FailedDependency_424: return "Failed Dependency";
  8111. case StatusCode::TooEarly_425: return "Too Early";
  8112. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  8113. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  8114. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  8115. case StatusCode::RequestHeaderFieldsTooLarge_431:
  8116. return "Request Header Fields Too Large";
  8117. case StatusCode::UnavailableForLegalReasons_451:
  8118. return "Unavailable For Legal Reasons";
  8119. case StatusCode::NotImplemented_501: return "Not Implemented";
  8120. case StatusCode::BadGateway_502: return "Bad Gateway";
  8121. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  8122. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  8123. case StatusCode::HttpVersionNotSupported_505:
  8124. return "HTTP Version Not Supported";
  8125. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  8126. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  8127. case StatusCode::LoopDetected_508: return "Loop Detected";
  8128. case StatusCode::NotExtended_510: return "Not Extended";
  8129. case StatusCode::NetworkAuthenticationRequired_511:
  8130. return "Network Authentication Required";
  8131. default:
  8132. case StatusCode::InternalServerError_500: return "Internal Server Error";
  8133. }
  8134. }
  8135. inline std::string to_string(const Error error) {
  8136. switch (error) {
  8137. case Error::Success: return "Success (no error)";
  8138. case Error::Unknown: return "Unknown";
  8139. case Error::Connection: return "Could not establish connection";
  8140. case Error::BindIPAddress: return "Failed to bind IP address";
  8141. case Error::Read: return "Failed to read connection";
  8142. case Error::Write: return "Failed to write connection";
  8143. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  8144. case Error::Canceled: return "Connection handling canceled";
  8145. case Error::SSLConnection: return "SSL connection failed";
  8146. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  8147. case Error::SSLServerVerification: return "SSL server verification failed";
  8148. case Error::SSLServerHostnameVerification:
  8149. return "SSL server hostname verification failed";
  8150. case Error::UnsupportedMultipartBoundaryChars:
  8151. return "Unsupported HTTP multipart boundary characters";
  8152. case Error::Compression: return "Compression failed";
  8153. case Error::ConnectionTimeout: return "Connection timed out";
  8154. case Error::ProxyConnection: return "Proxy connection failed";
  8155. case Error::ConnectionClosed: return "Connection closed by server";
  8156. case Error::Timeout: return "Read timeout";
  8157. case Error::ResourceExhaustion: return "Resource exhaustion";
  8158. case Error::TooManyFormDataFiles: return "Too many form data files";
  8159. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  8160. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  8161. case Error::ExceedMaxSocketDescriptorCount:
  8162. return "Exceeded maximum socket descriptor count";
  8163. case Error::InvalidRequestLine: return "Invalid request line";
  8164. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8165. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8166. case Error::InvalidHeaders: return "Invalid headers";
  8167. case Error::MultipartParsing: return "Multipart parsing failed";
  8168. case Error::OpenFile: return "Failed to open file";
  8169. case Error::Listen: return "Failed to listen on socket";
  8170. case Error::GetSockName: return "Failed to get socket name";
  8171. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8172. case Error::HTTPParsing: return "HTTP parsing failed";
  8173. case Error::InvalidRangeHeader: return "Invalid Range header";
  8174. default: break;
  8175. }
  8176. return "Invalid";
  8177. }
  8178. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8179. os << to_string(obj);
  8180. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8181. return os;
  8182. }
  8183. inline std::string hosted_at(const std::string &hostname) {
  8184. std::vector<std::string> addrs;
  8185. hosted_at(hostname, addrs);
  8186. if (addrs.empty()) { return std::string(); }
  8187. return addrs[0];
  8188. }
  8189. inline void hosted_at(const std::string &hostname,
  8190. std::vector<std::string> &addrs) {
  8191. struct addrinfo hints;
  8192. struct addrinfo *result;
  8193. memset(&hints, 0, sizeof(struct addrinfo));
  8194. hints.ai_family = AF_UNSPEC;
  8195. hints.ai_socktype = SOCK_STREAM;
  8196. hints.ai_protocol = 0;
  8197. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8198. &result, 0)) {
  8199. #if defined __linux__ && !defined __ANDROID__
  8200. res_init();
  8201. #endif
  8202. return;
  8203. }
  8204. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8205. for (auto rp = result; rp; rp = rp->ai_next) {
  8206. const auto &addr =
  8207. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8208. std::string ip;
  8209. auto dummy = -1;
  8210. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8211. dummy)) {
  8212. addrs.emplace_back(std::move(ip));
  8213. }
  8214. }
  8215. }
  8216. inline std::string encode_uri_component(const std::string &value) {
  8217. std::ostringstream escaped;
  8218. escaped.fill('0');
  8219. escaped << std::hex;
  8220. for (auto c : value) {
  8221. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8222. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8223. escaped << c;
  8224. } else {
  8225. escaped << std::uppercase;
  8226. escaped << '%' << std::setw(2)
  8227. << static_cast<int>(static_cast<unsigned char>(c));
  8228. escaped << std::nouppercase;
  8229. }
  8230. }
  8231. return escaped.str();
  8232. }
  8233. inline std::string encode_uri(const std::string &value) {
  8234. std::ostringstream escaped;
  8235. escaped.fill('0');
  8236. escaped << std::hex;
  8237. for (auto c : value) {
  8238. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8239. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8240. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8241. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8242. escaped << c;
  8243. } else {
  8244. escaped << std::uppercase;
  8245. escaped << '%' << std::setw(2)
  8246. << static_cast<int>(static_cast<unsigned char>(c));
  8247. escaped << std::nouppercase;
  8248. }
  8249. }
  8250. return escaped.str();
  8251. }
  8252. inline std::string decode_uri_component(const std::string &value) {
  8253. std::string result;
  8254. for (size_t i = 0; i < value.size(); i++) {
  8255. if (value[i] == '%' && i + 2 < value.size()) {
  8256. auto val = 0;
  8257. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8258. result += static_cast<char>(val);
  8259. i += 2;
  8260. } else {
  8261. result += value[i];
  8262. }
  8263. } else {
  8264. result += value[i];
  8265. }
  8266. }
  8267. return result;
  8268. }
  8269. inline std::string decode_uri(const std::string &value) {
  8270. std::string result;
  8271. for (size_t i = 0; i < value.size(); i++) {
  8272. if (value[i] == '%' && i + 2 < value.size()) {
  8273. auto val = 0;
  8274. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8275. result += static_cast<char>(val);
  8276. i += 2;
  8277. } else {
  8278. result += value[i];
  8279. }
  8280. } else {
  8281. result += value[i];
  8282. }
  8283. }
  8284. return result;
  8285. }
  8286. inline std::string encode_path_component(const std::string &component) {
  8287. std::string result;
  8288. result.reserve(component.size() * 3);
  8289. for (size_t i = 0; i < component.size(); i++) {
  8290. auto c = static_cast<unsigned char>(component[i]);
  8291. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8292. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8293. c == '_' || c == '~') {
  8294. result += static_cast<char>(c);
  8295. }
  8296. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8297. // "," / ";" / "="
  8298. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8299. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8300. c == '=') {
  8301. result += static_cast<char>(c);
  8302. }
  8303. // Colon is allowed in path segments except first segment
  8304. else if (c == ':') {
  8305. result += static_cast<char>(c);
  8306. }
  8307. // @ is allowed in path
  8308. else if (c == '@') {
  8309. result += static_cast<char>(c);
  8310. } else {
  8311. result += '%';
  8312. char hex[3];
  8313. snprintf(hex, sizeof(hex), "%02X", c);
  8314. result.append(hex, 2);
  8315. }
  8316. }
  8317. return result;
  8318. }
  8319. inline std::string decode_path_component(const std::string &component) {
  8320. std::string result;
  8321. result.reserve(component.size());
  8322. for (size_t i = 0; i < component.size(); i++) {
  8323. if (component[i] == '%' && i + 1 < component.size()) {
  8324. if (component[i + 1] == 'u') {
  8325. // Unicode %uXXXX encoding
  8326. auto val = 0;
  8327. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8328. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8329. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8330. char buff[4];
  8331. size_t len = detail::to_utf8(val, buff);
  8332. if (len > 0) { result.append(buff, len); }
  8333. i += 5; // 'u0000'
  8334. } else {
  8335. result += component[i];
  8336. }
  8337. } else {
  8338. // Standard %XX encoding
  8339. auto val = 0;
  8340. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8341. // 2 digits hex codes
  8342. result += static_cast<char>(val);
  8343. i += 2; // 'XX'
  8344. } else {
  8345. result += component[i];
  8346. }
  8347. }
  8348. } else {
  8349. result += component[i];
  8350. }
  8351. }
  8352. return result;
  8353. }
  8354. inline std::string encode_query_component(const std::string &component,
  8355. bool space_as_plus) {
  8356. std::string result;
  8357. result.reserve(component.size() * 3);
  8358. for (size_t i = 0; i < component.size(); i++) {
  8359. auto c = static_cast<unsigned char>(component[i]);
  8360. // Unreserved characters per RFC 3986
  8361. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8362. c == '_' || c == '~') {
  8363. result += static_cast<char>(c);
  8364. }
  8365. // Space handling
  8366. else if (c == ' ') {
  8367. if (space_as_plus) {
  8368. result += '+';
  8369. } else {
  8370. result += "%20";
  8371. }
  8372. }
  8373. // Plus sign handling
  8374. else if (c == '+') {
  8375. if (space_as_plus) {
  8376. result += "%2B";
  8377. } else {
  8378. result += static_cast<char>(c);
  8379. }
  8380. }
  8381. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8382. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8383. c == '*' || c == ',' || c == ';') {
  8384. result += static_cast<char>(c);
  8385. }
  8386. // Colon and @ are allowed in query
  8387. else if (c == ':' || c == '@') {
  8388. result += static_cast<char>(c);
  8389. }
  8390. // Forward slash is allowed in query values
  8391. else if (c == '/') {
  8392. result += static_cast<char>(c);
  8393. }
  8394. // Question mark is allowed in query values (after first ?)
  8395. else if (c == '?') {
  8396. result += static_cast<char>(c);
  8397. } else {
  8398. result += '%';
  8399. char hex[3];
  8400. snprintf(hex, sizeof(hex), "%02X", c);
  8401. result.append(hex, 2);
  8402. }
  8403. }
  8404. return result;
  8405. }
  8406. inline std::string decode_query_component(const std::string &component,
  8407. bool plus_as_space) {
  8408. std::string result;
  8409. result.reserve(component.size());
  8410. for (size_t i = 0; i < component.size(); i++) {
  8411. if (component[i] == '%' && i + 2 < component.size()) {
  8412. auto val = 0;
  8413. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8414. result += static_cast<char>(val);
  8415. i += 2;
  8416. } else {
  8417. result += component[i];
  8418. }
  8419. } else if (component[i] == '+' && plus_as_space) {
  8420. result += ' '; // + becomes space in form-urlencoded
  8421. } else {
  8422. result += component[i];
  8423. }
  8424. }
  8425. return result;
  8426. }
  8427. inline std::string sanitize_filename(const std::string &filename) {
  8428. // Extract basename: find the last path separator (/ or \)
  8429. auto pos = filename.find_last_of("/\\");
  8430. auto result =
  8431. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8432. // Strip null bytes
  8433. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8434. // Trim whitespace
  8435. {
  8436. auto start = result.find_first_not_of(" \t");
  8437. auto end = result.find_last_not_of(" \t");
  8438. result = (start == std::string::npos)
  8439. ? ""
  8440. : result.substr(start, end - start + 1);
  8441. }
  8442. // Reject . and ..
  8443. if (result == "." || result == "..") { return ""; }
  8444. return result;
  8445. }
  8446. inline std::string append_query_params(const std::string &path,
  8447. const Params &params) {
  8448. std::string path_with_query = path;
  8449. thread_local const std::regex re("[^?]+\\?.*");
  8450. auto delm = std::regex_match(path, re) ? '&' : '?';
  8451. path_with_query += delm + detail::params_to_query_str(params);
  8452. return path_with_query;
  8453. }
  8454. // Header utilities
  8455. inline std::pair<std::string, std::string>
  8456. make_range_header(const Ranges &ranges) {
  8457. std::string field = "bytes=";
  8458. auto i = 0;
  8459. for (const auto &r : ranges) {
  8460. if (i != 0) { field += ", "; }
  8461. if (r.first != -1) { field += std::to_string(r.first); }
  8462. field += '-';
  8463. if (r.second != -1) { field += std::to_string(r.second); }
  8464. i++;
  8465. }
  8466. return std::make_pair("Range", std::move(field));
  8467. }
  8468. inline std::pair<std::string, std::string>
  8469. make_basic_authentication_header(const std::string &username,
  8470. const std::string &password, bool is_proxy) {
  8471. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8472. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8473. return std::make_pair(key, std::move(field));
  8474. }
  8475. inline std::pair<std::string, std::string>
  8476. make_bearer_token_authentication_header(const std::string &token,
  8477. bool is_proxy = false) {
  8478. auto field = "Bearer " + token;
  8479. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8480. return std::make_pair(key, std::move(field));
  8481. }
  8482. // Request implementation
  8483. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8484. size_t id) const {
  8485. return detail::get_header_value_u64(headers, key, def, id);
  8486. }
  8487. inline bool Request::has_header(const std::string &key) const {
  8488. return detail::has_header(headers, key);
  8489. }
  8490. inline std::string Request::get_header_value(const std::string &key,
  8491. const char *def, size_t id) const {
  8492. return detail::get_header_value(headers, key, def, id);
  8493. }
  8494. inline size_t Request::get_header_value_count(const std::string &key) const {
  8495. return detail::get_header_value_count(headers, key);
  8496. }
  8497. inline void Request::set_header(const std::string &key,
  8498. const std::string &val) {
  8499. detail::set_header(headers, key, val);
  8500. }
  8501. inline bool Request::has_trailer(const std::string &key) const {
  8502. return trailers.find(key) != trailers.end();
  8503. }
  8504. inline std::string Request::get_trailer_value(const std::string &key,
  8505. size_t id) const {
  8506. return detail::get_multimap_value(trailers, key, id);
  8507. }
  8508. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8509. auto r = trailers.equal_range(key);
  8510. return static_cast<size_t>(std::distance(r.first, r.second));
  8511. }
  8512. inline bool Request::has_param(const std::string &key) const {
  8513. return params.find(key) != params.end();
  8514. }
  8515. inline std::string Request::get_param_value(const std::string &key,
  8516. size_t id) const {
  8517. return detail::get_multimap_value(params, key, id);
  8518. }
  8519. inline std::vector<std::string>
  8520. Request::get_param_values(const std::string &key) const {
  8521. auto rng = params.equal_range(key);
  8522. std::vector<std::string> values;
  8523. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8524. for (auto it = rng.first; it != rng.second; ++it) {
  8525. values.push_back(it->second);
  8526. }
  8527. return values;
  8528. }
  8529. inline size_t Request::get_param_value_count(const std::string &key) const {
  8530. auto r = params.equal_range(key);
  8531. return static_cast<size_t>(std::distance(r.first, r.second));
  8532. }
  8533. inline bool Request::is_multipart_form_data() const {
  8534. const auto &content_type = get_header_value("Content-Type");
  8535. return detail::extract_media_type(content_type) == "multipart/form-data";
  8536. }
  8537. // Multipart FormData implementation
  8538. inline std::string MultipartFormData::get_field(const std::string &key,
  8539. size_t id) const {
  8540. auto rng = fields.equal_range(key);
  8541. auto it = rng.first;
  8542. std::advance(it, static_cast<ssize_t>(id));
  8543. if (it != rng.second) { return it->second.content; }
  8544. return std::string();
  8545. }
  8546. inline std::vector<std::string>
  8547. MultipartFormData::get_fields(const std::string &key) const {
  8548. std::vector<std::string> values;
  8549. auto rng = fields.equal_range(key);
  8550. for (auto it = rng.first; it != rng.second; it++) {
  8551. values.push_back(it->second.content);
  8552. }
  8553. return values;
  8554. }
  8555. inline bool MultipartFormData::has_field(const std::string &key) const {
  8556. return fields.find(key) != fields.end();
  8557. }
  8558. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8559. auto r = fields.equal_range(key);
  8560. return static_cast<size_t>(std::distance(r.first, r.second));
  8561. }
  8562. inline FormData MultipartFormData::get_file(const std::string &key,
  8563. size_t id) const {
  8564. return detail::get_multimap_value(files, key, id);
  8565. }
  8566. inline std::vector<FormData>
  8567. MultipartFormData::get_files(const std::string &key) const {
  8568. std::vector<FormData> values;
  8569. auto rng = files.equal_range(key);
  8570. for (auto it = rng.first; it != rng.second; it++) {
  8571. values.push_back(it->second);
  8572. }
  8573. return values;
  8574. }
  8575. inline bool MultipartFormData::has_file(const std::string &key) const {
  8576. return files.find(key) != files.end();
  8577. }
  8578. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8579. auto r = files.equal_range(key);
  8580. return static_cast<size_t>(std::distance(r.first, r.second));
  8581. }
  8582. // Multipart FormData writer implementation
  8583. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8584. return detail::is_multipart_boundary_chars_valid(boundary);
  8585. }
  8586. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8587. : boundary_(detail::make_multipart_data_boundary()) {}
  8588. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8589. : boundary_(std::move(boundary)) {}
  8590. inline const std::string &MultipartFormDataWriter::boundary() const {
  8591. return boundary_;
  8592. }
  8593. inline std::string MultipartFormDataWriter::content_type() const {
  8594. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8595. }
  8596. inline std::string
  8597. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8598. return detail::serialize_multipart_formdata(items, boundary_);
  8599. }
  8600. inline size_t MultipartFormDataWriter::content_length(
  8601. const UploadFormDataItems &items) const {
  8602. return detail::get_multipart_content_length(items, boundary_);
  8603. }
  8604. inline std::string
  8605. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8606. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8607. }
  8608. inline std::string MultipartFormDataWriter::item_end() {
  8609. return detail::serialize_multipart_formdata_item_end();
  8610. }
  8611. inline std::string MultipartFormDataWriter::finish() const {
  8612. return detail::serialize_multipart_formdata_finish(boundary_);
  8613. }
  8614. // Response implementation
  8615. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8616. size_t id) const {
  8617. return detail::get_header_value_u64(headers, key, def, id);
  8618. }
  8619. inline bool Response::has_header(const std::string &key) const {
  8620. return headers.find(key) != headers.end();
  8621. }
  8622. inline std::string Response::get_header_value(const std::string &key,
  8623. const char *def,
  8624. size_t id) const {
  8625. return detail::get_header_value(headers, key, def, id);
  8626. }
  8627. inline size_t Response::get_header_value_count(const std::string &key) const {
  8628. return detail::get_header_value_count(headers, key);
  8629. }
  8630. inline void Response::set_header(const std::string &key,
  8631. const std::string &val) {
  8632. detail::set_header(headers, key, val);
  8633. }
  8634. inline bool Response::has_trailer(const std::string &key) const {
  8635. return trailers.find(key) != trailers.end();
  8636. }
  8637. inline std::string Response::get_trailer_value(const std::string &key,
  8638. size_t id) const {
  8639. return detail::get_multimap_value(trailers, key, id);
  8640. }
  8641. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8642. auto r = trailers.equal_range(key);
  8643. return static_cast<size_t>(std::distance(r.first, r.second));
  8644. }
  8645. inline void Response::set_redirect(const std::string &url, int stat) {
  8646. if (detail::fields::is_field_value(url)) {
  8647. set_header("Location", url);
  8648. if (300 <= stat && stat < 400) {
  8649. this->status = stat;
  8650. } else {
  8651. this->status = StatusCode::Found_302;
  8652. }
  8653. }
  8654. }
  8655. inline void Response::set_content(const char *s, size_t n,
  8656. const std::string &content_type) {
  8657. body.assign(s, n);
  8658. auto rng = headers.equal_range("Content-Type");
  8659. headers.erase(rng.first, rng.second);
  8660. set_header("Content-Type", content_type);
  8661. }
  8662. inline void Response::set_content(const std::string &s,
  8663. const std::string &content_type) {
  8664. set_content(s.data(), s.size(), content_type);
  8665. }
  8666. inline void Response::set_content(std::string &&s,
  8667. const std::string &content_type) {
  8668. body = std::move(s);
  8669. auto rng = headers.equal_range("Content-Type");
  8670. headers.erase(rng.first, rng.second);
  8671. set_header("Content-Type", content_type);
  8672. }
  8673. inline void Response::set_content_provider(
  8674. size_t in_length, const std::string &content_type, ContentProvider provider,
  8675. ContentProviderResourceReleaser resource_releaser) {
  8676. set_header("Content-Type", content_type);
  8677. content_length_ = in_length;
  8678. if (in_length > 0) { content_provider_ = std::move(provider); }
  8679. content_provider_resource_releaser_ = std::move(resource_releaser);
  8680. is_chunked_content_provider_ = false;
  8681. }
  8682. inline void Response::set_content_provider(
  8683. const std::string &content_type, ContentProviderWithoutLength provider,
  8684. ContentProviderResourceReleaser resource_releaser) {
  8685. set_header("Content-Type", content_type);
  8686. content_length_ = 0;
  8687. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8688. content_provider_resource_releaser_ = std::move(resource_releaser);
  8689. is_chunked_content_provider_ = false;
  8690. }
  8691. inline void Response::set_chunked_content_provider(
  8692. const std::string &content_type, ContentProviderWithoutLength provider,
  8693. ContentProviderResourceReleaser resource_releaser) {
  8694. set_header("Content-Type", content_type);
  8695. content_length_ = 0;
  8696. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8697. content_provider_resource_releaser_ = std::move(resource_releaser);
  8698. is_chunked_content_provider_ = true;
  8699. }
  8700. inline void Response::set_file_content(const std::string &path,
  8701. const std::string &content_type) {
  8702. file_content_path_ = path;
  8703. file_content_content_type_ = content_type;
  8704. }
  8705. inline void Response::set_file_content(const std::string &path) {
  8706. file_content_path_ = path;
  8707. }
  8708. // Result implementation
  8709. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8710. size_t def,
  8711. size_t id) const {
  8712. return detail::get_header_value_u64(request_headers_, key, def, id);
  8713. }
  8714. inline bool Result::has_request_header(const std::string &key) const {
  8715. return request_headers_.find(key) != request_headers_.end();
  8716. }
  8717. inline std::string Result::get_request_header_value(const std::string &key,
  8718. const char *def,
  8719. size_t id) const {
  8720. return detail::get_header_value(request_headers_, key, def, id);
  8721. }
  8722. inline size_t
  8723. Result::get_request_header_value_count(const std::string &key) const {
  8724. auto r = request_headers_.equal_range(key);
  8725. return static_cast<size_t>(std::distance(r.first, r.second));
  8726. }
  8727. // Stream implementation
  8728. inline ssize_t Stream::write(const char *ptr) {
  8729. return write(ptr, strlen(ptr));
  8730. }
  8731. inline ssize_t Stream::write(const std::string &s) {
  8732. return write(s.data(), s.size());
  8733. }
  8734. // BodyReader implementation
  8735. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8736. if (!stream) {
  8737. last_error = Error::Connection;
  8738. return -1;
  8739. }
  8740. if (eof) { return 0; }
  8741. if (!chunked) {
  8742. // Content-Length based reading
  8743. if (has_content_length && bytes_read >= content_length) {
  8744. eof = true;
  8745. return 0;
  8746. }
  8747. auto to_read = len;
  8748. if (has_content_length) {
  8749. auto remaining = content_length - bytes_read;
  8750. to_read = (std::min)(len, remaining);
  8751. }
  8752. auto n = stream->read(buf, to_read);
  8753. if (n < 0) {
  8754. last_error = stream->get_error();
  8755. if (last_error == Error::Success) { last_error = Error::Read; }
  8756. eof = true;
  8757. return n;
  8758. }
  8759. if (n == 0) {
  8760. // Unexpected EOF before content_length
  8761. last_error = stream->get_error();
  8762. if (last_error == Error::Success) { last_error = Error::Read; }
  8763. eof = true;
  8764. return 0;
  8765. }
  8766. bytes_read += static_cast<size_t>(n);
  8767. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8768. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8769. last_error = Error::ExceedMaxPayloadSize;
  8770. eof = true;
  8771. return -1;
  8772. }
  8773. return n;
  8774. }
  8775. // Chunked transfer encoding: delegate to shared decoder instance.
  8776. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8777. size_t chunk_offset = 0;
  8778. size_t chunk_total = 0;
  8779. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8780. if (n < 0) {
  8781. last_error = stream->get_error();
  8782. if (last_error == Error::Success) { last_error = Error::Read; }
  8783. eof = true;
  8784. return n;
  8785. }
  8786. if (n == 0) {
  8787. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8788. eof = true;
  8789. return 0;
  8790. }
  8791. bytes_read += static_cast<size_t>(n);
  8792. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8793. last_error = Error::ExceedMaxPayloadSize;
  8794. eof = true;
  8795. return -1;
  8796. }
  8797. return n;
  8798. }
  8799. // ThreadPool implementation
  8800. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8801. time_t idle_timeout_sec)
  8802. : base_thread_count_(n), max_queued_requests_(mqr),
  8803. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8804. shutdown_(false) {
  8805. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8806. if (max_n != 0 && max_n < n) {
  8807. std::string msg = "max_threads must be >= base_threads";
  8808. throw std::invalid_argument(msg);
  8809. }
  8810. #endif
  8811. max_thread_count_ = max_n == 0 ? n : max_n;
  8812. threads_.reserve(base_thread_count_);
  8813. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8814. try {
  8815. #endif
  8816. for (size_t i = 0; i < base_thread_count_; i++) {
  8817. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8818. }
  8819. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8820. } catch (...) {
  8821. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8822. // signal the workers we already spawned to exit and join them so the
  8823. // vector destructor does not see joinable threads (which would call
  8824. // std::terminate). Then rethrow so the caller learns of the failure.
  8825. {
  8826. std::unique_lock<std::mutex> lock(mutex_);
  8827. shutdown_ = true;
  8828. }
  8829. cond_.notify_all();
  8830. for (auto &t : threads_) {
  8831. if (t.joinable()) { t.join(); }
  8832. }
  8833. throw;
  8834. }
  8835. #endif
  8836. }
  8837. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8838. {
  8839. std::unique_lock<std::mutex> lock(mutex_);
  8840. if (shutdown_) { return false; }
  8841. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8842. return false;
  8843. }
  8844. jobs_.push_back(std::move(fn));
  8845. // Spawn a dynamic thread if no idle threads and under max
  8846. if (idle_thread_count_ == 0 &&
  8847. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8848. cleanup_finished_threads();
  8849. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8850. }
  8851. }
  8852. cond_.notify_one();
  8853. return true;
  8854. }
  8855. inline void ThreadPool::shutdown() {
  8856. {
  8857. std::unique_lock<std::mutex> lock(mutex_);
  8858. shutdown_ = true;
  8859. }
  8860. cond_.notify_all();
  8861. for (auto &t : threads_) {
  8862. if (t.joinable()) { t.join(); }
  8863. }
  8864. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8865. // with worker threads that call move_to_finished() concurrently.
  8866. std::list<std::thread> remaining_dynamic;
  8867. {
  8868. std::unique_lock<std::mutex> lock(mutex_);
  8869. remaining_dynamic = std::move(dynamic_threads_);
  8870. }
  8871. for (auto &t : remaining_dynamic) {
  8872. if (t.joinable()) { t.join(); }
  8873. }
  8874. std::unique_lock<std::mutex> lock(mutex_);
  8875. cleanup_finished_threads();
  8876. }
  8877. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8878. // Must be called with mutex_ held
  8879. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8880. if (it->get_id() == id) {
  8881. finished_threads_.push_back(std::move(*it));
  8882. dynamic_threads_.erase(it);
  8883. return;
  8884. }
  8885. }
  8886. }
  8887. inline void ThreadPool::cleanup_finished_threads() {
  8888. // Must be called with mutex_ held
  8889. for (auto &t : finished_threads_) {
  8890. if (t.joinable()) { t.join(); }
  8891. }
  8892. finished_threads_.clear();
  8893. }
  8894. inline void ThreadPool::worker(bool is_dynamic) {
  8895. for (;;) {
  8896. std::function<void()> fn;
  8897. {
  8898. std::unique_lock<std::mutex> lock(mutex_);
  8899. idle_thread_count_++;
  8900. if (is_dynamic) {
  8901. auto has_work =
  8902. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8903. [&] { return !jobs_.empty() || shutdown_; });
  8904. if (!has_work) {
  8905. // Timed out with no work - exit this dynamic thread
  8906. idle_thread_count_--;
  8907. move_to_finished(std::this_thread::get_id());
  8908. break;
  8909. }
  8910. } else {
  8911. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8912. }
  8913. idle_thread_count_--;
  8914. if (shutdown_ && jobs_.empty()) { break; }
  8915. fn = std::move(jobs_.front());
  8916. jobs_.pop_front();
  8917. }
  8918. assert(true == static_cast<bool>(fn));
  8919. fn();
  8920. }
  8921. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8922. !defined(LIBRESSL_VERSION_NUMBER)
  8923. OPENSSL_thread_stop();
  8924. #endif
  8925. }
  8926. /*
  8927. * Group 1 (continued): detail namespace - Stream implementations
  8928. */
  8929. namespace detail {
  8930. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8931. time_t timeout_sec, time_t timeout_usec,
  8932. time_t &actual_timeout_sec,
  8933. time_t &actual_timeout_usec) {
  8934. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8935. auto actual_timeout_msec =
  8936. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8937. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8938. actual_timeout_sec = actual_timeout_msec / 1000;
  8939. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8940. }
  8941. // Socket stream implementation
  8942. inline SocketStream::SocketStream(
  8943. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8944. time_t write_timeout_sec, time_t write_timeout_usec,
  8945. time_t max_timeout_msec,
  8946. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8947. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8948. read_timeout_usec_(read_timeout_usec),
  8949. write_timeout_sec_(write_timeout_sec),
  8950. write_timeout_usec_(write_timeout_usec),
  8951. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8952. read_buff_(read_buff_size_, 0) {}
  8953. inline SocketStream::~SocketStream() = default;
  8954. inline bool SocketStream::is_readable() const {
  8955. return read_buff_off_ < read_buff_content_size_;
  8956. }
  8957. inline bool SocketStream::wait_readable() const {
  8958. if (max_timeout_msec_ <= 0) {
  8959. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8960. }
  8961. time_t read_timeout_sec;
  8962. time_t read_timeout_usec;
  8963. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8964. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8965. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8966. }
  8967. inline bool SocketStream::wait_writable() const {
  8968. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8969. }
  8970. inline bool SocketStream::is_peer_alive() const {
  8971. return detail::is_socket_alive(sock_);
  8972. }
  8973. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8974. #ifdef _WIN32
  8975. size =
  8976. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8977. #else
  8978. size = (std::min)(size,
  8979. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8980. #endif
  8981. if (read_buff_off_ < read_buff_content_size_) {
  8982. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8983. if (size <= remaining_size) {
  8984. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8985. read_buff_off_ += size;
  8986. return static_cast<ssize_t>(size);
  8987. } else {
  8988. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8989. read_buff_off_ += remaining_size;
  8990. return static_cast<ssize_t>(remaining_size);
  8991. }
  8992. }
  8993. if (!wait_readable()) {
  8994. error_ = Error::Timeout;
  8995. return -1;
  8996. }
  8997. read_buff_off_ = 0;
  8998. read_buff_content_size_ = 0;
  8999. if (size < read_buff_size_) {
  9000. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  9001. CPPHTTPLIB_RECV_FLAGS);
  9002. if (n <= 0) {
  9003. if (n == 0) {
  9004. error_ = Error::ConnectionClosed;
  9005. } else {
  9006. error_ = Error::Read;
  9007. }
  9008. return n;
  9009. } else if (n <= static_cast<ssize_t>(size)) {
  9010. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  9011. return n;
  9012. } else {
  9013. memcpy(ptr, read_buff_.data(), size);
  9014. read_buff_off_ = size;
  9015. read_buff_content_size_ = static_cast<size_t>(n);
  9016. return static_cast<ssize_t>(size);
  9017. }
  9018. } else {
  9019. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  9020. if (n <= 0) {
  9021. if (n == 0) {
  9022. error_ = Error::ConnectionClosed;
  9023. } else {
  9024. error_ = Error::Read;
  9025. }
  9026. }
  9027. return n;
  9028. }
  9029. }
  9030. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  9031. if (!wait_writable()) { return -1; }
  9032. #if defined(_WIN32) && !defined(_WIN64)
  9033. size =
  9034. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  9035. #endif
  9036. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  9037. }
  9038. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  9039. int &port) const {
  9040. return detail::get_remote_ip_and_port(sock_, ip, port);
  9041. }
  9042. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  9043. int &port) const {
  9044. return detail::get_local_ip_and_port(sock_, ip, port);
  9045. }
  9046. inline socket_t SocketStream::socket() const { return sock_; }
  9047. inline time_t SocketStream::duration() const {
  9048. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9049. std::chrono::steady_clock::now() - start_time_)
  9050. .count();
  9051. }
  9052. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  9053. read_timeout_sec_ = sec;
  9054. read_timeout_usec_ = usec;
  9055. }
  9056. // Buffer stream implementation
  9057. inline bool BufferStream::is_readable() const { return true; }
  9058. inline bool BufferStream::wait_readable() const { return true; }
  9059. inline bool BufferStream::wait_writable() const { return true; }
  9060. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  9061. #if defined(_MSC_VER) && _MSC_VER < 1910
  9062. auto len_read = buffer._Copy_s(ptr, size, size, position);
  9063. #else
  9064. auto len_read = buffer.copy(ptr, size, position);
  9065. #endif
  9066. position += static_cast<size_t>(len_read);
  9067. return static_cast<ssize_t>(len_read);
  9068. }
  9069. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  9070. buffer.append(ptr, size);
  9071. return static_cast<ssize_t>(size);
  9072. }
  9073. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  9074. int & /*port*/) const {}
  9075. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  9076. int & /*port*/) const {}
  9077. inline socket_t BufferStream::socket() const { return 0; }
  9078. inline time_t BufferStream::duration() const { return 0; }
  9079. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  9080. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  9081. : MatcherBase(pattern) {
  9082. constexpr const char marker[] = "/:";
  9083. // One past the last ending position of a path param substring
  9084. std::size_t last_param_end = 0;
  9085. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9086. // Needed to ensure that parameter names are unique during matcher
  9087. // construction
  9088. // If exceptions are disabled, only last duplicate path
  9089. // parameter will be set
  9090. std::unordered_set<std::string> param_name_set;
  9091. #endif
  9092. while (true) {
  9093. const auto marker_pos = pattern.find(
  9094. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  9095. if (marker_pos == std::string::npos) { break; }
  9096. static_fragments_.push_back(
  9097. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  9098. const auto param_name_start = marker_pos + str_len(marker);
  9099. auto sep_pos = pattern.find(separator, param_name_start);
  9100. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  9101. auto param_name =
  9102. pattern.substr(param_name_start, sep_pos - param_name_start);
  9103. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9104. if (param_name_set.find(param_name) != param_name_set.cend()) {
  9105. std::string msg = "Encountered path parameter '" + param_name +
  9106. "' multiple times in route pattern '" + pattern + "'.";
  9107. throw std::invalid_argument(msg);
  9108. }
  9109. #endif
  9110. param_names_.push_back(std::move(param_name));
  9111. last_param_end = sep_pos + 1;
  9112. }
  9113. if (last_param_end < pattern.length()) {
  9114. static_fragments_.push_back(pattern.substr(last_param_end));
  9115. }
  9116. }
  9117. inline bool PathParamsMatcher::match(Request &request) const {
  9118. request.matches = std::smatch();
  9119. request.path_params.clear();
  9120. request.path_params.reserve(param_names_.size());
  9121. // One past the position at which the path matched the pattern last time
  9122. std::size_t starting_pos = 0;
  9123. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  9124. const auto &fragment = static_fragments_[i];
  9125. if (starting_pos + fragment.length() > request.path.length()) {
  9126. return false;
  9127. }
  9128. // Avoid unnecessary allocation by using strncmp instead of substr +
  9129. // comparison
  9130. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  9131. fragment.length()) != 0) {
  9132. return false;
  9133. }
  9134. starting_pos += fragment.length();
  9135. // Should only happen when we have a static fragment after a param
  9136. // Example: '/users/:id/subscriptions'
  9137. // The 'subscriptions' fragment here does not have a corresponding param
  9138. if (i >= param_names_.size()) { continue; }
  9139. auto sep_pos = request.path.find(separator, starting_pos);
  9140. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  9141. const auto &param_name = param_names_[i];
  9142. request.path_params.emplace(
  9143. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  9144. // Mark everything up to '/' as matched
  9145. starting_pos = sep_pos + 1;
  9146. }
  9147. // Returns false if the path is longer than the pattern
  9148. return starting_pos >= request.path.length();
  9149. }
  9150. inline bool RegexMatcher::match(Request &request) const {
  9151. request.path_params.clear();
  9152. return std::regex_match(request.path, request.matches, regex_);
  9153. }
  9154. // Enclose IPv6 address in brackets if needed
  9155. inline std::string prepare_host_string(const std::string &host) {
  9156. // Enclose IPv6 address in brackets (but not if already enclosed)
  9157. if (host.find(':') == std::string::npos ||
  9158. (!host.empty() && host[0] == '[')) {
  9159. // IPv4, hostname, or already bracketed IPv6
  9160. return host;
  9161. } else {
  9162. // IPv6 address without brackets
  9163. return "[" + host + "]";
  9164. }
  9165. }
  9166. inline std::string make_host_and_port_string(const std::string &host, int port,
  9167. bool is_ssl) {
  9168. auto result = prepare_host_string(host);
  9169. // Append port if not default
  9170. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9171. ; // do nothing
  9172. } else {
  9173. result += ":" + std::to_string(port);
  9174. }
  9175. return result;
  9176. }
  9177. // Create "host:port" string always including port number (for CONNECT method)
  9178. inline std::string
  9179. make_host_and_port_string_always_port(const std::string &host, int port) {
  9180. return prepare_host_string(host) + ":" + std::to_string(port);
  9181. }
  9182. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9183. NormalizedTarget normalize_target(const std::string &host);
  9184. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9185. bool host_matches_no_proxy(const NormalizedTarget &target,
  9186. const std::vector<NoProxyEntry> &entries);
  9187. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9188. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9189. if (prefix_bits == 0) { return true; }
  9190. int full_bytes = prefix_bits / 8;
  9191. int rem_bits = prefix_bits % 8;
  9192. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9193. static_cast<size_t>(full_bytes)) != 0) {
  9194. return false;
  9195. }
  9196. if (rem_bits == 0) { return true; }
  9197. auto i = static_cast<size_t>(full_bytes);
  9198. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9199. return (ip[i] & mask) == (net[i] & mask);
  9200. }
  9201. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9202. if (token.empty()) { return false; }
  9203. if (token == "*") {
  9204. out.kind = NoProxyKind::Wildcard;
  9205. return true;
  9206. }
  9207. auto slash = token.find('/');
  9208. std::string addr_part =
  9209. (slash == std::string::npos) ? token : token.substr(0, slash);
  9210. std::string prefix_part =
  9211. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9212. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9213. // don't silently treat it as a /32 (or /128).
  9214. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9215. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9216. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9217. // when brackets are present.
  9218. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9219. addr_part.back() == ']';
  9220. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9221. if (!bracketed) {
  9222. struct in_addr v4;
  9223. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9224. int prefix = 32;
  9225. if (!prefix_part.empty()) {
  9226. auto r = from_chars(prefix_part.data(),
  9227. prefix_part.data() + prefix_part.size(), prefix);
  9228. if (r.ec != std::errc{} ||
  9229. r.ptr != prefix_part.data() + prefix_part.size()) {
  9230. return false;
  9231. }
  9232. if (prefix < 0 || prefix > 32) { return false; }
  9233. }
  9234. out.kind = NoProxyKind::IPv4Cidr;
  9235. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9236. out.prefix_bits = prefix;
  9237. return true;
  9238. }
  9239. }
  9240. struct in6_addr v6;
  9241. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9242. int prefix = 128;
  9243. if (!prefix_part.empty()) {
  9244. auto r = from_chars(prefix_part.data(),
  9245. prefix_part.data() + prefix_part.size(), prefix);
  9246. if (r.ec != std::errc{} ||
  9247. r.ptr != prefix_part.data() + prefix_part.size()) {
  9248. return false;
  9249. }
  9250. if (prefix < 0 || prefix > 128) { return false; }
  9251. }
  9252. out.kind = NoProxyKind::IPv6Cidr;
  9253. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9254. out.prefix_bits = prefix;
  9255. return true;
  9256. }
  9257. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9258. // the entry is malformed — don't fall through to the hostname branch.
  9259. if (bracketed) { return false; }
  9260. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9261. if (slash != std::string::npos) { return false; }
  9262. // Port-specific entries (host:port) are not supported.
  9263. if (token.find(':') != std::string::npos) { return false; }
  9264. std::string hostname = case_ignore::to_lower(token);
  9265. while (!hostname.empty() && hostname.front() == '.') {
  9266. hostname.erase(hostname.begin());
  9267. }
  9268. while (!hostname.empty() && hostname.back() == '.') {
  9269. hostname.pop_back();
  9270. }
  9271. if (hostname.empty()) { return false; }
  9272. out.kind = NoProxyKind::HostnameSuffix;
  9273. out.hostname_pattern = std::move(hostname);
  9274. return true;
  9275. }
  9276. inline NormalizedTarget normalize_target(const std::string &host) {
  9277. NormalizedTarget t;
  9278. std::string h = host;
  9279. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9280. h = h.substr(1, h.size() - 2);
  9281. }
  9282. // Strip a single trailing dot so "example.com." canonicalizes to
  9283. // "example.com".
  9284. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9285. t.hostname = case_ignore::to_lower(h);
  9286. if (!t.hostname.empty()) {
  9287. struct in_addr v4;
  9288. struct in6_addr v6;
  9289. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9290. t.is_ipv4 = true;
  9291. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9292. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9293. t.is_ipv6 = true;
  9294. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9295. }
  9296. }
  9297. return t;
  9298. }
  9299. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9300. const std::vector<NoProxyEntry> &entries) {
  9301. if (target.hostname.empty()) { return false; }
  9302. for (const auto &e : entries) {
  9303. switch (e.kind) {
  9304. case NoProxyKind::Wildcard: return true;
  9305. case NoProxyKind::IPv4Cidr:
  9306. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9307. return true;
  9308. }
  9309. break;
  9310. case NoProxyKind::IPv6Cidr:
  9311. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9312. return true;
  9313. }
  9314. break;
  9315. case NoProxyKind::HostnameSuffix:
  9316. if (target.is_ipv4 || target.is_ipv6) { break; }
  9317. if (target.hostname == e.hostname_pattern) { return true; }
  9318. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9319. // an entry of "example.com".
  9320. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9321. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9322. if (target.hostname[offset - 1] == '.' &&
  9323. target.hostname.compare(offset, e.hostname_pattern.size(),
  9324. e.hostname_pattern) == 0) {
  9325. return true;
  9326. }
  9327. }
  9328. break;
  9329. }
  9330. }
  9331. return false;
  9332. }
  9333. template <typename T>
  9334. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9335. T header_writer, Error &error) {
  9336. for (const auto &h : headers) {
  9337. if (!detail::fields::is_field_valid(h.first, h.second)) {
  9338. error = Error::InvalidHeaders;
  9339. return false;
  9340. }
  9341. }
  9342. if (header_writer(strm, headers) <= 0) {
  9343. error = Error::Write;
  9344. return false;
  9345. }
  9346. return true;
  9347. }
  9348. } // namespace detail
  9349. /*
  9350. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9351. */
  9352. #ifdef CPPHTTPLIB_SSL_ENABLED
  9353. namespace detail {
  9354. // SSL socket stream implementation
  9355. inline SSLSocketStream::SSLSocketStream(
  9356. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9357. time_t read_timeout_usec, time_t write_timeout_sec,
  9358. time_t write_timeout_usec, time_t max_timeout_msec,
  9359. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9360. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9361. read_timeout_usec_(read_timeout_usec),
  9362. write_timeout_sec_(write_timeout_sec),
  9363. write_timeout_usec_(write_timeout_usec),
  9364. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9365. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9366. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9367. // Note: create_session() also clears this, but SSLClient currently
  9368. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9369. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9370. // SSL session was created.
  9371. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9372. #endif
  9373. }
  9374. inline SSLSocketStream::~SSLSocketStream() = default;
  9375. inline bool SSLSocketStream::is_readable() const {
  9376. return tls::pending(session_) > 0;
  9377. }
  9378. inline bool SSLSocketStream::wait_readable() const {
  9379. if (max_timeout_msec_ <= 0) {
  9380. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9381. }
  9382. time_t read_timeout_sec;
  9383. time_t read_timeout_usec;
  9384. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9385. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9386. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9387. }
  9388. inline bool SSLSocketStream::wait_writable() const {
  9389. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9390. !tls::is_peer_closed(session_, sock_);
  9391. }
  9392. inline bool SSLSocketStream::is_peer_alive() const {
  9393. return !tls::is_peer_closed(session_, sock_);
  9394. }
  9395. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9396. if (tls::pending(session_) > 0) {
  9397. tls::TlsError err;
  9398. auto ret = tls::read(session_, ptr, size, err);
  9399. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9400. error_ = Error::ConnectionClosed;
  9401. }
  9402. return ret;
  9403. } else if (wait_readable()) {
  9404. tls::TlsError err;
  9405. auto ret = tls::read(session_, ptr, size, err);
  9406. if (ret < 0) {
  9407. auto n = 1000;
  9408. #ifdef _WIN32
  9409. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9410. (err.code == tls::ErrorCode::SyscallError &&
  9411. WSAGetLastError() == WSAETIMEDOUT))) {
  9412. #else
  9413. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9414. #endif
  9415. if (tls::pending(session_) > 0) {
  9416. return tls::read(session_, ptr, size, err);
  9417. } else if (wait_readable()) {
  9418. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9419. ret = tls::read(session_, ptr, size, err);
  9420. if (ret >= 0) { return ret; }
  9421. } else {
  9422. break;
  9423. }
  9424. }
  9425. assert(ret < 0);
  9426. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9427. error_ = Error::ConnectionClosed;
  9428. }
  9429. return ret;
  9430. } else {
  9431. error_ = Error::Timeout;
  9432. return -1;
  9433. }
  9434. }
  9435. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9436. if (wait_writable()) {
  9437. auto handle_size =
  9438. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9439. tls::TlsError err;
  9440. auto ret = tls::write(session_, ptr, handle_size, err);
  9441. if (ret < 0) {
  9442. auto n = 1000;
  9443. #ifdef _WIN32
  9444. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9445. (err.code == tls::ErrorCode::SyscallError &&
  9446. WSAGetLastError() == WSAETIMEDOUT))) {
  9447. #else
  9448. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9449. #endif
  9450. if (wait_writable()) {
  9451. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9452. ret = tls::write(session_, ptr, handle_size, err);
  9453. if (ret >= 0) { return ret; }
  9454. } else {
  9455. break;
  9456. }
  9457. }
  9458. assert(ret < 0);
  9459. }
  9460. return ret;
  9461. }
  9462. return -1;
  9463. }
  9464. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9465. int &port) const {
  9466. detail::get_remote_ip_and_port(sock_, ip, port);
  9467. }
  9468. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9469. int &port) const {
  9470. detail::get_local_ip_and_port(sock_, ip, port);
  9471. }
  9472. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9473. inline time_t SSLSocketStream::duration() const {
  9474. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9475. std::chrono::steady_clock::now() - start_time_)
  9476. .count();
  9477. }
  9478. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9479. read_timeout_sec_ = sec;
  9480. read_timeout_usec_ = usec;
  9481. }
  9482. } // namespace detail
  9483. #endif // CPPHTTPLIB_SSL_ENABLED
  9484. /*
  9485. * Group 4: Server implementation
  9486. */
  9487. // HTTP server implementation
  9488. inline Server::Server()
  9489. : new_task_queue([] {
  9490. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9491. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9492. }) {
  9493. #ifndef _WIN32
  9494. signal(SIGPIPE, SIG_IGN);
  9495. #endif
  9496. }
  9497. inline Server::~Server() = default;
  9498. inline std::unique_ptr<detail::MatcherBase>
  9499. Server::make_matcher(const std::string &pattern) {
  9500. if (pattern.find("/:") != std::string::npos) {
  9501. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9502. } else {
  9503. return detail::make_unique<detail::RegexMatcher>(pattern);
  9504. }
  9505. }
  9506. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9507. return add_handler(get_handlers_, pattern, std::move(handler));
  9508. }
  9509. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9510. return add_handler(post_handlers_, pattern, std::move(handler));
  9511. }
  9512. inline Server &Server::Post(const std::string &pattern,
  9513. HandlerWithContentReader handler) {
  9514. return add_handler(post_handlers_for_content_reader_, pattern,
  9515. std::move(handler));
  9516. }
  9517. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9518. return add_handler(put_handlers_, pattern, std::move(handler));
  9519. }
  9520. inline Server &Server::Put(const std::string &pattern,
  9521. HandlerWithContentReader handler) {
  9522. return add_handler(put_handlers_for_content_reader_, pattern,
  9523. std::move(handler));
  9524. }
  9525. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9526. return add_handler(patch_handlers_, pattern, std::move(handler));
  9527. }
  9528. inline Server &Server::Patch(const std::string &pattern,
  9529. HandlerWithContentReader handler) {
  9530. return add_handler(patch_handlers_for_content_reader_, pattern,
  9531. std::move(handler));
  9532. }
  9533. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9534. return add_handler(delete_handlers_, pattern, std::move(handler));
  9535. }
  9536. inline Server &Server::Delete(const std::string &pattern,
  9537. HandlerWithContentReader handler) {
  9538. return add_handler(delete_handlers_for_content_reader_, pattern,
  9539. std::move(handler));
  9540. }
  9541. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9542. return add_handler(options_handlers_, pattern, std::move(handler));
  9543. }
  9544. inline Server &Server::WebSocket(const std::string &pattern,
  9545. WebSocketHandler handler) {
  9546. websocket_handlers_.push_back(
  9547. {make_matcher(pattern), std::move(handler), nullptr});
  9548. return *this;
  9549. }
  9550. inline Server &Server::WebSocket(const std::string &pattern,
  9551. WebSocketHandler handler,
  9552. SubProtocolSelector sub_protocol_selector) {
  9553. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9554. std::move(sub_protocol_selector)});
  9555. return *this;
  9556. }
  9557. inline bool Server::set_base_dir(const std::string &dir,
  9558. const std::string &mount_point) {
  9559. return set_mount_point(mount_point, dir);
  9560. }
  9561. inline bool Server::set_mount_point(const std::string &mount_point,
  9562. const std::string &dir, Headers headers) {
  9563. detail::FileStat stat(dir);
  9564. if (stat.is_dir()) {
  9565. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9566. if (!mnt.empty() && mnt[0] == '/') {
  9567. std::string resolved_base;
  9568. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9569. #if defined(_WIN32)
  9570. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9571. resolved_base += '\\';
  9572. }
  9573. #else
  9574. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9575. #endif
  9576. }
  9577. base_dirs_.push_back(
  9578. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9579. return true;
  9580. }
  9581. }
  9582. return false;
  9583. }
  9584. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9585. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9586. if (it->mount_point == mount_point) {
  9587. base_dirs_.erase(it);
  9588. return true;
  9589. }
  9590. }
  9591. return false;
  9592. }
  9593. inline Server &
  9594. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9595. const std::string &mime) {
  9596. file_extension_and_mimetype_map_[ext] = mime;
  9597. return *this;
  9598. }
  9599. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9600. default_file_mimetype_ = mime;
  9601. return *this;
  9602. }
  9603. inline Server &Server::set_file_request_handler(Handler handler) {
  9604. file_request_handler_ = std::move(handler);
  9605. return *this;
  9606. }
  9607. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9608. std::true_type) {
  9609. error_handler_ = std::move(handler);
  9610. return *this;
  9611. }
  9612. inline Server &Server::set_error_handler_core(Handler handler,
  9613. std::false_type) {
  9614. error_handler_ = [handler](const Request &req, Response &res) {
  9615. handler(req, res);
  9616. return HandlerResponse::Handled;
  9617. };
  9618. return *this;
  9619. }
  9620. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9621. exception_handler_ = std::move(handler);
  9622. return *this;
  9623. }
  9624. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9625. pre_routing_handler_ = std::move(handler);
  9626. return *this;
  9627. }
  9628. inline Server &Server::set_post_routing_handler(Handler handler) {
  9629. post_routing_handler_ = std::move(handler);
  9630. return *this;
  9631. }
  9632. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9633. pre_request_handler_ = std::move(handler);
  9634. return *this;
  9635. }
  9636. inline Server &Server::set_logger(Logger logger) {
  9637. logger_ = std::move(logger);
  9638. return *this;
  9639. }
  9640. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9641. error_logger_ = std::move(error_logger);
  9642. return *this;
  9643. }
  9644. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9645. pre_compression_logger_ = std::move(logger);
  9646. return *this;
  9647. }
  9648. inline Server &
  9649. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9650. expect_100_continue_handler_ = std::move(handler);
  9651. return *this;
  9652. }
  9653. inline Server &Server::set_start_handler(StartHandler handler) {
  9654. start_handler_ = std::move(handler);
  9655. return *this;
  9656. }
  9657. inline Server &Server::set_address_family(int family) {
  9658. address_family_ = family;
  9659. return *this;
  9660. }
  9661. inline Server &Server::set_tcp_nodelay(bool on) {
  9662. tcp_nodelay_ = on;
  9663. return *this;
  9664. }
  9665. inline Server &Server::set_ipv6_v6only(bool on) {
  9666. ipv6_v6only_ = on;
  9667. return *this;
  9668. }
  9669. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9670. socket_options_ = std::move(socket_options);
  9671. return *this;
  9672. }
  9673. inline Server &Server::set_default_headers(Headers headers) {
  9674. default_headers_ = std::move(headers);
  9675. return *this;
  9676. }
  9677. inline Server &Server::set_header_writer(
  9678. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9679. header_writer_ = writer;
  9680. return *this;
  9681. }
  9682. inline Server &
  9683. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9684. trusted_proxies_ = proxies;
  9685. return *this;
  9686. }
  9687. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9688. keep_alive_max_count_ = count;
  9689. return *this;
  9690. }
  9691. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9692. keep_alive_timeout_sec_ = sec;
  9693. return *this;
  9694. }
  9695. template <class Rep, class Period>
  9696. inline Server &Server::set_keep_alive_timeout(
  9697. const std::chrono::duration<Rep, Period> &duration) {
  9698. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9699. set_keep_alive_timeout(sec);
  9700. });
  9701. return *this;
  9702. }
  9703. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9704. read_timeout_sec_ = sec;
  9705. read_timeout_usec_ = usec;
  9706. return *this;
  9707. }
  9708. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9709. write_timeout_sec_ = sec;
  9710. write_timeout_usec_ = usec;
  9711. return *this;
  9712. }
  9713. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9714. idle_interval_sec_ = sec;
  9715. idle_interval_usec_ = usec;
  9716. return *this;
  9717. }
  9718. inline Server &Server::set_payload_max_length(size_t length) {
  9719. payload_max_length_ = length;
  9720. return *this;
  9721. }
  9722. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9723. websocket_max_missed_pongs_ = count;
  9724. return *this;
  9725. }
  9726. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9727. websocket_ping_interval_sec_ = sec;
  9728. return *this;
  9729. }
  9730. template <class Rep, class Period>
  9731. inline Server &Server::set_websocket_ping_interval(
  9732. const std::chrono::duration<Rep, Period> &duration) {
  9733. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9734. set_websocket_ping_interval(sec);
  9735. });
  9736. return *this;
  9737. }
  9738. inline bool Server::bind_to_port(const std::string &host, int port,
  9739. int socket_flags) {
  9740. auto ret = bind_internal(host, port, socket_flags);
  9741. if (ret == -1) { is_decommissioned = true; }
  9742. return ret >= 0;
  9743. }
  9744. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9745. auto ret = bind_internal(host, 0, socket_flags);
  9746. if (ret == -1) { is_decommissioned = true; }
  9747. return ret;
  9748. }
  9749. inline bool Server::listen_after_bind() { return listen_internal(); }
  9750. inline bool Server::listen(const std::string &host, int port,
  9751. int socket_flags) {
  9752. return bind_to_port(host, port, socket_flags) && listen_internal();
  9753. }
  9754. inline bool Server::is_running() const { return is_running_; }
  9755. inline void Server::wait_until_ready() const {
  9756. while (!is_running_ && !is_decommissioned) {
  9757. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9758. }
  9759. }
  9760. inline void Server::stop() noexcept {
  9761. // Release the listening socket whether or not the accept loop is running:
  9762. // bind_to_port() without listen_after_bind() still owns the descriptor. The
  9763. // exchange is what makes this safe to call concurrently with the accept loop.
  9764. socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
  9765. if (sock != INVALID_SOCKET) {
  9766. detail::shutdown_socket(sock);
  9767. detail::close_socket(sock);
  9768. }
  9769. is_decommissioned = false;
  9770. }
  9771. inline void Server::decommission() { is_decommissioned = true; }
  9772. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9773. auto len = strlen(s);
  9774. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9775. len -= 2;
  9776. {
  9777. size_t count = 0;
  9778. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9779. switch (count) {
  9780. case 0: req.method = std::string(b, e); break;
  9781. case 1: req.target = std::string(b, e); break;
  9782. case 2: req.version = std::string(b, e); break;
  9783. default: break;
  9784. }
  9785. count++;
  9786. });
  9787. if (count != 3) { return false; }
  9788. }
  9789. thread_local const std::set<std::string> methods{
  9790. "GET", "HEAD", "POST", "PUT", "DELETE",
  9791. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9792. if (methods.find(req.method) == methods.end()) {
  9793. output_error_log(Error::InvalidHTTPMethod, &req);
  9794. return false;
  9795. }
  9796. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9797. output_error_log(Error::InvalidHTTPVersion, &req);
  9798. return false;
  9799. }
  9800. {
  9801. // Skip URL fragment
  9802. for (size_t i = 0; i < req.target.size(); i++) {
  9803. if (req.target[i] == '#') {
  9804. req.target.erase(i);
  9805. break;
  9806. }
  9807. }
  9808. detail::divide(req.target, '?',
  9809. [&](const char *lhs_data, std::size_t lhs_size,
  9810. const char *rhs_data, std::size_t rhs_size) {
  9811. req.path =
  9812. decode_path_component(std::string(lhs_data, lhs_size));
  9813. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9814. });
  9815. }
  9816. return true;
  9817. }
  9818. inline bool Server::write_response(Stream &strm, bool close_connection,
  9819. Request &req, Response &res) {
  9820. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9821. // incorrectly to the error content.
  9822. req.ranges.clear();
  9823. return write_response_core(strm, close_connection, req, res, false);
  9824. }
  9825. inline bool Server::write_response_with_content(Stream &strm,
  9826. bool close_connection,
  9827. const Request &req,
  9828. Response &res) {
  9829. return write_response_core(strm, close_connection, req, res, true);
  9830. }
  9831. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9832. const Request &req, Response &res,
  9833. bool need_apply_ranges) {
  9834. assert(res.status != -1);
  9835. if (400 <= res.status && error_handler_ &&
  9836. error_handler_(req, res) == HandlerResponse::Handled) {
  9837. need_apply_ranges = true;
  9838. }
  9839. std::string content_type;
  9840. std::string boundary;
  9841. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9842. // Prepare additional headers
  9843. if (close_connection || req.get_header_value("Connection") == "close" ||
  9844. 400 <= res.status) { // Don't leave connections open after errors
  9845. res.set_header("Connection", "close");
  9846. } else {
  9847. std::string s = "timeout=";
  9848. s += std::to_string(keep_alive_timeout_sec_);
  9849. s += ", max=";
  9850. s += std::to_string(keep_alive_max_count_);
  9851. res.set_header("Keep-Alive", s);
  9852. }
  9853. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9854. !res.has_header("Content-Type")) {
  9855. res.set_header("Content-Type", "text/plain");
  9856. }
  9857. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9858. !res.has_header("Content-Length")) {
  9859. res.set_header("Content-Length", "0");
  9860. }
  9861. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9862. res.set_header("Accept-Ranges", "bytes");
  9863. }
  9864. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9865. // Response line and headers
  9866. detail::BufferStream bstrm;
  9867. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9868. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9869. // Combine small body with headers to reduce write syscalls
  9870. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9871. bstrm.write(res.body.data(), res.body.size());
  9872. }
  9873. // Log before writing to avoid race condition with client-side code that
  9874. // accesses logger-captured data immediately after receiving the response.
  9875. output_log(req, res);
  9876. // Flush buffer
  9877. auto &data = bstrm.get_buffer();
  9878. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9879. // Streaming body
  9880. auto ret = true;
  9881. if (req.method != "HEAD" && res.content_provider_) {
  9882. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9883. res.content_provider_success_ = true;
  9884. } else {
  9885. ret = false;
  9886. }
  9887. }
  9888. return ret;
  9889. }
  9890. inline bool
  9891. Server::write_content_with_provider(Stream &strm, const Request &req,
  9892. Response &res, const std::string &boundary,
  9893. const std::string &content_type) {
  9894. auto is_shutting_down = [this]() {
  9895. return this->svr_sock_ == INVALID_SOCKET;
  9896. };
  9897. if (res.content_length_ > 0) {
  9898. if (req.ranges.empty()) {
  9899. return detail::write_content(strm, res.content_provider_, 0,
  9900. res.content_length_, is_shutting_down);
  9901. } else if (req.ranges.size() == 1) {
  9902. auto offset_and_length = detail::get_range_offset_and_length(
  9903. req.ranges[0], res.content_length_);
  9904. return detail::write_content(strm, res.content_provider_,
  9905. offset_and_length.first,
  9906. offset_and_length.second, is_shutting_down);
  9907. } else {
  9908. return detail::write_multipart_ranges_data(
  9909. strm, req, res, boundary, content_type, res.content_length_,
  9910. is_shutting_down);
  9911. }
  9912. } else {
  9913. if (res.is_chunked_content_provider_) {
  9914. auto type = detail::encoding_type(req, res);
  9915. auto compressor = detail::make_compressor(type);
  9916. if (!compressor) {
  9917. compressor = detail::make_unique<detail::nocompressor>();
  9918. }
  9919. return detail::write_content_chunked(strm, res.content_provider_,
  9920. is_shutting_down, *compressor);
  9921. } else {
  9922. return detail::write_content_without_length(strm, res.content_provider_,
  9923. is_shutting_down);
  9924. }
  9925. }
  9926. }
  9927. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9928. FormFields::iterator cur_field;
  9929. FormFiles::iterator cur_file;
  9930. auto is_text_field = false;
  9931. size_t count = 0;
  9932. if (read_content_core(
  9933. strm, req, res,
  9934. // Regular
  9935. [&](const char *buf, size_t n) {
  9936. // Prevent arithmetic overflow when checking sizes.
  9937. // Avoid computing (req.body.size() + n) directly because
  9938. // adding two unsigned `size_t` values can wrap around and
  9939. // produce a small result instead of indicating overflow.
  9940. // Instead, check using subtraction: ensure `n` does not
  9941. // exceed the remaining capacity `max_size() - size()`.
  9942. if (req.body.size() >= req.body.max_size() ||
  9943. n > req.body.max_size() - req.body.size()) {
  9944. return false;
  9945. }
  9946. // Limit decompressed body size to payload_max_length_ to protect
  9947. // against "zip bomb" attacks where a small compressed payload
  9948. // decompresses to a massive size.
  9949. if (payload_max_length_ > 0 &&
  9950. (req.body.size() >= payload_max_length_ ||
  9951. n > payload_max_length_ - req.body.size())) {
  9952. return false;
  9953. }
  9954. req.body.append(buf, n);
  9955. return true;
  9956. },
  9957. // Multipart FormData
  9958. [&](const FormData &file) {
  9959. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9960. output_error_log(Error::TooManyFormDataFiles, &req);
  9961. return false;
  9962. }
  9963. if (file.filename.empty()) {
  9964. cur_field = req.form.fields.emplace(
  9965. file.name, FormField{file.name, file.content, file.headers});
  9966. is_text_field = true;
  9967. } else {
  9968. cur_file = req.form.files.emplace(file.name, file);
  9969. is_text_field = false;
  9970. }
  9971. return true;
  9972. },
  9973. [&](const char *buf, size_t n) {
  9974. if (is_text_field) {
  9975. auto &content = cur_field->second.content;
  9976. if (content.size() + n > content.max_size()) { return false; }
  9977. content.append(buf, n);
  9978. } else {
  9979. auto &content = cur_file->second.content;
  9980. if (content.size() + n > content.max_size()) { return false; }
  9981. content.append(buf, n);
  9982. }
  9983. return true;
  9984. })) {
  9985. const auto &content_type = req.get_header_value("Content-Type");
  9986. if (detail::extract_media_type(content_type) ==
  9987. "application/x-www-form-urlencoded") {
  9988. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9989. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9990. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9991. return false;
  9992. }
  9993. detail::parse_query_text(req.body, req.params);
  9994. }
  9995. return true;
  9996. }
  9997. return false;
  9998. }
  9999. inline bool Server::read_content_with_content_receiver(
  10000. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  10001. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  10002. return read_content_core(strm, req, res, std::move(receiver),
  10003. std::move(multipart_header),
  10004. std::move(multipart_receiver));
  10005. }
  10006. inline bool Server::read_content_core(
  10007. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  10008. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  10009. detail::FormDataParser multipart_form_data_parser;
  10010. ContentReceiverWithProgress out;
  10011. if (req.is_multipart_form_data()) {
  10012. const auto &content_type = req.get_header_value("Content-Type");
  10013. std::string boundary;
  10014. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  10015. res.status = StatusCode::BadRequest_400;
  10016. output_error_log(Error::MultipartParsing, &req);
  10017. return false;
  10018. }
  10019. multipart_form_data_parser.set_boundary(std::move(boundary));
  10020. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  10021. return multipart_form_data_parser.parse(buf, n, multipart_header,
  10022. multipart_receiver);
  10023. };
  10024. } else {
  10025. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  10026. size_t /*len*/) { return receiver(buf, n); };
  10027. }
  10028. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  10029. // For non-SSL builds we still scan non-persistent connections for stray
  10030. // body bytes so the payload limit is enforced (413). On keep-alive,
  10031. // pending bytes may be the next request (issue #2450), so skip.
  10032. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  10033. if (!req.has_header("Content-Length") &&
  10034. !detail::is_chunked_transfer_encoding(req.headers)) {
  10035. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  10036. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  10037. auto has_data = strm.is_readable();
  10038. if (!has_data) {
  10039. auto s = strm.socket();
  10040. if (s != INVALID_SOCKET) {
  10041. has_data = detail::select_read(s, 0, 0) > 0;
  10042. }
  10043. }
  10044. if (has_data) {
  10045. auto result =
  10046. detail::read_content_without_length(strm, payload_max_length_, out);
  10047. if (result == detail::ReadContentResult::PayloadTooLarge) {
  10048. res.status = StatusCode::PayloadTooLarge_413;
  10049. return false;
  10050. } else if (result != detail::ReadContentResult::Success) {
  10051. return false;
  10052. }
  10053. return true;
  10054. }
  10055. }
  10056. return true;
  10057. }
  10058. #else
  10059. if (!req.has_header("Content-Length") &&
  10060. !detail::is_chunked_transfer_encoding(req.headers)) {
  10061. return true;
  10062. }
  10063. #endif
  10064. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  10065. out, true)) {
  10066. return false;
  10067. }
  10068. req.body_consumed_ = true;
  10069. if (req.is_multipart_form_data()) {
  10070. if (!multipart_form_data_parser.is_valid()) {
  10071. res.status = StatusCode::BadRequest_400;
  10072. output_error_log(Error::MultipartParsing, &req);
  10073. return false;
  10074. }
  10075. }
  10076. return true;
  10077. }
  10078. inline bool Server::handle_file_request(Request &req, Response &res) {
  10079. for (const auto &entry : base_dirs_) {
  10080. // Prefix match
  10081. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  10082. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  10083. if (detail::is_valid_path(sub_path)) {
  10084. auto path = entry.base_dir + sub_path;
  10085. if (path.back() == '/') { path += "index.html"; }
  10086. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  10087. // but symlinks/junctions can still escape the base directory.
  10088. if (!entry.resolved_base_dir.empty()) {
  10089. std::string resolved_path;
  10090. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  10091. !detail::is_path_within_base(resolved_path,
  10092. entry.resolved_base_dir)) {
  10093. res.status = StatusCode::Forbidden_403;
  10094. return true;
  10095. }
  10096. }
  10097. detail::FileStat stat(path);
  10098. if (stat.is_dir()) {
  10099. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  10100. return true;
  10101. }
  10102. if (stat.is_file()) {
  10103. for (const auto &kv : entry.headers) {
  10104. res.set_header(kv.first, kv.second);
  10105. }
  10106. auto etag = detail::compute_etag(stat);
  10107. if (!etag.empty()) { res.set_header("ETag", etag); }
  10108. auto mtime = stat.mtime();
  10109. auto last_modified = detail::file_mtime_to_http_date(mtime);
  10110. if (!last_modified.empty()) {
  10111. res.set_header("Last-Modified", last_modified);
  10112. }
  10113. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  10114. check_if_range(req, etag, mtime);
  10115. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10116. if (!mm->is_open()) {
  10117. output_error_log(Error::OpenFile, &req);
  10118. return false;
  10119. }
  10120. res.set_content_provider(
  10121. mm->size(),
  10122. detail::find_content_type(path, file_extension_and_mimetype_map_,
  10123. default_file_mimetype_),
  10124. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10125. sink.write(mm->data() + offset, length);
  10126. return true;
  10127. });
  10128. if (req.method != "HEAD" && file_request_handler_) {
  10129. file_request_handler_(req, res);
  10130. }
  10131. return true;
  10132. } else {
  10133. output_error_log(Error::OpenFile, &req);
  10134. }
  10135. }
  10136. }
  10137. }
  10138. return false;
  10139. }
  10140. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  10141. const std::string &etag,
  10142. time_t mtime) const {
  10143. // Handle conditional GET:
  10144. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  10145. // 2. If-Modified-Since is checked only when If-None-Match is absent
  10146. if (req.has_header("If-None-Match")) {
  10147. if (!etag.empty()) {
  10148. auto val = req.get_header_value("If-None-Match");
  10149. // NOTE: We use exact string matching here. This works correctly
  10150. // because our server always generates weak ETags (W/"..."), and
  10151. // clients typically send back the same ETag they received.
  10152. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  10153. // If-None-Match, where W/"x" and "x" would match, but this
  10154. // simplified implementation requires exact matches.
  10155. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  10156. [&](const char *b, const char *e) {
  10157. auto seg_len = static_cast<size_t>(e - b);
  10158. return (seg_len == 1 && *b == '*') ||
  10159. (seg_len == etag.size() &&
  10160. std::equal(b, e, etag.begin()));
  10161. });
  10162. if (ret) {
  10163. res.status = StatusCode::NotModified_304;
  10164. return true;
  10165. }
  10166. }
  10167. } else if (req.has_header("If-Modified-Since")) {
  10168. auto val = req.get_header_value("If-Modified-Since");
  10169. auto t = detail::parse_http_date(val);
  10170. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10171. res.status = StatusCode::NotModified_304;
  10172. return true;
  10173. }
  10174. }
  10175. return false;
  10176. }
  10177. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10178. time_t mtime) const {
  10179. // Handle If-Range for partial content requests (RFC 9110
  10180. // Section 13.1.5). If-Range is only evaluated when Range header is
  10181. // present. If the validator matches, serve partial content; otherwise
  10182. // serve full content.
  10183. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10184. auto val = req.get_header_value("If-Range");
  10185. auto is_valid_range = [&]() {
  10186. if (detail::is_strong_etag(val)) {
  10187. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10188. // comparison.
  10189. return (!etag.empty() && val == etag);
  10190. } else if (detail::is_weak_etag(val)) {
  10191. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10192. return false;
  10193. } else {
  10194. // HTTP-date comparison
  10195. auto t = detail::parse_http_date(val);
  10196. return (t != static_cast<time_t>(-1) && mtime <= t);
  10197. }
  10198. };
  10199. if (!is_valid_range()) {
  10200. // Validator doesn't match: ignore Range and serve full content
  10201. req.ranges.clear();
  10202. return false;
  10203. }
  10204. }
  10205. return true;
  10206. }
  10207. inline socket_t
  10208. Server::create_server_socket(const std::string &host, int port,
  10209. int socket_flags,
  10210. SocketOptions socket_options) const {
  10211. return detail::create_socket(
  10212. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10213. ipv6_v6only_, std::move(socket_options),
  10214. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10215. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10216. output_error_log(Error::BindIPAddress, nullptr);
  10217. return false;
  10218. }
  10219. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10220. output_error_log(Error::Listen, nullptr);
  10221. return false;
  10222. }
  10223. return true;
  10224. });
  10225. }
  10226. inline int Server::bind_internal(const std::string &host, int port,
  10227. int socket_flags) {
  10228. if (is_decommissioned) { return -1; }
  10229. if (!is_valid()) { return -1; }
  10230. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10231. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10232. if (port == 0) {
  10233. struct sockaddr_storage addr;
  10234. socklen_t addr_len = sizeof(addr);
  10235. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10236. &addr_len) == -1) {
  10237. output_error_log(Error::GetSockName, nullptr);
  10238. return -1;
  10239. }
  10240. if (addr.ss_family == AF_INET) {
  10241. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10242. } else if (addr.ss_family == AF_INET6) {
  10243. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10244. } else {
  10245. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10246. return -1;
  10247. }
  10248. } else {
  10249. return port;
  10250. }
  10251. }
  10252. inline bool Server::listen_internal() {
  10253. // A stop() between bind and listen leaves nothing to accept on. Report
  10254. // failure instead of returning success without ever serving, and mark the
  10255. // server decommissioned the way any failed listen does so that a concurrent
  10256. // wait_until_ready() wakes up instead of spinning forever.
  10257. if (is_decommissioned || svr_sock_ == INVALID_SOCKET) {
  10258. is_decommissioned = true;
  10259. return false;
  10260. }
  10261. auto ret = true;
  10262. is_running_ = true;
  10263. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10264. if (start_handler_) { start_handler_(); }
  10265. {
  10266. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10267. while (svr_sock_ != INVALID_SOCKET) {
  10268. #ifndef _WIN32
  10269. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10270. #endif
  10271. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10272. idle_interval_usec_);
  10273. if (val == 0) { // Timeout
  10274. task_queue->on_idle();
  10275. continue;
  10276. }
  10277. #ifndef _WIN32
  10278. }
  10279. #endif
  10280. #if defined _WIN32
  10281. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10282. // OVERLAPPED
  10283. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10284. #elif defined SOCK_CLOEXEC
  10285. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10286. #else
  10287. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10288. #endif
  10289. if (sock == INVALID_SOCKET) {
  10290. if (errno == EMFILE) {
  10291. // The per-process limit of open file descriptors has been reached.
  10292. // Try to accept new connections after a short sleep.
  10293. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10294. continue;
  10295. } else if (errno == EINTR || errno == EAGAIN) {
  10296. continue;
  10297. }
  10298. if (svr_sock_ != INVALID_SOCKET) {
  10299. detail::close_socket(svr_sock_);
  10300. ret = false;
  10301. output_error_log(Error::Connection, nullptr);
  10302. } else {
  10303. ; // The server socket was closed by user.
  10304. }
  10305. break;
  10306. }
  10307. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10308. read_timeout_sec_, read_timeout_usec_);
  10309. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10310. write_timeout_sec_, write_timeout_usec_);
  10311. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10312. if (!task_queue->enqueue(
  10313. [this, sock]() { process_and_close_socket(sock); })) {
  10314. output_error_log(Error::ResourceExhaustion, nullptr);
  10315. detail::shutdown_socket(sock);
  10316. detail::close_socket(sock);
  10317. }
  10318. }
  10319. task_queue->shutdown();
  10320. }
  10321. is_decommissioned = !ret;
  10322. return ret;
  10323. }
  10324. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10325. if (pre_routing_handler_ &&
  10326. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10327. return true;
  10328. }
  10329. // File handler
  10330. if ((req.method == "GET" || req.method == "HEAD") &&
  10331. handle_file_request(req, res)) {
  10332. return true;
  10333. }
  10334. if (detail::expect_content(req)) {
  10335. // Content reader handler
  10336. {
  10337. // Track whether the ContentReader was aborted due to the decompressed
  10338. // payload exceeding `payload_max_length_`.
  10339. // The user handler runs after the lambda returns, so we must restore the
  10340. // 413 status if the handler overwrites it.
  10341. bool content_reader_payload_too_large = false;
  10342. ContentReader reader(
  10343. [&](ContentReceiver receiver) {
  10344. auto result = read_content_with_content_receiver(
  10345. strm, req, res, std::move(receiver), nullptr, nullptr);
  10346. if (!result) {
  10347. output_error_log(Error::Read, &req);
  10348. if (res.status == StatusCode::PayloadTooLarge_413) {
  10349. content_reader_payload_too_large = true;
  10350. }
  10351. }
  10352. return result;
  10353. },
  10354. [&](FormDataHeader header, ContentReceiver receiver) {
  10355. auto result = read_content_with_content_receiver(
  10356. strm, req, res, nullptr, std::move(header),
  10357. std::move(receiver));
  10358. if (!result) {
  10359. output_error_log(Error::Read, &req);
  10360. if (res.status == StatusCode::PayloadTooLarge_413) {
  10361. content_reader_payload_too_large = true;
  10362. }
  10363. }
  10364. return result;
  10365. });
  10366. bool dispatched = false;
  10367. if (req.method == "POST") {
  10368. dispatched = dispatch_request_for_content_reader(
  10369. req, res, std::move(reader), post_handlers_for_content_reader_);
  10370. } else if (req.method == "PUT") {
  10371. dispatched = dispatch_request_for_content_reader(
  10372. req, res, std::move(reader), put_handlers_for_content_reader_);
  10373. } else if (req.method == "PATCH") {
  10374. dispatched = dispatch_request_for_content_reader(
  10375. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10376. } else if (req.method == "DELETE") {
  10377. dispatched = dispatch_request_for_content_reader(
  10378. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10379. }
  10380. if (dispatched) {
  10381. if (content_reader_payload_too_large) {
  10382. // Enforce the limit: override any status the handler may have set
  10383. // and return false so the error path sends a plain 413 response.
  10384. res.status = StatusCode::PayloadTooLarge_413;
  10385. res.body.clear();
  10386. res.content_length_ = 0;
  10387. res.content_provider_ = nullptr;
  10388. return false;
  10389. }
  10390. return true;
  10391. }
  10392. }
  10393. // NOTE: `req.body` is not read here. For a regular handler the body is
  10394. // read inside dispatch_request(), after the route has matched and the
  10395. // pre-request handler has approved the request, so that a rejected
  10396. // request (e.g. failed authentication) never forces us to buffer a
  10397. // potentially large body.
  10398. }
  10399. // Regular handler
  10400. if (req.method == "GET" || req.method == "HEAD") {
  10401. return dispatch_request(req, res, get_handlers_, strm);
  10402. } else if (req.method == "POST") {
  10403. return dispatch_request(req, res, post_handlers_, strm);
  10404. } else if (req.method == "PUT") {
  10405. return dispatch_request(req, res, put_handlers_, strm);
  10406. } else if (req.method == "DELETE") {
  10407. return dispatch_request(req, res, delete_handlers_, strm);
  10408. } else if (req.method == "OPTIONS") {
  10409. return dispatch_request(req, res, options_handlers_, strm);
  10410. } else if (req.method == "PATCH") {
  10411. return dispatch_request(req, res, patch_handlers_, strm);
  10412. }
  10413. res.status = StatusCode::BadRequest_400;
  10414. return false;
  10415. }
  10416. inline bool Server::dispatch_request(Request &req, Response &res,
  10417. const Handlers &handlers, Stream &strm) {
  10418. for (const auto &x : handlers) {
  10419. const auto &matcher = x.first;
  10420. const auto &handler = x.second;
  10421. if (matcher->match(req)) {
  10422. req.matched_route = matcher->pattern();
  10423. // Run the pre-request handler before reading the body so a rejected
  10424. // request (e.g. failed authentication) never forces us to buffer a
  10425. // potentially large body. `req.matched_route` is available here.
  10426. if (pre_request_handler_ &&
  10427. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10428. return true;
  10429. }
  10430. // The route matched and the request was approved; read the body now.
  10431. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10432. output_error_log(Error::Read, &req);
  10433. return false;
  10434. }
  10435. handler(req, res);
  10436. return true;
  10437. }
  10438. }
  10439. return false;
  10440. }
  10441. inline void Server::apply_ranges(const Request &req, Response &res,
  10442. std::string &content_type,
  10443. std::string &boundary) const {
  10444. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10445. auto it = res.headers.find("Content-Type");
  10446. if (it != res.headers.end()) {
  10447. content_type = it->second;
  10448. res.headers.erase(it);
  10449. }
  10450. boundary = detail::make_multipart_data_boundary();
  10451. res.set_header("Content-Type",
  10452. "multipart/byteranges; boundary=" + boundary);
  10453. }
  10454. auto type = detail::encoding_type(req, res);
  10455. if (res.body.empty()) {
  10456. if (res.content_length_ > 0) {
  10457. size_t length = 0;
  10458. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10459. length = res.content_length_;
  10460. } else if (req.ranges.size() == 1) {
  10461. auto offset_and_length = detail::get_range_offset_and_length(
  10462. req.ranges[0], res.content_length_);
  10463. length = offset_and_length.second;
  10464. auto content_range = detail::make_content_range_header_field(
  10465. offset_and_length, res.content_length_);
  10466. res.set_header("Content-Range", content_range);
  10467. } else {
  10468. length = detail::get_multipart_ranges_data_length(
  10469. req, boundary, content_type, res.content_length_);
  10470. }
  10471. res.set_header("Content-Length", std::to_string(length));
  10472. } else {
  10473. if (res.content_provider_) {
  10474. if (res.is_chunked_content_provider_) {
  10475. res.set_header("Transfer-Encoding", "chunked");
  10476. if (type != detail::EncodingType::None) {
  10477. res.set_header("Content-Encoding", detail::encoding_name(type));
  10478. res.set_header("Vary", "Accept-Encoding");
  10479. }
  10480. }
  10481. }
  10482. }
  10483. } else {
  10484. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10485. ;
  10486. } else if (req.ranges.size() == 1) {
  10487. auto offset_and_length =
  10488. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10489. auto offset = offset_and_length.first;
  10490. auto length = offset_and_length.second;
  10491. auto content_range = detail::make_content_range_header_field(
  10492. offset_and_length, res.body.size());
  10493. res.set_header("Content-Range", content_range);
  10494. assert(offset + length <= res.body.size());
  10495. res.body = res.body.substr(offset, length);
  10496. } else {
  10497. std::string data;
  10498. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10499. res.body.size(), data);
  10500. res.body.swap(data);
  10501. }
  10502. if (type != detail::EncodingType::None) {
  10503. output_pre_compression_log(req, res);
  10504. if (auto compressor = detail::make_compressor(type)) {
  10505. std::string compressed;
  10506. if (compressor->compress(res.body.data(), res.body.size(), true,
  10507. [&](const char *data, size_t data_len) {
  10508. compressed.append(data, data_len);
  10509. return true;
  10510. })) {
  10511. res.body.swap(compressed);
  10512. res.set_header("Content-Encoding", detail::encoding_name(type));
  10513. res.set_header("Vary", "Accept-Encoding");
  10514. }
  10515. }
  10516. }
  10517. res.content_length_ = res.body.size();
  10518. res.set_header("Content-Length", std::to_string(res.content_length_));
  10519. }
  10520. }
  10521. inline bool Server::dispatch_request_for_content_reader(
  10522. Request &req, Response &res, ContentReader content_reader,
  10523. const HandlersForContentReader &handlers) const {
  10524. for (const auto &x : handlers) {
  10525. const auto &matcher = x.first;
  10526. const auto &handler = x.second;
  10527. if (matcher->match(req)) {
  10528. req.matched_route = matcher->pattern();
  10529. if (!pre_request_handler_ ||
  10530. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10531. handler(req, res, content_reader);
  10532. }
  10533. return true;
  10534. }
  10535. }
  10536. return false;
  10537. }
  10538. inline std::string
  10539. get_client_ip(const std::string &x_forwarded_for,
  10540. const std::vector<std::string> &trusted_proxies) {
  10541. // X-Forwarded-For is a comma-separated list per RFC 7239
  10542. std::vector<std::string> ip_list;
  10543. detail::split(x_forwarded_for.data(),
  10544. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10545. [&](const char *b, const char *e) {
  10546. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10547. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10548. });
  10549. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10550. // no segments. Signal "no client IP derived" with an empty string so the
  10551. // caller can fall back to the connection-level remote address.
  10552. if (ip_list.empty()) { return std::string(); }
  10553. // Each hop appends the address it received the request from, so the rightmost
  10554. // entries are the ones written by our own infrastructure while the leftmost
  10555. // are whatever the original client chose to send. Walk from the right and
  10556. // skip trusted proxies; the first address that is not a trusted proxy is the
  10557. // furthest point still attributable to a real hop, i.e. the client. Scanning
  10558. // from the left instead lets a client forge an arbitrary address by following
  10559. // it with a trusted proxy's address, which the left-to-right scan then
  10560. // returned as the client.
  10561. for (size_t i = ip_list.size(); i-- > 0;) {
  10562. const auto &ip = ip_list[i];
  10563. auto is_trusted_proxy =
  10564. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10565. [&](const std::string &proxy) { return ip == proxy; });
  10566. if (!is_trusted_proxy) { return ip; }
  10567. }
  10568. // Every hop was a trusted proxy; fall back to the first entry.
  10569. return ip_list.front();
  10570. }
  10571. inline bool
  10572. Server::process_request(Stream &strm, const std::string &remote_addr,
  10573. int remote_port, const std::string &local_addr,
  10574. int local_port, bool close_connection,
  10575. bool &connection_closed,
  10576. const std::function<void(Request &)> &setup_request,
  10577. bool *websocket_upgraded) {
  10578. std::array<char, 2048> buf{};
  10579. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10580. // Connection has been closed on client
  10581. if (!line_reader.getline()) { return false; }
  10582. Request req;
  10583. req.start_time_ = std::chrono::steady_clock::now();
  10584. req.remote_addr = remote_addr;
  10585. req.remote_port = remote_port;
  10586. req.local_addr = local_addr;
  10587. req.local_port = local_port;
  10588. Response res;
  10589. res.version = "HTTP/1.1";
  10590. res.headers = default_headers_;
  10591. // Request line and headers
  10592. if (!parse_request_line(line_reader.ptr(), req)) {
  10593. res.status = StatusCode::BadRequest_400;
  10594. output_error_log(Error::InvalidRequestLine, &req);
  10595. return write_response(strm, close_connection, req, res);
  10596. }
  10597. // Request headers
  10598. if (!detail::read_headers(strm, req.headers)) {
  10599. res.status = StatusCode::BadRequest_400;
  10600. output_error_log(Error::InvalidHeaders, &req);
  10601. return write_response(strm, close_connection, req, res);
  10602. }
  10603. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10604. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10605. // tolerated for compatibility with existing clients.
  10606. if (req.get_header_value_u64("Content-Length") > 0 &&
  10607. req.has_header("Transfer-Encoding")) {
  10608. connection_closed = true;
  10609. res.status = StatusCode::BadRequest_400;
  10610. return write_response(strm, close_connection, req, res);
  10611. }
  10612. // Check if the request URI doesn't exceed the limit
  10613. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10614. connection_closed = true;
  10615. res.status = StatusCode::UriTooLong_414;
  10616. output_error_log(Error::ExceedUriMaxLength, &req);
  10617. return write_response(strm, close_connection, req, res);
  10618. }
  10619. if (req.get_header_value("Connection") == "close") {
  10620. connection_closed = true;
  10621. }
  10622. if (req.version == "HTTP/1.0" &&
  10623. req.get_header_value("Connection") != "Keep-Alive") {
  10624. connection_closed = true;
  10625. }
  10626. // Only honor X-Forwarded-For if the peer on the actual TCP connection is
  10627. // itself a trusted proxy. Otherwise any direct client could spoof
  10628. // remote_addr simply by sending an arbitrary X-Forwarded-For header.
  10629. auto is_trusted_peer = std::any_of(
  10630. trusted_proxies_.begin(), trusted_proxies_.end(),
  10631. [&](const std::string &proxy) { return proxy == remote_addr; });
  10632. if (is_trusted_peer && req.has_header("X-Forwarded-For")) {
  10633. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10634. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10635. req.remote_addr = derived.empty() ? remote_addr : derived;
  10636. } else {
  10637. req.remote_addr = remote_addr;
  10638. }
  10639. req.remote_port = remote_port;
  10640. req.local_addr = local_addr;
  10641. req.local_port = local_port;
  10642. if (req.has_header("Accept")) {
  10643. const auto &accept_header = req.get_header_value("Accept");
  10644. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10645. connection_closed = true;
  10646. res.status = StatusCode::BadRequest_400;
  10647. output_error_log(Error::HTTPParsing, &req);
  10648. return write_response(strm, close_connection, req, res);
  10649. }
  10650. }
  10651. if (req.has_header("Range")) {
  10652. const auto &range_header_value = req.get_header_value("Range");
  10653. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10654. connection_closed = true;
  10655. res.status = StatusCode::RangeNotSatisfiable_416;
  10656. output_error_log(Error::InvalidRangeHeader, &req);
  10657. return write_response(strm, close_connection, req, res);
  10658. }
  10659. }
  10660. if (setup_request) { setup_request(req); }
  10661. if (req.get_header_value("Expect") == "100-continue") {
  10662. int status = StatusCode::Continue_100;
  10663. if (expect_100_continue_handler_) {
  10664. status = expect_100_continue_handler_(req, res);
  10665. }
  10666. switch (status) {
  10667. case StatusCode::Continue_100:
  10668. case StatusCode::ExpectationFailed_417:
  10669. detail::write_response_line(strm, status);
  10670. strm.write("\r\n");
  10671. break;
  10672. default:
  10673. connection_closed = true;
  10674. return write_response(strm, true, req, res);
  10675. }
  10676. }
  10677. // Setup `is_connection_closed` method
  10678. auto sock = strm.socket();
  10679. req.is_connection_closed = [sock]() {
  10680. return !detail::is_socket_alive(sock);
  10681. };
  10682. // WebSocket upgrade
  10683. // Check pre_routing_handler_ before upgrading so that authentication
  10684. // and other middleware can reject the request with an HTTP response
  10685. // (e.g., 401) before the protocol switches.
  10686. if (detail::is_websocket_upgrade(req)) {
  10687. if (pre_routing_handler_ &&
  10688. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10689. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10690. return write_response(strm, close_connection, req, res);
  10691. }
  10692. // Find matching WebSocket handler
  10693. for (const auto &entry : websocket_handlers_) {
  10694. if (entry.matcher->match(req)) {
  10695. // Compute accept key
  10696. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10697. auto accept_key = detail::websocket_accept_key(client_key);
  10698. // Negotiate subprotocol
  10699. std::string selected_subprotocol;
  10700. if (entry.sub_protocol_selector) {
  10701. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10702. if (!protocol_header.empty()) {
  10703. std::vector<std::string> protocols;
  10704. std::istringstream iss(protocol_header);
  10705. std::string token;
  10706. while (std::getline(iss, token, ',')) {
  10707. // Trim whitespace
  10708. auto start = token.find_first_not_of(' ');
  10709. auto end = token.find_last_not_of(' ');
  10710. if (start != std::string::npos) {
  10711. protocols.push_back(token.substr(start, end - start + 1));
  10712. }
  10713. }
  10714. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10715. }
  10716. }
  10717. // Send 101 Switching Protocols
  10718. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10719. "Upgrade: websocket\r\n"
  10720. "Connection: Upgrade\r\n"
  10721. "Sec-WebSocket-Accept: " +
  10722. accept_key + "\r\n";
  10723. if (!selected_subprotocol.empty()) {
  10724. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10725. return false;
  10726. }
  10727. handshake_response +=
  10728. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10729. }
  10730. handshake_response += "\r\n";
  10731. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10732. 0) {
  10733. return false;
  10734. }
  10735. connection_closed = true;
  10736. if (websocket_upgraded) { *websocket_upgraded = true; }
  10737. {
  10738. // Use WebSocket-specific read timeout instead of HTTP timeout
  10739. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10740. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10741. websocket_max_missed_pongs_);
  10742. entry.handler(req, ws);
  10743. }
  10744. return true;
  10745. }
  10746. }
  10747. // No matching handler - fall through to 404
  10748. }
  10749. // Routing
  10750. auto routed = false;
  10751. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10752. routed = routing(req, res, strm);
  10753. #else
  10754. try {
  10755. routed = routing(req, res, strm);
  10756. } catch (std::exception &) {
  10757. if (exception_handler_) {
  10758. auto ep = std::current_exception();
  10759. exception_handler_(req, res, ep);
  10760. routed = true;
  10761. } else {
  10762. res.status = StatusCode::InternalServerError_500;
  10763. }
  10764. } catch (...) {
  10765. if (exception_handler_) {
  10766. auto ep = std::current_exception();
  10767. exception_handler_(req, res, ep);
  10768. routed = true;
  10769. } else {
  10770. res.status = StatusCode::InternalServerError_500;
  10771. }
  10772. }
  10773. #endif
  10774. auto ret = false;
  10775. if (routed) {
  10776. if (res.status == -1) {
  10777. res.status = req.ranges.empty() ? StatusCode::OK_200
  10778. : StatusCode::PartialContent_206;
  10779. }
  10780. // Serve file content by using a content provider
  10781. auto file_open_error = false;
  10782. if (!res.file_content_path_.empty()) {
  10783. const auto &path = res.file_content_path_;
  10784. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10785. if (!mm->is_open()) {
  10786. res.body.clear();
  10787. res.content_length_ = 0;
  10788. res.content_provider_ = nullptr;
  10789. res.status = StatusCode::NotFound_404;
  10790. output_error_log(Error::OpenFile, &req);
  10791. file_open_error = true;
  10792. } else {
  10793. auto content_type = res.file_content_content_type_;
  10794. if (content_type.empty()) {
  10795. content_type = detail::find_content_type(
  10796. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10797. }
  10798. res.set_content_provider(
  10799. mm->size(), content_type,
  10800. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10801. sink.write(mm->data() + offset, length);
  10802. return true;
  10803. });
  10804. }
  10805. }
  10806. if (file_open_error) {
  10807. ret = write_response(strm, close_connection, req, res);
  10808. } else if (detail::range_error(req, res)) {
  10809. res.body.clear();
  10810. res.content_length_ = 0;
  10811. res.content_provider_ = nullptr;
  10812. res.status = StatusCode::RangeNotSatisfiable_416;
  10813. ret = write_response(strm, close_connection, req, res);
  10814. } else {
  10815. ret = write_response_with_content(strm, close_connection, req, res);
  10816. }
  10817. } else {
  10818. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10819. ret = write_response(strm, close_connection, req, res);
  10820. }
  10821. // Drain any unconsumed framed body to prevent request smuggling on
  10822. // keep-alive. Without framing there is no body to drain — reading would
  10823. // consume the next request (issue #2450). If the response has committed the
  10824. // connection to close, there is no next request to protect.
  10825. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10826. if (res.get_header_value("Connection") == "close") {
  10827. connection_closed = true;
  10828. } else {
  10829. int dummy_status;
  10830. if (!detail::read_content(
  10831. strm, req, payload_max_length_, dummy_status, nullptr,
  10832. [](const char *, size_t, size_t, size_t) { return true; },
  10833. false)) {
  10834. connection_closed = true;
  10835. }
  10836. }
  10837. }
  10838. return ret;
  10839. }
  10840. inline bool Server::is_valid() const { return true; }
  10841. inline bool Server::process_and_close_socket(socket_t sock) {
  10842. std::string remote_addr;
  10843. int remote_port = 0;
  10844. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10845. std::string local_addr;
  10846. int local_port = 0;
  10847. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10848. bool websocket_upgraded = false;
  10849. auto ret = detail::process_server_socket(
  10850. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10851. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10852. write_timeout_usec_,
  10853. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10854. return process_request(strm, remote_addr, remote_port, local_addr,
  10855. local_port, close_connection, connection_closed,
  10856. nullptr, &websocket_upgraded);
  10857. });
  10858. detail::shutdown_socket(sock);
  10859. detail::close_socket(sock);
  10860. return ret;
  10861. }
  10862. inline void Server::output_log(const Request &req, const Response &res) const {
  10863. if (logger_) {
  10864. std::lock_guard<std::mutex> guard(logger_mutex_);
  10865. logger_(req, res);
  10866. }
  10867. }
  10868. inline void Server::output_pre_compression_log(const Request &req,
  10869. const Response &res) const {
  10870. if (pre_compression_logger_) {
  10871. std::lock_guard<std::mutex> guard(logger_mutex_);
  10872. pre_compression_logger_(req, res);
  10873. }
  10874. }
  10875. inline void Server::output_error_log(const Error &err,
  10876. const Request *req) const {
  10877. if (error_logger_) {
  10878. std::lock_guard<std::mutex> guard(logger_mutex_);
  10879. error_logger_(err, req);
  10880. }
  10881. }
  10882. /*
  10883. * Group 5: ClientImpl and Client (Universal) implementation
  10884. */
  10885. // HTTP client implementation
  10886. inline ClientImpl::ClientImpl(const std::string &host)
  10887. : ClientImpl(host, 80, std::string(), std::string()) {}
  10888. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10889. : ClientImpl(host, port, std::string(), std::string()) {}
  10890. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10891. const std::string &client_cert_path,
  10892. const std::string &client_key_path)
  10893. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10894. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10895. inline ClientImpl::~ClientImpl() {
  10896. // Wait until all the requests in flight are handled.
  10897. size_t retry_count = 10;
  10898. while (retry_count-- > 0) {
  10899. {
  10900. std::lock_guard<std::mutex> guard(socket_mutex_);
  10901. if (socket_requests_in_flight_ == 0) { break; }
  10902. }
  10903. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10904. }
  10905. std::lock_guard<std::mutex> guard(socket_mutex_);
  10906. shutdown_socket(socket_);
  10907. close_socket(socket_);
  10908. }
  10909. inline bool ClientImpl::is_valid() const { return true; }
  10910. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10911. client_cert_path_ = rhs.client_cert_path_;
  10912. client_key_path_ = rhs.client_key_path_;
  10913. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10914. read_timeout_sec_ = rhs.read_timeout_sec_;
  10915. read_timeout_usec_ = rhs.read_timeout_usec_;
  10916. write_timeout_sec_ = rhs.write_timeout_sec_;
  10917. write_timeout_usec_ = rhs.write_timeout_usec_;
  10918. max_timeout_msec_ = rhs.max_timeout_msec_;
  10919. basic_auth_username_ = rhs.basic_auth_username_;
  10920. basic_auth_password_ = rhs.basic_auth_password_;
  10921. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10922. keep_alive_ = rhs.keep_alive_;
  10923. follow_location_ = rhs.follow_location_;
  10924. path_encode_ = rhs.path_encode_;
  10925. address_family_ = rhs.address_family_;
  10926. tcp_nodelay_ = rhs.tcp_nodelay_;
  10927. ipv6_v6only_ = rhs.ipv6_v6only_;
  10928. socket_options_ = rhs.socket_options_;
  10929. compress_ = rhs.compress_;
  10930. decompress_ = rhs.decompress_;
  10931. payload_max_length_ = rhs.payload_max_length_;
  10932. has_payload_max_length_ = rhs.has_payload_max_length_;
  10933. interface_ = rhs.interface_;
  10934. proxy_host_ = rhs.proxy_host_;
  10935. proxy_port_ = rhs.proxy_port_;
  10936. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10937. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10938. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10939. no_proxy_entries_ = rhs.no_proxy_entries_;
  10940. logger_ = rhs.logger_;
  10941. error_logger_ = rhs.error_logger_;
  10942. #ifdef CPPHTTPLIB_SSL_ENABLED
  10943. digest_auth_username_ = rhs.digest_auth_username_;
  10944. digest_auth_password_ = rhs.digest_auth_password_;
  10945. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10946. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10947. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10948. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10949. server_certificate_verification_ = rhs.server_certificate_verification_;
  10950. server_hostname_verification_ = rhs.server_hostname_verification_;
  10951. system_ca_mode_ = rhs.system_ca_mode_;
  10952. #endif
  10953. }
  10954. inline bool
  10955. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10956. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10957. if (no_proxy_entries_.empty()) { return true; }
  10958. // host_ is const so its normalized form is invariant; cache it. The
  10959. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10960. if (host == host_) {
  10961. if (!host_normalized_valid_) {
  10962. host_normalized_ = detail::normalize_target(host_);
  10963. host_normalized_valid_ = true;
  10964. }
  10965. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10966. }
  10967. auto target = detail::normalize_target(host);
  10968. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10969. }
  10970. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10971. if (is_proxy_enabled_for_host(host_)) {
  10972. return detail::create_client_socket(
  10973. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10974. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10975. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10976. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10977. }
  10978. // Check is custom IP or hostname specified for host_
  10979. std::string connect_host;
  10980. std::string ip;
  10981. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  10982. return detail::create_client_socket(
  10983. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10984. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10985. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10986. write_timeout_usec_, interface_, error);
  10987. }
  10988. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10989. Error &error) {
  10990. auto sock = create_client_socket(error);
  10991. if (sock == INVALID_SOCKET) { return false; }
  10992. socket.sock = sock;
  10993. return true;
  10994. }
  10995. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10996. return create_and_connect_socket(socket, error);
  10997. }
  10998. inline bool ClientImpl::setup_proxy_connection(
  10999. Socket & /*socket*/,
  11000. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  11001. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  11002. return true;
  11003. }
  11004. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  11005. bool /*shutdown_gracefully*/) {
  11006. // If there are any requests in flight from threads other than us, then it's
  11007. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  11008. assert(socket_requests_in_flight_ == 0 ||
  11009. socket_requests_are_from_thread_ == std::this_thread::get_id());
  11010. }
  11011. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  11012. if (socket.sock == INVALID_SOCKET) { return; }
  11013. detail::shutdown_socket(socket.sock);
  11014. }
  11015. inline void ClientImpl::close_socket(Socket &socket) {
  11016. // If there are requests in flight in another thread, usually closing
  11017. // the socket will be fine and they will simply receive an error when
  11018. // using the closed socket, but it is still a bug since rarely the OS
  11019. // may reassign the socket id to be used for a new socket, and then
  11020. // suddenly they will be operating on a live socket that is different
  11021. // than the one they intended!
  11022. assert(socket_requests_in_flight_ == 0 ||
  11023. socket_requests_are_from_thread_ == std::this_thread::get_id());
  11024. // It is also a bug if this happens while SSL is still active
  11025. #ifdef CPPHTTPLIB_SSL_ENABLED
  11026. assert(socket.ssl == nullptr);
  11027. #endif
  11028. if (socket.sock == INVALID_SOCKET) { return; }
  11029. detail::close_socket(socket.sock);
  11030. socket.sock = INVALID_SOCKET;
  11031. }
  11032. inline void ClientImpl::disconnect(bool gracefully) {
  11033. shutdown_ssl(socket_, gracefully);
  11034. shutdown_socket(socket_);
  11035. close_socket(socket_);
  11036. }
  11037. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  11038. Response &res,
  11039. bool skip_100_continue) const {
  11040. std::array<char, 2048> buf{};
  11041. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  11042. if (!line_reader.getline()) { return false; }
  11043. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  11044. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  11045. #else
  11046. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  11047. #endif
  11048. std::cmatch m;
  11049. if (!std::regex_match(line_reader.ptr(), m, re)) {
  11050. return req.method == "CONNECT";
  11051. }
  11052. res.version = std::string(m[1]);
  11053. res.status = std::stoi(std::string(m[2]));
  11054. res.reason = std::string(m[3]);
  11055. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  11056. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  11057. if (!line_reader.getline()) { return false; } // CRLF
  11058. if (!line_reader.getline()) { return false; } // next response line
  11059. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  11060. res.version = std::string(m[1]);
  11061. res.status = std::stoi(std::string(m[2]));
  11062. res.reason = std::string(m[3]);
  11063. }
  11064. return true;
  11065. }
  11066. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  11067. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  11068. auto ret = send_(req, res, error);
  11069. if (error == Error::SSLPeerCouldBeClosed_) {
  11070. assert(!ret);
  11071. ret = send_(req, res, error);
  11072. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  11073. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  11074. }
  11075. return ret;
  11076. }
  11077. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  11078. {
  11079. std::lock_guard<std::mutex> guard(socket_mutex_);
  11080. // Set this to false immediately - if it ever gets set to true by the end
  11081. // of the request, we know another thread instructed us to close the
  11082. // socket.
  11083. socket_should_be_closed_when_request_is_done_ = false;
  11084. auto is_alive = false;
  11085. if (socket_.is_open()) {
  11086. is_alive = detail::is_socket_alive(socket_.sock);
  11087. #ifdef CPPHTTPLIB_SSL_ENABLED
  11088. if (is_alive && is_ssl()) {
  11089. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11090. is_alive = false;
  11091. }
  11092. }
  11093. #endif
  11094. if (!is_alive) {
  11095. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  11096. disconnect(/*gracefully=*/false);
  11097. }
  11098. }
  11099. if (!is_alive) {
  11100. if (!ensure_socket_connection(socket_, error)) {
  11101. output_error_log(error, &req);
  11102. return false;
  11103. }
  11104. {
  11105. auto success = true;
  11106. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  11107. error)) {
  11108. if (!success) { output_error_log(error, &req); }
  11109. return success;
  11110. }
  11111. }
  11112. }
  11113. // Mark the current socket as being in use so that it cannot be closed by
  11114. // anyone else while this request is ongoing, even though we will be
  11115. // releasing the mutex.
  11116. if (socket_requests_in_flight_ > 1) {
  11117. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  11118. }
  11119. socket_requests_in_flight_ += 1;
  11120. socket_requests_are_from_thread_ = std::this_thread::get_id();
  11121. }
  11122. for (const auto &header : default_headers_) {
  11123. if (req.headers.find(header.first) == req.headers.end()) {
  11124. req.headers.insert(header);
  11125. }
  11126. }
  11127. auto ret = false;
  11128. auto close_connection = !keep_alive_;
  11129. auto se = detail::scope_exit([&]() {
  11130. // Briefly lock mutex in order to mark that a request is no longer ongoing
  11131. std::lock_guard<std::mutex> guard(socket_mutex_);
  11132. socket_requests_in_flight_ -= 1;
  11133. if (socket_requests_in_flight_ <= 0) {
  11134. assert(socket_requests_in_flight_ == 0);
  11135. socket_requests_are_from_thread_ = std::thread::id();
  11136. }
  11137. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  11138. !ret) {
  11139. disconnect(/*gracefully=*/true);
  11140. }
  11141. });
  11142. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  11143. return handle_request(strm, req, res, close_connection, error);
  11144. });
  11145. if (!ret) {
  11146. if (error == Error::Success) {
  11147. error = Error::Unknown;
  11148. output_error_log(error, &req);
  11149. }
  11150. }
  11151. return ret;
  11152. }
  11153. inline Result ClientImpl::send(const Request &req) {
  11154. auto req2 = req;
  11155. return send_(std::move(req2));
  11156. }
  11157. inline Result ClientImpl::send_(Request &&req) {
  11158. auto res = detail::make_unique<Response>();
  11159. auto error = Error::Success;
  11160. auto ret = send(req, *res, error);
  11161. #ifdef CPPHTTPLIB_SSL_ENABLED
  11162. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  11163. last_ssl_error_, last_backend_error_};
  11164. #else
  11165. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  11166. #endif
  11167. }
  11168. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  11169. const std::string &ct) {
  11170. (void)for_stream;
  11171. for (const auto &header : default_headers_) {
  11172. if (!r.has_header(header.first)) { r.headers.insert(header); }
  11173. }
  11174. if (!r.has_header("Host")) {
  11175. if (address_family_ == AF_UNIX) {
  11176. r.headers.emplace("Host", "localhost");
  11177. } else {
  11178. r.headers.emplace(
  11179. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  11180. }
  11181. }
  11182. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  11183. if (!r.content_receiver) {
  11184. if (!r.has_header("Accept-Encoding")) {
  11185. std::string accept_encoding;
  11186. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11187. accept_encoding = "br";
  11188. #endif
  11189. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11190. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11191. accept_encoding += "gzip, deflate";
  11192. #endif
  11193. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11194. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11195. accept_encoding += "zstd";
  11196. #endif
  11197. r.set_header("Accept-Encoding", accept_encoding);
  11198. }
  11199. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11200. if (!r.has_header("User-Agent")) {
  11201. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11202. r.set_header("User-Agent", agent);
  11203. }
  11204. #endif
  11205. }
  11206. if (!r.body.empty()) {
  11207. if (!ct.empty() && !r.has_header("Content-Type")) {
  11208. r.headers.emplace("Content-Type", ct);
  11209. }
  11210. if (!r.has_header("Content-Length")) {
  11211. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11212. }
  11213. }
  11214. }
  11215. inline ClientImpl::StreamHandle
  11216. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11217. const Params &params, const Headers &headers,
  11218. const std::string &body,
  11219. const std::string &content_type) {
  11220. StreamHandle handle;
  11221. handle.response = detail::make_unique<Response>();
  11222. handle.error = Error::Success;
  11223. // Encode the target exactly like the buffered send path does, so that the
  11224. // same `path` produces the same request line through either API.
  11225. auto raw_query_path =
  11226. params.empty() ? path : append_query_params(path, params);
  11227. auto query_path = detail::encode_request_target(raw_query_path, path_encode_);
  11228. handle.connection_ = detail::make_unique<ClientConnection>();
  11229. {
  11230. std::lock_guard<std::mutex> guard(socket_mutex_);
  11231. auto is_alive = false;
  11232. if (socket_.is_open()) {
  11233. is_alive = detail::is_socket_alive(socket_.sock);
  11234. #ifdef CPPHTTPLIB_SSL_ENABLED
  11235. if (is_alive && is_ssl()) {
  11236. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11237. is_alive = false;
  11238. }
  11239. }
  11240. #endif
  11241. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11242. }
  11243. if (!is_alive) {
  11244. if (!ensure_socket_connection(socket_, handle.error)) {
  11245. handle.response.reset();
  11246. return handle;
  11247. }
  11248. {
  11249. auto success = true;
  11250. auto start_time = std::chrono::steady_clock::now();
  11251. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11252. success, handle.error)) {
  11253. if (!success) { handle.response.reset(); }
  11254. return handle;
  11255. }
  11256. }
  11257. }
  11258. transfer_socket_ownership_to_handle(handle);
  11259. }
  11260. #ifdef CPPHTTPLIB_SSL_ENABLED
  11261. if (is_ssl() && handle.connection_->session) {
  11262. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11263. handle.connection_->sock, handle.connection_->session,
  11264. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11265. write_timeout_usec_);
  11266. } else {
  11267. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11268. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11269. write_timeout_sec_, write_timeout_usec_);
  11270. }
  11271. #else
  11272. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11273. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11274. write_timeout_sec_, write_timeout_usec_);
  11275. #endif
  11276. handle.stream_ = handle.socket_stream_.get();
  11277. Request req;
  11278. req.method = method;
  11279. req.path = query_path;
  11280. req.headers = headers;
  11281. req.body = body;
  11282. prepare_default_headers(req, true, content_type);
  11283. auto &strm = *handle.stream_;
  11284. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11285. handle.error = Error::Write;
  11286. handle.response.reset();
  11287. return handle;
  11288. }
  11289. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11290. handle.error)) {
  11291. handle.response.reset();
  11292. return handle;
  11293. }
  11294. if (!body.empty()) {
  11295. if (strm.write(body.data(), body.size()) < 0) {
  11296. handle.error = Error::Write;
  11297. handle.response.reset();
  11298. return handle;
  11299. }
  11300. }
  11301. if (!read_response_line(strm, req, *handle.response) ||
  11302. !detail::read_headers(strm, handle.response->headers)) {
  11303. handle.error = Error::Read;
  11304. handle.response.reset();
  11305. return handle;
  11306. }
  11307. handle.body_reader_.stream = handle.stream_;
  11308. handle.body_reader_.payload_max_length = payload_max_length_;
  11309. if (handle.response->has_header("Content-Length")) {
  11310. bool is_invalid = false;
  11311. auto content_length = detail::get_header_value_u64(
  11312. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11313. if (is_invalid) {
  11314. handle.error = Error::Read;
  11315. handle.response.reset();
  11316. return handle;
  11317. }
  11318. handle.body_reader_.has_content_length = true;
  11319. handle.body_reader_.content_length = content_length;
  11320. }
  11321. handle.body_reader_.chunked =
  11322. detail::is_chunked_transfer_encoding(handle.response->headers);
  11323. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11324. if (!content_encoding.empty()) {
  11325. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11326. }
  11327. return handle;
  11328. }
  11329. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11330. if (!is_valid() || !response) { return -1; }
  11331. if (decompressor_) { return read_with_decompression(buf, len); }
  11332. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11333. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11334. trailers_parsed_ = true;
  11335. if (body_reader_.chunked_decoder) {
  11336. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11337. response->trailers, response->headers)) {
  11338. return n;
  11339. }
  11340. } else {
  11341. detail::ChunkedDecoder dec(*stream_);
  11342. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11343. return n;
  11344. }
  11345. }
  11346. }
  11347. return n;
  11348. }
  11349. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11350. size_t len) {
  11351. if (decompress_offset_ < decompress_buffer_.size()) {
  11352. auto available = decompress_buffer_.size() - decompress_offset_;
  11353. auto to_copy = (std::min)(len, available);
  11354. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11355. decompress_offset_ += to_copy;
  11356. decompressed_bytes_read_ += to_copy;
  11357. return static_cast<ssize_t>(to_copy);
  11358. }
  11359. decompress_buffer_.clear();
  11360. decompress_offset_ = 0;
  11361. constexpr size_t kDecompressionBufferSize = 8192;
  11362. char compressed_buf[kDecompressionBufferSize];
  11363. while (true) {
  11364. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11365. sizeof(compressed_buf));
  11366. if (n <= 0) { return n; }
  11367. bool decompress_ok = decompressor_->decompress(
  11368. compressed_buf, static_cast<size_t>(n),
  11369. [this](const char *data, size_t data_len) {
  11370. decompress_buffer_.append(data, data_len);
  11371. auto limit = body_reader_.payload_max_length;
  11372. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11373. return false;
  11374. }
  11375. return true;
  11376. });
  11377. if (!decompress_ok) {
  11378. body_reader_.last_error = Error::Read;
  11379. return -1;
  11380. }
  11381. if (!decompress_buffer_.empty()) { break; }
  11382. }
  11383. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11384. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11385. decompress_offset_ = to_copy;
  11386. decompressed_bytes_read_ += to_copy;
  11387. return static_cast<ssize_t>(to_copy);
  11388. }
  11389. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11390. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11391. return;
  11392. }
  11393. trailers_parsed_ = true;
  11394. const auto bufsiz = 128;
  11395. char line_buf[bufsiz];
  11396. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11397. if (!line_reader.getline()) { return; }
  11398. if (!detail::parse_trailers(line_reader, response->trailers,
  11399. response->headers)) {
  11400. return;
  11401. }
  11402. }
  11403. namespace detail {
  11404. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11405. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11406. size_t &out_chunk_offset,
  11407. size_t &out_chunk_total) {
  11408. if (finished) { return 0; }
  11409. if (chunk_remaining == 0) {
  11410. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11411. if (!lr.getline()) { return -1; }
  11412. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11413. const char *p = lr.ptr();
  11414. int v = 0;
  11415. if (!is_hex(*p, v)) { return -1; }
  11416. size_t chunk_len = 0;
  11417. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11418. for (; is_hex(*p, v); ++p) {
  11419. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11420. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11421. }
  11422. while (is_space_or_tab(*p)) {
  11423. ++p;
  11424. }
  11425. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11426. if (chunk_len == 0) {
  11427. chunk_remaining = 0;
  11428. finished = true;
  11429. out_chunk_offset = 0;
  11430. out_chunk_total = 0;
  11431. return 0;
  11432. }
  11433. chunk_remaining = chunk_len;
  11434. last_chunk_total = chunk_remaining;
  11435. last_chunk_offset = 0;
  11436. }
  11437. auto to_read = (std::min)(chunk_remaining, len);
  11438. auto n = strm.read(buf, to_read);
  11439. if (n <= 0) { return -1; }
  11440. auto offset_before = last_chunk_offset;
  11441. last_chunk_offset += static_cast<size_t>(n);
  11442. chunk_remaining -= static_cast<size_t>(n);
  11443. out_chunk_offset = offset_before;
  11444. out_chunk_total = last_chunk_total;
  11445. if (chunk_remaining == 0) {
  11446. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11447. if (!lr.getline()) { return -1; }
  11448. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11449. }
  11450. return n;
  11451. }
  11452. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11453. const Headers &src_headers) {
  11454. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11455. if (!lr.getline()) { return false; }
  11456. return parse_trailers(lr, dest, src_headers);
  11457. }
  11458. } // namespace detail
  11459. inline void
  11460. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11461. handle.connection_->sock = socket_.sock;
  11462. #ifdef CPPHTTPLIB_SSL_ENABLED
  11463. handle.connection_->session = socket_.ssl;
  11464. socket_.ssl = nullptr;
  11465. #endif
  11466. socket_.sock = INVALID_SOCKET;
  11467. }
  11468. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11469. Response &res, bool close_connection,
  11470. Error &error) {
  11471. if (req.path.empty()) {
  11472. error = Error::Connection;
  11473. output_error_log(error, &req);
  11474. return false;
  11475. }
  11476. auto req_save = req;
  11477. bool ret;
  11478. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11479. auto req2 = req;
  11480. req2.path = "http://" +
  11481. detail::make_host_and_port_string(host_, port_, false) +
  11482. req.path;
  11483. ret = process_request(strm, req2, res, close_connection, error);
  11484. req = std::move(req2);
  11485. req.path = req_save.path;
  11486. } else {
  11487. ret = process_request(strm, req, res, close_connection, error);
  11488. }
  11489. if (!ret) { return false; }
  11490. if (res.get_header_value("Connection") == "close" ||
  11491. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11492. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11493. // for this to be safe.
  11494. // This is safe to call because handle_request is only called by send_
  11495. // which locks the request mutex during the process. It would be a bug
  11496. // to call it from a different thread since it's a thread-safety issue
  11497. // to do these things to the socket if another thread is using the socket.
  11498. std::lock_guard<std::mutex> guard(socket_mutex_);
  11499. disconnect(/*gracefully=*/true);
  11500. }
  11501. if (300 < res.status && res.status < 400 && follow_location_) {
  11502. req = std::move(req_save);
  11503. ret = redirect(req, res, error);
  11504. }
  11505. #ifdef CPPHTTPLIB_SSL_ENABLED
  11506. if ((res.status == StatusCode::Unauthorized_401 ||
  11507. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11508. req.authorization_count_ < 5) {
  11509. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11510. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11511. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11512. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11513. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11514. return ret;
  11515. }
  11516. const auto &username =
  11517. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11518. const auto &password =
  11519. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11520. if (!username.empty() && !password.empty()) {
  11521. std::map<std::string, std::string> auth;
  11522. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11523. Request new_req = req;
  11524. new_req.authorization_count_ += 1;
  11525. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11526. : "Authorization");
  11527. new_req.headers.insert(detail::make_digest_authentication_header(
  11528. req, auth, new_req.authorization_count_, detail::random_string(10),
  11529. username, password, is_proxy));
  11530. Response new_res;
  11531. ret = send(new_req, new_res, error);
  11532. if (ret) { res = std::move(new_res); }
  11533. }
  11534. }
  11535. }
  11536. #endif
  11537. return ret;
  11538. }
  11539. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11540. if (req.redirect_count_ == 0) {
  11541. error = Error::ExceedRedirectCount;
  11542. output_error_log(error, &req);
  11543. return false;
  11544. }
  11545. auto location = res.get_header_value("location");
  11546. if (location.empty()) { return false; }
  11547. detail::UrlComponents uc;
  11548. if (!detail::parse_url(location, uc)) { return false; }
  11549. // Only follow http/https redirects
  11550. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11551. return false;
  11552. }
  11553. auto scheme = is_ssl() ? "https" : "http";
  11554. auto next_scheme = std::move(uc.scheme);
  11555. auto next_host = std::move(uc.host);
  11556. auto port_str = std::move(uc.port);
  11557. auto next_path = std::move(uc.path);
  11558. auto next_query = std::move(uc.query);
  11559. auto next_port = port_;
  11560. if (!port_str.empty()) {
  11561. if (!detail::parse_port(port_str, next_port)) { return false; }
  11562. } else if (!next_scheme.empty()) {
  11563. next_port = next_scheme == "https" ? 443 : 80;
  11564. }
  11565. if (next_scheme.empty()) { next_scheme = scheme; }
  11566. if (next_host.empty()) { next_host = host_; }
  11567. if (next_path.empty()) { next_path = "/"; }
  11568. auto path = decode_path_component(next_path) + next_query;
  11569. // Same host redirect - use current client
  11570. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11571. return detail::redirect(*this, req, res, path, location, error);
  11572. }
  11573. // Cross-host/scheme redirect - create new client with robust setup
  11574. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11575. path, location, error);
  11576. }
  11577. // New method for robust redirect client creation
  11578. inline bool ClientImpl::create_redirect_client(
  11579. const std::string &scheme, const std::string &host, int port, Request &req,
  11580. Response &res, const std::string &path, const std::string &location,
  11581. Error &error) {
  11582. // Determine if we need SSL
  11583. auto need_ssl = (scheme == "https");
  11584. // Clean up request headers that are host/client specific
  11585. // Remove headers that should not be carried over to new host
  11586. auto headers_to_remove = std::vector<std::string>{
  11587. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  11588. for (const auto &header_name : headers_to_remove) {
  11589. auto it = req.headers.find(header_name);
  11590. while (it != req.headers.end()) {
  11591. it = req.headers.erase(it);
  11592. it = req.headers.find(header_name);
  11593. }
  11594. }
  11595. // Create appropriate client type and handle redirect
  11596. if (need_ssl) {
  11597. #ifdef CPPHTTPLIB_SSL_ENABLED
  11598. // Create SSL client for HTTPS redirect
  11599. SSLClient redirect_client(host, port);
  11600. // Setup basic client configuration first
  11601. setup_redirect_client(redirect_client);
  11602. redirect_client.enable_server_certificate_verification(
  11603. server_certificate_verification_);
  11604. redirect_client.enable_server_hostname_verification(
  11605. server_hostname_verification_);
  11606. redirect_client.system_ca_mode_ = system_ca_mode_;
  11607. // Transfer CA certificate to redirect client
  11608. if (!ca_cert_pem_.empty()) {
  11609. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11610. ca_cert_pem_.size());
  11611. }
  11612. if (!ca_cert_file_path_.empty()) {
  11613. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11614. }
  11615. // Client certificates are set through constructor for SSLClient
  11616. // NOTE: SSLClient constructor already takes client_cert_path and
  11617. // client_key_path so we need to create it properly if client certs are
  11618. // needed
  11619. // Execute the redirect
  11620. return detail::redirect(redirect_client, req, res, path, location, error);
  11621. #else
  11622. // SSL not supported - set appropriate error
  11623. error = Error::SSLConnection;
  11624. output_error_log(error, &req);
  11625. return false;
  11626. #endif
  11627. } else {
  11628. // HTTP redirect
  11629. ClientImpl redirect_client(host, port);
  11630. // Setup client with robust configuration
  11631. setup_redirect_client(redirect_client);
  11632. // Execute the redirect
  11633. return detail::redirect(redirect_client, req, res, path, location, error);
  11634. }
  11635. }
  11636. // New method for robust client setup (based on basic_manual_redirect.cpp
  11637. // logic)
  11638. template <typename ClientType>
  11639. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11640. // Copy basic settings first
  11641. client.set_connection_timeout(connection_timeout_sec_);
  11642. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11643. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11644. client.set_keep_alive(keep_alive_);
  11645. client.set_follow_location(
  11646. true); // Enable redirects to handle multi-step redirects
  11647. client.set_path_encode(path_encode_);
  11648. client.set_compress(compress_);
  11649. client.set_decompress(decompress_);
  11650. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11651. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11652. // 15.4, credentials must not be forwarded when redirecting to a different
  11653. // host. This function is only called for cross-host redirects; same-host
  11654. // redirects are handled directly in ClientImpl::redirect().
  11655. // Copy the proxy configuration unconditionally; the per-target bypass is
  11656. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11657. // still use the proxy.
  11658. client.no_proxy_entries_ = no_proxy_entries_;
  11659. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11660. client.set_proxy(proxy_host_, proxy_port_);
  11661. if (!proxy_basic_auth_username_.empty()) {
  11662. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11663. proxy_basic_auth_password_);
  11664. }
  11665. if (!proxy_bearer_token_auth_token_.empty()) {
  11666. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11667. }
  11668. #ifdef CPPHTTPLIB_SSL_ENABLED
  11669. if (!proxy_digest_auth_username_.empty()) {
  11670. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11671. proxy_digest_auth_password_);
  11672. }
  11673. #endif
  11674. }
  11675. // Copy network and socket settings
  11676. client.set_address_family(address_family_);
  11677. client.set_tcp_nodelay(tcp_nodelay_);
  11678. client.set_ipv6_v6only(ipv6_v6only_);
  11679. if (socket_options_) { client.set_socket_options(socket_options_); }
  11680. if (!interface_.empty()) { client.set_interface(interface_); }
  11681. // Copy logging and headers
  11682. if (logger_) { client.set_logger(logger_); }
  11683. if (error_logger_) { client.set_error_logger(error_logger_); }
  11684. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11685. // Each new client should generate its own headers based on its target host
  11686. }
  11687. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11688. const Request &req,
  11689. Error &error) const {
  11690. auto is_shutting_down = []() { return false; };
  11691. if (req.is_chunked_content_provider_) {
  11692. auto compressor = compress_ ? detail::create_compressor().first
  11693. : std::unique_ptr<detail::compressor>();
  11694. if (!compressor) {
  11695. compressor = detail::make_unique<detail::nocompressor>();
  11696. }
  11697. return detail::write_content_chunked(strm, req.content_provider_,
  11698. is_shutting_down, *compressor, error);
  11699. } else {
  11700. return detail::write_content_with_progress(
  11701. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11702. req.upload_progress, error);
  11703. }
  11704. }
  11705. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11706. bool close_connection, Error &error,
  11707. bool skip_body) {
  11708. // Prepare additional headers
  11709. if (close_connection) {
  11710. if (!req.has_header("Connection")) {
  11711. req.set_header("Connection", "close");
  11712. }
  11713. }
  11714. std::string ct_for_defaults;
  11715. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11716. ct_for_defaults = "text/plain";
  11717. }
  11718. prepare_default_headers(req, false, ct_for_defaults);
  11719. if (req.body.empty()) {
  11720. if (req.content_provider_) {
  11721. if (!req.is_chunked_content_provider_) {
  11722. if (!req.has_header("Content-Length")) {
  11723. auto length = std::to_string(req.content_length_);
  11724. req.set_header("Content-Length", length);
  11725. }
  11726. }
  11727. } else {
  11728. if (req.method == "POST" || req.method == "PUT" ||
  11729. req.method == "PATCH") {
  11730. req.set_header("Content-Length", "0");
  11731. }
  11732. }
  11733. }
  11734. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11735. if (!req.has_header("Authorization")) {
  11736. req.headers.insert(make_basic_authentication_header(
  11737. basic_auth_username_, basic_auth_password_, false));
  11738. }
  11739. }
  11740. if (!bearer_token_auth_token_.empty()) {
  11741. if (!req.has_header("Authorization")) {
  11742. req.headers.insert(make_bearer_token_authentication_header(
  11743. bearer_token_auth_token_, false));
  11744. }
  11745. }
  11746. // Proxy-Authorization is only sent when the proxy is actually used for
  11747. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11748. // credentials directly to the destination server.
  11749. if (is_proxy_enabled_for_host(host_)) {
  11750. if (!proxy_basic_auth_username_.empty() &&
  11751. !proxy_basic_auth_password_.empty() &&
  11752. !req.has_header("Proxy-Authorization")) {
  11753. req.headers.insert(make_basic_authentication_header(
  11754. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11755. }
  11756. if (!proxy_bearer_token_auth_token_.empty() &&
  11757. !req.has_header("Proxy-Authorization")) {
  11758. req.headers.insert(make_bearer_token_authentication_header(
  11759. proxy_bearer_token_auth_token_, true));
  11760. }
  11761. }
  11762. // Request line and headers
  11763. {
  11764. detail::BufferStream bstrm;
  11765. // Extract the query from req.path. The encoding itself is delegated to
  11766. // `encode_request_target`; the raw query is still needed here to decide
  11767. // between populating `req.params` from it and falling back to building a
  11768. // query out of caller-supplied `req.params`.
  11769. auto query_pos = req.path.find('?');
  11770. auto query_part = query_pos == std::string::npos
  11771. ? std::string()
  11772. : req.path.substr(query_pos + 1);
  11773. auto path_with_query =
  11774. detail::encode_request_target(req.path, path_encode_);
  11775. if (!query_part.empty()) {
  11776. // The query already came in through `req.path`; still populate
  11777. // `req.params` for handlers/users who read them.
  11778. detail::parse_query_text(query_part, req.params);
  11779. } else if (!req.params.empty()) {
  11780. // No query in `req.path`; build one from `req.params` so existing
  11781. // callers that pass `Params` separately continue to work.
  11782. path_with_query = append_query_params(path_with_query, req.params);
  11783. }
  11784. // Write request line and headers
  11785. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  11786. // A rejected target (e.g. CR/LF smuggled in via a decoded redirect
  11787. // Location under set_path_encode(false)) must fail the request cleanly
  11788. // instead of emitting a request-line-less, header-injecting request.
  11789. error = Error::Write;
  11790. output_error_log(error, &req);
  11791. return false;
  11792. }
  11793. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11794. error)) {
  11795. output_error_log(error, &req);
  11796. return false;
  11797. }
  11798. // Flush buffer
  11799. auto &data = bstrm.get_buffer();
  11800. if (!detail::write_data(strm, data.data(), data.size())) {
  11801. error = Error::Write;
  11802. output_error_log(error, &req);
  11803. return false;
  11804. }
  11805. }
  11806. // After sending request line and headers, wait briefly for an early server
  11807. // response (e.g. 4xx) and avoid sending a potentially large request body
  11808. // unnecessarily. This workaround is only enabled on Windows because Unix
  11809. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11810. // buffering can accept large writes even when the peer already responded.
  11811. // Check the stream first (which covers SSL via `is_readable()`), then
  11812. // fall back to select on the socket. Only perform the wait for very large
  11813. // request bodies to avoid interfering with normal small requests and
  11814. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11815. // response. Skip this check when using Expect: 100-continue, as the protocol
  11816. // handles early responses properly.
  11817. #if defined(_WIN32)
  11818. if (!skip_body &&
  11819. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11820. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11821. auto start = std::chrono::high_resolution_clock::now();
  11822. for (;;) {
  11823. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11824. // from SSL internals. If the underlying socket is readable, assume an
  11825. // early response may be present.
  11826. auto sock = strm.socket();
  11827. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11828. return false;
  11829. }
  11830. // Fallback to stream-level check for non-socket streams or when the
  11831. // socket isn't reporting readable. Avoid using `is_readable()` for
  11832. // SSL, since `SSL_pending()` may report buffered records that do not
  11833. // indicate a complete application-level response yet.
  11834. if (!is_ssl() && strm.is_readable()) { return false; }
  11835. auto now = std::chrono::high_resolution_clock::now();
  11836. auto elapsed =
  11837. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11838. .count();
  11839. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11840. break;
  11841. }
  11842. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11843. }
  11844. }
  11845. #endif
  11846. // Body
  11847. if (skip_body) { return true; }
  11848. return write_request_body(strm, req, error);
  11849. }
  11850. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11851. Error &error) {
  11852. if (req.body.empty()) {
  11853. return write_content_with_provider(strm, req, error);
  11854. }
  11855. if (req.upload_progress) {
  11856. auto body_size = req.body.size();
  11857. size_t written = 0;
  11858. auto data = req.body.data();
  11859. while (written < body_size) {
  11860. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11861. if (!detail::write_data(strm, data + written, to_write)) {
  11862. error = Error::Write;
  11863. output_error_log(error, &req);
  11864. return false;
  11865. }
  11866. written += to_write;
  11867. if (!req.upload_progress(written, body_size)) {
  11868. error = Error::Canceled;
  11869. output_error_log(error, &req);
  11870. return false;
  11871. }
  11872. }
  11873. } else {
  11874. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11875. error = Error::Write;
  11876. output_error_log(error, &req);
  11877. return false;
  11878. }
  11879. }
  11880. return true;
  11881. }
  11882. inline std::unique_ptr<Response>
  11883. ClientImpl::send_with_content_provider_and_receiver(
  11884. Request &req, const char *body, size_t content_length,
  11885. ContentProvider content_provider,
  11886. ContentProviderWithoutLength content_provider_without_length,
  11887. const std::string &content_type, ContentReceiver content_receiver,
  11888. Error &error) {
  11889. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11890. auto enc = compress_
  11891. ? detail::create_compressor()
  11892. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11893. nullptr, nullptr);
  11894. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11895. if (enc.first && !content_provider_without_length) {
  11896. auto &compressor = enc.first;
  11897. if (content_provider) {
  11898. auto ok = true;
  11899. size_t offset = 0;
  11900. DataSink data_sink;
  11901. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11902. if (ok) {
  11903. auto last = offset + data_len == content_length;
  11904. auto ret = compressor->compress(
  11905. data, data_len, last,
  11906. [&](const char *compressed_data, size_t compressed_data_len) {
  11907. req.body.append(compressed_data, compressed_data_len);
  11908. return true;
  11909. });
  11910. if (ret) {
  11911. offset += data_len;
  11912. } else {
  11913. ok = false;
  11914. }
  11915. }
  11916. return ok;
  11917. };
  11918. while (ok && offset < content_length) {
  11919. if (!content_provider(offset, content_length - offset, data_sink)) {
  11920. error = Error::Canceled;
  11921. output_error_log(error, &req);
  11922. return nullptr;
  11923. }
  11924. }
  11925. } else {
  11926. if (!compressor->compress(body, content_length, true,
  11927. [&](const char *data, size_t data_len) {
  11928. req.body.append(data, data_len);
  11929. return true;
  11930. })) {
  11931. error = Error::Compression;
  11932. output_error_log(error, &req);
  11933. return nullptr;
  11934. }
  11935. }
  11936. } else {
  11937. if (content_provider) {
  11938. req.content_length_ = content_length;
  11939. req.content_provider_ = std::move(content_provider);
  11940. req.is_chunked_content_provider_ = false;
  11941. } else if (content_provider_without_length) {
  11942. req.content_length_ = 0;
  11943. req.content_provider_ = detail::ContentProviderAdapter(
  11944. std::move(content_provider_without_length));
  11945. req.is_chunked_content_provider_ = true;
  11946. req.set_header("Transfer-Encoding", "chunked");
  11947. } else {
  11948. req.body.assign(body, content_length);
  11949. }
  11950. }
  11951. if (content_receiver) {
  11952. req.content_receiver =
  11953. [content_receiver](const char *data, size_t data_length,
  11954. size_t /*offset*/, size_t /*total_length*/) {
  11955. return content_receiver(data, data_length);
  11956. };
  11957. }
  11958. auto res = detail::make_unique<Response>();
  11959. return send(req, *res, error) ? std::move(res) : nullptr;
  11960. }
  11961. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11962. const std::string &method, const std::string &path, const Headers &headers,
  11963. const char *body, size_t content_length, ContentProvider content_provider,
  11964. ContentProviderWithoutLength content_provider_without_length,
  11965. const std::string &content_type, ContentReceiver content_receiver,
  11966. UploadProgress progress) {
  11967. Request req;
  11968. req.method = method;
  11969. req.headers = headers;
  11970. req.path = path;
  11971. req.upload_progress = std::move(progress);
  11972. if (max_timeout_msec_ > 0) {
  11973. req.start_time_ = std::chrono::steady_clock::now();
  11974. }
  11975. auto error = Error::Success;
  11976. auto res = send_with_content_provider_and_receiver(
  11977. req, body, content_length, std::move(content_provider),
  11978. std::move(content_provider_without_length), content_type,
  11979. std::move(content_receiver), error);
  11980. #ifdef CPPHTTPLIB_SSL_ENABLED
  11981. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11982. last_backend_error_};
  11983. #else
  11984. return Result{std::move(res), error, std::move(req.headers)};
  11985. #endif
  11986. }
  11987. inline void ClientImpl::output_log(const Request &req,
  11988. const Response &res) const {
  11989. if (logger_) {
  11990. std::lock_guard<std::mutex> guard(logger_mutex_);
  11991. logger_(req, res);
  11992. }
  11993. }
  11994. inline void ClientImpl::output_error_log(const Error &err,
  11995. const Request *req) const {
  11996. if (error_logger_) {
  11997. std::lock_guard<std::mutex> guard(logger_mutex_);
  11998. error_logger_(err, req);
  11999. }
  12000. }
  12001. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  12002. Response &res, bool close_connection,
  12003. Error &error) {
  12004. // Auto-add Expect: 100-continue for large bodies
  12005. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  12006. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  12007. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  12008. req.set_header("Expect", "100-continue");
  12009. }
  12010. }
  12011. // Check for Expect: 100-continue
  12012. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  12013. // Send request (skip body if using Expect: 100-continue)
  12014. auto write_request_success =
  12015. write_request(strm, req, close_connection, error, expect_100_continue);
  12016. #ifdef CPPHTTPLIB_SSL_ENABLED
  12017. if (is_ssl() && !expect_100_continue) {
  12018. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  12019. if (!is_proxy_enabled) {
  12020. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12021. error = Error::SSLPeerCouldBeClosed_;
  12022. output_error_log(error, &req);
  12023. return false;
  12024. }
  12025. }
  12026. }
  12027. #endif
  12028. // Handle Expect: 100-continue.
  12029. //
  12030. // Wait for an interim/early response by attempting to read the status line
  12031. // under a short timeout, instead of trusting raw socket readability. Over
  12032. // TLS, post-handshake records (e.g. session tickets) make the socket
  12033. // readable without any HTTP response being available; relying on
  12034. // `select_read` there caused the body to be withheld forever and the
  12035. // request to fail with `Read` (#2458). If no status line arrives within the
  12036. // timeout, send the body anyway (matching curl's behavior).
  12037. auto status_line_read = false;
  12038. if (expect_100_continue && write_request_success) {
  12039. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  12040. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  12041. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  12042. strm.set_read_timeout(sec, usec);
  12043. status_line_read = read_response_line(strm, req, res, false);
  12044. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  12045. }
  12046. if (!status_line_read) {
  12047. // No interim response within the timeout: send the body and handle the
  12048. // response as usual.
  12049. if (!write_request_body(strm, req, error)) { return false; }
  12050. expect_100_continue = false; // Switch to normal response handling
  12051. }
  12052. }
  12053. // Receive response and headers
  12054. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  12055. if ((!status_line_read &&
  12056. !read_response_line(strm, req, res, !expect_100_continue)) ||
  12057. !detail::read_headers(strm, res.headers)) {
  12058. if (write_request_success) { error = Error::Read; }
  12059. output_error_log(error, &req);
  12060. return false;
  12061. }
  12062. if (!write_request_success) { return false; }
  12063. // Handle Expect: 100-continue response
  12064. if (expect_100_continue) {
  12065. if (res.status == StatusCode::Continue_100) {
  12066. // Server accepted, send the body
  12067. if (!write_request_body(strm, req, error)) { return false; }
  12068. // Read the actual response
  12069. res.headers.clear();
  12070. res.body.clear();
  12071. if (!read_response_line(strm, req, res) ||
  12072. !detail::read_headers(strm, res.headers)) {
  12073. error = Error::Read;
  12074. output_error_log(error, &req);
  12075. return false;
  12076. }
  12077. }
  12078. // If not 100 Continue, server returned an error; proceed with that response
  12079. }
  12080. // Body
  12081. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  12082. req.method != "CONNECT") {
  12083. auto redirect = 300 < res.status && res.status < 400 &&
  12084. res.status != StatusCode::NotModified_304 &&
  12085. follow_location_;
  12086. if (req.response_handler && !redirect) {
  12087. if (!req.response_handler(res)) {
  12088. error = Error::Canceled;
  12089. output_error_log(error, &req);
  12090. return false;
  12091. }
  12092. }
  12093. auto out =
  12094. req.content_receiver
  12095. ? static_cast<ContentReceiverWithProgress>(
  12096. [&](const char *buf, size_t n, size_t off, size_t len) {
  12097. if (redirect) { return true; }
  12098. auto ret = req.content_receiver(buf, n, off, len);
  12099. if (!ret) {
  12100. error = Error::Canceled;
  12101. output_error_log(error, &req);
  12102. }
  12103. return ret;
  12104. })
  12105. : static_cast<ContentReceiverWithProgress>(
  12106. [&](const char *buf, size_t n, size_t /*off*/,
  12107. size_t /*len*/) {
  12108. assert(res.body.size() + n <= res.body.max_size());
  12109. if (payload_max_length_ > 0 &&
  12110. (res.body.size() >= payload_max_length_ ||
  12111. n > payload_max_length_ - res.body.size())) {
  12112. return false;
  12113. }
  12114. res.body.append(buf, n);
  12115. return true;
  12116. });
  12117. auto progress = [&](size_t current, size_t total) {
  12118. if (!req.download_progress || redirect) { return true; }
  12119. auto ret = req.download_progress(current, total);
  12120. if (!ret) {
  12121. error = Error::Canceled;
  12122. output_error_log(error, &req);
  12123. }
  12124. return ret;
  12125. };
  12126. if (res.has_header("Content-Length")) {
  12127. if (!req.content_receiver) {
  12128. auto len = res.get_header_value_u64("Content-Length");
  12129. if (len > res.body.max_size()) {
  12130. error = Error::Read;
  12131. output_error_log(error, &req);
  12132. return false;
  12133. }
  12134. // Cap the reservation by payload_max_length_ to avoid OOM when a
  12135. // hostile or malformed server sends an enormous Content-Length.
  12136. // The actual body read below is bounded by payload_max_length_,
  12137. // so reserving more than that is never useful.
  12138. auto reserve_len = static_cast<size_t>(len);
  12139. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  12140. reserve_len = payload_max_length_;
  12141. }
  12142. res.body.reserve(reserve_len);
  12143. }
  12144. }
  12145. if (res.status != StatusCode::NotModified_304) {
  12146. int dummy_status;
  12147. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  12148. ? (std::numeric_limits<size_t>::max)()
  12149. : payload_max_length_;
  12150. if (!detail::read_content(strm, res, max_length, dummy_status,
  12151. std::move(progress), std::move(out),
  12152. decompress_)) {
  12153. if (error != Error::Canceled) { error = Error::Read; }
  12154. output_error_log(error, &req);
  12155. return false;
  12156. }
  12157. }
  12158. }
  12159. // Log
  12160. output_log(req, res);
  12161. return true;
  12162. }
  12163. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  12164. const std::string &boundary, const UploadFormDataItems &items,
  12165. const FormDataProviderItems &provider_items) const {
  12166. size_t cur_item = 0;
  12167. size_t cur_start = 0;
  12168. // cur_item and cur_start are copied to within the std::function and
  12169. // maintain state between successive calls
  12170. return [&, cur_item, cur_start](size_t offset,
  12171. DataSink &sink) mutable -> bool {
  12172. if (!offset && !items.empty()) {
  12173. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12174. return true;
  12175. } else if (cur_item < provider_items.size()) {
  12176. if (!cur_start) {
  12177. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12178. provider_items[cur_item], boundary);
  12179. offset += begin.size();
  12180. cur_start = offset;
  12181. sink.os << begin;
  12182. }
  12183. DataSink cur_sink;
  12184. auto has_data = true;
  12185. cur_sink.write = sink.write;
  12186. cur_sink.done = [&]() { has_data = false; };
  12187. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12188. return false;
  12189. }
  12190. if (!has_data) {
  12191. sink.os << detail::serialize_multipart_formdata_item_end();
  12192. cur_item++;
  12193. cur_start = 0;
  12194. }
  12195. return true;
  12196. } else {
  12197. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12198. sink.done();
  12199. return true;
  12200. }
  12201. };
  12202. }
  12203. inline bool ClientImpl::process_socket(
  12204. const Socket &socket,
  12205. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12206. std::function<bool(Stream &strm)> callback) {
  12207. return detail::process_client_socket(
  12208. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12209. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12210. }
  12211. inline bool ClientImpl::is_ssl() const { return false; }
  12212. inline Result ClientImpl::Get(const std::string &path,
  12213. DownloadProgress progress) {
  12214. return Get(path, Headers(), std::move(progress));
  12215. }
  12216. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12217. DownloadProgress progress) {
  12218. return Get(path, params, Headers(), std::move(progress));
  12219. }
  12220. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12221. const Headers &headers,
  12222. DownloadProgress progress) {
  12223. if (params.empty()) { return Get(path, headers); }
  12224. std::string path_with_query = append_query_params(path, params);
  12225. return Get(path_with_query, headers, std::move(progress));
  12226. }
  12227. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12228. DownloadProgress progress) {
  12229. Request req;
  12230. req.method = "GET";
  12231. req.path = path;
  12232. req.headers = headers;
  12233. req.download_progress = std::move(progress);
  12234. if (max_timeout_msec_ > 0) {
  12235. req.start_time_ = std::chrono::steady_clock::now();
  12236. }
  12237. return send_(std::move(req));
  12238. }
  12239. inline Result ClientImpl::Get(const std::string &path,
  12240. ContentReceiver content_receiver,
  12241. DownloadProgress progress) {
  12242. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12243. std::move(progress));
  12244. }
  12245. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12246. ContentReceiver content_receiver,
  12247. DownloadProgress progress) {
  12248. return Get(path, headers, nullptr, std::move(content_receiver),
  12249. std::move(progress));
  12250. }
  12251. inline Result ClientImpl::Get(const std::string &path,
  12252. ResponseHandler response_handler,
  12253. ContentReceiver content_receiver,
  12254. DownloadProgress progress) {
  12255. return Get(path, Headers(), std::move(response_handler),
  12256. std::move(content_receiver), std::move(progress));
  12257. }
  12258. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12259. ResponseHandler response_handler,
  12260. ContentReceiver content_receiver,
  12261. DownloadProgress progress) {
  12262. Request req;
  12263. req.method = "GET";
  12264. req.path = path;
  12265. req.headers = headers;
  12266. req.response_handler = std::move(response_handler);
  12267. req.content_receiver =
  12268. [content_receiver](const char *data, size_t data_length,
  12269. size_t /*offset*/, size_t /*total_length*/) {
  12270. return content_receiver(data, data_length);
  12271. };
  12272. req.download_progress = std::move(progress);
  12273. if (max_timeout_msec_ > 0) {
  12274. req.start_time_ = std::chrono::steady_clock::now();
  12275. }
  12276. return send_(std::move(req));
  12277. }
  12278. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12279. const Headers &headers,
  12280. ContentReceiver content_receiver,
  12281. DownloadProgress progress) {
  12282. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12283. std::move(progress));
  12284. }
  12285. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12286. const Headers &headers,
  12287. ResponseHandler response_handler,
  12288. ContentReceiver content_receiver,
  12289. DownloadProgress progress) {
  12290. if (params.empty()) {
  12291. return Get(path, headers, std::move(response_handler),
  12292. std::move(content_receiver), std::move(progress));
  12293. }
  12294. std::string path_with_query = append_query_params(path, params);
  12295. return Get(path_with_query, headers, std::move(response_handler),
  12296. std::move(content_receiver), std::move(progress));
  12297. }
  12298. inline Result ClientImpl::Head(const std::string &path) {
  12299. return Head(path, Headers());
  12300. }
  12301. inline Result ClientImpl::Head(const std::string &path,
  12302. const Headers &headers) {
  12303. Request req;
  12304. req.method = "HEAD";
  12305. req.headers = headers;
  12306. req.path = path;
  12307. if (max_timeout_msec_ > 0) {
  12308. req.start_time_ = std::chrono::steady_clock::now();
  12309. }
  12310. return send_(std::move(req));
  12311. }
  12312. inline Result ClientImpl::Post(const std::string &path) {
  12313. return Post(path, std::string(), std::string());
  12314. }
  12315. inline Result ClientImpl::Post(const std::string &path,
  12316. const Headers &headers) {
  12317. return Post(path, headers, nullptr, 0, std::string());
  12318. }
  12319. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12320. size_t content_length,
  12321. const std::string &content_type,
  12322. UploadProgress progress) {
  12323. return Post(path, Headers(), body, content_length, content_type, progress);
  12324. }
  12325. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12326. const std::string &content_type,
  12327. UploadProgress progress) {
  12328. return Post(path, Headers(), body, content_type, progress);
  12329. }
  12330. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12331. return Post(path, Headers(), params);
  12332. }
  12333. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12334. ContentProvider content_provider,
  12335. const std::string &content_type,
  12336. UploadProgress progress) {
  12337. return Post(path, Headers(), content_length, std::move(content_provider),
  12338. content_type, progress);
  12339. }
  12340. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12341. ContentProvider content_provider,
  12342. const std::string &content_type,
  12343. ContentReceiver content_receiver,
  12344. UploadProgress progress) {
  12345. return Post(path, Headers(), content_length, std::move(content_provider),
  12346. content_type, std::move(content_receiver), progress);
  12347. }
  12348. inline Result ClientImpl::Post(const std::string &path,
  12349. ContentProviderWithoutLength content_provider,
  12350. const std::string &content_type,
  12351. UploadProgress progress) {
  12352. return Post(path, Headers(), std::move(content_provider), content_type,
  12353. progress);
  12354. }
  12355. inline Result ClientImpl::Post(const std::string &path,
  12356. ContentProviderWithoutLength content_provider,
  12357. const std::string &content_type,
  12358. ContentReceiver content_receiver,
  12359. UploadProgress progress) {
  12360. return Post(path, Headers(), std::move(content_provider), content_type,
  12361. std::move(content_receiver), progress);
  12362. }
  12363. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12364. const Params &params) {
  12365. auto query = detail::params_to_query_str(params);
  12366. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12367. }
  12368. inline Result ClientImpl::Post(const std::string &path,
  12369. const UploadFormDataItems &items,
  12370. UploadProgress progress) {
  12371. return Post(path, Headers(), items, progress);
  12372. }
  12373. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12374. const UploadFormDataItems &items,
  12375. UploadProgress progress) {
  12376. const auto &boundary = detail::make_multipart_data_boundary();
  12377. const auto &content_type =
  12378. detail::serialize_multipart_formdata_get_content_type(boundary);
  12379. auto content_length = detail::get_multipart_content_length(items, boundary);
  12380. return Post(path, headers, content_length,
  12381. detail::make_multipart_content_provider(items, boundary),
  12382. content_type, progress);
  12383. }
  12384. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12385. const UploadFormDataItems &items,
  12386. const std::string &boundary,
  12387. UploadProgress progress) {
  12388. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12389. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12390. }
  12391. const auto &content_type =
  12392. detail::serialize_multipart_formdata_get_content_type(boundary);
  12393. auto content_length = detail::get_multipart_content_length(items, boundary);
  12394. return Post(path, headers, content_length,
  12395. detail::make_multipart_content_provider(items, boundary),
  12396. content_type, progress);
  12397. }
  12398. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12399. const char *body, size_t content_length,
  12400. const std::string &content_type,
  12401. UploadProgress progress) {
  12402. return send_with_content_provider_and_receiver(
  12403. "POST", path, headers, body, content_length, nullptr, nullptr,
  12404. content_type, nullptr, progress);
  12405. }
  12406. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12407. const std::string &body,
  12408. const std::string &content_type,
  12409. UploadProgress progress) {
  12410. return send_with_content_provider_and_receiver(
  12411. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12412. content_type, nullptr, progress);
  12413. }
  12414. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12415. size_t content_length,
  12416. ContentProvider content_provider,
  12417. const std::string &content_type,
  12418. UploadProgress progress) {
  12419. return send_with_content_provider_and_receiver(
  12420. "POST", path, headers, nullptr, content_length,
  12421. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12422. }
  12423. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12424. size_t content_length,
  12425. ContentProvider content_provider,
  12426. const std::string &content_type,
  12427. ContentReceiver content_receiver,
  12428. DownloadProgress progress) {
  12429. return send_with_content_provider_and_receiver(
  12430. "POST", path, headers, nullptr, content_length,
  12431. std::move(content_provider), nullptr, content_type,
  12432. std::move(content_receiver), std::move(progress));
  12433. }
  12434. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12435. ContentProviderWithoutLength content_provider,
  12436. const std::string &content_type,
  12437. UploadProgress progress) {
  12438. return send_with_content_provider_and_receiver(
  12439. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12440. content_type, nullptr, progress);
  12441. }
  12442. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12443. ContentProviderWithoutLength content_provider,
  12444. const std::string &content_type,
  12445. ContentReceiver content_receiver,
  12446. DownloadProgress progress) {
  12447. return send_with_content_provider_and_receiver(
  12448. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12449. content_type, std::move(content_receiver), std::move(progress));
  12450. }
  12451. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12452. const UploadFormDataItems &items,
  12453. const FormDataProviderItems &provider_items,
  12454. UploadProgress progress) {
  12455. const auto &boundary = detail::make_multipart_data_boundary();
  12456. const auto &content_type =
  12457. detail::serialize_multipart_formdata_get_content_type(boundary);
  12458. return send_with_content_provider_and_receiver(
  12459. "POST", path, headers, nullptr, 0, nullptr,
  12460. get_multipart_content_provider(boundary, items, provider_items),
  12461. content_type, nullptr, progress);
  12462. }
  12463. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12464. const std::string &body,
  12465. const std::string &content_type,
  12466. ContentReceiver content_receiver,
  12467. DownloadProgress progress) {
  12468. Request req;
  12469. req.method = "POST";
  12470. req.path = path;
  12471. req.headers = headers;
  12472. req.body = body;
  12473. req.content_receiver =
  12474. [content_receiver](const char *data, size_t data_length,
  12475. size_t /*offset*/, size_t /*total_length*/) {
  12476. return content_receiver(data, data_length);
  12477. };
  12478. req.download_progress = std::move(progress);
  12479. if (max_timeout_msec_ > 0) {
  12480. req.start_time_ = std::chrono::steady_clock::now();
  12481. }
  12482. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12483. return send_(std::move(req));
  12484. }
  12485. inline Result ClientImpl::Put(const std::string &path) {
  12486. return Put(path, std::string(), std::string());
  12487. }
  12488. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12489. return Put(path, headers, nullptr, 0, std::string());
  12490. }
  12491. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12492. size_t content_length,
  12493. const std::string &content_type,
  12494. UploadProgress progress) {
  12495. return Put(path, Headers(), body, content_length, content_type, progress);
  12496. }
  12497. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12498. const std::string &content_type,
  12499. UploadProgress progress) {
  12500. return Put(path, Headers(), body, content_type, progress);
  12501. }
  12502. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12503. return Put(path, Headers(), params);
  12504. }
  12505. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12506. ContentProvider content_provider,
  12507. const std::string &content_type,
  12508. UploadProgress progress) {
  12509. return Put(path, Headers(), content_length, std::move(content_provider),
  12510. content_type, progress);
  12511. }
  12512. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12513. ContentProvider content_provider,
  12514. const std::string &content_type,
  12515. ContentReceiver content_receiver,
  12516. UploadProgress progress) {
  12517. return Put(path, Headers(), content_length, std::move(content_provider),
  12518. content_type, std::move(content_receiver), progress);
  12519. }
  12520. inline Result ClientImpl::Put(const std::string &path,
  12521. ContentProviderWithoutLength content_provider,
  12522. const std::string &content_type,
  12523. UploadProgress progress) {
  12524. return Put(path, Headers(), std::move(content_provider), content_type,
  12525. progress);
  12526. }
  12527. inline Result ClientImpl::Put(const std::string &path,
  12528. ContentProviderWithoutLength content_provider,
  12529. const std::string &content_type,
  12530. ContentReceiver content_receiver,
  12531. UploadProgress progress) {
  12532. return Put(path, Headers(), std::move(content_provider), content_type,
  12533. std::move(content_receiver), progress);
  12534. }
  12535. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12536. const Params &params) {
  12537. auto query = detail::params_to_query_str(params);
  12538. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12539. }
  12540. inline Result ClientImpl::Put(const std::string &path,
  12541. const UploadFormDataItems &items,
  12542. UploadProgress progress) {
  12543. return Put(path, Headers(), items, progress);
  12544. }
  12545. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12546. const UploadFormDataItems &items,
  12547. UploadProgress progress) {
  12548. const auto &boundary = detail::make_multipart_data_boundary();
  12549. const auto &content_type =
  12550. detail::serialize_multipart_formdata_get_content_type(boundary);
  12551. auto content_length = detail::get_multipart_content_length(items, boundary);
  12552. return Put(path, headers, content_length,
  12553. detail::make_multipart_content_provider(items, boundary),
  12554. content_type, progress);
  12555. }
  12556. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12557. const UploadFormDataItems &items,
  12558. const std::string &boundary,
  12559. UploadProgress progress) {
  12560. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12561. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12562. }
  12563. const auto &content_type =
  12564. detail::serialize_multipart_formdata_get_content_type(boundary);
  12565. auto content_length = detail::get_multipart_content_length(items, boundary);
  12566. return Put(path, headers, content_length,
  12567. detail::make_multipart_content_provider(items, boundary),
  12568. content_type, progress);
  12569. }
  12570. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12571. const char *body, size_t content_length,
  12572. const std::string &content_type,
  12573. UploadProgress progress) {
  12574. return send_with_content_provider_and_receiver(
  12575. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12576. content_type, nullptr, progress);
  12577. }
  12578. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12579. const std::string &body,
  12580. const std::string &content_type,
  12581. UploadProgress progress) {
  12582. return send_with_content_provider_and_receiver(
  12583. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12584. content_type, nullptr, progress);
  12585. }
  12586. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12587. size_t content_length,
  12588. ContentProvider content_provider,
  12589. const std::string &content_type,
  12590. UploadProgress progress) {
  12591. return send_with_content_provider_and_receiver(
  12592. "PUT", path, headers, nullptr, content_length,
  12593. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12594. }
  12595. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12596. size_t content_length,
  12597. ContentProvider content_provider,
  12598. const std::string &content_type,
  12599. ContentReceiver content_receiver,
  12600. UploadProgress progress) {
  12601. return send_with_content_provider_and_receiver(
  12602. "PUT", path, headers, nullptr, content_length,
  12603. std::move(content_provider), nullptr, content_type,
  12604. std::move(content_receiver), progress);
  12605. }
  12606. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12607. ContentProviderWithoutLength content_provider,
  12608. const std::string &content_type,
  12609. UploadProgress progress) {
  12610. return send_with_content_provider_and_receiver(
  12611. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12612. content_type, nullptr, progress);
  12613. }
  12614. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12615. ContentProviderWithoutLength content_provider,
  12616. const std::string &content_type,
  12617. ContentReceiver content_receiver,
  12618. UploadProgress progress) {
  12619. return send_with_content_provider_and_receiver(
  12620. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12621. content_type, std::move(content_receiver), progress);
  12622. }
  12623. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12624. const UploadFormDataItems &items,
  12625. const FormDataProviderItems &provider_items,
  12626. UploadProgress progress) {
  12627. const auto &boundary = detail::make_multipart_data_boundary();
  12628. const auto &content_type =
  12629. detail::serialize_multipart_formdata_get_content_type(boundary);
  12630. return send_with_content_provider_and_receiver(
  12631. "PUT", path, headers, nullptr, 0, nullptr,
  12632. get_multipart_content_provider(boundary, items, provider_items),
  12633. content_type, nullptr, progress);
  12634. }
  12635. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12636. const std::string &body,
  12637. const std::string &content_type,
  12638. ContentReceiver content_receiver,
  12639. DownloadProgress progress) {
  12640. Request req;
  12641. req.method = "PUT";
  12642. req.path = path;
  12643. req.headers = headers;
  12644. req.body = body;
  12645. req.content_receiver =
  12646. [content_receiver](const char *data, size_t data_length,
  12647. size_t /*offset*/, size_t /*total_length*/) {
  12648. return content_receiver(data, data_length);
  12649. };
  12650. req.download_progress = std::move(progress);
  12651. if (max_timeout_msec_ > 0) {
  12652. req.start_time_ = std::chrono::steady_clock::now();
  12653. }
  12654. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12655. return send_(std::move(req));
  12656. }
  12657. inline Result ClientImpl::Patch(const std::string &path) {
  12658. return Patch(path, std::string(), std::string());
  12659. }
  12660. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12661. UploadProgress progress) {
  12662. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12663. }
  12664. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12665. size_t content_length,
  12666. const std::string &content_type,
  12667. UploadProgress progress) {
  12668. return Patch(path, Headers(), body, content_length, content_type, progress);
  12669. }
  12670. inline Result ClientImpl::Patch(const std::string &path,
  12671. const std::string &body,
  12672. const std::string &content_type,
  12673. UploadProgress progress) {
  12674. return Patch(path, Headers(), body, content_type, progress);
  12675. }
  12676. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12677. return Patch(path, Headers(), params);
  12678. }
  12679. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12680. ContentProvider content_provider,
  12681. const std::string &content_type,
  12682. UploadProgress progress) {
  12683. return Patch(path, Headers(), content_length, std::move(content_provider),
  12684. content_type, progress);
  12685. }
  12686. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12687. ContentProvider content_provider,
  12688. const std::string &content_type,
  12689. ContentReceiver content_receiver,
  12690. UploadProgress progress) {
  12691. return Patch(path, Headers(), content_length, std::move(content_provider),
  12692. content_type, std::move(content_receiver), progress);
  12693. }
  12694. inline Result ClientImpl::Patch(const std::string &path,
  12695. ContentProviderWithoutLength content_provider,
  12696. const std::string &content_type,
  12697. UploadProgress progress) {
  12698. return Patch(path, Headers(), std::move(content_provider), content_type,
  12699. progress);
  12700. }
  12701. inline Result ClientImpl::Patch(const std::string &path,
  12702. ContentProviderWithoutLength content_provider,
  12703. const std::string &content_type,
  12704. ContentReceiver content_receiver,
  12705. UploadProgress progress) {
  12706. return Patch(path, Headers(), std::move(content_provider), content_type,
  12707. std::move(content_receiver), progress);
  12708. }
  12709. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12710. const Params &params) {
  12711. auto query = detail::params_to_query_str(params);
  12712. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12713. }
  12714. inline Result ClientImpl::Patch(const std::string &path,
  12715. const UploadFormDataItems &items,
  12716. UploadProgress progress) {
  12717. return Patch(path, Headers(), items, progress);
  12718. }
  12719. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12720. const UploadFormDataItems &items,
  12721. UploadProgress progress) {
  12722. const auto &boundary = detail::make_multipart_data_boundary();
  12723. const auto &content_type =
  12724. detail::serialize_multipart_formdata_get_content_type(boundary);
  12725. auto content_length = detail::get_multipart_content_length(items, boundary);
  12726. return Patch(path, headers, content_length,
  12727. detail::make_multipart_content_provider(items, boundary),
  12728. content_type, progress);
  12729. }
  12730. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12731. const UploadFormDataItems &items,
  12732. const std::string &boundary,
  12733. UploadProgress progress) {
  12734. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12735. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12736. }
  12737. const auto &content_type =
  12738. detail::serialize_multipart_formdata_get_content_type(boundary);
  12739. auto content_length = detail::get_multipart_content_length(items, boundary);
  12740. return Patch(path, headers, content_length,
  12741. detail::make_multipart_content_provider(items, boundary),
  12742. content_type, progress);
  12743. }
  12744. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12745. const char *body, size_t content_length,
  12746. const std::string &content_type,
  12747. UploadProgress progress) {
  12748. return send_with_content_provider_and_receiver(
  12749. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12750. content_type, nullptr, progress);
  12751. }
  12752. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12753. const std::string &body,
  12754. const std::string &content_type,
  12755. UploadProgress progress) {
  12756. return send_with_content_provider_and_receiver(
  12757. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12758. content_type, nullptr, progress);
  12759. }
  12760. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12761. size_t content_length,
  12762. ContentProvider content_provider,
  12763. const std::string &content_type,
  12764. UploadProgress progress) {
  12765. return send_with_content_provider_and_receiver(
  12766. "PATCH", path, headers, nullptr, content_length,
  12767. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12768. }
  12769. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12770. size_t content_length,
  12771. ContentProvider content_provider,
  12772. const std::string &content_type,
  12773. ContentReceiver content_receiver,
  12774. UploadProgress progress) {
  12775. return send_with_content_provider_and_receiver(
  12776. "PATCH", path, headers, nullptr, content_length,
  12777. std::move(content_provider), nullptr, content_type,
  12778. std::move(content_receiver), progress);
  12779. }
  12780. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12781. ContentProviderWithoutLength content_provider,
  12782. const std::string &content_type,
  12783. UploadProgress progress) {
  12784. return send_with_content_provider_and_receiver(
  12785. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12786. content_type, nullptr, progress);
  12787. }
  12788. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12789. ContentProviderWithoutLength content_provider,
  12790. const std::string &content_type,
  12791. ContentReceiver content_receiver,
  12792. UploadProgress progress) {
  12793. return send_with_content_provider_and_receiver(
  12794. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12795. content_type, std::move(content_receiver), progress);
  12796. }
  12797. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12798. const UploadFormDataItems &items,
  12799. const FormDataProviderItems &provider_items,
  12800. UploadProgress progress) {
  12801. const auto &boundary = detail::make_multipart_data_boundary();
  12802. const auto &content_type =
  12803. detail::serialize_multipart_formdata_get_content_type(boundary);
  12804. return send_with_content_provider_and_receiver(
  12805. "PATCH", path, headers, nullptr, 0, nullptr,
  12806. get_multipart_content_provider(boundary, items, provider_items),
  12807. content_type, nullptr, progress);
  12808. }
  12809. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12810. const std::string &body,
  12811. const std::string &content_type,
  12812. ContentReceiver content_receiver,
  12813. DownloadProgress progress) {
  12814. Request req;
  12815. req.method = "PATCH";
  12816. req.path = path;
  12817. req.headers = headers;
  12818. req.body = body;
  12819. req.content_receiver =
  12820. [content_receiver](const char *data, size_t data_length,
  12821. size_t /*offset*/, size_t /*total_length*/) {
  12822. return content_receiver(data, data_length);
  12823. };
  12824. req.download_progress = std::move(progress);
  12825. if (max_timeout_msec_ > 0) {
  12826. req.start_time_ = std::chrono::steady_clock::now();
  12827. }
  12828. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12829. return send_(std::move(req));
  12830. }
  12831. inline Result ClientImpl::Delete(const std::string &path,
  12832. DownloadProgress progress) {
  12833. return Delete(path, Headers(), std::string(), std::string(), progress);
  12834. }
  12835. inline Result ClientImpl::Delete(const std::string &path,
  12836. const Headers &headers,
  12837. DownloadProgress progress) {
  12838. return Delete(path, headers, std::string(), std::string(), progress);
  12839. }
  12840. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12841. size_t content_length,
  12842. const std::string &content_type,
  12843. DownloadProgress progress) {
  12844. return Delete(path, Headers(), body, content_length, content_type, progress);
  12845. }
  12846. inline Result ClientImpl::Delete(const std::string &path,
  12847. const std::string &body,
  12848. const std::string &content_type,
  12849. DownloadProgress progress) {
  12850. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12851. progress);
  12852. }
  12853. inline Result ClientImpl::Delete(const std::string &path,
  12854. const Headers &headers,
  12855. const std::string &body,
  12856. const std::string &content_type,
  12857. DownloadProgress progress) {
  12858. return Delete(path, headers, body.data(), body.size(), content_type,
  12859. progress);
  12860. }
  12861. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12862. DownloadProgress progress) {
  12863. return Delete(path, Headers(), params, progress);
  12864. }
  12865. inline Result ClientImpl::Delete(const std::string &path,
  12866. const Headers &headers, const Params &params,
  12867. DownloadProgress progress) {
  12868. auto query = detail::params_to_query_str(params);
  12869. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12870. progress);
  12871. }
  12872. inline Result ClientImpl::Delete(const std::string &path,
  12873. const Headers &headers, const char *body,
  12874. size_t content_length,
  12875. const std::string &content_type,
  12876. DownloadProgress progress) {
  12877. Request req;
  12878. req.method = "DELETE";
  12879. req.headers = headers;
  12880. req.path = path;
  12881. req.download_progress = std::move(progress);
  12882. if (max_timeout_msec_ > 0) {
  12883. req.start_time_ = std::chrono::steady_clock::now();
  12884. }
  12885. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12886. req.body.assign(body, content_length);
  12887. return send_(std::move(req));
  12888. }
  12889. inline Result ClientImpl::Options(const std::string &path) {
  12890. return Options(path, Headers());
  12891. }
  12892. inline Result ClientImpl::Options(const std::string &path,
  12893. const Headers &headers) {
  12894. Request req;
  12895. req.method = "OPTIONS";
  12896. req.headers = headers;
  12897. req.path = path;
  12898. if (max_timeout_msec_ > 0) {
  12899. req.start_time_ = std::chrono::steady_clock::now();
  12900. }
  12901. return send_(std::move(req));
  12902. }
  12903. inline void ClientImpl::stop() {
  12904. std::lock_guard<std::mutex> guard(socket_mutex_);
  12905. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12906. // do is to shutdown_socket, so that threads using this socket suddenly
  12907. // discover they can't read/write any more and error out. Everything else
  12908. // (closing the socket, shutting ssl down) is unsafe because these actions
  12909. // are not thread-safe.
  12910. if (socket_requests_in_flight_ > 0) {
  12911. shutdown_socket(socket_);
  12912. // Aside from that, we set a flag for the socket to be closed when we're
  12913. // done.
  12914. socket_should_be_closed_when_request_is_done_ = true;
  12915. return;
  12916. }
  12917. disconnect(/*gracefully=*/true);
  12918. }
  12919. inline std::string ClientImpl::host() const { return host_; }
  12920. inline int ClientImpl::port() const { return port_; }
  12921. inline size_t ClientImpl::is_socket_open() const {
  12922. std::lock_guard<std::mutex> guard(socket_mutex_);
  12923. return socket_.is_open();
  12924. }
  12925. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12926. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12927. connection_timeout_sec_ = sec;
  12928. connection_timeout_usec_ = usec;
  12929. }
  12930. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12931. read_timeout_sec_ = sec;
  12932. read_timeout_usec_ = usec;
  12933. }
  12934. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12935. write_timeout_sec_ = sec;
  12936. write_timeout_usec_ = usec;
  12937. }
  12938. inline void ClientImpl::set_max_timeout(time_t msec) {
  12939. max_timeout_msec_ = msec;
  12940. }
  12941. inline void ClientImpl::set_basic_auth(const std::string &username,
  12942. const std::string &password) {
  12943. basic_auth_username_ = username;
  12944. basic_auth_password_ = password;
  12945. }
  12946. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12947. bearer_token_auth_token_ = token;
  12948. }
  12949. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12950. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12951. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12952. inline void
  12953. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12954. addr_map_ = std::move(addr_map);
  12955. }
  12956. inline void ClientImpl::set_default_headers(Headers headers) {
  12957. default_headers_ = std::move(headers);
  12958. }
  12959. inline void ClientImpl::set_header_writer(
  12960. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12961. header_writer_ = writer;
  12962. }
  12963. inline void ClientImpl::set_address_family(int family) {
  12964. address_family_ = family;
  12965. }
  12966. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12967. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12968. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12969. socket_options_ = std::move(socket_options);
  12970. }
  12971. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12972. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12973. inline void ClientImpl::set_payload_max_length(size_t length) {
  12974. payload_max_length_ = length;
  12975. has_payload_max_length_ = true;
  12976. }
  12977. inline void ClientImpl::set_interface(const std::string &intf) {
  12978. interface_ = intf;
  12979. }
  12980. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12981. proxy_host_ = host;
  12982. proxy_port_ = port;
  12983. std::lock_guard<std::mutex> guard(socket_mutex_);
  12984. disconnect(/*gracefully=*/true);
  12985. }
  12986. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12987. const std::string &password) {
  12988. proxy_basic_auth_username_ = username;
  12989. proxy_basic_auth_password_ = password;
  12990. }
  12991. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12992. proxy_bearer_token_auth_token_ = token;
  12993. }
  12994. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12995. std::vector<detail::NoProxyEntry> parsed;
  12996. parsed.reserve(patterns.size());
  12997. for (const auto &p : patterns) {
  12998. auto trimmed = detail::trim_copy(p);
  12999. if (trimmed.empty()) { continue; }
  13000. detail::NoProxyEntry entry;
  13001. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  13002. parsed.push_back(std::move(entry));
  13003. }
  13004. }
  13005. no_proxy_entries_ = std::move(parsed);
  13006. std::lock_guard<std::mutex> guard(socket_mutex_);
  13007. disconnect(/*gracefully=*/true);
  13008. }
  13009. #ifdef CPPHTTPLIB_SSL_ENABLED
  13010. inline void ClientImpl::set_digest_auth(const std::string &username,
  13011. const std::string &password) {
  13012. digest_auth_username_ = username;
  13013. digest_auth_password_ = password;
  13014. }
  13015. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  13016. const std::string &ca_cert_dir_path) {
  13017. ca_cert_file_path_ = ca_cert_file_path;
  13018. ca_cert_dir_path_ = ca_cert_dir_path;
  13019. }
  13020. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  13021. const std::string &password) {
  13022. proxy_digest_auth_username_ = username;
  13023. proxy_digest_auth_password_ = password;
  13024. }
  13025. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  13026. server_certificate_verification_ = enabled;
  13027. }
  13028. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  13029. server_hostname_verification_ = enabled;
  13030. }
  13031. inline void ClientImpl::enable_system_ca(bool enabled) {
  13032. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  13033. }
  13034. #endif
  13035. inline void ClientImpl::set_logger(Logger logger) {
  13036. logger_ = std::move(logger);
  13037. }
  13038. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  13039. error_logger_ = std::move(error_logger);
  13040. }
  13041. /*
  13042. * SSL/TLS Common Implementation
  13043. */
  13044. inline ClientConnection::~ClientConnection() {
  13045. #ifdef CPPHTTPLIB_SSL_ENABLED
  13046. if (session) {
  13047. tls::shutdown(session, true);
  13048. tls::free_session(session);
  13049. session = nullptr;
  13050. }
  13051. #endif
  13052. if (sock != INVALID_SOCKET) {
  13053. detail::close_socket(sock);
  13054. sock = INVALID_SOCKET;
  13055. }
  13056. }
  13057. // Universal client implementation
  13058. inline Client::Client(const std::string &scheme_host_port)
  13059. : Client(scheme_host_port, std::string(), std::string()) {}
  13060. inline Client::Client(const std::string &scheme_host_port,
  13061. const std::string &client_cert_path,
  13062. const std::string &client_key_path) {
  13063. detail::UrlComponents uc;
  13064. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  13065. auto &scheme = uc.scheme;
  13066. #ifdef CPPHTTPLIB_SSL_ENABLED
  13067. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  13068. #else
  13069. if (!scheme.empty() && scheme != "http") {
  13070. #endif
  13071. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13072. std::string msg = "'" + scheme + "' scheme is not supported.";
  13073. throw std::invalid_argument(msg);
  13074. #endif
  13075. return;
  13076. }
  13077. auto is_ssl = scheme == "https";
  13078. auto host = std::move(uc.host);
  13079. auto port = is_ssl ? 443 : 80;
  13080. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  13081. if (is_ssl) {
  13082. #ifdef CPPHTTPLIB_SSL_ENABLED
  13083. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  13084. client_key_path);
  13085. is_ssl_ = is_ssl;
  13086. #endif
  13087. } else {
  13088. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13089. client_key_path);
  13090. }
  13091. } else {
  13092. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  13093. // if port param below changes.
  13094. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  13095. client_cert_path, client_key_path);
  13096. }
  13097. }
  13098. inline Client::Client(const std::string &host, int port)
  13099. : Client(host, port, std::string(), std::string()) {}
  13100. inline Client::Client(const std::string &host, int port,
  13101. const std::string &client_cert_path,
  13102. const std::string &client_key_path)
  13103. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13104. client_key_path)) {}
  13105. inline Client::~Client() = default;
  13106. inline bool Client::is_valid() const {
  13107. return cli_ != nullptr && cli_->is_valid();
  13108. }
  13109. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  13110. return cli_->Get(path, std::move(progress));
  13111. }
  13112. inline Result Client::Get(const std::string &path, const Headers &headers,
  13113. DownloadProgress progress) {
  13114. return cli_->Get(path, headers, std::move(progress));
  13115. }
  13116. inline Result Client::Get(const std::string &path,
  13117. ContentReceiver content_receiver,
  13118. DownloadProgress progress) {
  13119. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  13120. }
  13121. inline Result Client::Get(const std::string &path, const Headers &headers,
  13122. ContentReceiver content_receiver,
  13123. DownloadProgress progress) {
  13124. return cli_->Get(path, headers, std::move(content_receiver),
  13125. std::move(progress));
  13126. }
  13127. inline Result Client::Get(const std::string &path,
  13128. ResponseHandler response_handler,
  13129. ContentReceiver content_receiver,
  13130. DownloadProgress progress) {
  13131. return cli_->Get(path, std::move(response_handler),
  13132. std::move(content_receiver), std::move(progress));
  13133. }
  13134. inline Result Client::Get(const std::string &path, const Headers &headers,
  13135. ResponseHandler response_handler,
  13136. ContentReceiver content_receiver,
  13137. DownloadProgress progress) {
  13138. return cli_->Get(path, headers, std::move(response_handler),
  13139. std::move(content_receiver), std::move(progress));
  13140. }
  13141. inline Result Client::Get(const std::string &path, const Params &params,
  13142. DownloadProgress progress) {
  13143. return cli_->Get(path, params, std::move(progress));
  13144. }
  13145. inline Result Client::Get(const std::string &path, const Params &params,
  13146. const Headers &headers, DownloadProgress progress) {
  13147. return cli_->Get(path, params, headers, std::move(progress));
  13148. }
  13149. inline Result Client::Get(const std::string &path, const Params &params,
  13150. const Headers &headers,
  13151. ContentReceiver content_receiver,
  13152. DownloadProgress progress) {
  13153. return cli_->Get(path, params, headers, std::move(content_receiver),
  13154. std::move(progress));
  13155. }
  13156. inline Result Client::Get(const std::string &path, const Params &params,
  13157. const Headers &headers,
  13158. ResponseHandler response_handler,
  13159. ContentReceiver content_receiver,
  13160. DownloadProgress progress) {
  13161. return cli_->Get(path, params, headers, std::move(response_handler),
  13162. std::move(content_receiver), std::move(progress));
  13163. }
  13164. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  13165. inline Result Client::Head(const std::string &path, const Headers &headers) {
  13166. return cli_->Head(path, headers);
  13167. }
  13168. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  13169. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13170. return cli_->Post(path, headers);
  13171. }
  13172. inline Result Client::Post(const std::string &path, const char *body,
  13173. size_t content_length,
  13174. const std::string &content_type,
  13175. UploadProgress progress) {
  13176. return cli_->Post(path, body, content_length, content_type, progress);
  13177. }
  13178. inline Result Client::Post(const std::string &path, const Headers &headers,
  13179. const char *body, size_t content_length,
  13180. const std::string &content_type,
  13181. UploadProgress progress) {
  13182. return cli_->Post(path, headers, body, content_length, content_type,
  13183. progress);
  13184. }
  13185. inline Result Client::Post(const std::string &path, const std::string &body,
  13186. const std::string &content_type,
  13187. UploadProgress progress) {
  13188. return cli_->Post(path, body, content_type, progress);
  13189. }
  13190. inline Result Client::Post(const std::string &path, const Headers &headers,
  13191. const std::string &body,
  13192. const std::string &content_type,
  13193. UploadProgress progress) {
  13194. return cli_->Post(path, headers, body, content_type, progress);
  13195. }
  13196. inline Result Client::Post(const std::string &path, size_t content_length,
  13197. ContentProvider content_provider,
  13198. const std::string &content_type,
  13199. UploadProgress progress) {
  13200. return cli_->Post(path, content_length, std::move(content_provider),
  13201. content_type, progress);
  13202. }
  13203. inline Result Client::Post(const std::string &path, size_t content_length,
  13204. ContentProvider content_provider,
  13205. const std::string &content_type,
  13206. ContentReceiver content_receiver,
  13207. UploadProgress progress) {
  13208. return cli_->Post(path, content_length, std::move(content_provider),
  13209. content_type, std::move(content_receiver), progress);
  13210. }
  13211. inline Result Client::Post(const std::string &path,
  13212. ContentProviderWithoutLength content_provider,
  13213. const std::string &content_type,
  13214. UploadProgress progress) {
  13215. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13216. }
  13217. inline Result Client::Post(const std::string &path,
  13218. ContentProviderWithoutLength content_provider,
  13219. const std::string &content_type,
  13220. ContentReceiver content_receiver,
  13221. UploadProgress progress) {
  13222. return cli_->Post(path, std::move(content_provider), content_type,
  13223. std::move(content_receiver), progress);
  13224. }
  13225. inline Result Client::Post(const std::string &path, const Headers &headers,
  13226. size_t content_length,
  13227. ContentProvider content_provider,
  13228. const std::string &content_type,
  13229. UploadProgress progress) {
  13230. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13231. content_type, progress);
  13232. }
  13233. inline Result Client::Post(const std::string &path, const Headers &headers,
  13234. size_t content_length,
  13235. ContentProvider content_provider,
  13236. const std::string &content_type,
  13237. ContentReceiver content_receiver,
  13238. DownloadProgress progress) {
  13239. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13240. content_type, std::move(content_receiver), progress);
  13241. }
  13242. inline Result Client::Post(const std::string &path, const Headers &headers,
  13243. ContentProviderWithoutLength content_provider,
  13244. const std::string &content_type,
  13245. UploadProgress progress) {
  13246. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13247. progress);
  13248. }
  13249. inline Result Client::Post(const std::string &path, const Headers &headers,
  13250. ContentProviderWithoutLength content_provider,
  13251. const std::string &content_type,
  13252. ContentReceiver content_receiver,
  13253. DownloadProgress progress) {
  13254. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13255. std::move(content_receiver), progress);
  13256. }
  13257. inline Result Client::Post(const std::string &path, const Params &params) {
  13258. return cli_->Post(path, params);
  13259. }
  13260. inline Result Client::Post(const std::string &path, const Headers &headers,
  13261. const Params &params) {
  13262. return cli_->Post(path, headers, params);
  13263. }
  13264. inline Result Client::Post(const std::string &path,
  13265. const UploadFormDataItems &items,
  13266. UploadProgress progress) {
  13267. return cli_->Post(path, items, progress);
  13268. }
  13269. inline Result Client::Post(const std::string &path, const Headers &headers,
  13270. const UploadFormDataItems &items,
  13271. UploadProgress progress) {
  13272. return cli_->Post(path, headers, items, progress);
  13273. }
  13274. inline Result Client::Post(const std::string &path, const Headers &headers,
  13275. const UploadFormDataItems &items,
  13276. const std::string &boundary,
  13277. UploadProgress progress) {
  13278. return cli_->Post(path, headers, items, boundary, progress);
  13279. }
  13280. inline Result Client::Post(const std::string &path, const Headers &headers,
  13281. const UploadFormDataItems &items,
  13282. const FormDataProviderItems &provider_items,
  13283. UploadProgress progress) {
  13284. return cli_->Post(path, headers, items, provider_items, progress);
  13285. }
  13286. inline Result Client::Post(const std::string &path, const Headers &headers,
  13287. const std::string &body,
  13288. const std::string &content_type,
  13289. ContentReceiver content_receiver,
  13290. DownloadProgress progress) {
  13291. return cli_->Post(path, headers, body, content_type,
  13292. std::move(content_receiver), progress);
  13293. }
  13294. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13295. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13296. return cli_->Put(path, headers);
  13297. }
  13298. inline Result Client::Put(const std::string &path, const char *body,
  13299. size_t content_length,
  13300. const std::string &content_type,
  13301. UploadProgress progress) {
  13302. return cli_->Put(path, body, content_length, content_type, progress);
  13303. }
  13304. inline Result Client::Put(const std::string &path, const Headers &headers,
  13305. const char *body, size_t content_length,
  13306. const std::string &content_type,
  13307. UploadProgress progress) {
  13308. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13309. }
  13310. inline Result Client::Put(const std::string &path, const std::string &body,
  13311. const std::string &content_type,
  13312. UploadProgress progress) {
  13313. return cli_->Put(path, body, content_type, progress);
  13314. }
  13315. inline Result Client::Put(const std::string &path, const Headers &headers,
  13316. const std::string &body,
  13317. const std::string &content_type,
  13318. UploadProgress progress) {
  13319. return cli_->Put(path, headers, body, content_type, progress);
  13320. }
  13321. inline Result Client::Put(const std::string &path, size_t content_length,
  13322. ContentProvider content_provider,
  13323. const std::string &content_type,
  13324. UploadProgress progress) {
  13325. return cli_->Put(path, content_length, std::move(content_provider),
  13326. content_type, progress);
  13327. }
  13328. inline Result Client::Put(const std::string &path, size_t content_length,
  13329. ContentProvider content_provider,
  13330. const std::string &content_type,
  13331. ContentReceiver content_receiver,
  13332. UploadProgress progress) {
  13333. return cli_->Put(path, content_length, std::move(content_provider),
  13334. content_type, std::move(content_receiver), progress);
  13335. }
  13336. inline Result Client::Put(const std::string &path,
  13337. ContentProviderWithoutLength content_provider,
  13338. const std::string &content_type,
  13339. UploadProgress progress) {
  13340. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13341. }
  13342. inline Result Client::Put(const std::string &path,
  13343. ContentProviderWithoutLength content_provider,
  13344. const std::string &content_type,
  13345. ContentReceiver content_receiver,
  13346. UploadProgress progress) {
  13347. return cli_->Put(path, std::move(content_provider), content_type,
  13348. std::move(content_receiver), progress);
  13349. }
  13350. inline Result Client::Put(const std::string &path, const Headers &headers,
  13351. size_t content_length,
  13352. ContentProvider content_provider,
  13353. const std::string &content_type,
  13354. UploadProgress progress) {
  13355. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13356. content_type, progress);
  13357. }
  13358. inline Result Client::Put(const std::string &path, const Headers &headers,
  13359. size_t content_length,
  13360. ContentProvider content_provider,
  13361. const std::string &content_type,
  13362. ContentReceiver content_receiver,
  13363. UploadProgress progress) {
  13364. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13365. content_type, std::move(content_receiver), progress);
  13366. }
  13367. inline Result Client::Put(const std::string &path, const Headers &headers,
  13368. ContentProviderWithoutLength content_provider,
  13369. const std::string &content_type,
  13370. UploadProgress progress) {
  13371. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13372. progress);
  13373. }
  13374. inline Result Client::Put(const std::string &path, const Headers &headers,
  13375. ContentProviderWithoutLength content_provider,
  13376. const std::string &content_type,
  13377. ContentReceiver content_receiver,
  13378. UploadProgress progress) {
  13379. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13380. std::move(content_receiver), progress);
  13381. }
  13382. inline Result Client::Put(const std::string &path, const Params &params) {
  13383. return cli_->Put(path, params);
  13384. }
  13385. inline Result Client::Put(const std::string &path, const Headers &headers,
  13386. const Params &params) {
  13387. return cli_->Put(path, headers, params);
  13388. }
  13389. inline Result Client::Put(const std::string &path,
  13390. const UploadFormDataItems &items,
  13391. UploadProgress progress) {
  13392. return cli_->Put(path, items, progress);
  13393. }
  13394. inline Result Client::Put(const std::string &path, const Headers &headers,
  13395. const UploadFormDataItems &items,
  13396. UploadProgress progress) {
  13397. return cli_->Put(path, headers, items, progress);
  13398. }
  13399. inline Result Client::Put(const std::string &path, const Headers &headers,
  13400. const UploadFormDataItems &items,
  13401. const std::string &boundary,
  13402. UploadProgress progress) {
  13403. return cli_->Put(path, headers, items, boundary, progress);
  13404. }
  13405. inline Result Client::Put(const std::string &path, const Headers &headers,
  13406. const UploadFormDataItems &items,
  13407. const FormDataProviderItems &provider_items,
  13408. UploadProgress progress) {
  13409. return cli_->Put(path, headers, items, provider_items, progress);
  13410. }
  13411. inline Result Client::Put(const std::string &path, const Headers &headers,
  13412. const std::string &body,
  13413. const std::string &content_type,
  13414. ContentReceiver content_receiver,
  13415. DownloadProgress progress) {
  13416. return cli_->Put(path, headers, body, content_type, content_receiver,
  13417. progress);
  13418. }
  13419. inline Result Client::Patch(const std::string &path) {
  13420. return cli_->Patch(path);
  13421. }
  13422. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13423. return cli_->Patch(path, headers);
  13424. }
  13425. inline Result Client::Patch(const std::string &path, const char *body,
  13426. size_t content_length,
  13427. const std::string &content_type,
  13428. UploadProgress progress) {
  13429. return cli_->Patch(path, body, content_length, content_type, progress);
  13430. }
  13431. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13432. const char *body, size_t content_length,
  13433. const std::string &content_type,
  13434. UploadProgress progress) {
  13435. return cli_->Patch(path, headers, body, content_length, content_type,
  13436. progress);
  13437. }
  13438. inline Result Client::Patch(const std::string &path, const std::string &body,
  13439. const std::string &content_type,
  13440. UploadProgress progress) {
  13441. return cli_->Patch(path, body, content_type, progress);
  13442. }
  13443. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13444. const std::string &body,
  13445. const std::string &content_type,
  13446. UploadProgress progress) {
  13447. return cli_->Patch(path, headers, body, content_type, progress);
  13448. }
  13449. inline Result Client::Patch(const std::string &path, size_t content_length,
  13450. ContentProvider content_provider,
  13451. const std::string &content_type,
  13452. UploadProgress progress) {
  13453. return cli_->Patch(path, content_length, std::move(content_provider),
  13454. content_type, progress);
  13455. }
  13456. inline Result Client::Patch(const std::string &path, size_t content_length,
  13457. ContentProvider content_provider,
  13458. const std::string &content_type,
  13459. ContentReceiver content_receiver,
  13460. UploadProgress progress) {
  13461. return cli_->Patch(path, content_length, std::move(content_provider),
  13462. content_type, std::move(content_receiver), progress);
  13463. }
  13464. inline Result Client::Patch(const std::string &path,
  13465. ContentProviderWithoutLength content_provider,
  13466. const std::string &content_type,
  13467. UploadProgress progress) {
  13468. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13469. }
  13470. inline Result Client::Patch(const std::string &path,
  13471. ContentProviderWithoutLength content_provider,
  13472. const std::string &content_type,
  13473. ContentReceiver content_receiver,
  13474. UploadProgress progress) {
  13475. return cli_->Patch(path, std::move(content_provider), content_type,
  13476. std::move(content_receiver), progress);
  13477. }
  13478. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13479. size_t content_length,
  13480. ContentProvider content_provider,
  13481. const std::string &content_type,
  13482. UploadProgress progress) {
  13483. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13484. content_type, progress);
  13485. }
  13486. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13487. size_t content_length,
  13488. ContentProvider content_provider,
  13489. const std::string &content_type,
  13490. ContentReceiver content_receiver,
  13491. UploadProgress progress) {
  13492. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13493. content_type, std::move(content_receiver), progress);
  13494. }
  13495. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13496. ContentProviderWithoutLength content_provider,
  13497. const std::string &content_type,
  13498. UploadProgress progress) {
  13499. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13500. progress);
  13501. }
  13502. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13503. ContentProviderWithoutLength content_provider,
  13504. const std::string &content_type,
  13505. ContentReceiver content_receiver,
  13506. UploadProgress progress) {
  13507. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13508. std::move(content_receiver), progress);
  13509. }
  13510. inline Result Client::Patch(const std::string &path, const Params &params) {
  13511. return cli_->Patch(path, params);
  13512. }
  13513. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13514. const Params &params) {
  13515. return cli_->Patch(path, headers, params);
  13516. }
  13517. inline Result Client::Patch(const std::string &path,
  13518. const UploadFormDataItems &items,
  13519. UploadProgress progress) {
  13520. return cli_->Patch(path, items, progress);
  13521. }
  13522. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13523. const UploadFormDataItems &items,
  13524. UploadProgress progress) {
  13525. return cli_->Patch(path, headers, items, progress);
  13526. }
  13527. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13528. const UploadFormDataItems &items,
  13529. const std::string &boundary,
  13530. UploadProgress progress) {
  13531. return cli_->Patch(path, headers, items, boundary, progress);
  13532. }
  13533. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13534. const UploadFormDataItems &items,
  13535. const FormDataProviderItems &provider_items,
  13536. UploadProgress progress) {
  13537. return cli_->Patch(path, headers, items, provider_items, progress);
  13538. }
  13539. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13540. const std::string &body,
  13541. const std::string &content_type,
  13542. ContentReceiver content_receiver,
  13543. DownloadProgress progress) {
  13544. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13545. progress);
  13546. }
  13547. inline Result Client::Delete(const std::string &path,
  13548. DownloadProgress progress) {
  13549. return cli_->Delete(path, progress);
  13550. }
  13551. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13552. DownloadProgress progress) {
  13553. return cli_->Delete(path, headers, progress);
  13554. }
  13555. inline Result Client::Delete(const std::string &path, const char *body,
  13556. size_t content_length,
  13557. const std::string &content_type,
  13558. DownloadProgress progress) {
  13559. return cli_->Delete(path, body, content_length, content_type, progress);
  13560. }
  13561. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13562. const char *body, size_t content_length,
  13563. const std::string &content_type,
  13564. DownloadProgress progress) {
  13565. return cli_->Delete(path, headers, body, content_length, content_type,
  13566. progress);
  13567. }
  13568. inline Result Client::Delete(const std::string &path, const std::string &body,
  13569. const std::string &content_type,
  13570. DownloadProgress progress) {
  13571. return cli_->Delete(path, body, content_type, progress);
  13572. }
  13573. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13574. const std::string &body,
  13575. const std::string &content_type,
  13576. DownloadProgress progress) {
  13577. return cli_->Delete(path, headers, body, content_type, progress);
  13578. }
  13579. inline Result Client::Delete(const std::string &path, const Params &params,
  13580. DownloadProgress progress) {
  13581. return cli_->Delete(path, params, progress);
  13582. }
  13583. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13584. const Params &params, DownloadProgress progress) {
  13585. return cli_->Delete(path, headers, params, progress);
  13586. }
  13587. inline Result Client::Options(const std::string &path) {
  13588. return cli_->Options(path);
  13589. }
  13590. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13591. return cli_->Options(path, headers);
  13592. }
  13593. inline ClientImpl::StreamHandle
  13594. Client::open_stream(const std::string &method, const std::string &path,
  13595. const Params &params, const Headers &headers,
  13596. const std::string &body, const std::string &content_type) {
  13597. return cli_->open_stream(method, path, params, headers, body, content_type);
  13598. }
  13599. inline bool Client::send(Request &req, Response &res, Error &error) {
  13600. return cli_->send(req, res, error);
  13601. }
  13602. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13603. inline void Client::stop() { cli_->stop(); }
  13604. inline std::string Client::host() const { return cli_->host(); }
  13605. inline int Client::port() const { return cli_->port(); }
  13606. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13607. inline socket_t Client::socket() const { return cli_->socket(); }
  13608. inline void
  13609. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13610. cli_->set_hostname_addr_map(std::move(addr_map));
  13611. }
  13612. inline void Client::set_default_headers(Headers headers) {
  13613. cli_->set_default_headers(std::move(headers));
  13614. }
  13615. inline void Client::set_header_writer(
  13616. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13617. cli_->set_header_writer(writer);
  13618. }
  13619. inline void Client::set_address_family(int family) {
  13620. cli_->set_address_family(family);
  13621. }
  13622. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13623. inline void Client::set_socket_options(SocketOptions socket_options) {
  13624. cli_->set_socket_options(std::move(socket_options));
  13625. }
  13626. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13627. cli_->set_connection_timeout(sec, usec);
  13628. }
  13629. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13630. cli_->set_read_timeout(sec, usec);
  13631. }
  13632. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13633. cli_->set_write_timeout(sec, usec);
  13634. }
  13635. inline void Client::set_basic_auth(const std::string &username,
  13636. const std::string &password) {
  13637. cli_->set_basic_auth(username, password);
  13638. }
  13639. inline void Client::set_bearer_token_auth(const std::string &token) {
  13640. cli_->set_bearer_token_auth(token);
  13641. }
  13642. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13643. inline void Client::set_follow_location(bool on) {
  13644. cli_->set_follow_location(on);
  13645. }
  13646. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13647. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13648. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13649. inline void Client::set_payload_max_length(size_t length) {
  13650. cli_->set_payload_max_length(length);
  13651. }
  13652. inline void Client::set_interface(const std::string &intf) {
  13653. cli_->set_interface(intf);
  13654. }
  13655. inline void Client::set_proxy(const std::string &host, int port) {
  13656. cli_->set_proxy(host, port);
  13657. }
  13658. inline void Client::set_proxy_basic_auth(const std::string &username,
  13659. const std::string &password) {
  13660. cli_->set_proxy_basic_auth(username, password);
  13661. }
  13662. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13663. cli_->set_proxy_bearer_token_auth(token);
  13664. }
  13665. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13666. cli_->set_no_proxy(patterns);
  13667. }
  13668. inline void Client::set_logger(Logger logger) {
  13669. cli_->set_logger(std::move(logger));
  13670. }
  13671. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13672. cli_->set_error_logger(std::move(error_logger));
  13673. }
  13674. /*
  13675. * Group 6: SSL Server and Client implementation
  13676. */
  13677. #ifdef CPPHTTPLIB_SSL_ENABLED
  13678. // SSL HTTP server implementation
  13679. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13680. const char *client_ca_cert_file_path,
  13681. const char *client_ca_cert_dir_path,
  13682. const char *private_key_password) {
  13683. using namespace tls;
  13684. ctx_ = create_server_context();
  13685. if (!ctx_) { return; }
  13686. // Load server certificate and private key
  13687. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13688. private_key_password)) {
  13689. last_ssl_error_ = static_cast<int>(get_error());
  13690. free_context(ctx_);
  13691. ctx_ = nullptr;
  13692. return;
  13693. }
  13694. // Load client CA certificates for client authentication
  13695. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13696. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13697. client_ca_cert_dir_path)) {
  13698. last_ssl_error_ = static_cast<int>(get_error());
  13699. free_context(ctx_);
  13700. ctx_ = nullptr;
  13701. return;
  13702. }
  13703. // Enable client certificate verification
  13704. set_verify_client(ctx_, true);
  13705. }
  13706. }
  13707. inline SSLServer::SSLServer(const PemMemory &pem) {
  13708. using namespace tls;
  13709. ctx_ = create_server_context();
  13710. if (ctx_) {
  13711. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13712. pem.private_key_password)) {
  13713. last_ssl_error_ = static_cast<int>(get_error());
  13714. free_context(ctx_);
  13715. ctx_ = nullptr;
  13716. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13717. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13718. last_ssl_error_ = static_cast<int>(get_error());
  13719. free_context(ctx_);
  13720. ctx_ = nullptr;
  13721. } else {
  13722. set_verify_client(ctx_, true);
  13723. }
  13724. }
  13725. }
  13726. }
  13727. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13728. using namespace tls;
  13729. ctx_ = create_server_context();
  13730. if (ctx_) {
  13731. if (!setup_callback(ctx_)) {
  13732. free_context(ctx_);
  13733. ctx_ = nullptr;
  13734. }
  13735. }
  13736. }
  13737. inline SSLServer::~SSLServer() {
  13738. if (ctx_) { tls::free_context(ctx_); }
  13739. }
  13740. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13741. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13742. using namespace tls;
  13743. // Create TLS session with mutex protection
  13744. session_t session = nullptr;
  13745. {
  13746. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13747. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13748. }
  13749. if (!session) {
  13750. last_ssl_error_ = static_cast<int>(get_error());
  13751. detail::shutdown_socket(sock);
  13752. detail::close_socket(sock);
  13753. return false;
  13754. }
  13755. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13756. bool handshake_done = false;
  13757. bool ret = false;
  13758. bool websocket_upgraded = false;
  13759. auto cleanup = detail::scope_exit([&] {
  13760. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13761. free_session(session);
  13762. detail::shutdown_socket(sock);
  13763. detail::close_socket(sock);
  13764. });
  13765. // Perform TLS accept handshake with timeout
  13766. TlsError tls_err;
  13767. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13768. &tls_err)) {
  13769. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13770. // Map TlsError to legacy ssl_error for backward compatibility
  13771. if (tls_err.code == ErrorCode::WantRead) {
  13772. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13773. } else if (tls_err.code == ErrorCode::WantWrite) {
  13774. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13775. } else {
  13776. last_ssl_error_ = SSL_ERROR_SSL;
  13777. }
  13778. #else
  13779. last_ssl_error_ = static_cast<int>(get_error());
  13780. #endif
  13781. return false;
  13782. }
  13783. handshake_done = true;
  13784. std::string remote_addr;
  13785. int remote_port = 0;
  13786. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13787. std::string local_addr;
  13788. int local_port = 0;
  13789. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13790. ret = detail::process_server_socket_ssl(
  13791. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13792. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13793. write_timeout_usec_,
  13794. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13795. return process_request(
  13796. strm, remote_addr, remote_port, local_addr, local_port,
  13797. close_connection, connection_closed,
  13798. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13799. });
  13800. return ret;
  13801. }
  13802. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13803. const char *key_pem,
  13804. const char *client_ca_pem,
  13805. const char *password) {
  13806. if (!ctx_) { return false; }
  13807. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13808. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13809. return false;
  13810. }
  13811. if (client_ca_pem) {
  13812. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13813. }
  13814. return true;
  13815. }
  13816. // SSL HTTP client implementation
  13817. inline SSLClient::~SSLClient() {
  13818. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13819. // base function rather than the derived function once we get to the
  13820. // base class destructor, and won't free the SSL (causing a leak).
  13821. // This must happen before the context is freed below: some backends
  13822. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  13823. // context, so freeing the context first leaves close_notify reading
  13824. // freed memory.
  13825. shutdown_ssl_impl(socket_, true);
  13826. if (ctx_) {
  13827. tls::free_context(ctx_);
  13828. ctx_ = nullptr;
  13829. }
  13830. }
  13831. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13832. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13833. shutdown_ssl_impl(socket, shutdown_gracefully);
  13834. }
  13835. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13836. bool shutdown_gracefully) {
  13837. if (socket.sock == INVALID_SOCKET) {
  13838. assert(socket.ssl == nullptr);
  13839. return;
  13840. }
  13841. if (socket.ssl) {
  13842. tls::shutdown(socket.ssl, shutdown_gracefully);
  13843. {
  13844. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13845. tls::free_session(socket.ssl);
  13846. }
  13847. socket.ssl = nullptr;
  13848. }
  13849. assert(socket.ssl == nullptr);
  13850. }
  13851. inline bool SSLClient::process_socket(
  13852. const Socket &socket,
  13853. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13854. std::function<bool(Stream &strm)> callback) {
  13855. assert(socket.ssl);
  13856. return detail::process_client_socket_ssl(
  13857. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13858. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13859. std::move(callback));
  13860. }
  13861. inline bool SSLClient::is_ssl() const { return true; }
  13862. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13863. if (!is_valid()) {
  13864. error = Error::SSLConnection;
  13865. return false;
  13866. }
  13867. return ClientImpl::create_and_connect_socket(socket, error);
  13868. }
  13869. inline bool SSLClient::setup_proxy_connection(
  13870. Socket &socket,
  13871. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13872. Response &res, bool &success, Error &error) {
  13873. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13874. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13875. return false;
  13876. }
  13877. if (!initialize_ssl(socket, error)) {
  13878. success = false;
  13879. return false;
  13880. }
  13881. return true;
  13882. }
  13883. // Assumes that socket_mutex_ is locked and that there are no requests in
  13884. // flight
  13885. inline bool SSLClient::connect_with_proxy(
  13886. Socket &socket,
  13887. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13888. Response &res, bool &success, Error &error) {
  13889. success = true;
  13890. Response proxy_res;
  13891. if (!detail::process_client_socket(
  13892. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13893. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13894. start_time, [&](Stream &strm) {
  13895. Request req2;
  13896. req2.method = "CONNECT";
  13897. req2.path =
  13898. detail::make_host_and_port_string_always_port(host_, port_);
  13899. if (max_timeout_msec_ > 0) {
  13900. req2.start_time_ = std::chrono::steady_clock::now();
  13901. }
  13902. return process_request(strm, req2, proxy_res, false, error);
  13903. })) {
  13904. // Thread-safe to close everything because we are assuming there are no
  13905. // requests in flight
  13906. shutdown_ssl(socket, true);
  13907. shutdown_socket(socket);
  13908. close_socket(socket);
  13909. success = false;
  13910. return false;
  13911. }
  13912. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13913. if (!proxy_digest_auth_username_.empty() &&
  13914. !proxy_digest_auth_password_.empty()) {
  13915. std::map<std::string, std::string> auth;
  13916. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13917. // Close the current socket and create a new one for the authenticated
  13918. // request
  13919. shutdown_ssl(socket, true);
  13920. shutdown_socket(socket);
  13921. close_socket(socket);
  13922. // Create a new socket for the authenticated CONNECT request
  13923. if (!ensure_socket_connection(socket, error)) {
  13924. success = false;
  13925. output_error_log(error, nullptr);
  13926. return false;
  13927. }
  13928. proxy_res = Response();
  13929. if (!detail::process_client_socket(
  13930. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13931. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13932. start_time, [&](Stream &strm) {
  13933. Request req3;
  13934. req3.method = "CONNECT";
  13935. req3.path = detail::make_host_and_port_string_always_port(
  13936. host_, port_);
  13937. req3.headers.insert(detail::make_digest_authentication_header(
  13938. req3, auth, 1, detail::random_string(10),
  13939. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13940. true));
  13941. if (max_timeout_msec_ > 0) {
  13942. req3.start_time_ = std::chrono::steady_clock::now();
  13943. }
  13944. return process_request(strm, req3, proxy_res, false, error);
  13945. })) {
  13946. // Thread-safe to close everything because we are assuming there are
  13947. // no requests in flight
  13948. shutdown_ssl(socket, true);
  13949. shutdown_socket(socket);
  13950. close_socket(socket);
  13951. success = false;
  13952. return false;
  13953. }
  13954. }
  13955. }
  13956. }
  13957. // If status code is not 200, proxy request is failed.
  13958. // Set error to ProxyConnection and return proxy response
  13959. // as the response of the request
  13960. if (proxy_res.status != StatusCode::OK_200) {
  13961. error = Error::ProxyConnection;
  13962. output_error_log(error, nullptr);
  13963. res = std::move(proxy_res);
  13964. // Thread-safe to close everything because we are assuming there are
  13965. // no requests in flight
  13966. shutdown_ssl(socket, true);
  13967. shutdown_socket(socket);
  13968. close_socket(socket);
  13969. return false;
  13970. }
  13971. return true;
  13972. }
  13973. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13974. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13975. if (is_proxy_enabled_for_host(host_)) { return true; }
  13976. if (!initialize_ssl(socket, error)) {
  13977. shutdown_socket(socket);
  13978. close_socket(socket);
  13979. return false;
  13980. }
  13981. return true;
  13982. }
  13983. // SSL HTTP client implementation
  13984. inline SSLClient::SSLClient(const std::string &host)
  13985. : SSLClient(host, 443, std::string(), std::string()) {}
  13986. inline SSLClient::SSLClient(const std::string &host, int port)
  13987. : SSLClient(host, port, std::string(), std::string()) {}
  13988. inline void SSLClient::init_ctx() {
  13989. ctx_ = tls::create_client_context();
  13990. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13991. }
  13992. inline void SSLClient::reset_ctx_on_error() {
  13993. last_backend_error_ = tls::get_error();
  13994. tls::free_context(ctx_);
  13995. ctx_ = nullptr;
  13996. }
  13997. inline SSLClient::SSLClient(const std::string &host, int port,
  13998. const std::string &client_cert_path,
  13999. const std::string &client_key_path,
  14000. const std::string &private_key_password)
  14001. : ClientImpl(host, port, client_cert_path, client_key_path) {
  14002. init_ctx();
  14003. if (!ctx_) { return; }
  14004. if (!client_cert_path.empty() && !client_key_path.empty()) {
  14005. const char *password =
  14006. private_key_password.empty() ? nullptr : private_key_password.c_str();
  14007. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  14008. client_key_path.c_str(), password)) {
  14009. reset_ctx_on_error();
  14010. }
  14011. }
  14012. }
  14013. inline SSLClient::SSLClient(const std::string &host, int port,
  14014. const PemMemory &pem)
  14015. : ClientImpl(host, port) {
  14016. init_ctx();
  14017. if (!ctx_) { return; }
  14018. if (pem.cert_pem && pem.key_pem) {
  14019. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  14020. pem.private_key_password)) {
  14021. reset_ctx_on_error();
  14022. }
  14023. }
  14024. }
  14025. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14026. if (ca_cert_store && ctx_) {
  14027. // set_ca_store takes ownership of ca_cert_store
  14028. tls::set_ca_store(ctx_, ca_cert_store);
  14029. ca_cert_store_set_ = true;
  14030. } else if (ca_cert_store) {
  14031. tls::free_ca_store(ca_cert_store);
  14032. }
  14033. }
  14034. inline void
  14035. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14036. if (!ctx_) { return; }
  14037. tls::set_verify_callback(ctx_, verifier);
  14038. }
  14039. inline void SSLClient::set_session_verifier(
  14040. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14041. session_verifier_ = std::move(verifier);
  14042. }
  14043. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14044. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  14045. enable_windows_cert_verification_ = enabled;
  14046. }
  14047. #endif
  14048. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  14049. std::size_t size) {
  14050. if (ctx_ && ca_cert && size > 0) {
  14051. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  14052. tls::load_ca_pem(ctx_, ca_cert, size);
  14053. }
  14054. }
  14055. inline bool SSLClient::load_certs() {
  14056. auto ret = true;
  14057. std::call_once(initialize_cert_, [&]() {
  14058. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14059. ret = detail::load_client_ca_config(
  14060. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  14061. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  14062. last_backend_error_);
  14063. });
  14064. return ret;
  14065. }
  14066. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  14067. using namespace tls;
  14068. // Load CA certificates if server verification is enabled
  14069. if (server_certificate_verification_) {
  14070. if (!load_certs()) {
  14071. error = Error::SSLLoadingCerts;
  14072. output_error_log(error, nullptr);
  14073. return false;
  14074. }
  14075. }
  14076. bool is_ip = detail::is_ip_address(host_);
  14077. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  14078. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  14079. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  14080. // Chain verification happens during the handshake even for IP hosts; the
  14081. // certificate identity is verified post-handshake via verify_hostname().
  14082. set_verify_client(ctx_, server_certificate_verification_);
  14083. #endif
  14084. // Create TLS session
  14085. session_t session = nullptr;
  14086. {
  14087. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14088. session = create_session(ctx_, socket.sock);
  14089. }
  14090. if (!session) {
  14091. error = Error::SSLConnection;
  14092. last_backend_error_ = get_error();
  14093. return false;
  14094. }
  14095. // Use scope_exit to ensure session is freed on error paths
  14096. bool success = false;
  14097. auto session_guard = detail::scope_exit([&] {
  14098. if (!success) { free_session(session); }
  14099. });
  14100. // Set SNI extension (skip for IP addresses per RFC 6066).
  14101. // On MbedTLS, set_sni also enables hostname verification internally.
  14102. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  14103. if (!is_ip) {
  14104. if (!set_sni(session, host_.c_str())) {
  14105. error = Error::SSLConnection;
  14106. last_backend_error_ = get_error();
  14107. return false;
  14108. }
  14109. }
  14110. // Perform non-blocking TLS handshake with timeout
  14111. TlsError tls_err;
  14112. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  14113. connection_timeout_usec_, &tls_err)) {
  14114. last_ssl_error_ = static_cast<int>(tls_err.code);
  14115. last_backend_error_ = tls_err.backend_code;
  14116. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  14117. error = Error::SSLServerVerification;
  14118. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  14119. error = Error::SSLServerHostnameVerification;
  14120. } else {
  14121. error = Error::SSLConnection;
  14122. }
  14123. output_error_log(error, nullptr);
  14124. return false;
  14125. }
  14126. // Post-handshake session verifier callback
  14127. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  14128. if (session_verifier_) { verification_status = session_verifier_(session); }
  14129. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  14130. last_backend_error_ = get_error();
  14131. error = Error::SSLServerVerification;
  14132. output_error_log(error, nullptr);
  14133. return false;
  14134. }
  14135. // Default server certificate verification
  14136. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  14137. server_certificate_verification_) {
  14138. verify_result_ = tls::get_verify_result(session);
  14139. if (verify_result_ != 0) {
  14140. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  14141. error = Error::SSLServerVerification;
  14142. output_error_log(error, nullptr);
  14143. return false;
  14144. }
  14145. auto server_cert = get_peer_cert(session);
  14146. if (!server_cert) {
  14147. last_backend_error_ = get_error();
  14148. error = Error::SSLServerVerification;
  14149. output_error_log(error, nullptr);
  14150. return false;
  14151. }
  14152. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  14153. // Hostname verification (post-handshake for all cases).
  14154. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  14155. // On MbedTLS, set_sni already enabled hostname verification during
  14156. // handshake for non-IP hosts, but this check is still needed for IP
  14157. // addresses where SNI is not set.
  14158. if (server_hostname_verification_) {
  14159. if (!verify_hostname(server_cert, host_.c_str())) {
  14160. last_backend_error_ = hostname_mismatch_code();
  14161. error = Error::SSLServerHostnameVerification;
  14162. output_error_log(error, nullptr);
  14163. return false;
  14164. }
  14165. }
  14166. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14167. // Additional Windows Schannel verification.
  14168. // This provides real-time certificate validation with Windows Update
  14169. // integration, working with both OpenSSL and MbedTLS backends.
  14170. // Skip when a custom CA cert is specified, as the Windows certificate
  14171. // store would not know about user-provided CA certificates. Also skip
  14172. // when system CA trust is explicitly disabled.
  14173. if (enable_windows_cert_verification_ &&
  14174. system_ca_mode_ != SystemCAMode::Disabled &&
  14175. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  14176. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  14177. std::vector<unsigned char> der;
  14178. if (get_cert_der(server_cert, der)) {
  14179. uint64_t wincrypt_error = 0;
  14180. if (!detail::verify_cert_with_windows_schannel(
  14181. der, host_, server_hostname_verification_, wincrypt_error)) {
  14182. last_backend_error_ = wincrypt_error;
  14183. error = Error::SSLServerVerification;
  14184. output_error_log(error, nullptr);
  14185. return false;
  14186. }
  14187. }
  14188. }
  14189. #endif
  14190. }
  14191. success = true;
  14192. socket.ssl = session;
  14193. return true;
  14194. }
  14195. inline void Client::set_digest_auth(const std::string &username,
  14196. const std::string &password) {
  14197. cli_->set_digest_auth(username, password);
  14198. }
  14199. inline void Client::set_proxy_digest_auth(const std::string &username,
  14200. const std::string &password) {
  14201. cli_->set_proxy_digest_auth(username, password);
  14202. }
  14203. inline void Client::enable_server_certificate_verification(bool enabled) {
  14204. cli_->enable_server_certificate_verification(enabled);
  14205. }
  14206. inline void Client::enable_server_hostname_verification(bool enabled) {
  14207. cli_->enable_server_hostname_verification(enabled);
  14208. }
  14209. inline void Client::enable_system_ca(bool enabled) {
  14210. cli_->enable_system_ca(enabled);
  14211. }
  14212. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14213. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14214. if (is_ssl_) {
  14215. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14216. enabled);
  14217. }
  14218. }
  14219. #endif
  14220. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14221. const std::string &ca_cert_dir_path) {
  14222. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14223. }
  14224. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14225. if (is_ssl_) {
  14226. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14227. } else if (ca_cert_store) {
  14228. tls::free_ca_store(ca_cert_store);
  14229. }
  14230. }
  14231. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14232. if (is_ssl_) {
  14233. // Use the PEM-based path so the CA data is retained for redirect transfer
  14234. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14235. }
  14236. }
  14237. inline void
  14238. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14239. if (is_ssl_) {
  14240. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14241. std::move(verifier));
  14242. }
  14243. }
  14244. inline void Client::set_session_verifier(
  14245. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14246. if (is_ssl_) {
  14247. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14248. }
  14249. }
  14250. inline tls::ctx_t Client::tls_context() const {
  14251. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14252. return nullptr;
  14253. }
  14254. #endif // CPPHTTPLIB_SSL_ENABLED
  14255. /*
  14256. * Group 7: TLS abstraction layer - Common API
  14257. */
  14258. #ifdef CPPHTTPLIB_SSL_ENABLED
  14259. namespace tls {
  14260. // Helper for PeerCert construction
  14261. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14262. return PeerCert(get_peer_cert(session));
  14263. }
  14264. namespace impl {
  14265. inline VerifyCallback &get_verify_callback() {
  14266. static thread_local VerifyCallback callback;
  14267. return callback;
  14268. }
  14269. inline VerifyCallback &get_mbedtls_verify_callback() {
  14270. static thread_local VerifyCallback callback;
  14271. return callback;
  14272. }
  14273. // Check if a string is an IPv4 address
  14274. inline bool is_ipv4_address(const std::string &str) {
  14275. int dots = 0;
  14276. for (char c : str) {
  14277. if (c == '.') {
  14278. dots++;
  14279. } else if (!detail::is_ascii_digit(c)) {
  14280. return false;
  14281. }
  14282. }
  14283. return dots == 3;
  14284. }
  14285. // Parse IPv4 address string to bytes
  14286. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14287. const char *p = str.c_str();
  14288. for (int i = 0; i < 4; i++) {
  14289. if (i > 0) {
  14290. if (*p != '.') { return false; }
  14291. p++;
  14292. }
  14293. int val = 0;
  14294. int digits = 0;
  14295. while (detail::is_ascii_digit(*p)) {
  14296. val = val * 10 + (*p - '0');
  14297. if (val > 255) { return false; }
  14298. p++;
  14299. digits++;
  14300. }
  14301. if (digits == 0) { return false; }
  14302. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14303. if (digits > 1 && *(p - digits) == '0') { return false; }
  14304. out[i] = static_cast<unsigned char>(val);
  14305. }
  14306. return *p == '\0';
  14307. }
  14308. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14309. // `out` must have room for at least 16 bytes. Returns the address length
  14310. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14311. // literal. Used to match a host against iPAddress SANs the same way the
  14312. // OpenSSL backend does via X509_check_ip.
  14313. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14314. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14315. struct in6_addr addr6 = {};
  14316. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14317. memcpy(out, &addr6, 16);
  14318. return 16;
  14319. }
  14320. return 0;
  14321. }
  14322. #ifdef _WIN32
  14323. // Enumerate Windows system certificates and call callback with DER data
  14324. template <typename Callback>
  14325. inline bool enumerate_windows_system_certs(Callback cb) {
  14326. bool loaded = false;
  14327. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14328. for (auto store_name : store_names) {
  14329. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14330. if (hStore) {
  14331. PCCERT_CONTEXT pContext = nullptr;
  14332. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14333. nullptr) {
  14334. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14335. loaded = true;
  14336. }
  14337. }
  14338. CertCloseStore(hStore, 0);
  14339. }
  14340. }
  14341. return loaded;
  14342. }
  14343. #endif
  14344. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14345. // Enumerate macOS Keychain certificates and call callback with DER data
  14346. template <typename Callback>
  14347. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14348. bool loaded = false;
  14349. const SecTrustSettingsDomain domains[] = {
  14350. kSecTrustSettingsDomainSystem,
  14351. kSecTrustSettingsDomainAdmin,
  14352. kSecTrustSettingsDomainUser,
  14353. };
  14354. for (auto domain : domains) {
  14355. CFArrayRef certs = nullptr;
  14356. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14357. if (status != errSecSuccess || !certs) {
  14358. if (certs) CFRelease(certs);
  14359. continue;
  14360. }
  14361. CFIndex count = CFArrayGetCount(certs);
  14362. for (CFIndex i = 0; i < count; i++) {
  14363. SecCertificateRef cert =
  14364. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14365. CFDataRef data = SecCertificateCopyData(cert);
  14366. if (data) {
  14367. if (cb(CFDataGetBytePtr(data),
  14368. static_cast<size_t>(CFDataGetLength(data)))) {
  14369. loaded = true;
  14370. }
  14371. CFRelease(data);
  14372. }
  14373. }
  14374. CFRelease(certs);
  14375. }
  14376. return loaded;
  14377. }
  14378. #endif
  14379. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14380. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14381. // Common CA certificate file paths on Linux/Unix
  14382. inline const char **system_ca_paths() {
  14383. static const char *paths[] = {
  14384. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14385. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14386. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14387. "/etc/pki/tls/cacert.pem", // OpenELEC
  14388. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14389. nullptr};
  14390. return paths;
  14391. }
  14392. // Common CA certificate directory paths on Linux/Unix
  14393. inline const char **system_ca_dirs() {
  14394. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14395. "/etc/pki/tls/certs", // RHEL/CentOS
  14396. "/usr/share/ca-certificates", // Other
  14397. nullptr};
  14398. return dirs;
  14399. }
  14400. #endif
  14401. } // namespace impl
  14402. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14403. const char *ca_dir) {
  14404. if (!ctx) { return false; }
  14405. bool success = true;
  14406. if (ca_file && *ca_file) {
  14407. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14408. }
  14409. if (ca_dir && *ca_dir) {
  14410. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14411. }
  14412. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14413. // Set CA list for client certificate request (CertificateRequest message)
  14414. if (ca_file && *ca_file) {
  14415. auto list = SSL_load_client_CA_file(ca_file);
  14416. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14417. }
  14418. #endif
  14419. return success;
  14420. }
  14421. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14422. const char *password) {
  14423. return set_client_cert_pem(ctx, cert, key, password);
  14424. }
  14425. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14426. const char *key_path, const char *password) {
  14427. return set_client_cert_file(ctx, cert_path, key_path, password);
  14428. }
  14429. // PeerCert implementation
  14430. inline PeerCert::PeerCert() = default;
  14431. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14432. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14433. other.cert_ = nullptr;
  14434. }
  14435. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14436. if (this != &other) {
  14437. if (cert_) { free_cert(cert_); }
  14438. cert_ = other.cert_;
  14439. other.cert_ = nullptr;
  14440. }
  14441. return *this;
  14442. }
  14443. inline PeerCert::~PeerCert() {
  14444. if (cert_) { free_cert(cert_); }
  14445. }
  14446. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14447. inline std::string PeerCert::subject_cn() const {
  14448. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14449. }
  14450. inline std::string PeerCert::issuer_name() const {
  14451. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14452. }
  14453. inline bool PeerCert::check_hostname(const char *hostname) const {
  14454. return cert_ ? verify_hostname(cert_, hostname) : false;
  14455. }
  14456. inline std::vector<SanEntry> PeerCert::sans() const {
  14457. std::vector<SanEntry> result;
  14458. if (cert_) { get_cert_sans(cert_, result); }
  14459. return result;
  14460. }
  14461. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14462. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14463. }
  14464. inline std::string PeerCert::serial() const {
  14465. return cert_ ? get_cert_serial(cert_) : std::string();
  14466. }
  14467. // VerifyContext method implementations
  14468. inline std::string VerifyContext::subject_cn() const {
  14469. return cert ? get_cert_subject_cn(cert) : std::string();
  14470. }
  14471. inline std::string VerifyContext::issuer_name() const {
  14472. return cert ? get_cert_issuer_name(cert) : std::string();
  14473. }
  14474. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14475. return cert ? verify_hostname(cert, hostname) : false;
  14476. }
  14477. inline std::vector<SanEntry> VerifyContext::sans() const {
  14478. std::vector<SanEntry> result;
  14479. if (cert) { get_cert_sans(cert, result); }
  14480. return result;
  14481. }
  14482. inline bool VerifyContext::validity(time_t &not_before,
  14483. time_t &not_after) const {
  14484. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14485. }
  14486. inline std::string VerifyContext::serial() const {
  14487. return cert ? get_cert_serial(cert) : std::string();
  14488. }
  14489. // TlsError static method implementation
  14490. inline std::string TlsError::verify_error_to_string(long error_code) {
  14491. return verify_error_string(error_code);
  14492. }
  14493. } // namespace tls
  14494. // Request::peer_cert() implementation
  14495. inline tls::PeerCert Request::peer_cert() const {
  14496. return tls::get_peer_cert_from_session(ssl);
  14497. }
  14498. // Request::sni() implementation
  14499. inline std::string Request::sni() const {
  14500. if (!ssl) { return std::string(); }
  14501. const char *s = tls::get_sni(ssl);
  14502. return s ? std::string(s) : std::string();
  14503. }
  14504. #endif // CPPHTTPLIB_SSL_ENABLED
  14505. /*
  14506. * Group 8: TLS abstraction layer - OpenSSL backend
  14507. */
  14508. /*
  14509. * OpenSSL Backend Implementation
  14510. */
  14511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14512. namespace tls {
  14513. namespace impl {
  14514. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14515. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14516. switch (ssl_error) {
  14517. case SSL_ERROR_NONE: return ErrorCode::Success;
  14518. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14519. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14520. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14521. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14522. case SSL_ERROR_SSL:
  14523. default: return ErrorCode::Fatal;
  14524. }
  14525. }
  14526. // Helper: Create client CA list from PEM string
  14527. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14528. // Caller takes ownership of returned list
  14529. inline STACK_OF(X509_NAME) *
  14530. create_client_ca_list_from_pem(const char *ca_pem) {
  14531. if (!ca_pem) { return nullptr; }
  14532. auto ca_list = sk_X509_NAME_new_null();
  14533. if (!ca_list) { return nullptr; }
  14534. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14535. if (!bio) {
  14536. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14537. return nullptr;
  14538. }
  14539. X509 *cert = nullptr;
  14540. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14541. nullptr) {
  14542. const X509_NAME *name = X509_get_subject_name(cert);
  14543. if (name) {
  14544. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14545. }
  14546. X509_free(cert);
  14547. }
  14548. BIO_free(bio);
  14549. return ca_list;
  14550. }
  14551. // OpenSSL verify callback wrapper
  14552. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14553. auto &callback = get_verify_callback();
  14554. if (!callback) { return preverify_ok; }
  14555. // Get SSL object from X509_STORE_CTX
  14556. auto ssl = static_cast<SSL *>(
  14557. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14558. if (!ssl) { return preverify_ok; }
  14559. // Get current certificate and depth
  14560. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14561. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14562. int error = X509_STORE_CTX_get_error(ctx);
  14563. // Build context
  14564. VerifyContext verify_ctx;
  14565. verify_ctx.session = static_cast<session_t>(ssl);
  14566. verify_ctx.cert = static_cast<cert_t>(cert);
  14567. verify_ctx.depth = depth;
  14568. verify_ctx.preverify_ok = (preverify_ok != 0);
  14569. verify_ctx.error_code = error;
  14570. verify_ctx.error_string =
  14571. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14572. return callback(verify_ctx) ? 1 : 0;
  14573. }
  14574. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14575. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14576. // that must be released with release_store_objects
  14577. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14578. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14579. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14580. #endif
  14581. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14582. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14583. return X509_STORE_get1_objects(store);
  14584. #else
  14585. return X509_STORE_get0_objects(store);
  14586. #endif
  14587. }
  14588. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14589. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14590. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14591. #else
  14592. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14593. #endif
  14594. }
  14595. } // namespace impl
  14596. inline ctx_t create_client_context() {
  14597. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14598. if (ctx) {
  14599. // Disable auto-retry to properly handle non-blocking I/O
  14600. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14601. // Set minimum TLS version
  14602. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14603. }
  14604. return static_cast<ctx_t>(ctx);
  14605. }
  14606. inline void free_context(ctx_t ctx) {
  14607. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14608. }
  14609. inline bool set_min_version(ctx_t ctx, Version version) {
  14610. if (!ctx) return false;
  14611. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14612. static_cast<int>(version)) == 1;
  14613. }
  14614. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14615. if (!ctx || !pem || len == 0) return false;
  14616. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14617. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14618. if (!store) return false;
  14619. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14620. if (!bio) return false;
  14621. bool ok = true;
  14622. X509 *cert = nullptr;
  14623. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14624. nullptr) {
  14625. if (X509_STORE_add_cert(store, cert) != 1) {
  14626. // Ignore duplicate errors
  14627. auto err = ERR_peek_last_error();
  14628. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14629. ok = false;
  14630. }
  14631. }
  14632. X509_free(cert);
  14633. if (!ok) break;
  14634. }
  14635. BIO_free(bio);
  14636. // Clear any "no more certificates" errors
  14637. ERR_clear_error();
  14638. return ok;
  14639. }
  14640. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14641. if (!ctx || !file_path) return false;
  14642. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14643. nullptr) == 1;
  14644. }
  14645. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14646. if (!ctx || !dir_path) return false;
  14647. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14648. dir_path) == 1;
  14649. }
  14650. inline bool load_system_certs(ctx_t ctx) {
  14651. if (!ctx) return false;
  14652. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14653. #ifdef _WIN32
  14654. // Windows: Load from system certificate store (ROOT and CA)
  14655. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14656. if (!store) return false;
  14657. bool loaded_any = false;
  14658. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14659. for (auto store_name : store_names) {
  14660. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14661. if (!hStore) continue;
  14662. PCCERT_CONTEXT pContext = nullptr;
  14663. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14664. nullptr) {
  14665. const unsigned char *data = pContext->pbCertEncoded;
  14666. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14667. if (x509) {
  14668. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14669. X509_free(x509);
  14670. }
  14671. }
  14672. CertCloseStore(hStore, 0);
  14673. }
  14674. return loaded_any;
  14675. #elif defined(__APPLE__)
  14676. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14677. // macOS: Load from Keychain
  14678. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14679. if (!store) return false;
  14680. bool loaded_any = false;
  14681. const SecTrustSettingsDomain domains[] = {
  14682. kSecTrustSettingsDomainSystem,
  14683. kSecTrustSettingsDomainAdmin,
  14684. kSecTrustSettingsDomainUser,
  14685. };
  14686. for (auto domain : domains) {
  14687. CFArrayRef certs = nullptr;
  14688. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14689. !certs) {
  14690. if (certs) CFRelease(certs);
  14691. continue;
  14692. }
  14693. auto count = CFArrayGetCount(certs);
  14694. for (CFIndex i = 0; i < count; i++) {
  14695. auto cert = reinterpret_cast<SecCertificateRef>(
  14696. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14697. CFDataRef der = SecCertificateCopyData(cert);
  14698. if (der) {
  14699. const unsigned char *data = CFDataGetBytePtr(der);
  14700. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14701. if (x509) {
  14702. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14703. X509_free(x509);
  14704. }
  14705. CFRelease(der);
  14706. }
  14707. }
  14708. CFRelease(certs);
  14709. }
  14710. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14711. #else
  14712. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14713. #endif
  14714. #else
  14715. // Other Unix: use default verify paths
  14716. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14717. #endif
  14718. }
  14719. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14720. const char *password) {
  14721. if (!ctx || !cert || !key) return false;
  14722. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14723. // Load certificate
  14724. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14725. if (!cert_bio) return false;
  14726. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14727. BIO_free(cert_bio);
  14728. if (!x509) return false;
  14729. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14730. X509_free(x509);
  14731. if (!cert_ok) return false;
  14732. // Load private key
  14733. auto key_bio = BIO_new_mem_buf(key, -1);
  14734. if (!key_bio) return false;
  14735. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14736. password ? const_cast<char *>(password)
  14737. : nullptr);
  14738. BIO_free(key_bio);
  14739. if (!pkey) return false;
  14740. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14741. EVP_PKEY_free(pkey);
  14742. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14743. }
  14744. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14745. const char *key_path, const char *password) {
  14746. if (!ctx || !cert_path || !key_path) return false;
  14747. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14748. if (password && password[0] != '\0') {
  14749. SSL_CTX_set_default_passwd_cb_userdata(
  14750. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14751. }
  14752. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14753. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14754. }
  14755. inline ctx_t create_server_context() {
  14756. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14757. if (ctx) {
  14758. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14759. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14760. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14761. }
  14762. return static_cast<ctx_t>(ctx);
  14763. }
  14764. inline void set_verify_client(ctx_t ctx, bool require) {
  14765. if (!ctx) return;
  14766. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14767. require
  14768. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14769. : SSL_VERIFY_NONE,
  14770. nullptr);
  14771. }
  14772. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14773. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14774. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14775. SSL *ssl = SSL_new(ssl_ctx);
  14776. if (!ssl) return nullptr;
  14777. // Disable auto-retry for proper non-blocking I/O handling
  14778. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14779. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14780. if (!bio) {
  14781. SSL_free(ssl);
  14782. return nullptr;
  14783. }
  14784. SSL_set_bio(ssl, bio, bio);
  14785. return static_cast<session_t>(ssl);
  14786. }
  14787. inline void free_session(session_t session) {
  14788. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14789. }
  14790. inline bool set_sni(session_t session, const char *hostname) {
  14791. if (!session || !hostname) return false;
  14792. auto ssl = static_cast<SSL *>(session);
  14793. // Set SNI (Server Name Indication) only - does not enable verification
  14794. #if defined(OPENSSL_IS_BORINGSSL)
  14795. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14796. #else
  14797. // Direct call instead of macro to suppress -Wold-style-cast warning
  14798. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14799. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14800. #endif
  14801. }
  14802. inline bool set_hostname(session_t session, const char *hostname) {
  14803. if (!session || !hostname) return false;
  14804. auto ssl = static_cast<SSL *>(session);
  14805. // Enable hostname verification
  14806. auto param = SSL_get0_param(ssl);
  14807. if (!param) return false;
  14808. if (detail::is_ip_address(hostname)) {
  14809. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14810. // certificate's IP SANs instead of its DNS names
  14811. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14812. } else {
  14813. // Set SNI (Server Name Indication)
  14814. if (!set_sni(session, hostname)) { return false; }
  14815. X509_VERIFY_PARAM_set_hostflags(param,
  14816. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14817. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14818. }
  14819. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14820. return true;
  14821. }
  14822. inline TlsError connect(session_t session) {
  14823. if (!session) { return TlsError(); }
  14824. auto ssl = static_cast<SSL *>(session);
  14825. auto ret = SSL_connect(ssl);
  14826. TlsError err;
  14827. if (ret == 1) {
  14828. err.code = ErrorCode::Success;
  14829. } else {
  14830. auto ssl_err = SSL_get_error(ssl, ret);
  14831. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14832. err.backend_code = ERR_get_error();
  14833. }
  14834. return err;
  14835. }
  14836. inline TlsError accept(session_t session) {
  14837. if (!session) { return TlsError(); }
  14838. auto ssl = static_cast<SSL *>(session);
  14839. auto ret = SSL_accept(ssl);
  14840. TlsError err;
  14841. if (ret == 1) {
  14842. err.code = ErrorCode::Success;
  14843. } else {
  14844. auto ssl_err = SSL_get_error(ssl, ret);
  14845. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14846. err.backend_code = ERR_get_error();
  14847. }
  14848. return err;
  14849. }
  14850. inline bool connect_nonblocking(session_t session, socket_t sock,
  14851. time_t timeout_sec, time_t timeout_usec,
  14852. TlsError *err) {
  14853. if (!session) {
  14854. if (err) { err->code = ErrorCode::Fatal; }
  14855. return false;
  14856. }
  14857. auto ssl = static_cast<SSL *>(session);
  14858. auto bio = SSL_get_rbio(ssl);
  14859. // Set non-blocking mode for handshake
  14860. detail::set_nonblocking(sock, true);
  14861. if (bio) { BIO_set_nbio(bio, 1); }
  14862. auto cleanup = detail::scope_exit([&]() {
  14863. // Restore blocking mode after handshake
  14864. if (bio) { BIO_set_nbio(bio, 0); }
  14865. detail::set_nonblocking(sock, false);
  14866. });
  14867. auto res = 0;
  14868. while ((res = SSL_connect(ssl)) != 1) {
  14869. auto ssl_err = SSL_get_error(ssl, res);
  14870. switch (ssl_err) {
  14871. case SSL_ERROR_WANT_READ:
  14872. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14873. continue;
  14874. }
  14875. break;
  14876. case SSL_ERROR_WANT_WRITE:
  14877. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14878. continue;
  14879. }
  14880. break;
  14881. default: break;
  14882. }
  14883. if (err) {
  14884. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14885. err->backend_code = ERR_get_error();
  14886. }
  14887. return false;
  14888. }
  14889. if (err) { err->code = ErrorCode::Success; }
  14890. return true;
  14891. }
  14892. inline bool accept_nonblocking(session_t session, socket_t sock,
  14893. time_t timeout_sec, time_t timeout_usec,
  14894. TlsError *err) {
  14895. if (!session) {
  14896. if (err) { err->code = ErrorCode::Fatal; }
  14897. return false;
  14898. }
  14899. auto ssl = static_cast<SSL *>(session);
  14900. auto bio = SSL_get_rbio(ssl);
  14901. // Set non-blocking mode for handshake
  14902. detail::set_nonblocking(sock, true);
  14903. if (bio) { BIO_set_nbio(bio, 1); }
  14904. auto cleanup = detail::scope_exit([&]() {
  14905. // Restore blocking mode after handshake
  14906. if (bio) { BIO_set_nbio(bio, 0); }
  14907. detail::set_nonblocking(sock, false);
  14908. });
  14909. auto res = 0;
  14910. while ((res = SSL_accept(ssl)) != 1) {
  14911. auto ssl_err = SSL_get_error(ssl, res);
  14912. switch (ssl_err) {
  14913. case SSL_ERROR_WANT_READ:
  14914. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14915. continue;
  14916. }
  14917. break;
  14918. case SSL_ERROR_WANT_WRITE:
  14919. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14920. continue;
  14921. }
  14922. break;
  14923. default: break;
  14924. }
  14925. if (err) {
  14926. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14927. err->backend_code = ERR_get_error();
  14928. }
  14929. return false;
  14930. }
  14931. if (err) { err->code = ErrorCode::Success; }
  14932. return true;
  14933. }
  14934. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14935. if (!session || !buf) {
  14936. err.code = ErrorCode::Fatal;
  14937. return -1;
  14938. }
  14939. auto ssl = static_cast<SSL *>(session);
  14940. constexpr auto max_len =
  14941. static_cast<size_t>((std::numeric_limits<int>::max)());
  14942. if (len > max_len) { len = max_len; }
  14943. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14944. if (ret > 0) {
  14945. err.code = ErrorCode::Success;
  14946. return ret;
  14947. }
  14948. auto ssl_err = SSL_get_error(ssl, ret);
  14949. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14950. if (err.code == ErrorCode::PeerClosed) {
  14951. return 0;
  14952. } // Gracefully handle the peer closed state.
  14953. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14954. return -1;
  14955. }
  14956. inline ssize_t write(session_t session, const void *buf, size_t len,
  14957. TlsError &err) {
  14958. if (!session || !buf) {
  14959. err.code = ErrorCode::Fatal;
  14960. return -1;
  14961. }
  14962. auto ssl = static_cast<SSL *>(session);
  14963. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14964. if (ret > 0) {
  14965. err.code = ErrorCode::Success;
  14966. return ret;
  14967. }
  14968. auto ssl_err = SSL_get_error(ssl, ret);
  14969. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14970. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14971. return -1;
  14972. }
  14973. inline int pending(const_session_t session) {
  14974. if (!session) return 0;
  14975. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14976. }
  14977. inline void shutdown(session_t session, bool graceful) {
  14978. if (!session) return;
  14979. auto ssl = static_cast<SSL *>(session);
  14980. if (graceful) {
  14981. // First call sends close_notify
  14982. if (SSL_shutdown(ssl) == 0) {
  14983. // Second call waits for peer's close_notify
  14984. SSL_shutdown(ssl);
  14985. }
  14986. }
  14987. }
  14988. inline bool is_peer_closed(session_t session, socket_t sock) {
  14989. if (!session) return true;
  14990. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14991. detail::set_nonblocking(sock, true);
  14992. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14993. auto ssl = static_cast<SSL *>(session);
  14994. char buf;
  14995. auto ret = SSL_peek(ssl, &buf, 1);
  14996. if (ret > 0) return false;
  14997. auto err = SSL_get_error(ssl, ret);
  14998. return err == SSL_ERROR_ZERO_RETURN;
  14999. }
  15000. inline cert_t get_peer_cert(const_session_t session) {
  15001. if (!session) return nullptr;
  15002. return static_cast<cert_t>(SSL_get1_peer_certificate(
  15003. static_cast<SSL *>(const_cast<void *>(session))));
  15004. }
  15005. inline void free_cert(cert_t cert) {
  15006. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  15007. }
  15008. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15009. if (!cert || !hostname) return false;
  15010. auto x509 = static_cast<X509 *>(cert);
  15011. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  15012. if (detail::is_ip_address(hostname)) {
  15013. return X509_check_ip_asc(x509, hostname, 0) == 1;
  15014. }
  15015. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  15016. }
  15017. inline uint64_t hostname_mismatch_code() {
  15018. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  15019. }
  15020. inline long get_verify_result(const_session_t session) {
  15021. if (!session) return X509_V_ERR_UNSPECIFIED;
  15022. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  15023. }
  15024. inline std::string get_cert_subject_cn(cert_t cert) {
  15025. if (!cert) return "";
  15026. auto x509 = static_cast<X509 *>(cert);
  15027. auto subject_name = X509_get_subject_name(x509);
  15028. if (!subject_name) return "";
  15029. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  15030. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  15031. if (idx < 0) return "";
  15032. auto entry = X509_NAME_get_entry(subject_name, idx);
  15033. if (!entry) return "";
  15034. auto data = X509_NAME_ENTRY_get_data(entry);
  15035. if (!data) return "";
  15036. return std::string(
  15037. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  15038. static_cast<size_t>(ASN1_STRING_length(data)));
  15039. }
  15040. inline std::string get_cert_issuer_name(cert_t cert) {
  15041. if (!cert) return "";
  15042. auto x509 = static_cast<X509 *>(cert);
  15043. auto issuer_name = X509_get_issuer_name(x509);
  15044. if (!issuer_name) return "";
  15045. char buf[256];
  15046. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  15047. return std::string(buf);
  15048. }
  15049. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15050. sans.clear();
  15051. if (!cert) return false;
  15052. auto x509 = static_cast<X509 *>(cert);
  15053. auto names = static_cast<GENERAL_NAMES *>(
  15054. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  15055. if (!names) return true; // No SANs is valid
  15056. auto count = sk_GENERAL_NAME_num(names);
  15057. for (decltype(count) i = 0; i < count; i++) {
  15058. auto gen = sk_GENERAL_NAME_value(names, i);
  15059. if (!gen) continue;
  15060. SanEntry entry;
  15061. switch (gen->type) {
  15062. case GEN_DNS:
  15063. entry.type = SanType::DNS;
  15064. if (gen->d.dNSName) {
  15065. entry.value = std::string(
  15066. reinterpret_cast<const char *>(
  15067. ASN1_STRING_get0_data(gen->d.dNSName)),
  15068. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  15069. }
  15070. break;
  15071. case GEN_IPADD:
  15072. entry.type = SanType::IP;
  15073. if (gen->d.iPAddress) {
  15074. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  15075. auto len = ASN1_STRING_length(gen->d.iPAddress);
  15076. if (len == 4) {
  15077. // IPv4
  15078. char buf[INET_ADDRSTRLEN];
  15079. inet_ntop(AF_INET, data, buf, sizeof(buf));
  15080. entry.value = buf;
  15081. } else if (len == 16) {
  15082. // IPv6
  15083. char buf[INET6_ADDRSTRLEN];
  15084. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  15085. entry.value = buf;
  15086. }
  15087. }
  15088. break;
  15089. case GEN_EMAIL:
  15090. entry.type = SanType::EMAIL;
  15091. if (gen->d.rfc822Name) {
  15092. entry.value = std::string(
  15093. reinterpret_cast<const char *>(
  15094. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  15095. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  15096. }
  15097. break;
  15098. case GEN_URI:
  15099. entry.type = SanType::URI;
  15100. if (gen->d.uniformResourceIdentifier) {
  15101. entry.value = std::string(
  15102. reinterpret_cast<const char *>(
  15103. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  15104. static_cast<size_t>(
  15105. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  15106. }
  15107. break;
  15108. default: entry.type = SanType::OTHER; break;
  15109. }
  15110. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15111. }
  15112. GENERAL_NAMES_free(names);
  15113. return true;
  15114. }
  15115. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15116. time_t &not_after) {
  15117. if (!cert) return false;
  15118. auto x509 = static_cast<X509 *>(cert);
  15119. auto nb = X509_get0_notBefore(x509);
  15120. auto na = X509_get0_notAfter(x509);
  15121. if (!nb || !na) return false;
  15122. ASN1_TIME *epoch = ASN1_TIME_new();
  15123. if (!epoch) return false;
  15124. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  15125. if (!ASN1_TIME_set(epoch, 0)) return false;
  15126. int pday, psec;
  15127. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  15128. not_before = 86400 * (time_t)pday + psec;
  15129. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  15130. not_after = 86400 * (time_t)pday + psec;
  15131. return true;
  15132. }
  15133. inline std::string get_cert_serial(cert_t cert) {
  15134. if (!cert) return "";
  15135. auto x509 = static_cast<X509 *>(cert);
  15136. auto serial = X509_get_serialNumber(x509);
  15137. if (!serial) return "";
  15138. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  15139. if (!bn) return "";
  15140. auto hex = BN_bn2hex(bn);
  15141. BN_free(bn);
  15142. if (!hex) return "";
  15143. std::string result(hex);
  15144. OPENSSL_free(hex);
  15145. return result;
  15146. }
  15147. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15148. if (!cert) return false;
  15149. auto x509 = static_cast<X509 *>(cert);
  15150. auto len = i2d_X509(x509, nullptr);
  15151. if (len < 0) return false;
  15152. der.resize(static_cast<size_t>(len));
  15153. auto p = der.data();
  15154. i2d_X509(x509, &p);
  15155. return true;
  15156. }
  15157. inline const char *get_sni(const_session_t session) {
  15158. if (!session) return nullptr;
  15159. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15160. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15161. }
  15162. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  15163. inline uint64_t get_error() { return ERR_get_error(); }
  15164. inline std::string error_string(uint64_t code) {
  15165. char buf[256];
  15166. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  15167. return std::string(buf);
  15168. }
  15169. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15170. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  15171. if (!mem) { return nullptr; }
  15172. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  15173. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  15174. if (!inf) { return nullptr; }
  15175. auto store = X509_STORE_new();
  15176. if (store) {
  15177. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  15178. auto itmp = sk_X509_INFO_value(inf, i);
  15179. if (!itmp) { continue; }
  15180. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  15181. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  15182. }
  15183. }
  15184. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  15185. return static_cast<ca_store_t>(store);
  15186. }
  15187. inline void free_ca_store(ca_store_t store) {
  15188. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15189. }
  15190. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15191. if (!ctx || !store) { return false; }
  15192. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15193. auto x509_store = static_cast<X509_STORE *>(store);
  15194. // Check if same store is already set
  15195. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15196. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15197. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15198. return true;
  15199. }
  15200. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15201. certs.clear();
  15202. if (!ctx) { return 0; }
  15203. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15204. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15205. if (!store) { return 0; }
  15206. auto objs = impl::get_store_objects(store);
  15207. if (!objs) { return 0; }
  15208. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15209. auto count = sk_X509_OBJECT_num(objs);
  15210. for (decltype(count) i = 0; i < count; i++) {
  15211. auto obj = sk_X509_OBJECT_value(objs, i);
  15212. if (!obj) { continue; }
  15213. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15214. auto x509 = X509_OBJECT_get0_X509(obj);
  15215. if (x509) {
  15216. // Increment reference count so caller can free it
  15217. X509_up_ref(x509);
  15218. certs.push_back(static_cast<cert_t>(x509));
  15219. }
  15220. }
  15221. }
  15222. return certs.size();
  15223. }
  15224. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15225. std::vector<std::string> names;
  15226. if (!ctx) { return names; }
  15227. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15228. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15229. if (!store) { return names; }
  15230. auto objs = impl::get_store_objects(store);
  15231. if (!objs) { return names; }
  15232. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15233. auto count = sk_X509_OBJECT_num(objs);
  15234. for (decltype(count) i = 0; i < count; i++) {
  15235. auto obj = sk_X509_OBJECT_value(objs, i);
  15236. if (!obj) { continue; }
  15237. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15238. auto x509 = X509_OBJECT_get0_X509(obj);
  15239. if (x509) {
  15240. auto subject = X509_get_subject_name(x509);
  15241. if (subject) {
  15242. char buf[512];
  15243. X509_NAME_oneline(subject, buf, sizeof(buf));
  15244. names.push_back(buf);
  15245. }
  15246. }
  15247. }
  15248. }
  15249. return names;
  15250. }
  15251. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15252. const char *key_pem, const char *password) {
  15253. if (!ctx || !cert_pem || !key_pem) { return false; }
  15254. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15255. // Load certificate from PEM
  15256. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15257. if (!cert_bio) { return false; }
  15258. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15259. BIO_free(cert_bio);
  15260. if (!cert) { return false; }
  15261. // Load private key from PEM
  15262. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15263. if (!key_bio) {
  15264. X509_free(cert);
  15265. return false;
  15266. }
  15267. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15268. password ? const_cast<char *>(password)
  15269. : nullptr);
  15270. BIO_free(key_bio);
  15271. if (!key) {
  15272. X509_free(cert);
  15273. return false;
  15274. }
  15275. // Update certificate and key
  15276. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15277. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15278. X509_free(cert);
  15279. EVP_PKEY_free(key);
  15280. return ret;
  15281. }
  15282. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15283. if (!ctx || !ca_pem) { return false; }
  15284. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15285. // Create new X509_STORE from PEM
  15286. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15287. if (!store) { return false; }
  15288. // SSL_CTX_set_cert_store takes ownership
  15289. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15290. // Set client CA list for client certificate request
  15291. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15292. if (ca_list) {
  15293. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15294. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15295. }
  15296. return true;
  15297. }
  15298. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15299. if (!ctx) { return false; }
  15300. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15301. impl::get_verify_callback() = std::move(callback);
  15302. if (impl::get_verify_callback()) {
  15303. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15304. } else {
  15305. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15306. }
  15307. return true;
  15308. }
  15309. inline long get_verify_error(const_session_t session) {
  15310. if (!session) { return -1; }
  15311. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15312. return SSL_get_verify_result(ssl);
  15313. }
  15314. inline std::string verify_error_string(long error_code) {
  15315. if (error_code == X509_V_OK) { return ""; }
  15316. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15317. return str ? str : "unknown error";
  15318. }
  15319. } // namespace tls
  15320. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15321. /*
  15322. * Group 9: TLS abstraction layer - Mbed TLS backend
  15323. */
  15324. /*
  15325. * Mbed TLS Backend Implementation
  15326. */
  15327. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15328. namespace tls {
  15329. namespace impl {
  15330. // Mbed TLS session wrapper
  15331. struct MbedTlsSession {
  15332. mbedtls_ssl_context ssl;
  15333. socket_t sock = INVALID_SOCKET;
  15334. std::string hostname; // For client: set via set_sni
  15335. std::string sni_hostname; // For server: received from client via SNI callback
  15336. // Mbed TLS has no SSL_peek() equivalent, so is_peer_closed() must probe with
  15337. // a real 1-byte mbedtls_ssl_read(). If that probe lands on application data
  15338. // (e.g. a response that arrived while this side was still in its post-write
  15339. // check), the byte is pushed back here and served by the next read().
  15340. unsigned char peeked_byte = 0;
  15341. bool has_peeked_byte = false;
  15342. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15343. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15344. MbedTlsSession(const MbedTlsSession &) = delete;
  15345. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15346. };
  15347. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15348. // queue)
  15349. inline int &mbedtls_last_error() {
  15350. static thread_local int err = 0;
  15351. return err;
  15352. }
  15353. // Helper to map Mbed TLS error to ErrorCode
  15354. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15355. if (ret == 0) { return ErrorCode::Success; }
  15356. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15357. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15358. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15359. return ErrorCode::PeerClosed;
  15360. }
  15361. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15362. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15363. out_errno = errno;
  15364. return ErrorCode::SyscallError;
  15365. }
  15366. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15367. return ErrorCode::CertVerifyFailed;
  15368. }
  15369. return ErrorCode::Fatal;
  15370. }
  15371. // A TLS 1.3 NewSessionTicket (signaled by default on Mbed TLS 4.x) is a
  15372. // non-fatal notification delivered between records, not an error and not
  15373. // application data, so I/O calls that see it should just be retried. Kept in
  15374. // one helper so the retry loops keep an intact "do { } while (...)" instead of
  15375. // splitting the closing brace across an #if.
  15376. inline bool mbedtls_is_session_ticket(int ret) {
  15377. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  15378. return ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
  15379. #else
  15380. (void)ret;
  15381. return false;
  15382. #endif
  15383. }
  15384. // BIO-like send callback for Mbed TLS
  15385. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15386. size_t len) {
  15387. auto sock = *static_cast<socket_t *>(ctx);
  15388. #ifdef _WIN32
  15389. auto ret =
  15390. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15391. if (ret == SOCKET_ERROR) {
  15392. int err = WSAGetLastError();
  15393. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15394. return MBEDTLS_ERR_NET_SEND_FAILED;
  15395. }
  15396. #else
  15397. auto ret = send(sock, buf, len, 0);
  15398. if (ret < 0) {
  15399. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15400. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15401. }
  15402. return MBEDTLS_ERR_NET_SEND_FAILED;
  15403. }
  15404. #endif
  15405. return static_cast<int>(ret);
  15406. }
  15407. // BIO-like recv callback for Mbed TLS
  15408. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15409. auto sock = *static_cast<socket_t *>(ctx);
  15410. #ifdef _WIN32
  15411. auto ret =
  15412. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15413. if (ret == SOCKET_ERROR) {
  15414. int err = WSAGetLastError();
  15415. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15416. return MBEDTLS_ERR_NET_RECV_FAILED;
  15417. }
  15418. #else
  15419. auto ret = recv(sock, buf, len, 0);
  15420. if (ret < 0) {
  15421. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15422. return MBEDTLS_ERR_SSL_WANT_READ;
  15423. }
  15424. return MBEDTLS_ERR_NET_RECV_FAILED;
  15425. }
  15426. #endif
  15427. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15428. return static_cast<int>(ret);
  15429. }
  15430. // MbedTlsContext constructor/destructor implementations
  15431. inline MbedTlsContext::MbedTlsContext() {
  15432. mbedtls_ssl_config_init(&conf);
  15433. #ifndef CPPHTTPLIB_MBEDTLS_V4
  15434. mbedtls_entropy_init(&entropy);
  15435. mbedtls_ctr_drbg_init(&ctr_drbg);
  15436. #endif
  15437. mbedtls_x509_crt_init(&ca_chain);
  15438. mbedtls_x509_crt_init(&own_cert);
  15439. mbedtls_pk_init(&own_key);
  15440. }
  15441. inline MbedTlsContext::~MbedTlsContext() {
  15442. mbedtls_pk_free(&own_key);
  15443. mbedtls_x509_crt_free(&own_cert);
  15444. mbedtls_x509_crt_free(&ca_chain);
  15445. #ifndef CPPHTTPLIB_MBEDTLS_V4
  15446. mbedtls_ctr_drbg_free(&ctr_drbg);
  15447. mbedtls_entropy_free(&entropy);
  15448. #endif
  15449. mbedtls_ssl_config_free(&conf);
  15450. }
  15451. // Thread-local storage for SNI captured during handshake
  15452. // This is needed because the SNI callback doesn't have a way to pass
  15453. // session-specific data before the session is fully set up
  15454. inline std::string &mbedpending_sni() {
  15455. static thread_local std::string sni;
  15456. return sni;
  15457. }
  15458. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15459. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15460. const unsigned char *name, size_t name_len) {
  15461. (void)p_ctx;
  15462. (void)ssl;
  15463. // Store SNI name in thread-local storage
  15464. // It will be retrieved and stored in the session after handshake
  15465. if (name && name_len > 0) {
  15466. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15467. } else {
  15468. mbedpending_sni().clear();
  15469. }
  15470. return 0; // Accept any SNI
  15471. }
  15472. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15473. int cert_depth, uint32_t *flags);
  15474. // MbedTLS verify callback wrapper
  15475. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15476. int cert_depth, uint32_t *flags) {
  15477. auto &callback = get_verify_callback();
  15478. if (!callback) { return 0; } // Continue with default verification
  15479. // data points to the MbedTlsSession
  15480. auto *session = static_cast<MbedTlsSession *>(data);
  15481. // Build context
  15482. VerifyContext verify_ctx;
  15483. verify_ctx.session = static_cast<session_t>(session);
  15484. verify_ctx.cert = static_cast<cert_t>(crt);
  15485. verify_ctx.depth = cert_depth;
  15486. verify_ctx.preverify_ok = (*flags == 0);
  15487. verify_ctx.error_code = static_cast<long>(*flags);
  15488. // Convert Mbed TLS flags to error string
  15489. static thread_local char error_buf[256];
  15490. if (*flags != 0) {
  15491. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15492. verify_ctx.error_string = error_buf;
  15493. } else {
  15494. verify_ctx.error_string = nullptr;
  15495. }
  15496. bool accepted = callback(verify_ctx);
  15497. if (accepted) {
  15498. *flags = 0; // Clear all error flags
  15499. return 0;
  15500. }
  15501. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15502. }
  15503. } // namespace impl
  15504. inline ctx_t create_client_context() {
  15505. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15506. if (!ctx) { return nullptr; }
  15507. ctx->is_server = false;
  15508. #ifdef CPPHTTPLIB_MBEDTLS_V4
  15509. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  15510. if (!detail::ensure_mbedtls_psa_crypto()) {
  15511. delete ctx;
  15512. return nullptr;
  15513. }
  15514. int ret;
  15515. #else
  15516. // Seed the random number generator
  15517. const char *pers = "httplib_client";
  15518. int ret = mbedtls_ctr_drbg_seed(
  15519. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15520. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15521. if (ret != 0) {
  15522. impl::mbedtls_last_error() = ret;
  15523. delete ctx;
  15524. return nullptr;
  15525. }
  15526. #endif
  15527. // Set up SSL config for client
  15528. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15529. MBEDTLS_SSL_TRANSPORT_STREAM,
  15530. MBEDTLS_SSL_PRESET_DEFAULT);
  15531. if (ret != 0) {
  15532. impl::mbedtls_last_error() = ret;
  15533. delete ctx;
  15534. return nullptr;
  15535. }
  15536. #ifndef CPPHTTPLIB_MBEDTLS_V4
  15537. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  15538. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15539. #endif
  15540. // Default: verify peer certificate
  15541. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15542. // Set minimum TLS version to 1.2
  15543. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15544. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15545. #else
  15546. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15547. MBEDTLS_SSL_MINOR_VERSION_3);
  15548. #endif
  15549. return static_cast<ctx_t>(ctx);
  15550. }
  15551. inline ctx_t create_server_context() {
  15552. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15553. if (!ctx) { return nullptr; }
  15554. ctx->is_server = true;
  15555. #ifdef CPPHTTPLIB_MBEDTLS_V4
  15556. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  15557. if (!detail::ensure_mbedtls_psa_crypto()) {
  15558. delete ctx;
  15559. return nullptr;
  15560. }
  15561. int ret;
  15562. #else
  15563. // Seed the random number generator
  15564. const char *pers = "httplib_server";
  15565. int ret = mbedtls_ctr_drbg_seed(
  15566. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15567. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15568. if (ret != 0) {
  15569. impl::mbedtls_last_error() = ret;
  15570. delete ctx;
  15571. return nullptr;
  15572. }
  15573. #endif
  15574. // Set up SSL config for server
  15575. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15576. MBEDTLS_SSL_TRANSPORT_STREAM,
  15577. MBEDTLS_SSL_PRESET_DEFAULT);
  15578. if (ret != 0) {
  15579. impl::mbedtls_last_error() = ret;
  15580. delete ctx;
  15581. return nullptr;
  15582. }
  15583. #ifndef CPPHTTPLIB_MBEDTLS_V4
  15584. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  15585. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15586. #endif
  15587. // Default: don't verify client
  15588. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15589. // Set minimum TLS version to 1.2
  15590. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15591. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15592. #else
  15593. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15594. MBEDTLS_SSL_MINOR_VERSION_3);
  15595. #endif
  15596. // Set SNI callback to capture client's SNI hostname
  15597. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15598. return static_cast<ctx_t>(ctx);
  15599. }
  15600. inline void free_context(ctx_t ctx) {
  15601. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15602. }
  15603. inline bool set_min_version(ctx_t ctx, Version version) {
  15604. if (!ctx) { return false; }
  15605. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15606. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15607. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15608. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15609. if (version >= Version::TLS1_3) {
  15610. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15611. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15612. #endif
  15613. }
  15614. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15615. #else
  15616. // Mbed TLS 2.x uses major/minor version numbers
  15617. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15618. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15619. if (version >= Version::TLS1_3) {
  15620. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15621. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15622. #else
  15623. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15624. #endif
  15625. }
  15626. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15627. #endif
  15628. return true;
  15629. }
  15630. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15631. if (!ctx || !pem) { return false; }
  15632. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15633. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15634. // Add null terminator if not present
  15635. std::string pem_str(pem, len);
  15636. int ret = mbedtls_x509_crt_parse(
  15637. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15638. pem_str.size() + 1);
  15639. if (ret != 0) {
  15640. impl::mbedtls_last_error() = ret;
  15641. return false;
  15642. }
  15643. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15644. return true;
  15645. }
  15646. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15647. if (!ctx || !file_path) { return false; }
  15648. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15649. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15650. if (ret != 0) {
  15651. impl::mbedtls_last_error() = ret;
  15652. return false;
  15653. }
  15654. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15655. return true;
  15656. }
  15657. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15658. if (!ctx || !dir_path) { return false; }
  15659. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15660. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15661. if (ret < 0) { // Returns number of certs on success, negative on error
  15662. impl::mbedtls_last_error() = ret;
  15663. return false;
  15664. }
  15665. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15666. return true;
  15667. }
  15668. inline bool load_system_certs(ctx_t ctx) {
  15669. if (!ctx) { return false; }
  15670. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15671. bool loaded = false;
  15672. #ifdef _WIN32
  15673. loaded = impl::enumerate_windows_system_certs(
  15674. [&](const unsigned char *data, size_t len) {
  15675. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15676. });
  15677. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15678. loaded = impl::enumerate_macos_keychain_certs(
  15679. [&](const unsigned char *data, size_t len) {
  15680. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15681. });
  15682. #else
  15683. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15684. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15685. loaded = true;
  15686. break;
  15687. }
  15688. }
  15689. if (!loaded) {
  15690. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15691. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15692. loaded = true;
  15693. break;
  15694. }
  15695. }
  15696. }
  15697. #endif
  15698. if (loaded) {
  15699. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15700. }
  15701. return loaded;
  15702. }
  15703. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15704. const char *password) {
  15705. if (!ctx || !cert || !key) { return false; }
  15706. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15707. // Parse certificate
  15708. std::string cert_str(cert);
  15709. int ret = mbedtls_x509_crt_parse(
  15710. &mctx->own_cert,
  15711. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15712. cert_str.size() + 1);
  15713. if (ret != 0) {
  15714. impl::mbedtls_last_error() = ret;
  15715. return false;
  15716. }
  15717. // Parse private key
  15718. std::string key_str(key);
  15719. const unsigned char *pwd =
  15720. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15721. size_t pwd_len = password ? strlen(password) : 0;
  15722. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  15723. ret = mbedtls_pk_parse_key(
  15724. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15725. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15726. &mctx->ctr_drbg);
  15727. #else
  15728. ret = mbedtls_pk_parse_key(
  15729. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15730. key_str.size() + 1, pwd, pwd_len);
  15731. #endif
  15732. if (ret != 0) {
  15733. impl::mbedtls_last_error() = ret;
  15734. return false;
  15735. }
  15736. // Verify that the certificate and private key match.
  15737. // Mbed TLS 4.x: mbedtls_pk_check_pair() reports a spurious mismatch for
  15738. // PSA-backed keys, so skip it and let the handshake surface a real mismatch.
  15739. #ifndef CPPHTTPLIB_MBEDTLS_V4
  15740. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15741. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15742. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15743. #else
  15744. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15745. #endif
  15746. if (ret != 0) {
  15747. impl::mbedtls_last_error() = ret;
  15748. return false;
  15749. }
  15750. #endif
  15751. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15752. if (ret != 0) {
  15753. impl::mbedtls_last_error() = ret;
  15754. return false;
  15755. }
  15756. return true;
  15757. }
  15758. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15759. const char *key_path, const char *password) {
  15760. if (!ctx || !cert_path || !key_path) { return false; }
  15761. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15762. // Parse certificate file
  15763. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15764. if (ret != 0) {
  15765. impl::mbedtls_last_error() = ret;
  15766. return false;
  15767. }
  15768. // Parse private key file
  15769. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  15770. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15771. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15772. #else
  15773. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15774. #endif
  15775. if (ret != 0) {
  15776. impl::mbedtls_last_error() = ret;
  15777. return false;
  15778. }
  15779. // Verify that the certificate and private key match.
  15780. // Mbed TLS 4.x: see set_client_cert() — skip the spurious check_pair.
  15781. #ifndef CPPHTTPLIB_MBEDTLS_V4
  15782. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15783. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15784. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15785. #else
  15786. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15787. #endif
  15788. if (ret != 0) {
  15789. impl::mbedtls_last_error() = ret;
  15790. return false;
  15791. }
  15792. #endif
  15793. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15794. if (ret != 0) {
  15795. impl::mbedtls_last_error() = ret;
  15796. return false;
  15797. }
  15798. return true;
  15799. }
  15800. inline void set_verify_client(ctx_t ctx, bool require) {
  15801. if (!ctx) { return; }
  15802. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15803. mctx->verify_client = require;
  15804. if (require) {
  15805. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15806. } else {
  15807. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15808. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15809. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15810. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15811. : MBEDTLS_SSL_VERIFY_NONE);
  15812. }
  15813. }
  15814. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15815. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15816. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15817. auto session = new (std::nothrow) impl::MbedTlsSession();
  15818. if (!session) { return nullptr; }
  15819. session->sock = sock;
  15820. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15821. if (ret != 0) {
  15822. impl::mbedtls_last_error() = ret;
  15823. delete session;
  15824. return nullptr;
  15825. }
  15826. // Explicitly opt out of in-handshake hostname verification by default;
  15827. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15828. // fails outright when no hostname was set. set_sni() installs the real
  15829. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15830. // caller verifies the certificate identity post-handshake via
  15831. // verify_hostname().
  15832. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15833. // Set BIO callbacks
  15834. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15835. impl::mbedtls_net_recv_cb, nullptr);
  15836. // Set per-session verify callback with session pointer if callback is
  15837. // registered
  15838. if (mctx->has_verify_callback) {
  15839. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15840. session);
  15841. }
  15842. return static_cast<session_t>(session);
  15843. }
  15844. inline void free_session(session_t session) {
  15845. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15846. }
  15847. inline bool set_sni(session_t session, const char *hostname) {
  15848. if (!session || !hostname) { return false; }
  15849. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15850. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15851. if (ret != 0) {
  15852. impl::mbedtls_last_error() = ret;
  15853. return false;
  15854. }
  15855. msession->hostname = hostname;
  15856. return true;
  15857. }
  15858. inline bool set_hostname(session_t session, const char *hostname) {
  15859. // In Mbed TLS, set_hostname also sets up hostname verification
  15860. return set_sni(session, hostname);
  15861. }
  15862. inline TlsError connect(session_t session) {
  15863. TlsError err;
  15864. if (!session) {
  15865. err.code = ErrorCode::Fatal;
  15866. return err;
  15867. }
  15868. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15869. int ret;
  15870. do {
  15871. ret = mbedtls_ssl_handshake(&msession->ssl);
  15872. } while (impl::mbedtls_is_session_ticket(ret));
  15873. if (ret == 0) {
  15874. err.code = ErrorCode::Success;
  15875. } else {
  15876. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15877. err.backend_code = static_cast<uint64_t>(-ret);
  15878. impl::mbedtls_last_error() = ret;
  15879. }
  15880. return err;
  15881. }
  15882. inline TlsError accept(session_t session) {
  15883. // Same as connect for Mbed TLS - handshake works for both client and server
  15884. auto result = connect(session);
  15885. // After successful handshake, capture SNI from thread-local storage
  15886. if (result.code == ErrorCode::Success && session) {
  15887. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15888. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15889. impl::mbedpending_sni().clear();
  15890. }
  15891. return result;
  15892. }
  15893. inline bool connect_nonblocking(session_t session, socket_t sock,
  15894. time_t timeout_sec, time_t timeout_usec,
  15895. TlsError *err) {
  15896. if (!session) {
  15897. if (err) { err->code = ErrorCode::Fatal; }
  15898. return false;
  15899. }
  15900. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15901. // Set socket to non-blocking mode
  15902. detail::set_nonblocking(sock, true);
  15903. auto cleanup =
  15904. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15905. int ret;
  15906. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15907. // Non-fatal TLS 1.3 ticket; retry immediately.
  15908. if (impl::mbedtls_is_session_ticket(ret)) { continue; }
  15909. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15910. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15911. continue;
  15912. }
  15913. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15914. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15915. continue;
  15916. }
  15917. }
  15918. // TlsError or timeout
  15919. if (err) {
  15920. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15921. err->backend_code = static_cast<uint64_t>(-ret);
  15922. }
  15923. impl::mbedtls_last_error() = ret;
  15924. return false;
  15925. }
  15926. if (err) { err->code = ErrorCode::Success; }
  15927. return true;
  15928. }
  15929. inline bool accept_nonblocking(session_t session, socket_t sock,
  15930. time_t timeout_sec, time_t timeout_usec,
  15931. TlsError *err) {
  15932. // Same implementation as connect for Mbed TLS
  15933. bool result =
  15934. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15935. // After successful handshake, capture SNI from thread-local storage
  15936. if (result && session) {
  15937. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15938. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15939. impl::mbedpending_sni().clear();
  15940. }
  15941. return result;
  15942. }
  15943. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15944. if (!session || !buf) {
  15945. err.code = ErrorCode::Fatal;
  15946. return -1;
  15947. }
  15948. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15949. // Serve a byte consumed by the is_peer_closed() probe before reading more.
  15950. if (msession->has_peeked_byte) {
  15951. if (len == 0) { return 0; }
  15952. auto p = static_cast<unsigned char *>(buf);
  15953. p[0] = msession->peeked_byte;
  15954. msession->has_peeked_byte = false;
  15955. size_t n = 1;
  15956. // Top up with any already-decrypted bytes without risking a block.
  15957. if (len > 1 && mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  15958. int extra = mbedtls_ssl_read(&msession->ssl, p + 1, len - 1);
  15959. if (extra > 0) { n += static_cast<size_t>(extra); }
  15960. }
  15961. err.code = ErrorCode::Success;
  15962. return static_cast<ssize_t>(n);
  15963. }
  15964. int ret;
  15965. do {
  15966. ret = mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf),
  15967. len);
  15968. } while (impl::mbedtls_is_session_ticket(ret));
  15969. if (ret > 0) {
  15970. err.code = ErrorCode::Success;
  15971. return static_cast<ssize_t>(ret);
  15972. }
  15973. if (ret == 0) {
  15974. err.code = ErrorCode::PeerClosed;
  15975. return 0;
  15976. }
  15977. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15978. err.backend_code = static_cast<uint64_t>(-ret);
  15979. impl::mbedtls_last_error() = ret;
  15980. // mbedTLS signals a clean close_notify via a negative error code rather
  15981. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15982. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15983. return -1;
  15984. }
  15985. inline ssize_t write(session_t session, const void *buf, size_t len,
  15986. TlsError &err) {
  15987. if (!session || !buf) {
  15988. err.code = ErrorCode::Fatal;
  15989. return -1;
  15990. }
  15991. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15992. int ret;
  15993. do {
  15994. ret = mbedtls_ssl_write(&msession->ssl,
  15995. static_cast<const unsigned char *>(buf), len);
  15996. } while (impl::mbedtls_is_session_ticket(ret));
  15997. if (ret > 0) {
  15998. err.code = ErrorCode::Success;
  15999. return static_cast<ssize_t>(ret);
  16000. }
  16001. if (ret == 0) {
  16002. err.code = ErrorCode::PeerClosed;
  16003. return 0;
  16004. }
  16005. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  16006. err.backend_code = static_cast<uint64_t>(-ret);
  16007. impl::mbedtls_last_error() = ret;
  16008. return -1;
  16009. }
  16010. inline int pending(const_session_t session) {
  16011. if (!session) { return 0; }
  16012. auto msession =
  16013. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16014. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl)) +
  16015. (msession->has_peeked_byte ? 1 : 0);
  16016. }
  16017. inline void shutdown(session_t session, bool graceful) {
  16018. if (!session) { return; }
  16019. auto msession = static_cast<impl::MbedTlsSession *>(session);
  16020. if (graceful) {
  16021. // Try to send close_notify, but don't block forever
  16022. int ret;
  16023. int attempts = 0;
  16024. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  16025. attempts < 3) {
  16026. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  16027. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  16028. break;
  16029. }
  16030. attempts++;
  16031. }
  16032. }
  16033. }
  16034. inline bool is_peer_closed(session_t session, socket_t sock) {
  16035. if (!session || sock == INVALID_SOCKET) { return true; }
  16036. auto msession = static_cast<impl::MbedTlsSession *>(session);
  16037. // Check if there's already decrypted or pushed-back data available.
  16038. // If so, the connection is definitely alive.
  16039. if (msession->has_peeked_byte ||
  16040. mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  16041. return false;
  16042. }
  16043. // Set socket to non-blocking to avoid blocking on read
  16044. detail::set_nonblocking(sock, true);
  16045. auto cleanup =
  16046. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16047. // Probe with a 1-byte read (Mbed TLS has no peek API). If the probe lands
  16048. // on application data — e.g. a response that already arrived — push the
  16049. // byte back so the next read() delivers it instead of losing it.
  16050. unsigned char buf;
  16051. int ret;
  16052. do {
  16053. ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  16054. } while (impl::mbedtls_is_session_ticket(ret));
  16055. // If we got data or WANT_READ (would block), connection is alive
  16056. if (ret > 0) {
  16057. msession->peeked_byte = buf;
  16058. msession->has_peeked_byte = true;
  16059. return false;
  16060. }
  16061. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  16062. // If we get a peer close notify or a connection reset, the peer is closed
  16063. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  16064. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  16065. }
  16066. inline cert_t get_peer_cert(const_session_t session) {
  16067. if (!session) { return nullptr; }
  16068. auto msession =
  16069. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16070. // Mbed TLS returns a pointer to the internal peer cert chain.
  16071. // WARNING: This pointer is only valid while the session is active.
  16072. // Do not use the certificate after calling free_session().
  16073. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  16074. return const_cast<mbedtls_x509_crt *>(cert);
  16075. }
  16076. inline void free_cert(cert_t cert) {
  16077. // Mbed TLS: peer certificate is owned by the SSL context.
  16078. // No-op here, but callers should still call this for cross-backend
  16079. // portability.
  16080. (void)cert;
  16081. }
  16082. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16083. if (!cert || !hostname) { return false; }
  16084. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  16085. std::string host_str(hostname);
  16086. // Check if hostname is an IP address (IPv4 or IPv6)
  16087. unsigned char ip_bytes[16];
  16088. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16089. auto is_ip = ip_len > 0;
  16090. // Check Subject Alternative Names (SAN)
  16091. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  16092. // - DNS names: raw string bytes
  16093. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  16094. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  16095. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  16096. const unsigned char *p = san->buf.p;
  16097. size_t len = san->buf.len;
  16098. if (is_ip) {
  16099. // For an IP host, only a matching iPAddress SAN of the same family
  16100. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  16101. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  16102. } else {
  16103. // Check if this SAN is a DNS name (printable ASCII string)
  16104. bool is_dns = len > 0;
  16105. for (size_t i = 0; i < len && is_dns; i++) {
  16106. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  16107. }
  16108. if (is_dns) {
  16109. std::string san_name(reinterpret_cast<const char *>(p), len);
  16110. if (detail::match_hostname(san_name, host_str)) { return true; }
  16111. }
  16112. }
  16113. san = san->next;
  16114. }
  16115. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16116. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16117. // the OpenSSL backend's X509_check_ip behaves the same way).
  16118. if (!is_ip) {
  16119. char cn[256];
  16120. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  16121. if (ret > 0) {
  16122. std::string cn_str(cn);
  16123. // Look for "CN=" in the DN string
  16124. size_t cn_pos = cn_str.find("CN=");
  16125. if (cn_pos != std::string::npos) {
  16126. size_t start = cn_pos + 3;
  16127. size_t end = cn_str.find(',', start);
  16128. std::string cn_value =
  16129. cn_str.substr(start, end == std::string::npos ? end : end - start);
  16130. if (detail::match_hostname(cn_value, host_str)) { return true; }
  16131. }
  16132. }
  16133. }
  16134. return false;
  16135. }
  16136. inline uint64_t hostname_mismatch_code() {
  16137. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  16138. }
  16139. inline long get_verify_result(const_session_t session) {
  16140. if (!session) { return -1; }
  16141. auto msession =
  16142. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16143. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  16144. // Return 0 (X509_V_OK equivalent) if verification passed
  16145. return flags == 0 ? 0 : static_cast<long>(flags);
  16146. }
  16147. inline std::string get_cert_subject_cn(cert_t cert) {
  16148. if (!cert) return "";
  16149. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16150. // Find the CN in the subject
  16151. const mbedtls_x509_name *name = &x509->subject;
  16152. while (name != nullptr) {
  16153. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  16154. return std::string(reinterpret_cast<const char *>(name->val.p),
  16155. name->val.len);
  16156. }
  16157. name = name->next;
  16158. }
  16159. return "";
  16160. }
  16161. inline std::string get_cert_issuer_name(cert_t cert) {
  16162. if (!cert) return "";
  16163. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16164. // Build a human-readable issuer name string
  16165. char buf[512];
  16166. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  16167. if (ret < 0) return "";
  16168. return std::string(buf);
  16169. }
  16170. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16171. sans.clear();
  16172. if (!cert) return false;
  16173. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16174. // Parse the Subject Alternative Name extension
  16175. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  16176. while (cur != nullptr) {
  16177. if (cur->buf.len > 0) {
  16178. // Mbed TLS stores SAN as ASN.1 sequences
  16179. // The tag byte indicates the type
  16180. const unsigned char *p = cur->buf.p;
  16181. size_t len = cur->buf.len;
  16182. // First byte is the tag
  16183. unsigned char tag = *p;
  16184. p++;
  16185. len--;
  16186. // Parse length (simple single-byte length assumed)
  16187. if (len > 0 && *p < 0x80) {
  16188. size_t value_len = *p;
  16189. p++;
  16190. len--;
  16191. if (value_len <= len) {
  16192. SanEntry entry;
  16193. // ASN.1 context tags for GeneralName
  16194. switch (tag & 0x1F) {
  16195. case 2: // dNSName
  16196. entry.type = SanType::DNS;
  16197. entry.value =
  16198. std::string(reinterpret_cast<const char *>(p), value_len);
  16199. break;
  16200. case 7: // iPAddress
  16201. entry.type = SanType::IP;
  16202. if (value_len == 4) {
  16203. // IPv4
  16204. char buf[16];
  16205. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  16206. entry.value = buf;
  16207. } else if (value_len == 16) {
  16208. // IPv6
  16209. char buf[64];
  16210. snprintf(buf, sizeof(buf),
  16211. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16212. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16213. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  16214. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  16215. entry.value = buf;
  16216. }
  16217. break;
  16218. case 1: // rfc822Name (email)
  16219. entry.type = SanType::EMAIL;
  16220. entry.value =
  16221. std::string(reinterpret_cast<const char *>(p), value_len);
  16222. break;
  16223. case 6: // uniformResourceIdentifier
  16224. entry.type = SanType::URI;
  16225. entry.value =
  16226. std::string(reinterpret_cast<const char *>(p), value_len);
  16227. break;
  16228. default: entry.type = SanType::OTHER; break;
  16229. }
  16230. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16231. }
  16232. }
  16233. }
  16234. cur = cur->next;
  16235. }
  16236. return true;
  16237. }
  16238. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16239. time_t &not_after) {
  16240. if (!cert) return false;
  16241. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16242. // Convert mbedtls_x509_time to time_t
  16243. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  16244. struct tm tm_time = {};
  16245. tm_time.tm_year = t.year - 1900;
  16246. tm_time.tm_mon = t.mon - 1;
  16247. tm_time.tm_mday = t.day;
  16248. tm_time.tm_hour = t.hour;
  16249. tm_time.tm_min = t.min;
  16250. tm_time.tm_sec = t.sec;
  16251. #ifdef _WIN32
  16252. return _mkgmtime(&tm_time);
  16253. #else
  16254. return timegm(&tm_time);
  16255. #endif
  16256. };
  16257. not_before = to_time_t(x509->valid_from);
  16258. not_after = to_time_t(x509->valid_to);
  16259. return true;
  16260. }
  16261. inline std::string get_cert_serial(cert_t cert) {
  16262. if (!cert) return "";
  16263. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16264. // Convert serial number to hex string
  16265. std::string result;
  16266. result.reserve(x509->serial.len * 2);
  16267. for (size_t i = 0; i < x509->serial.len; i++) {
  16268. char hex[3];
  16269. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  16270. result += hex;
  16271. }
  16272. return result;
  16273. }
  16274. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16275. if (!cert) return false;
  16276. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16277. if (!crt->raw.p || crt->raw.len == 0) return false;
  16278. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16279. return true;
  16280. }
  16281. inline const char *get_sni(const_session_t session) {
  16282. if (!session) return nullptr;
  16283. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16284. // For server: return SNI received from client during handshake
  16285. if (!msession->sni_hostname.empty()) {
  16286. return msession->sni_hostname.c_str();
  16287. }
  16288. // For client: return the hostname set via set_sni
  16289. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16290. return nullptr;
  16291. }
  16292. inline uint64_t peek_error() {
  16293. // Mbed TLS doesn't have an error queue, return the last error
  16294. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16295. }
  16296. inline uint64_t get_error() {
  16297. // Mbed TLS doesn't have an error queue, return and clear the last error
  16298. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16299. impl::mbedtls_last_error() = 0;
  16300. return err;
  16301. }
  16302. inline std::string error_string(uint64_t code) {
  16303. char buf[256];
  16304. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16305. return std::string(buf);
  16306. }
  16307. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16308. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16309. if (!ca_chain) { return nullptr; }
  16310. mbedtls_x509_crt_init(ca_chain);
  16311. // mbedtls_x509_crt_parse expects null-terminated PEM
  16312. int ret = mbedtls_x509_crt_parse(ca_chain,
  16313. reinterpret_cast<const unsigned char *>(pem),
  16314. len + 1); // +1 for null terminator
  16315. if (ret != 0) {
  16316. // Try without +1 in case PEM is already null-terminated
  16317. ret = mbedtls_x509_crt_parse(
  16318. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16319. if (ret != 0) {
  16320. mbedtls_x509_crt_free(ca_chain);
  16321. delete ca_chain;
  16322. return nullptr;
  16323. }
  16324. }
  16325. return static_cast<ca_store_t>(ca_chain);
  16326. }
  16327. inline void free_ca_store(ca_store_t store) {
  16328. if (store) {
  16329. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16330. mbedtls_x509_crt_free(ca_chain);
  16331. delete ca_chain;
  16332. }
  16333. }
  16334. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16335. if (!ctx || !store) { return false; }
  16336. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16337. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16338. // Free existing CA chain
  16339. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16340. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16341. // Copy the CA chain (deep copy)
  16342. // Parse from the raw data of the source cert
  16343. mbedtls_x509_crt *src = ca_chain;
  16344. while (src != nullptr) {
  16345. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16346. src->raw.len);
  16347. if (ret != 0) {
  16348. free_ca_store(store);
  16349. return false;
  16350. }
  16351. src = src->next;
  16352. }
  16353. // This function takes ownership of the store; the chain was deep-copied
  16354. // above, so release the source
  16355. free_ca_store(store);
  16356. // Update the SSL config to use the new CA chain
  16357. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16358. return true;
  16359. }
  16360. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16361. certs.clear();
  16362. if (!ctx) { return 0; }
  16363. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16364. // Iterate through the CA chain
  16365. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16366. while (cert != nullptr && cert->raw.len > 0) {
  16367. // Create a copy of the certificate for the caller
  16368. auto *copy = new mbedtls_x509_crt;
  16369. mbedtls_x509_crt_init(copy);
  16370. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16371. if (ret == 0) {
  16372. certs.push_back(static_cast<cert_t>(copy));
  16373. } else {
  16374. mbedtls_x509_crt_free(copy);
  16375. delete copy;
  16376. }
  16377. cert = cert->next;
  16378. }
  16379. return certs.size();
  16380. }
  16381. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16382. std::vector<std::string> names;
  16383. if (!ctx) { return names; }
  16384. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16385. // Iterate through the CA chain
  16386. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16387. while (cert != nullptr && cert->raw.len > 0) {
  16388. char buf[512];
  16389. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16390. if (ret > 0) { names.push_back(buf); }
  16391. cert = cert->next;
  16392. }
  16393. return names;
  16394. }
  16395. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16396. const char *key_pem, const char *password) {
  16397. if (!ctx || !cert_pem || !key_pem) { return false; }
  16398. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16399. // Free existing certificate and key
  16400. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16401. mbedtls_pk_free(&mbed_ctx->own_key);
  16402. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16403. mbedtls_pk_init(&mbed_ctx->own_key);
  16404. // Parse certificate PEM
  16405. int ret = mbedtls_x509_crt_parse(
  16406. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16407. strlen(cert_pem) + 1);
  16408. if (ret != 0) {
  16409. impl::mbedtls_last_error() = ret;
  16410. return false;
  16411. }
  16412. // Parse private key PEM
  16413. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  16414. ret = mbedtls_pk_parse_key(
  16415. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16416. strlen(key_pem) + 1,
  16417. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16418. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16419. &mbed_ctx->ctr_drbg);
  16420. #else
  16421. ret = mbedtls_pk_parse_key(
  16422. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16423. strlen(key_pem) + 1,
  16424. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16425. password ? strlen(password) : 0);
  16426. #endif
  16427. if (ret != 0) {
  16428. impl::mbedtls_last_error() = ret;
  16429. return false;
  16430. }
  16431. // Configure SSL to use the new certificate and key
  16432. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16433. &mbed_ctx->own_key);
  16434. if (ret != 0) {
  16435. impl::mbedtls_last_error() = ret;
  16436. return false;
  16437. }
  16438. return true;
  16439. }
  16440. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16441. if (!ctx || !ca_pem) { return false; }
  16442. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16443. // Free existing CA chain
  16444. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16445. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16446. // Parse CA PEM
  16447. int ret = mbedtls_x509_crt_parse(
  16448. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16449. strlen(ca_pem) + 1);
  16450. if (ret != 0) {
  16451. impl::mbedtls_last_error() = ret;
  16452. return false;
  16453. }
  16454. // Update SSL config to use new CA chain
  16455. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16456. return true;
  16457. }
  16458. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16459. if (!ctx) { return false; }
  16460. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16461. impl::get_verify_callback() = std::move(callback);
  16462. mbed_ctx->has_verify_callback =
  16463. static_cast<bool>(impl::get_verify_callback());
  16464. if (mbed_ctx->has_verify_callback) {
  16465. // Set OPTIONAL mode to ensure callback is called even when verification
  16466. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16467. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16468. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16469. nullptr);
  16470. } else {
  16471. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16472. }
  16473. return true;
  16474. }
  16475. inline long get_verify_error(const_session_t session) {
  16476. if (!session) { return -1; }
  16477. auto *msession =
  16478. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16479. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16480. }
  16481. inline std::string verify_error_string(long error_code) {
  16482. if (error_code == 0) { return ""; }
  16483. char buf[256];
  16484. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16485. static_cast<uint32_t>(error_code));
  16486. // Remove trailing newline if present
  16487. std::string result(buf);
  16488. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16489. result.pop_back();
  16490. }
  16491. return result;
  16492. }
  16493. } // namespace tls
  16494. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16495. /*
  16496. * Group 10: TLS abstraction layer - wolfSSL backend
  16497. */
  16498. /*
  16499. * wolfSSL Backend Implementation
  16500. */
  16501. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16502. namespace tls {
  16503. namespace impl {
  16504. // wolfSSL session wrapper
  16505. struct WolfSSLSession {
  16506. WOLFSSL *ssl = nullptr;
  16507. socket_t sock = INVALID_SOCKET;
  16508. std::string hostname; // For client: set via set_sni
  16509. std::string sni_hostname; // For server: received from client via SNI callback
  16510. WolfSSLSession() = default;
  16511. ~WolfSSLSession() {
  16512. if (ssl) { wolfSSL_free(ssl); }
  16513. }
  16514. WolfSSLSession(const WolfSSLSession &) = delete;
  16515. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16516. };
  16517. // Thread-local error code accessor for wolfSSL
  16518. inline uint64_t &wolfssl_last_error() {
  16519. static thread_local uint64_t err = 0;
  16520. return err;
  16521. }
  16522. // Helper to map wolfSSL error to ErrorCode.
  16523. // ssl_error is the value from wolfSSL_get_error().
  16524. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16525. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16526. int &out_errno) {
  16527. switch (ssl_error) {
  16528. case SSL_ERROR_NONE: return ErrorCode::Success;
  16529. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16530. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16531. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16532. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16533. default:
  16534. if (ssl) {
  16535. // wolfSSL stores the low-level error code as a negative value.
  16536. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16537. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16538. if (low_err == DOMAIN_NAME_MISMATCH) {
  16539. return ErrorCode::HostnameMismatch;
  16540. }
  16541. // Check verify result to distinguish cert verification from generic SSL
  16542. // errors.
  16543. long vr = wolfSSL_get_verify_result(ssl);
  16544. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16545. }
  16546. return ErrorCode::Fatal;
  16547. }
  16548. }
  16549. // WolfSSLContext constructor/destructor implementations
  16550. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16551. inline WolfSSLContext::~WolfSSLContext() {
  16552. if (ctx) { wolfSSL_CTX_free(ctx); }
  16553. }
  16554. // Thread-local storage for SNI captured during handshake
  16555. inline std::string &wolfssl_pending_sni() {
  16556. static thread_local std::string sni;
  16557. return sni;
  16558. }
  16559. // SNI callback for wolfSSL server to capture client's SNI hostname
  16560. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16561. (void)ret;
  16562. (void)exArg;
  16563. void *name_data = nullptr;
  16564. unsigned short name_len =
  16565. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16566. if (name_data && name_len > 0) {
  16567. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16568. name_len);
  16569. } else {
  16570. wolfssl_pending_sni().clear();
  16571. }
  16572. return 0; // Continue regardless
  16573. }
  16574. // wolfSSL verify callback wrapper
  16575. inline int wolfssl_verify_callback(int preverify_ok,
  16576. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16577. auto &callback = get_verify_callback();
  16578. if (!callback) { return preverify_ok; }
  16579. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16580. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16581. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16582. // Get the WOLFSSL object from the X509_STORE_CTX
  16583. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16584. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16585. VerifyContext verify_ctx;
  16586. verify_ctx.session = static_cast<session_t>(ssl);
  16587. verify_ctx.cert = static_cast<cert_t>(cert);
  16588. verify_ctx.depth = depth;
  16589. verify_ctx.preverify_ok = (preverify_ok != 0);
  16590. verify_ctx.error_code = static_cast<long>(err);
  16591. if (err != 0) {
  16592. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16593. } else {
  16594. verify_ctx.error_string = nullptr;
  16595. }
  16596. bool accepted = callback(verify_ctx);
  16597. return accepted ? 1 : 0;
  16598. }
  16599. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16600. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16601. wolfSSL_CTX_set_default_passwd_cb(
  16602. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16603. auto *pwd = static_cast<const char *>(userdata);
  16604. if (!pwd) return 0;
  16605. auto len = static_cast<int>(strlen(pwd));
  16606. if (len > size) len = size;
  16607. memcpy(buf, pwd, static_cast<size_t>(len));
  16608. return len;
  16609. });
  16610. }
  16611. } // namespace impl
  16612. inline ctx_t create_client_context() {
  16613. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16614. if (!ctx) { return nullptr; }
  16615. ctx->is_server = false;
  16616. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16617. if (!method) {
  16618. delete ctx;
  16619. return nullptr;
  16620. }
  16621. ctx->ctx = wolfSSL_CTX_new(method);
  16622. if (!ctx->ctx) {
  16623. delete ctx;
  16624. return nullptr;
  16625. }
  16626. // Default: verify peer certificate
  16627. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16628. return static_cast<ctx_t>(ctx);
  16629. }
  16630. inline ctx_t create_server_context() {
  16631. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16632. if (!ctx) { return nullptr; }
  16633. ctx->is_server = true;
  16634. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16635. if (!method) {
  16636. delete ctx;
  16637. return nullptr;
  16638. }
  16639. ctx->ctx = wolfSSL_CTX_new(method);
  16640. if (!ctx->ctx) {
  16641. delete ctx;
  16642. return nullptr;
  16643. }
  16644. // Default: don't verify client
  16645. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16646. // Enable SNI on server
  16647. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16648. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16649. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16650. return static_cast<ctx_t>(ctx);
  16651. }
  16652. inline void free_context(ctx_t ctx) {
  16653. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16654. }
  16655. inline bool set_min_version(ctx_t ctx, Version version) {
  16656. if (!ctx) { return false; }
  16657. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16658. int min_ver = WOLFSSL_TLSV1_2;
  16659. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16660. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16661. }
  16662. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16663. if (!ctx || !pem) { return false; }
  16664. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16665. int ret = wolfSSL_CTX_load_verify_buffer(
  16666. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16667. static_cast<long>(len), SSL_FILETYPE_PEM);
  16668. if (ret != SSL_SUCCESS) {
  16669. impl::wolfssl_last_error() =
  16670. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16671. return false;
  16672. }
  16673. wctx->ca_pem_data_.append(pem, len);
  16674. return true;
  16675. }
  16676. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16677. if (!ctx || !file_path) { return false; }
  16678. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16679. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16680. if (ret != SSL_SUCCESS) {
  16681. impl::wolfssl_last_error() =
  16682. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16683. return false;
  16684. }
  16685. return true;
  16686. }
  16687. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16688. if (!ctx || !dir_path) { return false; }
  16689. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16690. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16691. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16692. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16693. // immediately. Return true even on failure since the CA file may have
  16694. // already been loaded, matching OpenSSL's lenient behavior.
  16695. (void)ret;
  16696. return true;
  16697. }
  16698. inline bool load_system_certs(ctx_t ctx) {
  16699. if (!ctx) { return false; }
  16700. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16701. bool loaded = false;
  16702. #ifdef _WIN32
  16703. loaded = impl::enumerate_windows_system_certs(
  16704. [&](const unsigned char *data, size_t len) {
  16705. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16706. static_cast<long>(len),
  16707. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16708. });
  16709. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16710. loaded = impl::enumerate_macos_keychain_certs(
  16711. [&](const unsigned char *data, size_t len) {
  16712. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16713. static_cast<long>(len),
  16714. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16715. });
  16716. #else
  16717. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16718. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16719. SSL_SUCCESS) {
  16720. loaded = true;
  16721. break;
  16722. }
  16723. }
  16724. if (!loaded) {
  16725. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16726. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16727. SSL_SUCCESS) {
  16728. loaded = true;
  16729. break;
  16730. }
  16731. }
  16732. }
  16733. #endif
  16734. return loaded;
  16735. }
  16736. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16737. const char *password) {
  16738. if (!ctx || !cert || !key) { return false; }
  16739. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16740. // Load certificate
  16741. int ret = wolfSSL_CTX_use_certificate_buffer(
  16742. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16743. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16744. if (ret != SSL_SUCCESS) {
  16745. impl::wolfssl_last_error() =
  16746. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16747. return false;
  16748. }
  16749. // Set password callback if password is provided
  16750. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16751. // Load private key
  16752. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16753. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16754. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16755. if (ret != SSL_SUCCESS) {
  16756. impl::wolfssl_last_error() =
  16757. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16758. return false;
  16759. }
  16760. // Verify that the certificate and private key match
  16761. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16762. }
  16763. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16764. const char *key_path, const char *password) {
  16765. if (!ctx || !cert_path || !key_path) { return false; }
  16766. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16767. // Load certificate file
  16768. int ret =
  16769. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16770. if (ret != SSL_SUCCESS) {
  16771. impl::wolfssl_last_error() =
  16772. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16773. return false;
  16774. }
  16775. // Set password callback if password is provided
  16776. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16777. // Load private key file
  16778. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16779. if (ret != SSL_SUCCESS) {
  16780. impl::wolfssl_last_error() =
  16781. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16782. return false;
  16783. }
  16784. // Verify that the certificate and private key match
  16785. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16786. }
  16787. inline void set_verify_client(ctx_t ctx, bool require) {
  16788. if (!ctx) { return; }
  16789. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16790. wctx->verify_client = require;
  16791. if (require) {
  16792. wolfSSL_CTX_set_verify(
  16793. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16794. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16795. } else {
  16796. if (wctx->has_verify_callback) {
  16797. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16798. impl::wolfssl_verify_callback);
  16799. } else {
  16800. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16801. }
  16802. }
  16803. }
  16804. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16805. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16806. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16807. auto session = new (std::nothrow) impl::WolfSSLSession();
  16808. if (!session) { return nullptr; }
  16809. session->sock = sock;
  16810. session->ssl = wolfSSL_new(wctx->ctx);
  16811. if (!session->ssl) {
  16812. impl::wolfssl_last_error() =
  16813. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16814. delete session;
  16815. return nullptr;
  16816. }
  16817. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16818. return static_cast<session_t>(session);
  16819. }
  16820. inline void free_session(session_t session) {
  16821. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16822. }
  16823. inline bool set_sni(session_t session, const char *hostname) {
  16824. if (!session || !hostname) { return false; }
  16825. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16826. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16827. static_cast<word16>(strlen(hostname)));
  16828. if (ret != WOLFSSL_SUCCESS) {
  16829. impl::wolfssl_last_error() =
  16830. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16831. return false;
  16832. }
  16833. // Also set hostname for verification
  16834. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16835. wsession->hostname = hostname;
  16836. return true;
  16837. }
  16838. inline bool set_hostname(session_t session, const char *hostname) {
  16839. // In wolfSSL, set_hostname also sets up hostname verification
  16840. return set_sni(session, hostname);
  16841. }
  16842. inline TlsError connect(session_t session) {
  16843. TlsError err;
  16844. if (!session) {
  16845. err.code = ErrorCode::Fatal;
  16846. return err;
  16847. }
  16848. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16849. int ret = wolfSSL_connect(wsession->ssl);
  16850. if (ret == SSL_SUCCESS) {
  16851. err.code = ErrorCode::Success;
  16852. } else {
  16853. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16854. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16855. err.backend_code = static_cast<uint64_t>(ssl_error);
  16856. impl::wolfssl_last_error() = err.backend_code;
  16857. }
  16858. return err;
  16859. }
  16860. inline TlsError accept(session_t session) {
  16861. TlsError err;
  16862. if (!session) {
  16863. err.code = ErrorCode::Fatal;
  16864. return err;
  16865. }
  16866. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16867. int ret = wolfSSL_accept(wsession->ssl);
  16868. if (ret == SSL_SUCCESS) {
  16869. err.code = ErrorCode::Success;
  16870. // Capture SNI from thread-local storage after successful handshake
  16871. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16872. impl::wolfssl_pending_sni().clear();
  16873. } else {
  16874. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16875. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16876. err.backend_code = static_cast<uint64_t>(ssl_error);
  16877. impl::wolfssl_last_error() = err.backend_code;
  16878. }
  16879. return err;
  16880. }
  16881. inline bool connect_nonblocking(session_t session, socket_t sock,
  16882. time_t timeout_sec, time_t timeout_usec,
  16883. TlsError *err) {
  16884. if (!session) {
  16885. if (err) { err->code = ErrorCode::Fatal; }
  16886. return false;
  16887. }
  16888. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16889. // Set socket to non-blocking mode
  16890. detail::set_nonblocking(sock, true);
  16891. auto cleanup =
  16892. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16893. int ret;
  16894. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16895. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16896. if (ssl_error == SSL_ERROR_WANT_READ) {
  16897. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16898. continue;
  16899. }
  16900. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16901. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16902. continue;
  16903. }
  16904. }
  16905. // Error or timeout
  16906. if (err) {
  16907. err->code =
  16908. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16909. err->backend_code = static_cast<uint64_t>(ssl_error);
  16910. }
  16911. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16912. return false;
  16913. }
  16914. if (err) { err->code = ErrorCode::Success; }
  16915. return true;
  16916. }
  16917. inline bool accept_nonblocking(session_t session, socket_t sock,
  16918. time_t timeout_sec, time_t timeout_usec,
  16919. TlsError *err) {
  16920. if (!session) {
  16921. if (err) { err->code = ErrorCode::Fatal; }
  16922. return false;
  16923. }
  16924. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16925. // Set socket to non-blocking mode
  16926. detail::set_nonblocking(sock, true);
  16927. auto cleanup =
  16928. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16929. int ret;
  16930. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16931. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16932. if (ssl_error == SSL_ERROR_WANT_READ) {
  16933. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16934. continue;
  16935. }
  16936. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16937. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16938. continue;
  16939. }
  16940. }
  16941. // Error or timeout
  16942. if (err) {
  16943. err->code =
  16944. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16945. err->backend_code = static_cast<uint64_t>(ssl_error);
  16946. }
  16947. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16948. return false;
  16949. }
  16950. if (err) { err->code = ErrorCode::Success; }
  16951. // Capture SNI from thread-local storage after successful handshake
  16952. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16953. impl::wolfssl_pending_sni().clear();
  16954. return true;
  16955. }
  16956. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16957. if (!session || !buf) {
  16958. err.code = ErrorCode::Fatal;
  16959. return -1;
  16960. }
  16961. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16962. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16963. if (ret > 0) {
  16964. err.code = ErrorCode::Success;
  16965. return static_cast<ssize_t>(ret);
  16966. }
  16967. if (ret == 0) {
  16968. err.code = ErrorCode::PeerClosed;
  16969. return 0;
  16970. }
  16971. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16972. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16973. err.backend_code = static_cast<uint64_t>(ssl_error);
  16974. impl::wolfssl_last_error() = err.backend_code;
  16975. return -1;
  16976. }
  16977. inline ssize_t write(session_t session, const void *buf, size_t len,
  16978. TlsError &err) {
  16979. if (!session || !buf) {
  16980. err.code = ErrorCode::Fatal;
  16981. return -1;
  16982. }
  16983. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16984. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16985. if (ret > 0) {
  16986. err.code = ErrorCode::Success;
  16987. return static_cast<ssize_t>(ret);
  16988. }
  16989. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16990. // Treat this as an error (return -1) so callers don't spin in a
  16991. // write loop adding zero to the offset.
  16992. if (ret == 0) {
  16993. err.code = ErrorCode::PeerClosed;
  16994. return -1;
  16995. }
  16996. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16997. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16998. err.backend_code = static_cast<uint64_t>(ssl_error);
  16999. impl::wolfssl_last_error() = err.backend_code;
  17000. return -1;
  17001. }
  17002. inline int pending(const_session_t session) {
  17003. if (!session) { return 0; }
  17004. auto wsession =
  17005. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17006. return wolfSSL_pending(wsession->ssl);
  17007. }
  17008. inline void shutdown(session_t session, bool graceful) {
  17009. if (!session) { return; }
  17010. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  17011. if (graceful) {
  17012. int ret;
  17013. int attempts = 0;
  17014. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  17015. attempts < 3) {
  17016. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  17017. if (ssl_error != SSL_ERROR_WANT_READ &&
  17018. ssl_error != SSL_ERROR_WANT_WRITE) {
  17019. break;
  17020. }
  17021. attempts++;
  17022. }
  17023. } else {
  17024. wolfSSL_shutdown(wsession->ssl);
  17025. }
  17026. }
  17027. inline bool is_peer_closed(session_t session, socket_t sock) {
  17028. if (!session || sock == INVALID_SOCKET) { return true; }
  17029. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  17030. // Check if there's already decrypted data available
  17031. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  17032. // Set socket to non-blocking to avoid blocking on read
  17033. detail::set_nonblocking(sock, true);
  17034. auto cleanup =
  17035. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17036. // Peek 1 byte to check connection status without consuming data
  17037. unsigned char buf;
  17038. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  17039. // If we got data or WANT_READ (would block), connection is alive
  17040. if (ret > 0) { return false; }
  17041. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  17042. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  17043. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  17044. ret == 0;
  17045. }
  17046. inline cert_t get_peer_cert(const_session_t session) {
  17047. if (!session) { return nullptr; }
  17048. auto wsession =
  17049. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17050. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  17051. return static_cast<cert_t>(cert);
  17052. }
  17053. inline void free_cert(cert_t cert) {
  17054. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  17055. }
  17056. inline bool verify_hostname(cert_t cert, const char *hostname) {
  17057. if (!cert || !hostname) { return false; }
  17058. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17059. std::string host_str(hostname);
  17060. // Check if hostname is an IP address (IPv4 or IPv6)
  17061. unsigned char ip_bytes[16];
  17062. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  17063. auto is_ip = ip_len > 0;
  17064. // Check Subject Alternative Names
  17065. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  17066. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  17067. if (san_names) {
  17068. int san_count = wolfSSL_sk_num(san_names);
  17069. for (int i = 0; i < san_count; i++) {
  17070. auto *names =
  17071. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  17072. if (!names) continue;
  17073. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  17074. // DNS name
  17075. unsigned char *dns_name = nullptr;
  17076. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  17077. if (dns_name && dns_len > 0) {
  17078. std::string san_name(reinterpret_cast<char *>(dns_name),
  17079. static_cast<size_t>(dns_len));
  17080. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  17081. if (detail::match_hostname(san_name, host_str)) {
  17082. wolfSSL_sk_free(san_names);
  17083. return true;
  17084. }
  17085. }
  17086. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  17087. // IP address: only an iPAddress SAN of the same family (4 bytes for
  17088. // IPv4, 16 bytes for IPv6) may authenticate the host.
  17089. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  17090. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  17091. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  17092. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  17093. wolfSSL_sk_free(san_names);
  17094. return true;
  17095. }
  17096. }
  17097. }
  17098. wolfSSL_sk_free(san_names);
  17099. }
  17100. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  17101. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  17102. // the OpenSSL backend's X509_check_ip behaves the same way).
  17103. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  17104. if (subject) {
  17105. char cn[256] = {};
  17106. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  17107. sizeof(cn));
  17108. if (cn_len > 0) {
  17109. std::string cn_str(cn, static_cast<size_t>(cn_len));
  17110. if (detail::match_hostname(cn_str, host_str)) { return true; }
  17111. }
  17112. }
  17113. return false;
  17114. }
  17115. inline uint64_t hostname_mismatch_code() {
  17116. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  17117. }
  17118. inline long get_verify_result(const_session_t session) {
  17119. if (!session) { return -1; }
  17120. auto wsession =
  17121. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17122. long result = wolfSSL_get_verify_result(wsession->ssl);
  17123. return result;
  17124. }
  17125. inline std::string get_cert_subject_cn(cert_t cert) {
  17126. if (!cert) return "";
  17127. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17128. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17129. if (!subject) return "";
  17130. char cn[256] = {};
  17131. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  17132. sizeof(cn));
  17133. if (cn_len <= 0) return "";
  17134. return std::string(cn, static_cast<size_t>(cn_len));
  17135. }
  17136. inline std::string get_cert_issuer_name(cert_t cert) {
  17137. if (!cert) return "";
  17138. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17139. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  17140. if (!issuer) return "";
  17141. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  17142. if (!name_str) return "";
  17143. std::string result(name_str);
  17144. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17145. return result;
  17146. }
  17147. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  17148. sans.clear();
  17149. if (!cert) return false;
  17150. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17151. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  17152. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  17153. if (!san_names) return true; // No SANs is not an error
  17154. int count = wolfSSL_sk_num(san_names);
  17155. for (int i = 0; i < count; i++) {
  17156. auto *name =
  17157. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  17158. if (!name) continue;
  17159. SanEntry entry;
  17160. switch (name->type) {
  17161. case WOLFSSL_GEN_DNS: {
  17162. entry.type = SanType::DNS;
  17163. unsigned char *dns_name = nullptr;
  17164. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  17165. if (dns_name && dns_len > 0) {
  17166. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  17167. static_cast<size_t>(dns_len));
  17168. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  17169. }
  17170. break;
  17171. }
  17172. case WOLFSSL_GEN_IPADD: {
  17173. entry.type = SanType::IP;
  17174. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  17175. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  17176. if (ip_data && ip_len == 4) {
  17177. char buf[16];
  17178. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  17179. ip_data[2], ip_data[3]);
  17180. entry.value = buf;
  17181. } else if (ip_data && ip_len == 16) {
  17182. char buf[64];
  17183. snprintf(buf, sizeof(buf),
  17184. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  17185. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  17186. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  17187. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  17188. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  17189. ip_data[14], ip_data[15]);
  17190. entry.value = buf;
  17191. }
  17192. break;
  17193. }
  17194. case WOLFSSL_GEN_EMAIL:
  17195. entry.type = SanType::EMAIL;
  17196. {
  17197. unsigned char *email = nullptr;
  17198. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  17199. if (email && email_len > 0) {
  17200. entry.value = std::string(reinterpret_cast<char *>(email),
  17201. static_cast<size_t>(email_len));
  17202. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  17203. }
  17204. }
  17205. break;
  17206. case WOLFSSL_GEN_URI:
  17207. entry.type = SanType::URI;
  17208. {
  17209. unsigned char *uri = nullptr;
  17210. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  17211. &uri, name->d.uniformResourceIdentifier);
  17212. if (uri && uri_len > 0) {
  17213. entry.value = std::string(reinterpret_cast<char *>(uri),
  17214. static_cast<size_t>(uri_len));
  17215. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  17216. }
  17217. }
  17218. break;
  17219. default: entry.type = SanType::OTHER; break;
  17220. }
  17221. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17222. }
  17223. wolfSSL_sk_free(san_names);
  17224. return true;
  17225. }
  17226. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17227. time_t &not_after) {
  17228. if (!cert) return false;
  17229. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17230. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  17231. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  17232. if (!nb || !na) return false;
  17233. // wolfSSL_ASN1_TIME_to_tm is available
  17234. struct tm tm_nb = {}, tm_na = {};
  17235. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  17236. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  17237. #ifdef _WIN32
  17238. not_before = _mkgmtime(&tm_nb);
  17239. not_after = _mkgmtime(&tm_na);
  17240. #else
  17241. not_before = timegm(&tm_nb);
  17242. not_after = timegm(&tm_na);
  17243. #endif
  17244. return true;
  17245. }
  17246. inline std::string get_cert_serial(cert_t cert) {
  17247. if (!cert) return "";
  17248. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17249. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  17250. if (!serial_asn1) return "";
  17251. // Get the serial number data
  17252. int len = serial_asn1->length;
  17253. unsigned char *data = serial_asn1->data;
  17254. if (!data || len <= 0) return "";
  17255. std::string result;
  17256. result.reserve(static_cast<size_t>(len) * 2);
  17257. for (int i = 0; i < len; i++) {
  17258. char hex[3];
  17259. snprintf(hex, sizeof(hex), "%02X", data[i]);
  17260. result += hex;
  17261. }
  17262. return result;
  17263. }
  17264. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17265. if (!cert) return false;
  17266. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17267. int der_len = 0;
  17268. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  17269. if (!der_data || der_len <= 0) return false;
  17270. der.assign(der_data, der_data + der_len);
  17271. return true;
  17272. }
  17273. inline const char *get_sni(const_session_t session) {
  17274. if (!session) return nullptr;
  17275. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17276. // For server: return SNI received from client during handshake
  17277. if (!wsession->sni_hostname.empty()) {
  17278. return wsession->sni_hostname.c_str();
  17279. }
  17280. // For client: return the hostname set via set_sni
  17281. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17282. return nullptr;
  17283. }
  17284. inline uint64_t peek_error() {
  17285. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17286. }
  17287. inline uint64_t get_error() {
  17288. uint64_t err = impl::wolfssl_last_error();
  17289. impl::wolfssl_last_error() = 0;
  17290. return err;
  17291. }
  17292. inline std::string error_string(uint64_t code) {
  17293. char buf[256];
  17294. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17295. return std::string(buf);
  17296. }
  17297. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17298. if (!pem || len == 0) { return nullptr; }
  17299. // Validate by attempting to load into a temporary ctx
  17300. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17301. if (!tmp_ctx) { return nullptr; }
  17302. int ret = wolfSSL_CTX_load_verify_buffer(
  17303. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17304. static_cast<long>(len), SSL_FILETYPE_PEM);
  17305. wolfSSL_CTX_free(tmp_ctx);
  17306. if (ret != SSL_SUCCESS) { return nullptr; }
  17307. return static_cast<ca_store_t>(
  17308. new impl::WolfSSLCAStore{std::string(pem, len)});
  17309. }
  17310. inline void free_ca_store(ca_store_t store) {
  17311. delete static_cast<impl::WolfSSLCAStore *>(store);
  17312. }
  17313. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17314. if (!ctx || !store) { return false; }
  17315. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17316. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17317. int ret = wolfSSL_CTX_load_verify_buffer(
  17318. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17319. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17320. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17321. // This function takes ownership of the store; the PEM data was copied into
  17322. // the context, so release the source
  17323. free_ca_store(store);
  17324. return ret == SSL_SUCCESS;
  17325. }
  17326. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17327. certs.clear();
  17328. if (!ctx) { return 0; }
  17329. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17330. if (wctx->ca_pem_data_.empty()) { return 0; }
  17331. const std::string &pem = wctx->ca_pem_data_;
  17332. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17333. const std::string end_marker = "-----END CERTIFICATE-----";
  17334. size_t pos = 0;
  17335. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17336. size_t end_pos = pem.find(end_marker, pos);
  17337. if (end_pos == std::string::npos) { break; }
  17338. end_pos += end_marker.size();
  17339. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17340. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17341. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17342. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17343. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17344. pos = end_pos;
  17345. }
  17346. return certs.size();
  17347. }
  17348. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17349. std::vector<std::string> names;
  17350. if (!ctx) { return names; }
  17351. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17352. if (wctx->ca_pem_data_.empty()) { return names; }
  17353. const std::string &pem = wctx->ca_pem_data_;
  17354. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17355. const std::string end_marker = "-----END CERTIFICATE-----";
  17356. size_t pos = 0;
  17357. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17358. size_t end_pos = pem.find(end_marker, pos);
  17359. if (end_pos == std::string::npos) { break; }
  17360. end_pos += end_marker.size();
  17361. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17362. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17363. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17364. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17365. if (x509) {
  17366. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17367. if (subject) {
  17368. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17369. if (name_str) {
  17370. names.push_back(name_str);
  17371. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17372. }
  17373. }
  17374. wolfSSL_X509_free(x509);
  17375. }
  17376. pos = end_pos;
  17377. }
  17378. return names;
  17379. }
  17380. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17381. const char *key_pem, const char *password) {
  17382. if (!ctx || !cert_pem || !key_pem) { return false; }
  17383. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17384. // Load new certificate
  17385. int ret = wolfSSL_CTX_use_certificate_buffer(
  17386. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17387. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17388. if (ret != SSL_SUCCESS) {
  17389. impl::wolfssl_last_error() =
  17390. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17391. return false;
  17392. }
  17393. // Set password if provided
  17394. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17395. // Load new private key
  17396. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17397. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17398. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17399. if (ret != SSL_SUCCESS) {
  17400. impl::wolfssl_last_error() =
  17401. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17402. return false;
  17403. }
  17404. return true;
  17405. }
  17406. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17407. if (!ctx || !ca_pem) { return false; }
  17408. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17409. int ret = wolfSSL_CTX_load_verify_buffer(
  17410. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17411. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17412. if (ret != SSL_SUCCESS) {
  17413. impl::wolfssl_last_error() =
  17414. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17415. return false;
  17416. }
  17417. return true;
  17418. }
  17419. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17420. if (!ctx) { return false; }
  17421. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17422. impl::get_verify_callback() = std::move(callback);
  17423. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17424. if (wctx->has_verify_callback) {
  17425. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17426. impl::wolfssl_verify_callback);
  17427. } else {
  17428. wolfSSL_CTX_set_verify(
  17429. wctx->ctx,
  17430. wctx->verify_client
  17431. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17432. : SSL_VERIFY_NONE,
  17433. nullptr);
  17434. }
  17435. return true;
  17436. }
  17437. inline long get_verify_error(const_session_t session) {
  17438. if (!session) { return -1; }
  17439. auto *wsession =
  17440. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17441. return wolfSSL_get_verify_result(wsession->ssl);
  17442. }
  17443. inline std::string verify_error_string(long error_code) {
  17444. if (error_code == 0) { return ""; }
  17445. const char *str =
  17446. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17447. return str ? std::string(str) : std::string();
  17448. }
  17449. } // namespace tls
  17450. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17451. // WebSocket implementation
  17452. namespace ws {
  17453. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17454. bool fin) {
  17455. std::lock_guard<std::mutex> lock(write_mutex_);
  17456. if (closed_) { return false; }
  17457. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17458. }
  17459. inline ReadResult WebSocket::read(std::string &msg) {
  17460. while (!closed_) {
  17461. Opcode opcode;
  17462. std::string payload;
  17463. bool fin;
  17464. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17465. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17466. closed_ = true;
  17467. return Fail;
  17468. }
  17469. switch (opcode) {
  17470. case Opcode::Ping: {
  17471. std::lock_guard<std::mutex> lock(write_mutex_);
  17472. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17473. payload.size(), true, !is_server_);
  17474. continue;
  17475. }
  17476. case Opcode::Pong: {
  17477. std::lock_guard<std::mutex> lock(ping_mutex_);
  17478. unacked_pings_ = 0;
  17479. continue;
  17480. }
  17481. case Opcode::Close: {
  17482. if (!closed_.exchange(true)) {
  17483. // Echo close frame back
  17484. std::lock_guard<std::mutex> lock(write_mutex_);
  17485. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17486. payload.size(), true, !is_server_);
  17487. }
  17488. return Fail;
  17489. }
  17490. case Opcode::Text:
  17491. case Opcode::Binary: {
  17492. auto result = opcode == Opcode::Text ? Text : Binary;
  17493. msg = std::move(payload);
  17494. // Handle fragmentation
  17495. if (!fin) {
  17496. while (true) {
  17497. Opcode cont_opcode;
  17498. std::string cont_payload;
  17499. bool cont_fin;
  17500. if (!impl::read_websocket_frame(
  17501. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17502. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17503. closed_ = true;
  17504. return Fail;
  17505. }
  17506. if (cont_opcode == Opcode::Ping) {
  17507. std::lock_guard<std::mutex> lock(write_mutex_);
  17508. detail::write_websocket_frame(
  17509. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17510. true, !is_server_);
  17511. continue;
  17512. }
  17513. if (cont_opcode == Opcode::Pong) {
  17514. std::lock_guard<std::mutex> lock(ping_mutex_);
  17515. unacked_pings_ = 0;
  17516. continue;
  17517. }
  17518. if (cont_opcode == Opcode::Close) {
  17519. if (!closed_.exchange(true)) {
  17520. std::lock_guard<std::mutex> lock(write_mutex_);
  17521. detail::write_websocket_frame(
  17522. strm_, Opcode::Close, cont_payload.data(),
  17523. cont_payload.size(), true, !is_server_);
  17524. }
  17525. return Fail;
  17526. }
  17527. // RFC 6455: continuation frames must use opcode 0x0
  17528. if (cont_opcode != Opcode::Continuation) {
  17529. closed_ = true;
  17530. return Fail;
  17531. }
  17532. msg += cont_payload;
  17533. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17534. closed_ = true;
  17535. return Fail;
  17536. }
  17537. if (cont_fin) { break; }
  17538. }
  17539. }
  17540. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17541. if (result == Text && !impl::is_valid_utf8(msg)) {
  17542. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17543. return Fail;
  17544. }
  17545. return result;
  17546. }
  17547. default: closed_ = true; return Fail;
  17548. }
  17549. }
  17550. return Fail;
  17551. }
  17552. inline bool WebSocket::send(const std::string &data) {
  17553. return send_frame(Opcode::Text, data.data(), data.size());
  17554. }
  17555. inline bool WebSocket::send(const char *data, size_t len) {
  17556. return send_frame(Opcode::Binary, data, len);
  17557. }
  17558. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17559. if (closed_.exchange(true)) { return; }
  17560. ping_cv_.notify_all();
  17561. std::string payload;
  17562. auto code = static_cast<uint16_t>(status);
  17563. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17564. payload.push_back(static_cast<char>(code & 0xFF));
  17565. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17566. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17567. payload += reason.substr(0, 123);
  17568. {
  17569. std::lock_guard<std::mutex> lock(write_mutex_);
  17570. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17571. payload.size(), true, !is_server_);
  17572. }
  17573. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17574. // Close response before closing the TCP connection. Use a short timeout to
  17575. // avoid hanging if the peer doesn't respond.
  17576. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17577. Opcode op;
  17578. std::string resp;
  17579. bool fin;
  17580. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17581. if (op == Opcode::Close) { break; }
  17582. }
  17583. }
  17584. inline WebSocket::~WebSocket() {
  17585. {
  17586. std::lock_guard<std::mutex> lock(ping_mutex_);
  17587. closed_ = true;
  17588. }
  17589. ping_cv_.notify_all();
  17590. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17591. }
  17592. inline void WebSocket::start_heartbeat() {
  17593. if (ping_interval_sec_ == 0) { return; }
  17594. ping_thread_ = std::thread([this]() {
  17595. std::unique_lock<std::mutex> lock(ping_mutex_);
  17596. while (!closed_) {
  17597. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17598. if (closed_) { break; }
  17599. // If the peer has failed to respond to the previous pings, give up.
  17600. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17601. // opt-in liveness check controlled by max_missed_pongs_.
  17602. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17603. lock.unlock();
  17604. close(CloseStatus::GoingAway, "pong timeout");
  17605. return;
  17606. }
  17607. lock.unlock();
  17608. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17609. lock.lock();
  17610. closed_ = true;
  17611. break;
  17612. }
  17613. lock.lock();
  17614. unacked_pings_++;
  17615. }
  17616. });
  17617. }
  17618. inline const Request &WebSocket::request() const { return req_; }
  17619. inline bool WebSocket::is_open() const { return !closed_; }
  17620. // WebSocketClient implementation
  17621. inline WebSocketClient::WebSocketClient(
  17622. const std::string &scheme_host_port_path, const Headers &headers)
  17623. : headers_(headers) {
  17624. detail::UrlComponents uc;
  17625. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17626. !uc.host.empty() && !uc.path.empty()) {
  17627. auto &scheme = uc.scheme;
  17628. #ifdef CPPHTTPLIB_SSL_ENABLED
  17629. if (scheme != "ws" && scheme != "wss") {
  17630. #else
  17631. if (scheme != "ws") {
  17632. #endif
  17633. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17634. std::string msg = "'" + scheme + "' scheme is not supported.";
  17635. throw std::invalid_argument(msg);
  17636. #endif
  17637. return;
  17638. }
  17639. auto is_ssl = scheme == "wss";
  17640. host_ = std::move(uc.host);
  17641. port_ = is_ssl ? 443 : 80;
  17642. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17643. path_ = std::move(uc.path);
  17644. if (!uc.query.empty()) { path_ += uc.query; }
  17645. #ifdef CPPHTTPLIB_SSL_ENABLED
  17646. is_ssl_ = is_ssl;
  17647. if (is_ssl_) {
  17648. // The context lives as long as the client so that CA configuration
  17649. // survives reconnects; sessions are created per connection.
  17650. tls_ctx_ = tls::create_client_context();
  17651. if (!tls_ctx_) { return; }
  17652. }
  17653. #else
  17654. if (is_ssl) { return; }
  17655. #endif
  17656. is_valid_ = true;
  17657. }
  17658. }
  17659. inline WebSocketClient::~WebSocketClient() {
  17660. shutdown_and_close();
  17661. #ifdef CPPHTTPLIB_SSL_ENABLED
  17662. if (tls_ctx_) {
  17663. tls::free_context(tls_ctx_);
  17664. tls_ctx_ = nullptr;
  17665. }
  17666. #endif
  17667. }
  17668. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17669. inline void WebSocketClient::shutdown_and_close() {
  17670. // Send the close frame while the TLS session is still alive: ws_ holds an
  17671. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  17672. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  17673. if (ws_ && ws_->is_open()) { ws_->close(); }
  17674. ws_.reset();
  17675. #ifdef CPPHTTPLIB_SSL_ENABLED
  17676. if (is_ssl_) {
  17677. if (tls_session_) {
  17678. tls::shutdown(tls_session_, true);
  17679. tls::free_session(tls_session_);
  17680. tls_session_ = nullptr;
  17681. }
  17682. }
  17683. #endif
  17684. if (sock_ != INVALID_SOCKET) {
  17685. detail::shutdown_socket(sock_);
  17686. detail::close_socket(sock_);
  17687. sock_ = INVALID_SOCKET;
  17688. }
  17689. }
  17690. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17691. #ifdef CPPHTTPLIB_SSL_ENABLED
  17692. if (is_ssl_) {
  17693. if (server_certificate_verification_ && !certs_loaded_) {
  17694. uint64_t backend_error = 0;
  17695. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17696. custom_ca_loaded_, system_ca_mode_,
  17697. backend_error);
  17698. certs_loaded_ = true;
  17699. }
  17700. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17701. server_certificate_verification_,
  17702. read_timeout_sec_,
  17703. read_timeout_usec_)) {
  17704. return false;
  17705. }
  17706. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17707. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17708. write_timeout_sec_, write_timeout_usec_));
  17709. return true;
  17710. }
  17711. #endif
  17712. strm = std::unique_ptr<Stream>(
  17713. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17714. write_timeout_sec_, write_timeout_usec_));
  17715. return true;
  17716. }
  17717. inline void WebSocketClient::prepare_default_headers(Request &req) {
  17718. #ifdef CPPHTTPLIB_SSL_ENABLED
  17719. auto is_ssl = is_ssl_;
  17720. #else
  17721. auto is_ssl = false;
  17722. #endif
  17723. if (!req.has_header("Host")) {
  17724. if (address_family_ == AF_UNIX) {
  17725. req.headers.emplace("Host", "localhost");
  17726. } else {
  17727. req.headers.emplace(
  17728. "Host", detail::make_host_and_port_string(host_, port_, is_ssl));
  17729. }
  17730. }
  17731. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  17732. if (!req.has_header("User-Agent")) {
  17733. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  17734. req.set_header("User-Agent", agent);
  17735. }
  17736. #endif
  17737. }
  17738. inline bool WebSocketClient::connect() {
  17739. if (!is_valid_) { return false; }
  17740. shutdown_and_close();
  17741. // Check is custom IP or hostname specified for host_
  17742. std::string connect_host;
  17743. std::string ip;
  17744. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  17745. Error error;
  17746. sock_ = detail::create_client_socket(
  17747. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17748. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17749. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17750. write_timeout_usec_, interface_, error);
  17751. if (sock_ == INVALID_SOCKET) { return false; }
  17752. std::unique_ptr<Stream> strm;
  17753. if (!create_stream(strm)) {
  17754. shutdown_and_close();
  17755. return false;
  17756. }
  17757. Request req;
  17758. req.method = "GET";
  17759. req.path = path_;
  17760. req.headers = headers_;
  17761. prepare_default_headers(req);
  17762. std::string selected_subprotocol;
  17763. if (!detail::perform_websocket_handshake(*strm, req, selected_subprotocol)) {
  17764. shutdown_and_close();
  17765. return false;
  17766. }
  17767. subprotocol_ = std::move(selected_subprotocol);
  17768. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17769. websocket_ping_interval_sec_,
  17770. websocket_max_missed_pongs_));
  17771. return true;
  17772. }
  17773. inline ReadResult WebSocketClient::read(std::string &msg) {
  17774. if (!ws_) { return Fail; }
  17775. return ws_->read(msg);
  17776. }
  17777. inline bool WebSocketClient::send(const std::string &data) {
  17778. if (!ws_) { return false; }
  17779. return ws_->send(data);
  17780. }
  17781. inline bool WebSocketClient::send(const char *data, size_t len) {
  17782. if (!ws_) { return false; }
  17783. return ws_->send(data, len);
  17784. }
  17785. inline void WebSocketClient::close(CloseStatus status,
  17786. const std::string &reason) {
  17787. if (ws_) { ws_->close(status, reason); }
  17788. }
  17789. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17790. inline const std::string &WebSocketClient::subprotocol() const {
  17791. return subprotocol_;
  17792. }
  17793. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17794. read_timeout_sec_ = sec;
  17795. read_timeout_usec_ = usec;
  17796. }
  17797. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17798. write_timeout_sec_ = sec;
  17799. write_timeout_usec_ = usec;
  17800. }
  17801. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17802. websocket_ping_interval_sec_ = sec;
  17803. }
  17804. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17805. websocket_max_missed_pongs_ = count;
  17806. }
  17807. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17808. inline void WebSocketClient::set_address_family(int family) {
  17809. address_family_ = family;
  17810. }
  17811. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17812. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17813. socket_options_ = std::move(socket_options);
  17814. }
  17815. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17816. connection_timeout_sec_ = sec;
  17817. connection_timeout_usec_ = usec;
  17818. }
  17819. inline void WebSocketClient::set_interface(const std::string &intf) {
  17820. interface_ = intf;
  17821. }
  17822. inline void WebSocketClient::set_hostname_addr_map(
  17823. std::map<std::string, std::string> addr_map) {
  17824. addr_map_ = std::move(addr_map);
  17825. }
  17826. #ifdef CPPHTTPLIB_SSL_ENABLED
  17827. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17828. ca_cert_file_path_ = path;
  17829. }
  17830. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17831. if (store && tls_ctx_) {
  17832. // set_ca_store takes ownership of store
  17833. tls::set_ca_store(tls_ctx_, store);
  17834. custom_ca_loaded_ = true;
  17835. } else if (store) {
  17836. tls::free_ca_store(store);
  17837. }
  17838. }
  17839. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17840. std::size_t size) {
  17841. if (tls_ctx_ && ca_cert && size > 0) {
  17842. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17843. custom_ca_loaded_ = true;
  17844. }
  17845. }
  17846. inline void
  17847. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17848. server_certificate_verification_ = enabled;
  17849. }
  17850. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17851. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17852. }
  17853. #endif // CPPHTTPLIB_SSL_ENABLED
  17854. } // namespace ws
  17855. // ----------------------------------------------------------------------------
  17856. } // namespace httplib
  17857. #endif // CPPHTTPLIB_HTTPLIB_H