httplib.h 689 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818
  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.50.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003201"
  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 5
  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. #include <mbedtls/ctr_drbg.h>
  343. #include <mbedtls/entropy.h>
  344. #include <mbedtls/error.h>
  345. #include <mbedtls/md5.h>
  346. #include <mbedtls/net_sockets.h>
  347. #include <mbedtls/oid.h>
  348. #include <mbedtls/pk.h>
  349. #include <mbedtls/sha1.h>
  350. #include <mbedtls/sha256.h>
  351. #include <mbedtls/sha512.h>
  352. #include <mbedtls/ssl.h>
  353. #include <mbedtls/x509_crt.h>
  354. #ifdef _WIN32
  355. #include <wincrypt.h>
  356. #ifdef _MSC_VER
  357. #pragma comment(lib, "crypt32.lib")
  358. #endif
  359. #endif // _WIN32
  360. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  361. #if TARGET_OS_OSX
  362. #include <Security/Security.h>
  363. #endif
  364. #endif
  365. // Mbed TLS 3.x API compatibility
  366. #if MBEDTLS_VERSION_MAJOR >= 3
  367. #define CPPHTTPLIB_MBEDTLS_V3
  368. #endif
  369. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  370. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  371. #include <wolfssl/options.h>
  372. #include <wolfssl/openssl/x509v3.h>
  373. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  374. #ifndef WOLFSSL_GEN_EMAIL
  375. #define WOLFSSL_GEN_EMAIL 1
  376. #endif
  377. #ifndef WOLFSSL_GEN_DNS
  378. #define WOLFSSL_GEN_DNS 2
  379. #endif
  380. #ifndef WOLFSSL_GEN_URI
  381. #define WOLFSSL_GEN_URI 6
  382. #endif
  383. #ifndef WOLFSSL_GEN_IPADD
  384. #define WOLFSSL_GEN_IPADD 7
  385. #endif
  386. #include <wolfssl/ssl.h>
  387. #include <wolfssl/wolfcrypt/hash.h>
  388. #include <wolfssl/wolfcrypt/md5.h>
  389. #include <wolfssl/wolfcrypt/sha256.h>
  390. #include <wolfssl/wolfcrypt/sha512.h>
  391. #ifdef _WIN32
  392. #include <wincrypt.h>
  393. #ifdef _MSC_VER
  394. #pragma comment(lib, "crypt32.lib")
  395. #endif
  396. #endif // _WIN32
  397. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  398. #if TARGET_OS_OSX
  399. #include <Security/Security.h>
  400. #endif
  401. #endif
  402. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  403. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  404. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  405. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  406. #define CPPHTTPLIB_SSL_ENABLED
  407. #endif
  408. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  409. #include <zlib.h>
  410. #endif
  411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  412. #include <brotli/decode.h>
  413. #include <brotli/encode.h>
  414. #endif
  415. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  416. #include <zstd.h>
  417. #endif
  418. /*
  419. * Declaration
  420. */
  421. namespace httplib {
  422. namespace ws {
  423. class WebSocket;
  424. } // namespace ws
  425. namespace detail {
  426. /*
  427. * Backport std::make_unique from C++14.
  428. *
  429. * NOTE: This code came up with the following stackoverflow post:
  430. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  431. *
  432. */
  433. template <class T, class... Args>
  434. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  435. make_unique(Args &&...args) {
  436. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  437. }
  438. template <class T>
  439. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  440. make_unique(std::size_t n) {
  441. typedef typename std::remove_extent<T>::type RT;
  442. return std::unique_ptr<T>(new RT[n]);
  443. }
  444. // Locale-independent ASCII character classification. The <cctype>
  445. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  446. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  447. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  448. // classified without regard to the locale.
  449. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  450. inline bool is_ascii_alpha(char c) {
  451. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  452. }
  453. inline bool is_ascii_alnum(char c) {
  454. return is_ascii_digit(c) || is_ascii_alpha(c);
  455. }
  456. namespace case_ignore {
  457. inline unsigned char to_lower(int c) {
  458. const static unsigned char table[256] = {
  459. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  460. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  461. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  462. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  463. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  464. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  465. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  466. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  467. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  468. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  469. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  470. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  471. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  472. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  473. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  474. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  475. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  476. 255,
  477. };
  478. return table[(unsigned char)(char)c];
  479. }
  480. inline std::string to_lower(const std::string &s) {
  481. std::string result = s;
  482. std::transform(
  483. result.begin(), result.end(), result.begin(),
  484. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  485. return result;
  486. }
  487. inline bool equal(const std::string &a, const std::string &b) {
  488. return a.size() == b.size() &&
  489. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  490. return to_lower(ca) == to_lower(cb);
  491. });
  492. }
  493. struct equal_to {
  494. bool operator()(const std::string &a, const std::string &b) const {
  495. return equal(a, b);
  496. }
  497. };
  498. struct hash {
  499. size_t operator()(const std::string &key) const {
  500. return hash_core(key.data(), key.size(), 0);
  501. }
  502. size_t hash_core(const char *s, size_t l, size_t h) const {
  503. return (l == 0) ? h
  504. : hash_core(s + 1, l - 1,
  505. // Unsets the 6 high bits of h, therefore no
  506. // overflow happens
  507. (((std::numeric_limits<size_t>::max)() >> 6) &
  508. h * 33) ^
  509. static_cast<unsigned char>(to_lower(*s)));
  510. }
  511. };
  512. template <typename T>
  513. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  514. detail::case_ignore::equal_to>;
  515. } // namespace case_ignore
  516. // This is based on
  517. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  518. struct scope_exit {
  519. explicit scope_exit(std::function<void(void)> &&f)
  520. : exit_function(std::move(f)), execute_on_destruction{true} {}
  521. scope_exit(scope_exit &&rhs) noexcept
  522. : exit_function(std::move(rhs.exit_function)),
  523. execute_on_destruction{rhs.execute_on_destruction} {
  524. rhs.release();
  525. }
  526. ~scope_exit() {
  527. if (execute_on_destruction) { this->exit_function(); }
  528. }
  529. void release() { this->execute_on_destruction = false; }
  530. private:
  531. scope_exit(const scope_exit &) = delete;
  532. void operator=(const scope_exit &) = delete;
  533. scope_exit &operator=(scope_exit &&) = delete;
  534. std::function<void(void)> exit_function;
  535. bool execute_on_destruction;
  536. };
  537. // Simple from_chars implementation for integer and double types (C++17
  538. // substitute)
  539. template <typename T> struct from_chars_result {
  540. const char *ptr;
  541. std::errc ec;
  542. };
  543. template <typename T>
  544. inline from_chars_result<T> from_chars(const char *first, const char *last,
  545. T &value, int base = 10) {
  546. value = 0;
  547. const char *p = first;
  548. bool negative = false;
  549. if (p != last && *p == '-') {
  550. negative = true;
  551. ++p;
  552. }
  553. if (p == last) { return {first, std::errc::invalid_argument}; }
  554. T result = 0;
  555. for (; p != last; ++p) {
  556. char c = *p;
  557. int digit = -1;
  558. if (is_ascii_digit(c)) {
  559. digit = c - '0';
  560. } else if ('a' <= c && c <= 'z') {
  561. digit = c - 'a' + 10;
  562. } else if ('A' <= c && c <= 'Z') {
  563. digit = c - 'A' + 10;
  564. } else {
  565. break;
  566. }
  567. if (digit < 0 || digit >= base) { break; }
  568. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  569. return {p, std::errc::result_out_of_range};
  570. }
  571. result = result * base + digit;
  572. }
  573. if (p == first || (negative && p == first + 1)) {
  574. return {first, std::errc::invalid_argument};
  575. }
  576. value = negative ? T(0) - result : result;
  577. return {p, std::errc{}};
  578. }
  579. // from_chars for double (hand-written, locale-independent)
  580. //
  581. // The only double consumed by this library is the HTTP quality value, whose
  582. // grammar is (RFC 9110 12.4.2):
  583. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  584. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  585. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  586. // '.' always the decimal separator (std::strtod would instead read it from the
  587. // global C locale, mis-parsing q-values once an embedder calls
  588. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  589. // the result to [0, 1], so inputs outside that range need not be distinguished
  590. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  591. // cases that exponent and wide-range handling would introduce.
  592. inline from_chars_result<double> from_chars(const char *first, const char *last,
  593. double &value) {
  594. value = 0.0;
  595. const char *p = first;
  596. // Each 1eN is exactly representable, so a single final division by the
  597. // matching entry yields a correctly-rounded result.
  598. static const double powers_of_ten[] = {
  599. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  600. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  601. const int max_frac_digits =
  602. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  603. // Accumulate digits into a 64-bit integer and remember how many were
  604. // fractional. Two independent caps keep this bounded and safe:
  605. // * accumulation saturates before mantissa could overflow uint64_t, and
  606. // * frac_digits is capped at max_frac_digits so it is always a valid index
  607. // into powers_of_ten (without this an input like "0.000...0" would never
  608. // grow mantissa, so the saturation cap alone would not bound it).
  609. // Both caps only drop digits far beyond the precision a q-value needs; any
  610. // value they would change is well outside [0, 1] and rejected by the caller.
  611. uint64_t mantissa = 0;
  612. int frac_digits = 0;
  613. bool seen_digit = false;
  614. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  615. auto accumulate = [&](char c) {
  616. if (mantissa <= limit) {
  617. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  618. return true;
  619. }
  620. return false;
  621. };
  622. for (; p != last && is_ascii_digit(*p); ++p) {
  623. seen_digit = true;
  624. accumulate(*p);
  625. }
  626. if (p != last && *p == '.') {
  627. ++p;
  628. for (; p != last && is_ascii_digit(*p); ++p) {
  629. seen_digit = true;
  630. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  631. }
  632. }
  633. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  634. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  635. return {p, std::errc{}};
  636. }
  637. inline bool parse_port(const char *s, size_t len, int &port) {
  638. int val = 0;
  639. auto r = from_chars(s, s + len, val);
  640. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  641. port = val;
  642. return true;
  643. }
  644. inline bool parse_port(const std::string &s, int &port) {
  645. return parse_port(s.data(), s.size(), port);
  646. }
  647. struct UrlComponents {
  648. std::string scheme;
  649. std::string host;
  650. std::string port;
  651. std::string path;
  652. std::string query;
  653. };
  654. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  655. uc = {};
  656. size_t pos = 0;
  657. auto sep = url.find("://");
  658. if (sep != std::string::npos) {
  659. uc.scheme = url.substr(0, sep);
  660. // Scheme must be [a-z]+ only
  661. if (uc.scheme.empty()) { return false; }
  662. for (auto c : uc.scheme) {
  663. if (c < 'a' || c > 'z') { return false; }
  664. }
  665. pos = sep + 3;
  666. } else if (url.compare(0, 2, "//") == 0) {
  667. pos = 2;
  668. }
  669. auto has_authority_prefix = pos > 0;
  670. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  671. url[0] != '?' && url[0] != '#');
  672. if (has_authority) {
  673. if (pos < url.size() && url[pos] == '[') {
  674. auto close = url.find(']', pos);
  675. if (close == std::string::npos) { return false; }
  676. uc.host = url.substr(pos + 1, close - pos - 1);
  677. // IPv6 host must be [a-fA-F0-9:]+ only
  678. if (uc.host.empty()) { return false; }
  679. for (auto c : uc.host) {
  680. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  681. (c >= 'A' && c <= 'F') || c == ':')) {
  682. return false;
  683. }
  684. }
  685. pos = close + 1;
  686. } else {
  687. auto end = url.find_first_of(":/?#", pos);
  688. if (end == std::string::npos) { end = url.size(); }
  689. uc.host = url.substr(pos, end - pos);
  690. pos = end;
  691. }
  692. if (pos < url.size() && url[pos] == ':') {
  693. ++pos;
  694. auto end = url.find_first_of("/?#", pos);
  695. if (end == std::string::npos) { end = url.size(); }
  696. uc.port = url.substr(pos, end - pos);
  697. pos = end;
  698. }
  699. // Without :// or //, the entire input must be consumed as host[:port].
  700. // If there is leftover (path, query, etc.), this is not a valid
  701. // host[:port] string — clear and reparse as a plain path.
  702. if (!has_authority_prefix && pos < url.size()) {
  703. uc.host.clear();
  704. uc.port.clear();
  705. pos = 0;
  706. }
  707. }
  708. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  709. auto end = url.find_first_of("?#", pos);
  710. if (end == std::string::npos) { end = url.size(); }
  711. uc.path = url.substr(pos, end - pos);
  712. pos = end;
  713. }
  714. if (pos < url.size() && url[pos] == '?') {
  715. auto end = url.find('#', pos);
  716. if (end == std::string::npos) { end = url.size(); }
  717. uc.query = url.substr(pos, end - pos);
  718. }
  719. return true;
  720. }
  721. } // namespace detail
  722. enum class SSLVerifierResponse {
  723. // no decision has been made, use the built-in certificate verifier
  724. NoDecisionMade,
  725. // connection certificate is verified and accepted
  726. CertificateAccepted,
  727. // connection certificate was processed but is rejected
  728. CertificateRejected
  729. };
  730. // System CA loading policy for SSL clients. Auto (the default) loads system
  731. // CA certs only when no custom CA is configured; enable_system_ca() switches
  732. // to an explicit policy.
  733. enum class SystemCAMode { Auto, Enabled, Disabled };
  734. enum StatusCode {
  735. // Information responses
  736. Continue_100 = 100,
  737. SwitchingProtocol_101 = 101,
  738. Processing_102 = 102,
  739. EarlyHints_103 = 103,
  740. // Successful responses
  741. OK_200 = 200,
  742. Created_201 = 201,
  743. Accepted_202 = 202,
  744. NonAuthoritativeInformation_203 = 203,
  745. NoContent_204 = 204,
  746. ResetContent_205 = 205,
  747. PartialContent_206 = 206,
  748. MultiStatus_207 = 207,
  749. AlreadyReported_208 = 208,
  750. IMUsed_226 = 226,
  751. // Redirection messages
  752. MultipleChoices_300 = 300,
  753. MovedPermanently_301 = 301,
  754. Found_302 = 302,
  755. SeeOther_303 = 303,
  756. NotModified_304 = 304,
  757. UseProxy_305 = 305,
  758. unused_306 = 306,
  759. TemporaryRedirect_307 = 307,
  760. PermanentRedirect_308 = 308,
  761. // Client error responses
  762. BadRequest_400 = 400,
  763. Unauthorized_401 = 401,
  764. PaymentRequired_402 = 402,
  765. Forbidden_403 = 403,
  766. NotFound_404 = 404,
  767. MethodNotAllowed_405 = 405,
  768. NotAcceptable_406 = 406,
  769. ProxyAuthenticationRequired_407 = 407,
  770. RequestTimeout_408 = 408,
  771. Conflict_409 = 409,
  772. Gone_410 = 410,
  773. LengthRequired_411 = 411,
  774. PreconditionFailed_412 = 412,
  775. PayloadTooLarge_413 = 413,
  776. UriTooLong_414 = 414,
  777. UnsupportedMediaType_415 = 415,
  778. RangeNotSatisfiable_416 = 416,
  779. ExpectationFailed_417 = 417,
  780. ImATeapot_418 = 418,
  781. MisdirectedRequest_421 = 421,
  782. UnprocessableContent_422 = 422,
  783. Locked_423 = 423,
  784. FailedDependency_424 = 424,
  785. TooEarly_425 = 425,
  786. UpgradeRequired_426 = 426,
  787. PreconditionRequired_428 = 428,
  788. TooManyRequests_429 = 429,
  789. RequestHeaderFieldsTooLarge_431 = 431,
  790. UnavailableForLegalReasons_451 = 451,
  791. // Server error responses
  792. InternalServerError_500 = 500,
  793. NotImplemented_501 = 501,
  794. BadGateway_502 = 502,
  795. ServiceUnavailable_503 = 503,
  796. GatewayTimeout_504 = 504,
  797. HttpVersionNotSupported_505 = 505,
  798. VariantAlsoNegotiates_506 = 506,
  799. InsufficientStorage_507 = 507,
  800. LoopDetected_508 = 508,
  801. NotExtended_510 = 510,
  802. NetworkAuthenticationRequired_511 = 511,
  803. };
  804. using Headers =
  805. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  806. detail::case_ignore::equal_to>;
  807. using Params = std::multimap<std::string, std::string>;
  808. using Match = std::smatch;
  809. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  810. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  811. /*
  812. * detail: type-erased storage used by UserData.
  813. * ABI-stable regardless of C++ standard — always uses this custom
  814. * implementation instead of std::any.
  815. */
  816. namespace detail {
  817. using any_type_id = const void *;
  818. template <typename T> any_type_id any_typeid() noexcept {
  819. static const char id = 0;
  820. return &id;
  821. }
  822. struct any_storage {
  823. virtual ~any_storage() = default;
  824. virtual std::unique_ptr<any_storage> clone() const = 0;
  825. virtual any_type_id type_id() const noexcept = 0;
  826. };
  827. template <typename T> struct any_value final : any_storage {
  828. T value;
  829. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  830. std::unique_ptr<any_storage> clone() const override {
  831. return std::unique_ptr<any_storage>(new any_value<T>(value));
  832. }
  833. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  834. };
  835. } // namespace detail
  836. class UserData {
  837. public:
  838. UserData() = default;
  839. UserData(UserData &&) noexcept = default;
  840. UserData &operator=(UserData &&) noexcept = default;
  841. UserData(const UserData &o) {
  842. for (const auto &e : o.entries_) {
  843. if (e.second) { entries_[e.first] = e.second->clone(); }
  844. }
  845. }
  846. UserData &operator=(const UserData &o) {
  847. if (this != &o) {
  848. entries_.clear();
  849. for (const auto &e : o.entries_) {
  850. if (e.second) { entries_[e.first] = e.second->clone(); }
  851. }
  852. }
  853. return *this;
  854. }
  855. template <typename T> void set(const std::string &key, T &&value) {
  856. using D = typename std::decay<T>::type;
  857. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  858. }
  859. template <typename T> T *get(const std::string &key) noexcept {
  860. auto it = entries_.find(key);
  861. if (it == entries_.end() || !it->second) { return nullptr; }
  862. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  863. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  864. }
  865. template <typename T> const T *get(const std::string &key) const noexcept {
  866. auto it = entries_.find(key);
  867. if (it == entries_.end() || !it->second) { return nullptr; }
  868. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  869. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  870. }
  871. bool has(const std::string &key) const noexcept {
  872. return entries_.find(key) != entries_.end();
  873. }
  874. void erase(const std::string &key) { entries_.erase(key); }
  875. void clear() noexcept { entries_.clear(); }
  876. private:
  877. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  878. entries_;
  879. };
  880. struct Response;
  881. using ResponseHandler = std::function<bool(const Response &response)>;
  882. struct FormData {
  883. std::string name;
  884. std::string content;
  885. std::string filename;
  886. std::string content_type;
  887. Headers headers;
  888. };
  889. struct FormField {
  890. std::string name;
  891. std::string content;
  892. Headers headers;
  893. };
  894. using FormFields = std::multimap<std::string, FormField>;
  895. using FormFiles = std::multimap<std::string, FormData>;
  896. struct MultipartFormData {
  897. FormFields fields; // Text fields from multipart
  898. FormFiles files; // Files from multipart
  899. // Text field access
  900. std::string get_field(const std::string &key, size_t id = 0) const;
  901. std::vector<std::string> get_fields(const std::string &key) const;
  902. bool has_field(const std::string &key) const;
  903. size_t get_field_count(const std::string &key) const;
  904. // File access
  905. FormData get_file(const std::string &key, size_t id = 0) const;
  906. std::vector<FormData> get_files(const std::string &key) const;
  907. bool has_file(const std::string &key) const;
  908. size_t get_file_count(const std::string &key) const;
  909. };
  910. struct UploadFormData {
  911. std::string name;
  912. std::string content;
  913. std::string filename;
  914. std::string content_type;
  915. };
  916. using UploadFormDataItems = std::vector<UploadFormData>;
  917. class DataSink {
  918. public:
  919. DataSink() : os(&sb_), sb_(*this) {}
  920. DataSink(const DataSink &) = delete;
  921. DataSink &operator=(const DataSink &) = delete;
  922. DataSink(DataSink &&) = delete;
  923. DataSink &operator=(DataSink &&) = delete;
  924. std::function<bool(const char *data, size_t data_len)> write;
  925. std::function<bool()> is_writable;
  926. std::function<void()> done;
  927. std::function<void(const Headers &trailer)> done_with_trailer;
  928. std::ostream os;
  929. private:
  930. class data_sink_streambuf final : public std::streambuf {
  931. public:
  932. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  933. protected:
  934. std::streamsize xsputn(const char *s, std::streamsize n) override {
  935. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  936. return 0;
  937. }
  938. private:
  939. DataSink &sink_;
  940. };
  941. data_sink_streambuf sb_;
  942. };
  943. using ContentProvider =
  944. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  945. using ContentProviderWithoutLength =
  946. std::function<bool(size_t offset, DataSink &sink)>;
  947. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  948. struct FormDataProvider {
  949. std::string name;
  950. ContentProviderWithoutLength provider;
  951. std::string filename;
  952. std::string content_type;
  953. };
  954. using FormDataProviderItems = std::vector<FormDataProvider>;
  955. inline FormDataProvider
  956. make_file_provider(const std::string &name, const std::string &filepath,
  957. const std::string &filename = std::string(),
  958. const std::string &content_type = std::string()) {
  959. FormDataProvider fdp;
  960. fdp.name = name;
  961. fdp.filename = filename.empty() ? filepath : filename;
  962. fdp.content_type = content_type;
  963. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  964. std::ifstream f(filepath, std::ios::binary);
  965. if (!f) { return false; }
  966. if (offset > 0) {
  967. f.seekg(static_cast<std::streamoff>(offset));
  968. if (!f.good()) {
  969. sink.done();
  970. return true;
  971. }
  972. }
  973. char buf[8192];
  974. f.read(buf, sizeof(buf));
  975. auto n = static_cast<size_t>(f.gcount());
  976. if (n > 0) { return sink.write(buf, n); }
  977. sink.done(); // EOF
  978. return true;
  979. };
  980. return fdp;
  981. }
  982. inline std::pair<size_t, ContentProvider>
  983. make_file_body(const std::string &filepath) {
  984. size_t size = 0;
  985. {
  986. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  987. if (!f) { return {0, ContentProvider{}}; }
  988. size = static_cast<size_t>(f.tellg());
  989. }
  990. ContentProvider provider = [filepath](size_t offset, size_t length,
  991. DataSink &sink) -> bool {
  992. std::ifstream f(filepath, std::ios::binary);
  993. if (!f) { return false; }
  994. f.seekg(static_cast<std::streamoff>(offset));
  995. if (!f.good()) { return false; }
  996. char buf[8192];
  997. while (length > 0) {
  998. auto to_read = (std::min)(sizeof(buf), length);
  999. f.read(buf, static_cast<std::streamsize>(to_read));
  1000. auto n = static_cast<size_t>(f.gcount());
  1001. if (n == 0) { break; }
  1002. if (!sink.write(buf, n)) { return false; }
  1003. length -= n;
  1004. }
  1005. return true;
  1006. };
  1007. return {size, std::move(provider)};
  1008. }
  1009. using ContentReceiverWithProgress = std::function<bool(
  1010. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1011. using ContentReceiver =
  1012. std::function<bool(const char *data, size_t data_length)>;
  1013. using FormDataHeader = std::function<bool(const FormData &file)>;
  1014. class ContentReader {
  1015. public:
  1016. using Reader = std::function<bool(ContentReceiver receiver)>;
  1017. using FormDataReader =
  1018. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1019. ContentReader(Reader reader, FormDataReader multipart_reader)
  1020. : reader_(std::move(reader)),
  1021. formdata_reader_(std::move(multipart_reader)) {}
  1022. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1023. return formdata_reader_(std::move(header), std::move(receiver));
  1024. }
  1025. bool operator()(ContentReceiver receiver) const {
  1026. return reader_(std::move(receiver));
  1027. }
  1028. Reader reader_;
  1029. FormDataReader formdata_reader_;
  1030. };
  1031. using Range = std::pair<ssize_t, ssize_t>;
  1032. using Ranges = std::vector<Range>;
  1033. #ifdef CPPHTTPLIB_SSL_ENABLED
  1034. // TLS abstraction layer - public type definitions and API
  1035. namespace tls {
  1036. // Opaque handles (defined as void* for abstraction)
  1037. using ctx_t = void *;
  1038. using session_t = void *;
  1039. using const_session_t = const void *; // For read-only session access
  1040. using cert_t = void *;
  1041. using ca_store_t = void *;
  1042. // TLS versions
  1043. enum class Version {
  1044. TLS1_2 = 0x0303,
  1045. TLS1_3 = 0x0304,
  1046. };
  1047. // Subject Alternative Names (SAN) entry types
  1048. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1049. // SAN entry structure
  1050. struct SanEntry {
  1051. SanType type;
  1052. std::string value;
  1053. };
  1054. // Verification context for certificate verification callback
  1055. struct VerifyContext {
  1056. session_t session; // TLS session handle
  1057. cert_t cert; // Current certificate being verified
  1058. int depth; // Certificate chain depth (0 = leaf)
  1059. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1060. long error_code; // Backend-specific error code (0 = no error)
  1061. const char *error_string; // Human-readable error description
  1062. // Certificate introspection methods
  1063. std::string subject_cn() const;
  1064. std::string issuer_name() const;
  1065. bool check_hostname(const char *hostname) const;
  1066. std::vector<SanEntry> sans() const;
  1067. bool validity(time_t &not_before, time_t &not_after) const;
  1068. std::string serial() const;
  1069. };
  1070. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1071. // TlsError codes for TLS operations (backend-independent)
  1072. enum class ErrorCode : int {
  1073. Success = 0,
  1074. WantRead, // Non-blocking: need to wait for read
  1075. WantWrite, // Non-blocking: need to wait for write
  1076. PeerClosed, // Peer closed the connection
  1077. Fatal, // Unrecoverable error
  1078. SyscallError, // System call error (check sys_errno)
  1079. CertVerifyFailed, // Certificate verification failed
  1080. HostnameMismatch, // Hostname verification failed
  1081. };
  1082. // TLS error information
  1083. struct TlsError {
  1084. ErrorCode code = ErrorCode::Fatal;
  1085. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1086. int sys_errno = 0; // errno when SyscallError
  1087. // Convert verification error code to human-readable string
  1088. static std::string verify_error_to_string(long error_code);
  1089. };
  1090. // RAII wrapper for peer certificate
  1091. class PeerCert {
  1092. public:
  1093. PeerCert();
  1094. PeerCert(PeerCert &&other) noexcept;
  1095. PeerCert &operator=(PeerCert &&other) noexcept;
  1096. ~PeerCert();
  1097. PeerCert(const PeerCert &) = delete;
  1098. PeerCert &operator=(const PeerCert &) = delete;
  1099. explicit operator bool() const;
  1100. std::string subject_cn() const;
  1101. std::string issuer_name() const;
  1102. bool check_hostname(const char *hostname) const;
  1103. std::vector<SanEntry> sans() const;
  1104. bool validity(time_t &not_before, time_t &not_after) const;
  1105. std::string serial() const;
  1106. private:
  1107. explicit PeerCert(cert_t cert);
  1108. cert_t cert_ = nullptr;
  1109. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1110. };
  1111. // Callback for TLS context setup (used by SSLServer constructor)
  1112. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1113. } // namespace tls
  1114. #endif
  1115. struct Request {
  1116. std::string method;
  1117. std::string path;
  1118. std::string matched_route;
  1119. Params params;
  1120. Headers headers;
  1121. Headers trailers;
  1122. std::string body;
  1123. std::string remote_addr;
  1124. int remote_port = -1;
  1125. std::string local_addr;
  1126. int local_port = -1;
  1127. // for server
  1128. std::string version;
  1129. std::string target;
  1130. MultipartFormData form;
  1131. Ranges ranges;
  1132. Match matches;
  1133. std::unordered_map<std::string, std::string> path_params;
  1134. std::function<bool()> is_connection_closed = []() { return true; };
  1135. // for client
  1136. std::vector<std::string> accept_content_types;
  1137. ResponseHandler response_handler;
  1138. ContentReceiverWithProgress content_receiver;
  1139. DownloadProgress download_progress;
  1140. UploadProgress upload_progress;
  1141. bool has_header(const std::string &key) const;
  1142. std::string get_header_value(const std::string &key, const char *def = "",
  1143. size_t id = 0) const;
  1144. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1145. size_t id = 0) const;
  1146. size_t get_header_value_count(const std::string &key) const;
  1147. void set_header(const std::string &key, const std::string &val);
  1148. bool has_trailer(const std::string &key) const;
  1149. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1150. size_t get_trailer_value_count(const std::string &key) const;
  1151. bool has_param(const std::string &key) const;
  1152. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1153. std::vector<std::string> get_param_values(const std::string &key) const;
  1154. size_t get_param_value_count(const std::string &key) const;
  1155. bool is_multipart_form_data() const;
  1156. // private members...
  1157. bool body_consumed_ = false;
  1158. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1159. size_t content_length_ = 0;
  1160. ContentProvider content_provider_;
  1161. bool is_chunked_content_provider_ = false;
  1162. size_t authorization_count_ = 0;
  1163. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1164. (std::chrono::steady_clock::time_point::min)();
  1165. #ifdef CPPHTTPLIB_SSL_ENABLED
  1166. tls::const_session_t ssl = nullptr;
  1167. tls::PeerCert peer_cert() const;
  1168. std::string sni() const;
  1169. #endif
  1170. };
  1171. struct Response {
  1172. std::string version;
  1173. int status = -1;
  1174. std::string reason;
  1175. Headers headers;
  1176. Headers trailers;
  1177. std::string body;
  1178. std::string location; // Redirect location
  1179. // User-defined context — set by pre-routing/pre-request handlers and read
  1180. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1181. UserData user_data;
  1182. bool has_header(const std::string &key) const;
  1183. std::string get_header_value(const std::string &key, const char *def = "",
  1184. size_t id = 0) const;
  1185. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1186. size_t id = 0) const;
  1187. size_t get_header_value_count(const std::string &key) const;
  1188. void set_header(const std::string &key, const std::string &val);
  1189. bool has_trailer(const std::string &key) const;
  1190. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1191. size_t get_trailer_value_count(const std::string &key) const;
  1192. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1193. void set_content(const char *s, size_t n, const std::string &content_type);
  1194. void set_content(const std::string &s, const std::string &content_type);
  1195. void set_content(std::string &&s, const std::string &content_type);
  1196. void set_content_provider(
  1197. size_t length, const std::string &content_type, ContentProvider provider,
  1198. ContentProviderResourceReleaser resource_releaser = nullptr);
  1199. void set_content_provider(
  1200. const std::string &content_type, ContentProviderWithoutLength provider,
  1201. ContentProviderResourceReleaser resource_releaser = nullptr);
  1202. void set_chunked_content_provider(
  1203. const std::string &content_type, ContentProviderWithoutLength provider,
  1204. ContentProviderResourceReleaser resource_releaser = nullptr);
  1205. void set_file_content(const std::string &path,
  1206. const std::string &content_type);
  1207. void set_file_content(const std::string &path);
  1208. Response() = default;
  1209. Response(const Response &) = default;
  1210. Response &operator=(const Response &) = default;
  1211. Response(Response &&) = default;
  1212. Response &operator=(Response &&) = default;
  1213. ~Response() {
  1214. if (content_provider_resource_releaser_) {
  1215. content_provider_resource_releaser_(content_provider_success_);
  1216. }
  1217. }
  1218. // private members...
  1219. size_t content_length_ = 0;
  1220. ContentProvider content_provider_;
  1221. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1222. bool is_chunked_content_provider_ = false;
  1223. bool content_provider_success_ = false;
  1224. std::string file_content_path_;
  1225. std::string file_content_content_type_;
  1226. };
  1227. enum class Error {
  1228. Success = 0,
  1229. Unknown,
  1230. Connection,
  1231. BindIPAddress,
  1232. Read,
  1233. Write,
  1234. ExceedRedirectCount,
  1235. Canceled,
  1236. SSLConnection,
  1237. SSLLoadingCerts,
  1238. SSLServerVerification,
  1239. SSLServerHostnameVerification,
  1240. UnsupportedMultipartBoundaryChars,
  1241. Compression,
  1242. ConnectionTimeout,
  1243. ProxyConnection,
  1244. ConnectionClosed,
  1245. Timeout,
  1246. ResourceExhaustion,
  1247. TooManyFormDataFiles,
  1248. ExceedMaxPayloadSize,
  1249. ExceedUriMaxLength,
  1250. ExceedMaxSocketDescriptorCount,
  1251. InvalidRequestLine,
  1252. InvalidHTTPMethod,
  1253. InvalidHTTPVersion,
  1254. InvalidHeaders,
  1255. MultipartParsing,
  1256. OpenFile,
  1257. Listen,
  1258. GetSockName,
  1259. UnsupportedAddressFamily,
  1260. HTTPParsing,
  1261. InvalidRangeHeader,
  1262. // For internal use only
  1263. SSLPeerCouldBeClosed_,
  1264. };
  1265. std::string to_string(Error error);
  1266. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1267. class Stream {
  1268. public:
  1269. virtual ~Stream() = default;
  1270. virtual bool is_readable() const = 0;
  1271. virtual bool wait_readable() const = 0;
  1272. virtual bool wait_writable() const = 0;
  1273. virtual bool is_peer_alive() const { return wait_writable(); }
  1274. virtual ssize_t read(char *ptr, size_t size) = 0;
  1275. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1276. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1277. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1278. virtual socket_t socket() const = 0;
  1279. virtual time_t duration() const = 0;
  1280. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1281. (void)sec;
  1282. (void)usec;
  1283. }
  1284. ssize_t write(const char *ptr);
  1285. ssize_t write(const std::string &s);
  1286. Error get_error() const { return error_; }
  1287. protected:
  1288. Error error_ = Error::Success;
  1289. };
  1290. class TaskQueue {
  1291. public:
  1292. TaskQueue() = default;
  1293. virtual ~TaskQueue() = default;
  1294. virtual bool enqueue(std::function<void()> fn) = 0;
  1295. virtual void shutdown() = 0;
  1296. virtual void on_idle() {}
  1297. };
  1298. class ThreadPool final : public TaskQueue {
  1299. public:
  1300. explicit ThreadPool(
  1301. size_t n, size_t max_n = 0, size_t mqr = 0,
  1302. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1303. ThreadPool(const ThreadPool &) = delete;
  1304. ~ThreadPool() override = default;
  1305. bool enqueue(std::function<void()> fn) override;
  1306. void shutdown() override;
  1307. private:
  1308. void worker(bool is_dynamic);
  1309. void move_to_finished(std::thread::id id);
  1310. void cleanup_finished_threads();
  1311. size_t base_thread_count_;
  1312. size_t max_thread_count_;
  1313. size_t max_queued_requests_;
  1314. time_t idle_timeout_sec_;
  1315. size_t idle_thread_count_;
  1316. bool shutdown_;
  1317. std::list<std::function<void()>> jobs_;
  1318. std::vector<std::thread> threads_; // base threads
  1319. std::list<std::thread> dynamic_threads_; // dynamic threads
  1320. std::vector<std::thread>
  1321. finished_threads_; // exited dynamic threads awaiting join
  1322. std::condition_variable cond_;
  1323. std::mutex mutex_;
  1324. };
  1325. using Logger = std::function<void(const Request &, const Response &)>;
  1326. // Forward declaration for Error type
  1327. enum class Error;
  1328. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1329. using SocketOptions = std::function<void(socket_t sock)>;
  1330. void default_socket_options(socket_t sock);
  1331. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1332. const char *status_message(int status);
  1333. std::string to_string(Error error);
  1334. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1335. std::string get_bearer_token_auth(const Request &req);
  1336. namespace detail {
  1337. class MatcherBase {
  1338. public:
  1339. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1340. virtual ~MatcherBase() = default;
  1341. const std::string &pattern() const { return pattern_; }
  1342. // Match request path and populate its matches and
  1343. virtual bool match(Request &request) const = 0;
  1344. private:
  1345. std::string pattern_;
  1346. };
  1347. /**
  1348. * Captures parameters in request path and stores them in Request::path_params
  1349. *
  1350. * Capture name is a substring of a pattern from : to /.
  1351. * The rest of the pattern is matched against the request path directly
  1352. * Parameters are captured starting from the next character after
  1353. * the end of the last matched static pattern fragment until the next /.
  1354. *
  1355. * Example pattern:
  1356. * "/path/fragments/:capture/more/fragments/:second_capture"
  1357. * Static fragments:
  1358. * "/path/fragments/", "more/fragments/"
  1359. *
  1360. * Given the following request path:
  1361. * "/path/fragments/:1/more/fragments/:2"
  1362. * the resulting capture will be
  1363. * {{"capture", "1"}, {"second_capture", "2"}}
  1364. */
  1365. class PathParamsMatcher final : public MatcherBase {
  1366. public:
  1367. PathParamsMatcher(const std::string &pattern);
  1368. bool match(Request &request) const override;
  1369. private:
  1370. // Treat segment separators as the end of path parameter capture
  1371. // Does not need to handle query parameters as they are parsed before path
  1372. // matching
  1373. static constexpr char separator = '/';
  1374. // Contains static path fragments to match against, excluding the '/' after
  1375. // path params
  1376. // Fragments are separated by path params
  1377. std::vector<std::string> static_fragments_;
  1378. // Stores the names of the path parameters to be used as keys in the
  1379. // Request::path_params map
  1380. std::vector<std::string> param_names_;
  1381. };
  1382. /**
  1383. * Performs std::regex_match on request path
  1384. * and stores the result in Request::matches
  1385. *
  1386. * Note that regex match is performed directly on the whole request.
  1387. * This means that wildcard patterns may match multiple path segments with /:
  1388. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1389. */
  1390. class RegexMatcher final : public MatcherBase {
  1391. public:
  1392. RegexMatcher(const std::string &pattern)
  1393. : MatcherBase(pattern), regex_(pattern) {}
  1394. bool match(Request &request) const override;
  1395. private:
  1396. std::regex regex_;
  1397. };
  1398. int close_socket(socket_t sock) noexcept;
  1399. ssize_t write_headers(Stream &strm, const Headers &headers);
  1400. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1401. time_t usec);
  1402. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1403. const std::string &boundary);
  1404. ContentProvider
  1405. make_multipart_content_provider(const UploadFormDataItems &items,
  1406. const std::string &boundary);
  1407. } // namespace detail
  1408. bool is_valid_multipart_boundary(const std::string &boundary);
  1409. // Serializer for multipart/form-data request bodies. The boundary is owned
  1410. // by the writer so that per-part framing and the final terminator always
  1411. // agree. Field names and filenames are escaped following the WHATWG HTML
  1412. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1413. // in content types.
  1414. class MultipartFormDataWriter {
  1415. public:
  1416. MultipartFormDataWriter();
  1417. // precondition: is_valid_multipart_boundary(boundary)
  1418. explicit MultipartFormDataWriter(std::string boundary);
  1419. const std::string &boundary() const;
  1420. std::string content_type() const;
  1421. // In-memory items -> whole body (known length)
  1422. std::string serialize(const UploadFormDataItems &items) const;
  1423. size_t content_length(const UploadFormDataItems &items) const;
  1424. // Per-part framing for streaming via a content provider
  1425. std::string item_begin(const UploadFormData &item) const;
  1426. static std::string item_end();
  1427. std::string finish() const;
  1428. private:
  1429. std::string boundary_;
  1430. };
  1431. class Server {
  1432. public:
  1433. using Handler = std::function<void(const Request &, Response &)>;
  1434. using ExceptionHandler =
  1435. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1436. enum class HandlerResponse {
  1437. Handled,
  1438. Unhandled,
  1439. };
  1440. using HandlerWithResponse =
  1441. std::function<HandlerResponse(const Request &, Response &)>;
  1442. using HandlerWithContentReader = std::function<void(
  1443. const Request &, Response &, const ContentReader &content_reader)>;
  1444. using Expect100ContinueHandler =
  1445. std::function<int(const Request &, Response &)>;
  1446. using StartHandler = std::function<void()>;
  1447. using WebSocketHandler =
  1448. std::function<void(const Request &, ws::WebSocket &)>;
  1449. using SubProtocolSelector =
  1450. std::function<std::string(const std::vector<std::string> &protocols)>;
  1451. Server();
  1452. virtual ~Server();
  1453. virtual bool is_valid() const;
  1454. Server &Get(const std::string &pattern, Handler handler);
  1455. Server &Post(const std::string &pattern, Handler handler);
  1456. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1457. Server &Put(const std::string &pattern, Handler handler);
  1458. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1459. Server &Patch(const std::string &pattern, Handler handler);
  1460. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1461. Server &Delete(const std::string &pattern, Handler handler);
  1462. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1463. Server &Options(const std::string &pattern, Handler handler);
  1464. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1465. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1466. SubProtocolSelector sub_protocol_selector);
  1467. bool set_base_dir(const std::string &dir,
  1468. const std::string &mount_point = std::string());
  1469. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1470. Headers headers = Headers());
  1471. bool remove_mount_point(const std::string &mount_point);
  1472. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1473. const std::string &mime);
  1474. Server &set_default_file_mimetype(const std::string &mime);
  1475. Server &set_file_request_handler(Handler handler);
  1476. template <class ErrorHandlerFunc>
  1477. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1478. return set_error_handler_core(
  1479. std::forward<ErrorHandlerFunc>(handler),
  1480. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1481. }
  1482. Server &set_exception_handler(ExceptionHandler handler);
  1483. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1484. Server &set_post_routing_handler(Handler handler);
  1485. Server &set_pre_request_handler(HandlerWithResponse handler);
  1486. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1487. Server &set_start_handler(StartHandler handler);
  1488. Server &set_logger(Logger logger);
  1489. Server &set_pre_compression_logger(Logger logger);
  1490. Server &set_error_logger(ErrorLogger error_logger);
  1491. Server &set_address_family(int family);
  1492. Server &set_tcp_nodelay(bool on);
  1493. Server &set_ipv6_v6only(bool on);
  1494. Server &set_socket_options(SocketOptions socket_options);
  1495. Server &set_default_headers(Headers headers);
  1496. Server &
  1497. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1498. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1499. Server &set_keep_alive_max_count(size_t count);
  1500. Server &set_keep_alive_timeout(time_t sec);
  1501. template <class Rep, class Period>
  1502. Server &
  1503. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1504. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1505. template <class Rep, class Period>
  1506. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1507. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1508. template <class Rep, class Period>
  1509. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1510. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1511. template <class Rep, class Period>
  1512. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1513. Server &set_payload_max_length(size_t length);
  1514. Server &set_websocket_ping_interval(time_t sec);
  1515. template <class Rep, class Period>
  1516. Server &set_websocket_ping_interval(
  1517. const std::chrono::duration<Rep, Period> &duration);
  1518. Server &set_websocket_max_missed_pongs(int count);
  1519. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1520. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1521. bool listen_after_bind();
  1522. bool listen(const std::string &host, int port, int socket_flags = 0);
  1523. bool is_running() const;
  1524. void wait_until_ready() const;
  1525. void stop() noexcept;
  1526. void decommission();
  1527. std::function<TaskQueue *(void)> new_task_queue;
  1528. protected:
  1529. bool process_request(Stream &strm, const std::string &remote_addr,
  1530. int remote_port, const std::string &local_addr,
  1531. int local_port, bool close_connection,
  1532. bool &connection_closed,
  1533. const std::function<void(Request &)> &setup_request,
  1534. bool *websocket_upgraded = nullptr);
  1535. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1536. std::vector<std::string> trusted_proxies_;
  1537. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1538. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1539. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1540. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1541. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1542. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1543. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1544. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1545. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1546. time_t websocket_ping_interval_sec_ =
  1547. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1548. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1549. private:
  1550. using Handlers =
  1551. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1552. using HandlersForContentReader =
  1553. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1554. HandlerWithContentReader>>;
  1555. static std::unique_ptr<detail::MatcherBase>
  1556. make_matcher(const std::string &pattern);
  1557. template <typename H>
  1558. Server &add_handler(
  1559. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1560. const std::string &pattern, H handler) {
  1561. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1562. return *this;
  1563. }
  1564. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1565. Server &set_error_handler_core(Handler handler, std::false_type);
  1566. socket_t create_server_socket(const std::string &host, int port,
  1567. int socket_flags,
  1568. SocketOptions socket_options) const;
  1569. int bind_internal(const std::string &host, int port, int socket_flags);
  1570. bool listen_internal();
  1571. bool routing(Request &req, Response &res, Stream &strm);
  1572. bool handle_file_request(Request &req, Response &res);
  1573. bool check_if_not_modified(const Request &req, Response &res,
  1574. const std::string &etag, time_t mtime) const;
  1575. bool check_if_range(Request &req, const std::string &etag,
  1576. time_t mtime) const;
  1577. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1578. Stream &strm);
  1579. bool dispatch_request_for_content_reader(
  1580. Request &req, Response &res, ContentReader content_reader,
  1581. const HandlersForContentReader &handlers) const;
  1582. bool parse_request_line(const char *s, Request &req) const;
  1583. void apply_ranges(const Request &req, Response &res,
  1584. std::string &content_type, std::string &boundary) const;
  1585. bool write_response(Stream &strm, bool close_connection, Request &req,
  1586. Response &res);
  1587. bool write_response_with_content(Stream &strm, bool close_connection,
  1588. const Request &req, Response &res);
  1589. bool write_response_core(Stream &strm, bool close_connection,
  1590. const Request &req, Response &res,
  1591. bool need_apply_ranges);
  1592. bool write_content_with_provider(Stream &strm, const Request &req,
  1593. Response &res, const std::string &boundary,
  1594. const std::string &content_type);
  1595. bool read_content(Stream &strm, Request &req, Response &res);
  1596. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1597. Response &res,
  1598. ContentReceiver receiver,
  1599. FormDataHeader multipart_header,
  1600. ContentReceiver multipart_receiver);
  1601. bool read_content_core(Stream &strm, Request &req, Response &res,
  1602. ContentReceiver receiver,
  1603. FormDataHeader multipart_header,
  1604. ContentReceiver multipart_receiver) const;
  1605. virtual bool process_and_close_socket(socket_t sock);
  1606. void output_log(const Request &req, const Response &res) const;
  1607. void output_pre_compression_log(const Request &req,
  1608. const Response &res) const;
  1609. void output_error_log(const Error &err, const Request *req) const;
  1610. std::atomic<bool> is_running_{false};
  1611. std::atomic<bool> is_decommissioned{false};
  1612. struct MountPointEntry {
  1613. std::string mount_point;
  1614. std::string base_dir;
  1615. std::string resolved_base_dir;
  1616. Headers headers;
  1617. };
  1618. std::vector<MountPointEntry> base_dirs_;
  1619. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1620. std::string default_file_mimetype_ = "application/octet-stream";
  1621. Handler file_request_handler_;
  1622. Handlers get_handlers_;
  1623. Handlers post_handlers_;
  1624. HandlersForContentReader post_handlers_for_content_reader_;
  1625. Handlers put_handlers_;
  1626. HandlersForContentReader put_handlers_for_content_reader_;
  1627. Handlers patch_handlers_;
  1628. HandlersForContentReader patch_handlers_for_content_reader_;
  1629. Handlers delete_handlers_;
  1630. HandlersForContentReader delete_handlers_for_content_reader_;
  1631. Handlers options_handlers_;
  1632. struct WebSocketHandlerEntry {
  1633. std::unique_ptr<detail::MatcherBase> matcher;
  1634. WebSocketHandler handler;
  1635. SubProtocolSelector sub_protocol_selector;
  1636. };
  1637. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1638. WebSocketHandlers websocket_handlers_;
  1639. HandlerWithResponse error_handler_;
  1640. ExceptionHandler exception_handler_;
  1641. HandlerWithResponse pre_routing_handler_;
  1642. Handler post_routing_handler_;
  1643. HandlerWithResponse pre_request_handler_;
  1644. Expect100ContinueHandler expect_100_continue_handler_;
  1645. StartHandler start_handler_;
  1646. mutable std::mutex logger_mutex_;
  1647. Logger logger_;
  1648. Logger pre_compression_logger_;
  1649. ErrorLogger error_logger_;
  1650. int address_family_ = AF_UNSPEC;
  1651. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1652. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1653. SocketOptions socket_options_ = default_socket_options;
  1654. Headers default_headers_;
  1655. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1656. detail::write_headers;
  1657. };
  1658. class Result {
  1659. public:
  1660. Result() = default;
  1661. Result(std::unique_ptr<Response> &&res, Error err,
  1662. Headers &&request_headers = Headers{})
  1663. : res_(std::move(res)), err_(err),
  1664. request_headers_(std::move(request_headers)) {}
  1665. // Response
  1666. operator bool() const { return res_ != nullptr; }
  1667. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1668. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1669. const Response &value() const { return *res_; }
  1670. Response &value() { return *res_; }
  1671. const Response &operator*() const { return *res_; }
  1672. Response &operator*() { return *res_; }
  1673. const Response *operator->() const { return res_.get(); }
  1674. Response *operator->() { return res_.get(); }
  1675. // Error
  1676. Error error() const { return err_; }
  1677. // Request Headers
  1678. bool has_request_header(const std::string &key) const;
  1679. std::string get_request_header_value(const std::string &key,
  1680. const char *def = "",
  1681. size_t id = 0) const;
  1682. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1683. size_t id = 0) const;
  1684. size_t get_request_header_value_count(const std::string &key) const;
  1685. private:
  1686. std::unique_ptr<Response> res_;
  1687. Error err_ = Error::Unknown;
  1688. Headers request_headers_;
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. public:
  1691. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1692. int ssl_error)
  1693. : res_(std::move(res)), err_(err),
  1694. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1695. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1696. int ssl_error, uint64_t ssl_backend_error)
  1697. : res_(std::move(res)), err_(err),
  1698. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1699. ssl_backend_error_(ssl_backend_error) {}
  1700. int ssl_error() const { return ssl_error_; }
  1701. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1702. private:
  1703. int ssl_error_ = 0;
  1704. uint64_t ssl_backend_error_ = 0;
  1705. #endif
  1706. };
  1707. struct ClientConnection {
  1708. socket_t sock = INVALID_SOCKET;
  1709. bool is_open() const { return sock != INVALID_SOCKET; }
  1710. ClientConnection() = default;
  1711. ~ClientConnection();
  1712. ClientConnection(const ClientConnection &) = delete;
  1713. ClientConnection &operator=(const ClientConnection &) = delete;
  1714. ClientConnection(ClientConnection &&other) noexcept
  1715. : sock(other.sock)
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. ,
  1718. session(other.session)
  1719. #endif
  1720. {
  1721. other.sock = INVALID_SOCKET;
  1722. #ifdef CPPHTTPLIB_SSL_ENABLED
  1723. other.session = nullptr;
  1724. #endif
  1725. }
  1726. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1727. if (this != &other) {
  1728. sock = other.sock;
  1729. other.sock = INVALID_SOCKET;
  1730. #ifdef CPPHTTPLIB_SSL_ENABLED
  1731. session = other.session;
  1732. other.session = nullptr;
  1733. #endif
  1734. }
  1735. return *this;
  1736. }
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. tls::session_t session = nullptr;
  1739. #endif
  1740. };
  1741. namespace detail {
  1742. struct ChunkedDecoder;
  1743. struct BodyReader {
  1744. Stream *stream = nullptr;
  1745. bool has_content_length = false;
  1746. size_t content_length = 0;
  1747. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1748. size_t bytes_read = 0;
  1749. bool chunked = false;
  1750. bool eof = false;
  1751. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1752. Error last_error = Error::Success;
  1753. ssize_t read(char *buf, size_t len);
  1754. bool has_error() const { return last_error != Error::Success; }
  1755. };
  1756. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1757. size_t len) {
  1758. (void)stream;
  1759. return br.read(buf, len);
  1760. }
  1761. class decompressor;
  1762. enum class NoProxyKind {
  1763. Wildcard, // "*"
  1764. HostnameSuffix, // "example.com" or ".example.com"
  1765. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1766. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1767. };
  1768. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1769. // Lets one CIDR matcher cover both families.
  1770. using IPBytes = std::array<uint8_t, 16>;
  1771. struct NoProxyEntry {
  1772. NoProxyKind kind = NoProxyKind::Wildcard;
  1773. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1774. IPBytes net{};
  1775. int prefix_bits = 0;
  1776. };
  1777. struct NormalizedTarget {
  1778. std::string hostname; // lowercase; brackets and trailing dot removed
  1779. bool is_ipv4 = false;
  1780. bool is_ipv6 = false;
  1781. IPBytes ip{};
  1782. };
  1783. } // namespace detail
  1784. class ClientImpl {
  1785. public:
  1786. explicit ClientImpl(const std::string &host);
  1787. explicit ClientImpl(const std::string &host, int port);
  1788. explicit ClientImpl(const std::string &host, int port,
  1789. const std::string &client_cert_path,
  1790. const std::string &client_key_path);
  1791. virtual ~ClientImpl();
  1792. virtual bool is_valid() const;
  1793. struct StreamHandle {
  1794. std::unique_ptr<Response> response;
  1795. Error error = Error::Success;
  1796. StreamHandle() = default;
  1797. StreamHandle(const StreamHandle &) = delete;
  1798. StreamHandle &operator=(const StreamHandle &) = delete;
  1799. StreamHandle(StreamHandle &&) = default;
  1800. StreamHandle &operator=(StreamHandle &&) = default;
  1801. ~StreamHandle() = default;
  1802. bool is_valid() const {
  1803. return response != nullptr && error == Error::Success;
  1804. }
  1805. ssize_t read(char *buf, size_t len);
  1806. void parse_trailers_if_needed();
  1807. Error get_read_error() const { return body_reader_.last_error; }
  1808. bool has_read_error() const { return body_reader_.has_error(); }
  1809. bool trailers_parsed_ = false;
  1810. private:
  1811. friend class ClientImpl;
  1812. ssize_t read_with_decompression(char *buf, size_t len);
  1813. std::unique_ptr<ClientConnection> connection_;
  1814. std::unique_ptr<Stream> socket_stream_;
  1815. Stream *stream_ = nullptr;
  1816. detail::BodyReader body_reader_;
  1817. std::unique_ptr<detail::decompressor> decompressor_;
  1818. std::string decompress_buffer_;
  1819. size_t decompress_offset_ = 0;
  1820. size_t decompressed_bytes_read_ = 0;
  1821. };
  1822. // clang-format off
  1823. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1824. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1825. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1826. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1827. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1828. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1829. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1830. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1831. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1832. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1833. Result Head(const std::string &path);
  1834. Result Head(const std::string &path, const Headers &headers);
  1835. Result Post(const std::string &path);
  1836. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1837. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1838. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1839. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1840. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1841. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1842. Result Post(const std::string &path, const Params &params);
  1843. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1844. Result Post(const std::string &path, const Headers &headers);
  1845. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1847. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1848. 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);
  1849. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1850. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1851. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1852. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1853. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1854. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1855. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1856. Result Put(const std::string &path);
  1857. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1859. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1861. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1862. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1863. Result Put(const std::string &path, const Params &params);
  1864. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1865. Result Put(const std::string &path, const Headers &headers);
  1866. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1868. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1869. 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);
  1870. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1871. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1872. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1873. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1874. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1875. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1876. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1877. Result Patch(const std::string &path);
  1878. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1880. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1882. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1883. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1884. Result Patch(const std::string &path, const Params &params);
  1885. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1886. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1887. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1888. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1889. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1890. 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);
  1891. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1892. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1893. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1894. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1895. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1896. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1897. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1898. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1899. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1900. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1901. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1902. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1903. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1904. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1905. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1906. Result Options(const std::string &path);
  1907. Result Options(const std::string &path, const Headers &headers);
  1908. // clang-format on
  1909. // Streaming API: Open a stream for reading response body incrementally
  1910. // Socket ownership is transferred to StreamHandle for true streaming
  1911. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1912. StreamHandle open_stream(const std::string &method, const std::string &path,
  1913. const Params &params = {},
  1914. const Headers &headers = {},
  1915. const std::string &body = {},
  1916. const std::string &content_type = {});
  1917. bool send(Request &req, Response &res, Error &error);
  1918. Result send(const Request &req);
  1919. void stop();
  1920. std::string host() const;
  1921. int port() const;
  1922. size_t is_socket_open() const;
  1923. socket_t socket() const;
  1924. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1925. void set_default_headers(Headers headers);
  1926. void
  1927. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1928. void set_address_family(int family);
  1929. void set_tcp_nodelay(bool on);
  1930. void set_ipv6_v6only(bool on);
  1931. void set_socket_options(SocketOptions socket_options);
  1932. void set_connection_timeout(time_t sec, time_t usec = 0);
  1933. template <class Rep, class Period>
  1934. void
  1935. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1936. void set_read_timeout(time_t sec, time_t usec = 0);
  1937. template <class Rep, class Period>
  1938. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1939. void set_write_timeout(time_t sec, time_t usec = 0);
  1940. template <class Rep, class Period>
  1941. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1942. void set_max_timeout(time_t msec);
  1943. template <class Rep, class Period>
  1944. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1945. void set_basic_auth(const std::string &username, const std::string &password);
  1946. void set_bearer_token_auth(const std::string &token);
  1947. void set_keep_alive(bool on);
  1948. void set_follow_location(bool on);
  1949. void set_path_encode(bool on);
  1950. void set_compress(bool on);
  1951. void set_decompress(bool on);
  1952. void set_payload_max_length(size_t length);
  1953. void set_interface(const std::string &intf);
  1954. void set_proxy(const std::string &host, int port);
  1955. void set_proxy_basic_auth(const std::string &username,
  1956. const std::string &password);
  1957. void set_proxy_bearer_token_auth(const std::string &token);
  1958. void set_no_proxy(const std::vector<std::string> &patterns);
  1959. void set_logger(Logger logger);
  1960. void set_error_logger(ErrorLogger error_logger);
  1961. protected:
  1962. struct Socket {
  1963. socket_t sock = INVALID_SOCKET;
  1964. // For Mbed TLS compatibility: start_time for request timeout tracking
  1965. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1966. bool is_open() const { return sock != INVALID_SOCKET; }
  1967. #ifdef CPPHTTPLIB_SSL_ENABLED
  1968. tls::session_t ssl = nullptr;
  1969. #endif
  1970. };
  1971. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1972. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1973. virtual bool setup_proxy_connection(
  1974. Socket &socket,
  1975. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1976. Response &res, bool &success, Error &error);
  1977. bool is_proxy_enabled_for_host(const std::string &host) const;
  1978. // All of:
  1979. // shutdown_ssl
  1980. // shutdown_socket
  1981. // close_socket
  1982. // disconnect
  1983. // should ONLY be called when socket_mutex_ is locked, and only when
  1984. // no other thread is using the socket.
  1985. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1986. void shutdown_socket(Socket &socket) const;
  1987. void close_socket(Socket &socket);
  1988. void disconnect(bool gracefully);
  1989. bool process_request(Stream &strm, Request &req, Response &res,
  1990. bool close_connection, Error &error);
  1991. bool write_content_with_provider(Stream &strm, const Request &req,
  1992. Error &error) const;
  1993. void copy_settings(const ClientImpl &rhs);
  1994. void output_log(const Request &req, const Response &res) const;
  1995. void output_error_log(const Error &err, const Request *req) const;
  1996. // Socket endpoint information
  1997. const std::string host_;
  1998. const int port_;
  1999. // Current open socket
  2000. Socket socket_;
  2001. mutable std::mutex socket_mutex_;
  2002. std::recursive_mutex request_mutex_;
  2003. // These are all protected under socket_mutex
  2004. size_t socket_requests_in_flight_ = 0;
  2005. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2006. bool socket_should_be_closed_when_request_is_done_ = false;
  2007. // Hostname-IP map
  2008. std::map<std::string, std::string> addr_map_;
  2009. // Default headers
  2010. Headers default_headers_;
  2011. // Header writer
  2012. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2013. detail::write_headers;
  2014. // Settings
  2015. std::string client_cert_path_;
  2016. std::string client_key_path_;
  2017. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2018. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2019. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2020. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2021. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2022. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2023. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2024. std::string basic_auth_username_;
  2025. std::string basic_auth_password_;
  2026. std::string bearer_token_auth_token_;
  2027. bool keep_alive_ = false;
  2028. bool follow_location_ = false;
  2029. bool path_encode_ = true;
  2030. int address_family_ = AF_UNSPEC;
  2031. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2032. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2033. SocketOptions socket_options_ = nullptr;
  2034. bool compress_ = false;
  2035. bool decompress_ = true;
  2036. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2037. bool has_payload_max_length_ = false;
  2038. std::string interface_;
  2039. std::string proxy_host_;
  2040. int proxy_port_ = -1;
  2041. std::string proxy_basic_auth_username_;
  2042. std::string proxy_basic_auth_password_;
  2043. std::string proxy_bearer_token_auth_token_;
  2044. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2045. mutable detail::NormalizedTarget host_normalized_;
  2046. mutable bool host_normalized_valid_ = false;
  2047. mutable std::mutex logger_mutex_;
  2048. Logger logger_;
  2049. ErrorLogger error_logger_;
  2050. private:
  2051. bool send_(Request &req, Response &res, Error &error);
  2052. Result send_(Request &&req);
  2053. socket_t create_client_socket(Error &error) const;
  2054. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2055. bool skip_100_continue = true) const;
  2056. bool write_request(Stream &strm, Request &req, bool close_connection,
  2057. Error &error, bool skip_body = false);
  2058. bool write_request_body(Stream &strm, Request &req, Error &error);
  2059. void prepare_default_headers(Request &r, bool for_stream,
  2060. const std::string &ct);
  2061. bool redirect(Request &req, Response &res, Error &error);
  2062. bool create_redirect_client(const std::string &scheme,
  2063. const std::string &host, int port, Request &req,
  2064. Response &res, const std::string &path,
  2065. const std::string &location, Error &error);
  2066. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2067. bool handle_request(Stream &strm, Request &req, Response &res,
  2068. bool close_connection, Error &error);
  2069. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2070. Request &req, const char *body, size_t content_length,
  2071. ContentProvider content_provider,
  2072. ContentProviderWithoutLength content_provider_without_length,
  2073. const std::string &content_type, ContentReceiver content_receiver,
  2074. Error &error);
  2075. Result send_with_content_provider_and_receiver(
  2076. const std::string &method, const std::string &path,
  2077. const Headers &headers, const char *body, size_t content_length,
  2078. ContentProvider content_provider,
  2079. ContentProviderWithoutLength content_provider_without_length,
  2080. const std::string &content_type, ContentReceiver content_receiver,
  2081. UploadProgress progress);
  2082. ContentProviderWithoutLength get_multipart_content_provider(
  2083. const std::string &boundary, const UploadFormDataItems &items,
  2084. const FormDataProviderItems &provider_items) const;
  2085. virtual bool
  2086. process_socket(const Socket &socket,
  2087. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2088. std::function<bool(Stream &strm)> callback);
  2089. virtual bool is_ssl() const;
  2090. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2091. #ifdef CPPHTTPLIB_SSL_ENABLED
  2092. public:
  2093. void set_digest_auth(const std::string &username,
  2094. const std::string &password);
  2095. void set_proxy_digest_auth(const std::string &username,
  2096. const std::string &password);
  2097. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2098. const std::string &ca_cert_dir_path = std::string());
  2099. void enable_server_certificate_verification(bool enabled);
  2100. void enable_server_hostname_verification(bool enabled);
  2101. void enable_system_ca(bool enabled);
  2102. protected:
  2103. std::string digest_auth_username_;
  2104. std::string digest_auth_password_;
  2105. std::string proxy_digest_auth_username_;
  2106. std::string proxy_digest_auth_password_;
  2107. std::string ca_cert_file_path_;
  2108. std::string ca_cert_dir_path_;
  2109. bool server_certificate_verification_ = true;
  2110. bool server_hostname_verification_ = true;
  2111. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2112. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2113. int last_ssl_error_ = 0;
  2114. uint64_t last_backend_error_ = 0;
  2115. #endif
  2116. };
  2117. class Client {
  2118. public:
  2119. // Universal interface
  2120. explicit Client(const std::string &scheme_host_port);
  2121. explicit Client(const std::string &scheme_host_port,
  2122. const std::string &client_cert_path,
  2123. const std::string &client_key_path);
  2124. // HTTP only interface
  2125. explicit Client(const std::string &host, int port);
  2126. explicit Client(const std::string &host, int port,
  2127. const std::string &client_cert_path,
  2128. const std::string &client_key_path);
  2129. Client(Client &&) = default;
  2130. Client &operator=(Client &&) = default;
  2131. ~Client();
  2132. bool is_valid() const;
  2133. // clang-format off
  2134. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2135. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2136. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2137. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2138. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2139. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2140. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2141. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2142. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2143. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2144. Result Head(const std::string &path);
  2145. Result Head(const std::string &path, const Headers &headers);
  2146. Result Post(const std::string &path);
  2147. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2149. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2150. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2151. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2152. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const Params &params);
  2154. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2155. Result Post(const std::string &path, const Headers &headers);
  2156. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2157. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2158. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2159. 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);
  2160. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2161. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2162. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2163. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2164. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2165. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2166. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2167. Result Put(const std::string &path);
  2168. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2171. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2172. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2173. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const Params &params);
  2175. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2176. Result Put(const std::string &path, const Headers &headers);
  2177. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2178. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2179. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2180. 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);
  2181. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2182. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2184. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2185. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2186. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2187. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2188. Result Patch(const std::string &path);
  2189. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2192. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2193. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2194. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const Params &params);
  2196. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2197. Result Patch(const std::string &path, const Headers &headers);
  2198. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2199. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2200. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2201. 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);
  2202. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2203. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2205. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2206. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2207. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2208. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2209. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2210. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2211. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2212. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2213. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2214. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2215. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2216. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2217. Result Options(const std::string &path);
  2218. Result Options(const std::string &path, const Headers &headers);
  2219. // clang-format on
  2220. // Streaming API: Open a stream for reading response body incrementally
  2221. // Socket ownership is transferred to StreamHandle for true streaming
  2222. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2223. ClientImpl::StreamHandle open_stream(const std::string &method,
  2224. const std::string &path,
  2225. const Params &params = {},
  2226. const Headers &headers = {},
  2227. const std::string &body = {},
  2228. const std::string &content_type = {});
  2229. bool send(Request &req, Response &res, Error &error);
  2230. Result send(const Request &req);
  2231. void stop();
  2232. std::string host() const;
  2233. int port() const;
  2234. size_t is_socket_open() const;
  2235. socket_t socket() const;
  2236. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2237. void set_default_headers(Headers headers);
  2238. void
  2239. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2240. void set_address_family(int family);
  2241. void set_tcp_nodelay(bool on);
  2242. void set_socket_options(SocketOptions socket_options);
  2243. void set_connection_timeout(time_t sec, time_t usec = 0);
  2244. template <class Rep, class Period>
  2245. void
  2246. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2247. void set_read_timeout(time_t sec, time_t usec = 0);
  2248. template <class Rep, class Period>
  2249. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2250. void set_write_timeout(time_t sec, time_t usec = 0);
  2251. template <class Rep, class Period>
  2252. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2253. void set_max_timeout(time_t msec);
  2254. template <class Rep, class Period>
  2255. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2256. void set_basic_auth(const std::string &username, const std::string &password);
  2257. void set_bearer_token_auth(const std::string &token);
  2258. void set_keep_alive(bool on);
  2259. void set_follow_location(bool on);
  2260. void set_path_encode(bool on);
  2261. void set_compress(bool on);
  2262. void set_decompress(bool on);
  2263. void set_payload_max_length(size_t length);
  2264. void set_interface(const std::string &intf);
  2265. void set_proxy(const std::string &host, int port);
  2266. void set_proxy_basic_auth(const std::string &username,
  2267. const std::string &password);
  2268. void set_proxy_bearer_token_auth(const std::string &token);
  2269. void set_no_proxy(const std::vector<std::string> &patterns);
  2270. void set_logger(Logger logger);
  2271. void set_error_logger(ErrorLogger error_logger);
  2272. private:
  2273. std::unique_ptr<ClientImpl> cli_;
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. public:
  2276. void set_digest_auth(const std::string &username,
  2277. const std::string &password);
  2278. void set_proxy_digest_auth(const std::string &username,
  2279. const std::string &password);
  2280. void enable_server_certificate_verification(bool enabled);
  2281. void enable_server_hostname_verification(bool enabled);
  2282. void enable_system_ca(bool enabled);
  2283. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2284. const std::string &ca_cert_dir_path = std::string());
  2285. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2286. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2287. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2288. void set_session_verifier(
  2289. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2290. tls::ctx_t tls_context() const;
  2291. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2292. void enable_windows_certificate_verification(bool enabled);
  2293. #endif
  2294. private:
  2295. bool is_ssl_ = false;
  2296. #endif
  2297. };
  2298. #ifdef CPPHTTPLIB_SSL_ENABLED
  2299. class SSLServer : public Server {
  2300. public:
  2301. SSLServer(const char *cert_path, const char *private_key_path,
  2302. const char *client_ca_cert_file_path = nullptr,
  2303. const char *client_ca_cert_dir_path = nullptr,
  2304. const char *private_key_password = nullptr);
  2305. struct PemMemory {
  2306. const char *cert_pem;
  2307. size_t cert_pem_len;
  2308. const char *key_pem;
  2309. size_t key_pem_len;
  2310. const char *client_ca_pem;
  2311. size_t client_ca_pem_len;
  2312. const char *private_key_password;
  2313. };
  2314. explicit SSLServer(const PemMemory &pem);
  2315. // The callback receives the ctx_t handle which can be cast to the
  2316. // appropriate backend type (SSL_CTX* for OpenSSL,
  2317. // tls::impl::MbedTlsContext* for Mbed TLS)
  2318. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2319. ~SSLServer() override;
  2320. bool is_valid() const override;
  2321. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2322. const char *client_ca_pem = nullptr,
  2323. const char *password = nullptr);
  2324. tls::ctx_t tls_context() const { return ctx_; }
  2325. int ssl_last_error() const { return last_ssl_error_; }
  2326. private:
  2327. bool process_and_close_socket(socket_t sock) override;
  2328. tls::ctx_t ctx_ = nullptr;
  2329. std::mutex ctx_mutex_;
  2330. int last_ssl_error_ = 0;
  2331. };
  2332. class SSLClient final : public ClientImpl {
  2333. public:
  2334. explicit SSLClient(const std::string &host);
  2335. explicit SSLClient(const std::string &host, int port);
  2336. explicit SSLClient(const std::string &host, int port,
  2337. const std::string &client_cert_path,
  2338. const std::string &client_key_path,
  2339. const std::string &private_key_password = std::string());
  2340. struct PemMemory {
  2341. const char *cert_pem;
  2342. size_t cert_pem_len;
  2343. const char *key_pem;
  2344. size_t key_pem_len;
  2345. const char *private_key_password;
  2346. };
  2347. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2348. ~SSLClient() override;
  2349. bool is_valid() const override;
  2350. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2351. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2352. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2353. // Post-handshake session verifier (backend-independent)
  2354. void set_session_verifier(
  2355. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2356. tls::ctx_t tls_context() const { return ctx_; }
  2357. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2358. void enable_windows_certificate_verification(bool enabled);
  2359. #endif
  2360. private:
  2361. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2362. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2363. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2364. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2365. bool
  2366. process_socket(const Socket &socket,
  2367. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2368. std::function<bool(Stream &strm)> callback) override;
  2369. bool is_ssl() const override;
  2370. bool setup_proxy_connection(
  2371. Socket &socket,
  2372. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2373. Response &res, bool &success, Error &error) override;
  2374. bool connect_with_proxy(
  2375. Socket &sock,
  2376. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2377. Response &res, bool &success, Error &error);
  2378. bool initialize_ssl(Socket &socket, Error &error);
  2379. void init_ctx();
  2380. void reset_ctx_on_error();
  2381. bool load_certs();
  2382. tls::ctx_t ctx_ = nullptr;
  2383. std::mutex ctx_mutex_;
  2384. std::once_flag initialize_cert_;
  2385. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2386. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2387. // Used to keep custom CA configuration exclusive with system CA loading.
  2388. bool ca_cert_store_set_ = false;
  2389. long verify_result_ = 0;
  2390. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2391. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2392. bool enable_windows_cert_verification_ = true;
  2393. #endif
  2394. friend class ClientImpl;
  2395. };
  2396. #endif // CPPHTTPLIB_SSL_ENABLED
  2397. namespace detail {
  2398. template <typename T, typename U>
  2399. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2400. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2401. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2402. duration - std::chrono::seconds(sec))
  2403. .count();
  2404. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2405. }
  2406. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2407. return N - 1;
  2408. }
  2409. inline bool is_numeric(const std::string &str) {
  2410. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2411. }
  2412. inline size_t get_header_value_u64(const Headers &headers,
  2413. const std::string &key, size_t def,
  2414. size_t id, bool &is_invalid_value) {
  2415. is_invalid_value = false;
  2416. auto rng = headers.equal_range(key);
  2417. auto it = rng.first;
  2418. std::advance(it, static_cast<ssize_t>(id));
  2419. if (it != rng.second) {
  2420. if (is_numeric(it->second)) {
  2421. // Parse at size_t width so an out-of-range Content-Length is reported
  2422. // rather than silently saturated/truncated (a value above 2^32 would
  2423. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  2424. // and return SIZE_MAX so the existing oversized-value guards reject it.
  2425. size_t val = 0;
  2426. const auto &s = it->second;
  2427. auto r = from_chars(s.data(), s.data() + s.size(), val);
  2428. if (r.ec == std::errc::result_out_of_range) {
  2429. is_invalid_value = true;
  2430. return (std::numeric_limits<size_t>::max)();
  2431. }
  2432. return val;
  2433. } else {
  2434. is_invalid_value = true;
  2435. }
  2436. }
  2437. return def;
  2438. }
  2439. inline size_t get_header_value_u64(const Headers &headers,
  2440. const std::string &key, size_t def,
  2441. size_t id) {
  2442. auto dummy = false;
  2443. return get_header_value_u64(headers, key, def, id, dummy);
  2444. }
  2445. } // namespace detail
  2446. template <class Rep, class Period>
  2447. inline Server &
  2448. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2449. detail::duration_to_sec_and_usec(
  2450. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2451. return *this;
  2452. }
  2453. template <class Rep, class Period>
  2454. inline Server &
  2455. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2456. detail::duration_to_sec_and_usec(
  2457. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2458. return *this;
  2459. }
  2460. template <class Rep, class Period>
  2461. inline Server &
  2462. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2463. detail::duration_to_sec_and_usec(
  2464. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2465. return *this;
  2466. }
  2467. template <class Rep, class Period>
  2468. inline void ClientImpl::set_connection_timeout(
  2469. const std::chrono::duration<Rep, Period> &duration) {
  2470. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2471. set_connection_timeout(sec, usec);
  2472. });
  2473. }
  2474. template <class Rep, class Period>
  2475. inline void ClientImpl::set_read_timeout(
  2476. const std::chrono::duration<Rep, Period> &duration) {
  2477. detail::duration_to_sec_and_usec(
  2478. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2479. }
  2480. template <class Rep, class Period>
  2481. inline void ClientImpl::set_write_timeout(
  2482. const std::chrono::duration<Rep, Period> &duration) {
  2483. detail::duration_to_sec_and_usec(
  2484. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2485. }
  2486. template <class Rep, class Period>
  2487. inline void ClientImpl::set_max_timeout(
  2488. const std::chrono::duration<Rep, Period> &duration) {
  2489. auto msec =
  2490. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2491. set_max_timeout(msec);
  2492. }
  2493. template <class Rep, class Period>
  2494. inline void Client::set_connection_timeout(
  2495. const std::chrono::duration<Rep, Period> &duration) {
  2496. cli_->set_connection_timeout(duration);
  2497. }
  2498. template <class Rep, class Period>
  2499. inline void
  2500. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2501. cli_->set_read_timeout(duration);
  2502. }
  2503. template <class Rep, class Period>
  2504. inline void
  2505. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2506. cli_->set_write_timeout(duration);
  2507. }
  2508. inline void Client::set_max_timeout(time_t msec) {
  2509. cli_->set_max_timeout(msec);
  2510. }
  2511. template <class Rep, class Period>
  2512. inline void
  2513. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2514. cli_->set_max_timeout(duration);
  2515. }
  2516. /*
  2517. * Forward declarations and types that will be part of the .h file if split into
  2518. * .h + .cc.
  2519. */
  2520. std::string hosted_at(const std::string &hostname);
  2521. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2522. // JavaScript-style URL encoding/decoding functions
  2523. std::string encode_uri_component(const std::string &value);
  2524. std::string encode_uri(const std::string &value);
  2525. std::string decode_uri_component(const std::string &value);
  2526. std::string decode_uri(const std::string &value);
  2527. // RFC 3986 compliant URL component encoding/decoding functions
  2528. std::string encode_path_component(const std::string &component);
  2529. std::string decode_path_component(const std::string &component);
  2530. std::string encode_query_component(const std::string &component,
  2531. bool space_as_plus = true);
  2532. std::string decode_query_component(const std::string &component,
  2533. bool plus_as_space = true);
  2534. std::string sanitize_filename(const std::string &filename);
  2535. std::string append_query_params(const std::string &path, const Params &params);
  2536. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2537. std::pair<std::string, std::string>
  2538. make_basic_authentication_header(const std::string &username,
  2539. const std::string &password,
  2540. bool is_proxy = false);
  2541. namespace detail {
  2542. #if defined(_WIN32)
  2543. inline std::wstring u8string_to_wstring(const char *s) {
  2544. if (!s) { return std::wstring(); }
  2545. auto len = static_cast<int>(strlen(s));
  2546. if (!len) { return std::wstring(); }
  2547. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2548. if (!wlen) { return std::wstring(); }
  2549. std::wstring ws;
  2550. ws.resize(wlen);
  2551. wlen = ::MultiByteToWideChar(
  2552. CP_UTF8, 0, s, len,
  2553. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2554. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2555. return ws;
  2556. }
  2557. #endif
  2558. struct FileStat {
  2559. FileStat(const std::string &path);
  2560. bool is_file() const;
  2561. bool is_dir() const;
  2562. time_t mtime() const;
  2563. size_t size() const;
  2564. private:
  2565. #if defined(_WIN32)
  2566. struct _stat st_;
  2567. #else
  2568. struct stat st_;
  2569. #endif
  2570. int ret_ = -1;
  2571. };
  2572. std::string make_host_and_port_string(const std::string &host, int port,
  2573. bool is_ssl);
  2574. std::string trim_copy(const std::string &s);
  2575. void divide(
  2576. const char *data, std::size_t size, char d,
  2577. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2578. fn);
  2579. void divide(
  2580. const std::string &str, char d,
  2581. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2582. fn);
  2583. void split(const char *b, const char *e, char d,
  2584. std::function<void(const char *, const char *)> fn);
  2585. void split(const char *b, const char *e, char d, size_t m,
  2586. std::function<void(const char *, const char *)> fn);
  2587. bool process_client_socket(
  2588. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2589. time_t write_timeout_sec, time_t write_timeout_usec,
  2590. time_t max_timeout_msec,
  2591. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2592. std::function<bool(Stream &)> callback);
  2593. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2594. int port, int address_family, bool tcp_nodelay,
  2595. bool ipv6_v6only, SocketOptions socket_options,
  2596. time_t connection_timeout_sec,
  2597. time_t connection_timeout_usec,
  2598. time_t read_timeout_sec, time_t read_timeout_usec,
  2599. time_t write_timeout_sec,
  2600. time_t write_timeout_usec,
  2601. const std::string &intf, Error &error);
  2602. const char *get_header_value(const Headers &headers, const std::string &key,
  2603. const char *def, size_t id);
  2604. std::string params_to_query_str(const Params &params);
  2605. void parse_query_text(const char *data, std::size_t size, Params &params);
  2606. void parse_query_text(const std::string &s, Params &params);
  2607. bool parse_multipart_boundary(const std::string &content_type,
  2608. std::string &boundary);
  2609. bool parse_range_header(const std::string &s, Ranges &ranges);
  2610. bool parse_accept_header(const std::string &s,
  2611. std::vector<std::string> &content_types);
  2612. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2613. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2614. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2615. EncodingType encoding_type(const Request &req, const Response &res);
  2616. class BufferStream final : public Stream {
  2617. public:
  2618. BufferStream() = default;
  2619. ~BufferStream() override = default;
  2620. bool is_readable() const override;
  2621. bool wait_readable() const override;
  2622. bool wait_writable() const override;
  2623. ssize_t read(char *ptr, size_t size) override;
  2624. ssize_t write(const char *ptr, size_t size) override;
  2625. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2626. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2627. socket_t socket() const override;
  2628. time_t duration() const override;
  2629. const std::string &get_buffer() const;
  2630. private:
  2631. std::string buffer;
  2632. size_t position = 0;
  2633. };
  2634. class compressor {
  2635. public:
  2636. virtual ~compressor() = default;
  2637. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2638. virtual bool compress(const char *data, size_t data_length, bool last,
  2639. Callback callback) = 0;
  2640. };
  2641. class decompressor {
  2642. public:
  2643. virtual ~decompressor() = default;
  2644. virtual bool is_valid() const = 0;
  2645. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2646. virtual bool decompress(const char *data, size_t data_length,
  2647. Callback callback) = 0;
  2648. };
  2649. class nocompressor final : public compressor {
  2650. public:
  2651. ~nocompressor() override = default;
  2652. bool compress(const char *data, size_t data_length, bool /*last*/,
  2653. Callback callback) override;
  2654. };
  2655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2656. class gzip_compressor final : public compressor {
  2657. public:
  2658. gzip_compressor();
  2659. ~gzip_compressor() override;
  2660. bool compress(const char *data, size_t data_length, bool last,
  2661. Callback callback) override;
  2662. private:
  2663. bool is_valid_ = false;
  2664. z_stream strm_;
  2665. };
  2666. class gzip_decompressor final : public decompressor {
  2667. public:
  2668. gzip_decompressor();
  2669. ~gzip_decompressor() override;
  2670. bool is_valid() const override;
  2671. bool decompress(const char *data, size_t data_length,
  2672. Callback callback) override;
  2673. private:
  2674. bool is_valid_ = false;
  2675. z_stream strm_;
  2676. };
  2677. #endif
  2678. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2679. class brotli_compressor final : public compressor {
  2680. public:
  2681. brotli_compressor();
  2682. ~brotli_compressor();
  2683. bool compress(const char *data, size_t data_length, bool last,
  2684. Callback callback) override;
  2685. private:
  2686. BrotliEncoderState *state_ = nullptr;
  2687. };
  2688. class brotli_decompressor final : public decompressor {
  2689. public:
  2690. brotli_decompressor();
  2691. ~brotli_decompressor();
  2692. bool is_valid() const override;
  2693. bool decompress(const char *data, size_t data_length,
  2694. Callback callback) override;
  2695. private:
  2696. BrotliDecoderResult decoder_r;
  2697. BrotliDecoderState *decoder_s = nullptr;
  2698. };
  2699. #endif
  2700. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2701. class zstd_compressor : public compressor {
  2702. public:
  2703. zstd_compressor();
  2704. ~zstd_compressor();
  2705. bool compress(const char *data, size_t data_length, bool last,
  2706. Callback callback) override;
  2707. private:
  2708. ZSTD_CCtx *ctx_ = nullptr;
  2709. };
  2710. class zstd_decompressor : public decompressor {
  2711. public:
  2712. zstd_decompressor();
  2713. ~zstd_decompressor();
  2714. bool is_valid() const override;
  2715. bool decompress(const char *data, size_t data_length,
  2716. Callback callback) override;
  2717. private:
  2718. ZSTD_DCtx *ctx_ = nullptr;
  2719. };
  2720. #endif
  2721. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2722. // to store data. The call can set memory on stack for performance.
  2723. class stream_line_reader {
  2724. public:
  2725. stream_line_reader(Stream &strm, char *fixed_buffer,
  2726. size_t fixed_buffer_size);
  2727. const char *ptr() const;
  2728. size_t size() const;
  2729. bool end_with_crlf() const;
  2730. bool getline();
  2731. private:
  2732. void append(char c);
  2733. Stream &strm_;
  2734. char *fixed_buffer_;
  2735. const size_t fixed_buffer_size_;
  2736. size_t fixed_buffer_used_size_ = 0;
  2737. std::string growable_buffer_;
  2738. };
  2739. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2740. const Headers &src_headers);
  2741. struct ChunkedDecoder {
  2742. Stream &strm;
  2743. size_t chunk_remaining = 0;
  2744. bool finished = false;
  2745. char line_buf[64];
  2746. size_t last_chunk_total = 0;
  2747. size_t last_chunk_offset = 0;
  2748. explicit ChunkedDecoder(Stream &s);
  2749. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2750. size_t &out_chunk_total);
  2751. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2752. };
  2753. class mmap {
  2754. public:
  2755. mmap(const char *path);
  2756. ~mmap();
  2757. bool open(const char *path);
  2758. void close();
  2759. bool is_open() const;
  2760. size_t size() const;
  2761. const char *data() const;
  2762. private:
  2763. #if defined(_WIN32)
  2764. HANDLE hFile_ = NULL;
  2765. HANDLE hMapping_ = NULL;
  2766. #else
  2767. int fd_ = -1;
  2768. #endif
  2769. size_t size_ = 0;
  2770. void *addr_ = nullptr;
  2771. bool is_open_empty_file = false;
  2772. };
  2773. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2774. namespace fields {
  2775. bool is_token_char(char c);
  2776. bool is_token(const std::string &s);
  2777. bool is_field_name(const std::string &s);
  2778. bool is_vchar(char c);
  2779. bool is_obs_text(char c);
  2780. bool is_field_vchar(char c);
  2781. bool is_field_content(const std::string &s);
  2782. bool is_field_value(const std::string &s);
  2783. } // namespace fields
  2784. } // namespace detail
  2785. /*
  2786. * TLS Abstraction Layer Declarations
  2787. */
  2788. #ifdef CPPHTTPLIB_SSL_ENABLED
  2789. // TLS abstraction layer - backend-specific type declarations
  2790. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2791. namespace tls {
  2792. namespace impl {
  2793. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2794. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2795. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2796. struct MbedTlsContext {
  2797. mbedtls_ssl_config conf;
  2798. mbedtls_entropy_context entropy;
  2799. mbedtls_ctr_drbg_context ctr_drbg;
  2800. mbedtls_x509_crt ca_chain;
  2801. mbedtls_x509_crt own_cert;
  2802. mbedtls_pk_context own_key;
  2803. bool is_server = false;
  2804. bool verify_client = false;
  2805. bool has_verify_callback = false;
  2806. MbedTlsContext();
  2807. ~MbedTlsContext();
  2808. MbedTlsContext(const MbedTlsContext &) = delete;
  2809. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2810. };
  2811. } // namespace impl
  2812. } // namespace tls
  2813. #endif
  2814. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2815. namespace tls {
  2816. namespace impl {
  2817. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2818. // This struct is accessible via tls::impl for use in SSL context
  2819. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2820. struct WolfSSLContext {
  2821. WOLFSSL_CTX *ctx = nullptr;
  2822. bool is_server = false;
  2823. bool verify_client = false;
  2824. bool has_verify_callback = false;
  2825. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2826. WolfSSLContext();
  2827. ~WolfSSLContext();
  2828. WolfSSLContext(const WolfSSLContext &) = delete;
  2829. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2830. };
  2831. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2832. struct WolfSSLCAStore {
  2833. std::string pem_data;
  2834. };
  2835. } // namespace impl
  2836. } // namespace tls
  2837. #endif
  2838. #endif // CPPHTTPLIB_SSL_ENABLED
  2839. namespace stream {
  2840. class Result {
  2841. public:
  2842. Result();
  2843. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2844. Result(Result &&other) noexcept;
  2845. Result &operator=(Result &&other) noexcept;
  2846. Result(const Result &) = delete;
  2847. Result &operator=(const Result &) = delete;
  2848. // Response info
  2849. bool is_valid() const;
  2850. explicit operator bool() const;
  2851. int status() const;
  2852. const Headers &headers() const;
  2853. std::string get_header_value(const std::string &key,
  2854. const char *def = "") const;
  2855. bool has_header(const std::string &key) const;
  2856. Error error() const;
  2857. Error read_error() const;
  2858. bool has_read_error() const;
  2859. // Stream reading
  2860. bool next();
  2861. const char *data() const;
  2862. size_t size() const;
  2863. std::string read_all();
  2864. private:
  2865. ClientImpl::StreamHandle handle_;
  2866. std::string buffer_;
  2867. size_t current_size_ = 0;
  2868. size_t chunk_size_;
  2869. bool finished_ = false;
  2870. };
  2871. // GET
  2872. template <typename ClientType>
  2873. inline Result Get(ClientType &cli, const std::string &path,
  2874. size_t chunk_size = 8192) {
  2875. return Result{cli.open_stream("GET", path), chunk_size};
  2876. }
  2877. template <typename ClientType>
  2878. inline Result Get(ClientType &cli, const std::string &path,
  2879. const Headers &headers, size_t chunk_size = 8192) {
  2880. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2881. }
  2882. template <typename ClientType>
  2883. inline Result Get(ClientType &cli, const std::string &path,
  2884. const Params &params, size_t chunk_size = 8192) {
  2885. return Result{cli.open_stream("GET", path, params), chunk_size};
  2886. }
  2887. template <typename ClientType>
  2888. inline Result Get(ClientType &cli, const std::string &path,
  2889. const Params &params, const Headers &headers,
  2890. size_t chunk_size = 8192) {
  2891. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2892. }
  2893. // POST
  2894. template <typename ClientType>
  2895. inline Result Post(ClientType &cli, const std::string &path,
  2896. const std::string &body, const std::string &content_type,
  2897. size_t chunk_size = 8192) {
  2898. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2899. chunk_size};
  2900. }
  2901. template <typename ClientType>
  2902. inline Result Post(ClientType &cli, const std::string &path,
  2903. const Headers &headers, const std::string &body,
  2904. const std::string &content_type, size_t chunk_size = 8192) {
  2905. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2906. chunk_size};
  2907. }
  2908. template <typename ClientType>
  2909. inline Result Post(ClientType &cli, const std::string &path,
  2910. const Params &params, const std::string &body,
  2911. const std::string &content_type, size_t chunk_size = 8192) {
  2912. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2913. chunk_size};
  2914. }
  2915. template <typename ClientType>
  2916. inline Result Post(ClientType &cli, const std::string &path,
  2917. const Params &params, const Headers &headers,
  2918. const std::string &body, const std::string &content_type,
  2919. size_t chunk_size = 8192) {
  2920. return Result{
  2921. cli.open_stream("POST", path, params, headers, body, content_type),
  2922. chunk_size};
  2923. }
  2924. // PUT
  2925. template <typename ClientType>
  2926. inline Result Put(ClientType &cli, const std::string &path,
  2927. const std::string &body, const std::string &content_type,
  2928. size_t chunk_size = 8192) {
  2929. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2930. chunk_size};
  2931. }
  2932. template <typename ClientType>
  2933. inline Result Put(ClientType &cli, const std::string &path,
  2934. const Headers &headers, const std::string &body,
  2935. const std::string &content_type, size_t chunk_size = 8192) {
  2936. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2937. chunk_size};
  2938. }
  2939. template <typename ClientType>
  2940. inline Result Put(ClientType &cli, const std::string &path,
  2941. const Params &params, const std::string &body,
  2942. const std::string &content_type, size_t chunk_size = 8192) {
  2943. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2944. chunk_size};
  2945. }
  2946. template <typename ClientType>
  2947. inline Result Put(ClientType &cli, const std::string &path,
  2948. const Params &params, const Headers &headers,
  2949. const std::string &body, const std::string &content_type,
  2950. size_t chunk_size = 8192) {
  2951. return Result{
  2952. cli.open_stream("PUT", path, params, headers, body, content_type),
  2953. chunk_size};
  2954. }
  2955. // PATCH
  2956. template <typename ClientType>
  2957. inline Result Patch(ClientType &cli, const std::string &path,
  2958. const std::string &body, const std::string &content_type,
  2959. size_t chunk_size = 8192) {
  2960. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2961. chunk_size};
  2962. }
  2963. template <typename ClientType>
  2964. inline Result Patch(ClientType &cli, const std::string &path,
  2965. const Headers &headers, const std::string &body,
  2966. const std::string &content_type, size_t chunk_size = 8192) {
  2967. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2968. chunk_size};
  2969. }
  2970. template <typename ClientType>
  2971. inline Result Patch(ClientType &cli, const std::string &path,
  2972. const Params &params, const std::string &body,
  2973. const std::string &content_type, size_t chunk_size = 8192) {
  2974. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2975. chunk_size};
  2976. }
  2977. template <typename ClientType>
  2978. inline Result Patch(ClientType &cli, const std::string &path,
  2979. const Params &params, const Headers &headers,
  2980. const std::string &body, const std::string &content_type,
  2981. size_t chunk_size = 8192) {
  2982. return Result{
  2983. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2984. chunk_size};
  2985. }
  2986. // DELETE
  2987. template <typename ClientType>
  2988. inline Result Delete(ClientType &cli, const std::string &path,
  2989. size_t chunk_size = 8192) {
  2990. return Result{cli.open_stream("DELETE", path), chunk_size};
  2991. }
  2992. template <typename ClientType>
  2993. inline Result Delete(ClientType &cli, const std::string &path,
  2994. const Headers &headers, size_t chunk_size = 8192) {
  2995. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2996. }
  2997. template <typename ClientType>
  2998. inline Result Delete(ClientType &cli, const std::string &path,
  2999. const std::string &body, const std::string &content_type,
  3000. size_t chunk_size = 8192) {
  3001. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3002. chunk_size};
  3003. }
  3004. template <typename ClientType>
  3005. inline Result Delete(ClientType &cli, const std::string &path,
  3006. const Headers &headers, const std::string &body,
  3007. const std::string &content_type,
  3008. size_t chunk_size = 8192) {
  3009. return Result{
  3010. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3011. chunk_size};
  3012. }
  3013. template <typename ClientType>
  3014. inline Result Delete(ClientType &cli, const std::string &path,
  3015. const Params &params, size_t chunk_size = 8192) {
  3016. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3017. }
  3018. template <typename ClientType>
  3019. inline Result Delete(ClientType &cli, const std::string &path,
  3020. const Params &params, const Headers &headers,
  3021. size_t chunk_size = 8192) {
  3022. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3023. }
  3024. template <typename ClientType>
  3025. inline Result Delete(ClientType &cli, const std::string &path,
  3026. const Params &params, const std::string &body,
  3027. const std::string &content_type,
  3028. size_t chunk_size = 8192) {
  3029. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3030. chunk_size};
  3031. }
  3032. template <typename ClientType>
  3033. inline Result Delete(ClientType &cli, const std::string &path,
  3034. const Params &params, const Headers &headers,
  3035. const std::string &body, const std::string &content_type,
  3036. size_t chunk_size = 8192) {
  3037. return Result{
  3038. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3039. chunk_size};
  3040. }
  3041. // HEAD
  3042. template <typename ClientType>
  3043. inline Result Head(ClientType &cli, const std::string &path,
  3044. size_t chunk_size = 8192) {
  3045. return Result{cli.open_stream("HEAD", path), chunk_size};
  3046. }
  3047. template <typename ClientType>
  3048. inline Result Head(ClientType &cli, const std::string &path,
  3049. const Headers &headers, size_t chunk_size = 8192) {
  3050. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3051. }
  3052. template <typename ClientType>
  3053. inline Result Head(ClientType &cli, const std::string &path,
  3054. const Params &params, size_t chunk_size = 8192) {
  3055. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3056. }
  3057. template <typename ClientType>
  3058. inline Result Head(ClientType &cli, const std::string &path,
  3059. const Params &params, const Headers &headers,
  3060. size_t chunk_size = 8192) {
  3061. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3062. }
  3063. // OPTIONS
  3064. template <typename ClientType>
  3065. inline Result Options(ClientType &cli, const std::string &path,
  3066. size_t chunk_size = 8192) {
  3067. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3068. }
  3069. template <typename ClientType>
  3070. inline Result Options(ClientType &cli, const std::string &path,
  3071. const Headers &headers, size_t chunk_size = 8192) {
  3072. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3073. }
  3074. template <typename ClientType>
  3075. inline Result Options(ClientType &cli, const std::string &path,
  3076. const Params &params, size_t chunk_size = 8192) {
  3077. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3078. }
  3079. template <typename ClientType>
  3080. inline Result Options(ClientType &cli, const std::string &path,
  3081. const Params &params, const Headers &headers,
  3082. size_t chunk_size = 8192) {
  3083. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3084. }
  3085. } // namespace stream
  3086. namespace sse {
  3087. struct SSEMessage {
  3088. std::string event; // Event type (default: "message")
  3089. std::string data; // Event payload
  3090. std::string id; // Event ID for Last-Event-ID header
  3091. SSEMessage();
  3092. void clear();
  3093. };
  3094. class SSEClient {
  3095. public:
  3096. using MessageHandler = std::function<void(const SSEMessage &)>;
  3097. using ErrorHandler = std::function<void(Error)>;
  3098. using OpenHandler = std::function<void()>;
  3099. SSEClient(Client &client, const std::string &path);
  3100. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3101. ~SSEClient();
  3102. SSEClient(const SSEClient &) = delete;
  3103. SSEClient &operator=(const SSEClient &) = delete;
  3104. // Event handlers
  3105. SSEClient &on_message(MessageHandler handler);
  3106. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3107. SSEClient &on_open(OpenHandler handler);
  3108. SSEClient &on_error(ErrorHandler handler);
  3109. SSEClient &set_reconnect_interval(int ms);
  3110. SSEClient &set_max_reconnect_attempts(int n);
  3111. // Update headers (thread-safe)
  3112. SSEClient &set_headers(const Headers &headers);
  3113. // State accessors
  3114. bool is_connected() const;
  3115. const std::string &last_event_id() const;
  3116. // Blocking start - runs event loop with auto-reconnect
  3117. void start();
  3118. // Non-blocking start - runs in background thread
  3119. void start_async();
  3120. // Stop the client (thread-safe)
  3121. void stop();
  3122. private:
  3123. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3124. void run_event_loop();
  3125. void dispatch_event(const SSEMessage &msg);
  3126. bool should_reconnect(int count) const;
  3127. void wait_for_reconnect();
  3128. // Client and path
  3129. Client &client_;
  3130. std::string path_;
  3131. Headers headers_;
  3132. mutable std::mutex headers_mutex_;
  3133. // Callbacks
  3134. MessageHandler on_message_;
  3135. std::map<std::string, MessageHandler> event_handlers_;
  3136. OpenHandler on_open_;
  3137. ErrorHandler on_error_;
  3138. // Configuration
  3139. int reconnect_interval_ms_ = 3000;
  3140. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3141. // State
  3142. std::atomic<bool> running_{false};
  3143. std::atomic<bool> connected_{false};
  3144. std::string last_event_id_;
  3145. // Async support
  3146. std::thread async_thread_;
  3147. };
  3148. } // namespace sse
  3149. namespace ws {
  3150. enum class Opcode : uint8_t {
  3151. Continuation = 0x0,
  3152. Text = 0x1,
  3153. Binary = 0x2,
  3154. Close = 0x8,
  3155. Ping = 0x9,
  3156. Pong = 0xA,
  3157. };
  3158. enum class CloseStatus : uint16_t {
  3159. Normal = 1000,
  3160. GoingAway = 1001,
  3161. ProtocolError = 1002,
  3162. UnsupportedData = 1003,
  3163. NoStatus = 1005,
  3164. Abnormal = 1006,
  3165. InvalidPayload = 1007,
  3166. PolicyViolation = 1008,
  3167. MessageTooBig = 1009,
  3168. MandatoryExtension = 1010,
  3169. InternalError = 1011,
  3170. };
  3171. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3172. class WebSocket {
  3173. public:
  3174. WebSocket(const WebSocket &) = delete;
  3175. WebSocket &operator=(const WebSocket &) = delete;
  3176. ~WebSocket();
  3177. ReadResult read(std::string &msg);
  3178. bool send(const std::string &data);
  3179. bool send(const char *data, size_t len);
  3180. void close(CloseStatus status = CloseStatus::Normal,
  3181. const std::string &reason = "");
  3182. const Request &request() const;
  3183. bool is_open() const;
  3184. private:
  3185. friend class httplib::Server;
  3186. friend class WebSocketClient;
  3187. WebSocket(
  3188. Stream &strm, const Request &req, bool is_server,
  3189. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3190. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3191. : strm_(strm), req_(req), is_server_(is_server),
  3192. ping_interval_sec_(ping_interval_sec),
  3193. max_missed_pongs_(max_missed_pongs) {
  3194. start_heartbeat();
  3195. }
  3196. WebSocket(
  3197. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3198. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3199. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3200. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3201. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3202. max_missed_pongs_(max_missed_pongs) {
  3203. start_heartbeat();
  3204. }
  3205. void start_heartbeat();
  3206. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3207. Stream &strm_;
  3208. std::unique_ptr<Stream> owned_strm_;
  3209. Request req_;
  3210. bool is_server_;
  3211. time_t ping_interval_sec_;
  3212. int max_missed_pongs_;
  3213. int unacked_pings_ = 0;
  3214. std::atomic<bool> closed_{false};
  3215. std::mutex write_mutex_;
  3216. std::thread ping_thread_;
  3217. std::mutex ping_mutex_;
  3218. std::condition_variable ping_cv_;
  3219. };
  3220. class WebSocketClient {
  3221. public:
  3222. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3223. const Headers &headers = {});
  3224. ~WebSocketClient();
  3225. WebSocketClient(const WebSocketClient &) = delete;
  3226. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3227. bool is_valid() const;
  3228. bool connect();
  3229. ReadResult read(std::string &msg);
  3230. bool send(const std::string &data);
  3231. bool send(const char *data, size_t len);
  3232. void close(CloseStatus status = CloseStatus::Normal,
  3233. const std::string &reason = "");
  3234. bool is_open() const;
  3235. const std::string &subprotocol() const;
  3236. void set_read_timeout(time_t sec, time_t usec = 0);
  3237. void set_write_timeout(time_t sec, time_t usec = 0);
  3238. void set_websocket_ping_interval(time_t sec);
  3239. void set_websocket_max_missed_pongs(int count);
  3240. void set_tcp_nodelay(bool on);
  3241. void set_address_family(int family);
  3242. void set_ipv6_v6only(bool on);
  3243. void set_socket_options(SocketOptions socket_options);
  3244. void set_connection_timeout(time_t sec, time_t usec = 0);
  3245. void set_interface(const std::string &intf);
  3246. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3247. #ifdef CPPHTTPLIB_SSL_ENABLED
  3248. void set_ca_cert_path(const std::string &path);
  3249. void set_ca_cert_store(tls::ca_store_t store);
  3250. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3251. void enable_server_certificate_verification(bool enabled);
  3252. void enable_system_ca(bool enabled);
  3253. #endif
  3254. private:
  3255. void shutdown_and_close();
  3256. bool create_stream(std::unique_ptr<Stream> &strm);
  3257. std::string host_;
  3258. int port_;
  3259. std::string path_;
  3260. Headers headers_;
  3261. std::string subprotocol_;
  3262. bool is_valid_ = false;
  3263. socket_t sock_ = INVALID_SOCKET;
  3264. std::unique_ptr<WebSocket> ws_;
  3265. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3266. time_t read_timeout_usec_ = 0;
  3267. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3268. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3269. time_t websocket_ping_interval_sec_ =
  3270. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3271. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3272. int address_family_ = AF_UNSPEC;
  3273. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3274. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3275. SocketOptions socket_options_ = nullptr;
  3276. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3277. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3278. std::string interface_;
  3279. // Hostname-IP map
  3280. std::map<std::string, std::string> addr_map_;
  3281. #ifdef CPPHTTPLIB_SSL_ENABLED
  3282. bool is_ssl_ = false;
  3283. tls::ctx_t tls_ctx_ = nullptr;
  3284. tls::session_t tls_session_ = nullptr;
  3285. std::string ca_cert_file_path_;
  3286. bool custom_ca_loaded_ = false;
  3287. bool certs_loaded_ = false;
  3288. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3289. bool server_certificate_verification_ = true;
  3290. #endif
  3291. };
  3292. namespace impl {
  3293. bool is_valid_utf8(const std::string &s);
  3294. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3295. bool &fin, bool expect_masked, size_t max_len);
  3296. } // namespace impl
  3297. } // namespace ws
  3298. // ----------------------------------------------------------------------------
  3299. /*
  3300. * Implementation that will be part of the .cc file if split into .h + .cc.
  3301. */
  3302. namespace stream {
  3303. // stream::Result implementations
  3304. inline Result::Result() : chunk_size_(8192) {}
  3305. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3306. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3307. inline Result::Result(Result &&other) noexcept
  3308. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3309. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3310. finished_(other.finished_) {
  3311. other.current_size_ = 0;
  3312. other.finished_ = true;
  3313. }
  3314. inline Result &Result::operator=(Result &&other) noexcept {
  3315. if (this != &other) {
  3316. handle_ = std::move(other.handle_);
  3317. buffer_ = std::move(other.buffer_);
  3318. current_size_ = other.current_size_;
  3319. chunk_size_ = other.chunk_size_;
  3320. finished_ = other.finished_;
  3321. other.current_size_ = 0;
  3322. other.finished_ = true;
  3323. }
  3324. return *this;
  3325. }
  3326. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3327. inline Result::operator bool() const { return is_valid(); }
  3328. inline int Result::status() const {
  3329. return handle_.response ? handle_.response->status : -1;
  3330. }
  3331. inline const Headers &Result::headers() const {
  3332. static const Headers empty_headers;
  3333. return handle_.response ? handle_.response->headers : empty_headers;
  3334. }
  3335. inline std::string Result::get_header_value(const std::string &key,
  3336. const char *def) const {
  3337. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3338. }
  3339. inline bool Result::has_header(const std::string &key) const {
  3340. return handle_.response ? handle_.response->has_header(key) : false;
  3341. }
  3342. inline Error Result::error() const { return handle_.error; }
  3343. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3344. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3345. inline bool Result::next() {
  3346. if (!handle_.is_valid() || finished_) { return false; }
  3347. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3348. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3349. if (n > 0) {
  3350. current_size_ = static_cast<size_t>(n);
  3351. return true;
  3352. }
  3353. current_size_ = 0;
  3354. finished_ = true;
  3355. return false;
  3356. }
  3357. inline const char *Result::data() const { return buffer_.data(); }
  3358. inline size_t Result::size() const { return current_size_; }
  3359. inline std::string Result::read_all() {
  3360. std::string result;
  3361. while (next()) {
  3362. result.append(data(), size());
  3363. }
  3364. return result;
  3365. }
  3366. } // namespace stream
  3367. namespace sse {
  3368. // SSEMessage implementations
  3369. inline SSEMessage::SSEMessage() : event("message") {}
  3370. inline void SSEMessage::clear() {
  3371. event = "message";
  3372. data.clear();
  3373. id.clear();
  3374. }
  3375. // SSEClient implementations
  3376. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3377. : client_(client), path_(path) {}
  3378. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3379. const Headers &headers)
  3380. : client_(client), path_(path), headers_(headers) {}
  3381. inline SSEClient::~SSEClient() { stop(); }
  3382. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3383. on_message_ = std::move(handler);
  3384. return *this;
  3385. }
  3386. inline SSEClient &SSEClient::on_event(const std::string &type,
  3387. MessageHandler handler) {
  3388. event_handlers_[type] = std::move(handler);
  3389. return *this;
  3390. }
  3391. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3392. on_open_ = std::move(handler);
  3393. return *this;
  3394. }
  3395. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3396. on_error_ = std::move(handler);
  3397. return *this;
  3398. }
  3399. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3400. reconnect_interval_ms_ = ms;
  3401. return *this;
  3402. }
  3403. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3404. max_reconnect_attempts_ = n;
  3405. return *this;
  3406. }
  3407. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3408. std::lock_guard<std::mutex> lock(headers_mutex_);
  3409. headers_ = headers;
  3410. return *this;
  3411. }
  3412. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3413. inline const std::string &SSEClient::last_event_id() const {
  3414. return last_event_id_;
  3415. }
  3416. inline void SSEClient::start() {
  3417. running_.store(true);
  3418. run_event_loop();
  3419. }
  3420. inline void SSEClient::start_async() {
  3421. running_.store(true);
  3422. async_thread_ = std::thread([this]() { run_event_loop(); });
  3423. }
  3424. inline void SSEClient::stop() {
  3425. running_.store(false);
  3426. client_.stop(); // Cancel any pending operations
  3427. if (async_thread_.joinable()) { async_thread_.join(); }
  3428. }
  3429. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3430. int &retry_ms) {
  3431. // Blank line signals end of event
  3432. if (line.empty() || line == "\r") { return true; }
  3433. // Lines starting with ':' are comments (ignored)
  3434. if (!line.empty() && line[0] == ':') { return false; }
  3435. // Find the colon separator
  3436. auto colon_pos = line.find(':');
  3437. if (colon_pos == std::string::npos) {
  3438. // Line with no colon is treated as field name with empty value
  3439. return false;
  3440. }
  3441. auto field = line.substr(0, colon_pos);
  3442. std::string value;
  3443. // Value starts after colon, skip optional single space
  3444. if (colon_pos + 1 < line.size()) {
  3445. auto value_start = colon_pos + 1;
  3446. if (line[value_start] == ' ') { value_start++; }
  3447. value = line.substr(value_start);
  3448. // Remove trailing \r if present
  3449. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3450. }
  3451. // Handle known fields
  3452. if (field == "event") {
  3453. msg.event = value;
  3454. } else if (field == "data") {
  3455. // Multiple data lines are concatenated with newlines
  3456. if (!msg.data.empty()) { msg.data += "\n"; }
  3457. msg.data += value;
  3458. } else if (field == "id") {
  3459. // Empty id is valid (clears the last event ID)
  3460. msg.id = value;
  3461. } else if (field == "retry") {
  3462. // Parse retry interval in milliseconds
  3463. {
  3464. int v = 0;
  3465. auto res =
  3466. detail::from_chars(value.data(), value.data() + value.size(), v);
  3467. if (res.ec == std::errc{}) { retry_ms = v; }
  3468. }
  3469. }
  3470. // Unknown fields are ignored per SSE spec
  3471. return false;
  3472. }
  3473. inline void SSEClient::run_event_loop() {
  3474. auto reconnect_count = 0;
  3475. while (running_.load()) {
  3476. // Build headers, including Last-Event-ID if we have one
  3477. Headers request_headers;
  3478. {
  3479. std::lock_guard<std::mutex> lock(headers_mutex_);
  3480. request_headers = headers_;
  3481. }
  3482. if (!last_event_id_.empty()) {
  3483. request_headers.emplace("Last-Event-ID", last_event_id_);
  3484. }
  3485. // Open streaming connection
  3486. auto result = stream::Get(client_, path_, request_headers);
  3487. // Connection error handling
  3488. if (!result) {
  3489. connected_.store(false);
  3490. if (on_error_) { on_error_(result.error()); }
  3491. if (!should_reconnect(reconnect_count)) { break; }
  3492. wait_for_reconnect();
  3493. reconnect_count++;
  3494. continue;
  3495. }
  3496. if (result.status() != StatusCode::OK_200) {
  3497. connected_.store(false);
  3498. if (on_error_) { on_error_(Error::Connection); }
  3499. // For certain errors, don't reconnect.
  3500. // Note: 401 is intentionally absent so that handlers can refresh
  3501. // credentials via set_headers() and let the client reconnect.
  3502. if (result.status() == StatusCode::NoContent_204 ||
  3503. result.status() == StatusCode::NotFound_404 ||
  3504. result.status() == StatusCode::Forbidden_403) {
  3505. break;
  3506. }
  3507. if (!should_reconnect(reconnect_count)) { break; }
  3508. wait_for_reconnect();
  3509. reconnect_count++;
  3510. continue;
  3511. }
  3512. // Connection successful
  3513. connected_.store(true);
  3514. reconnect_count = 0;
  3515. if (on_open_) { on_open_(); }
  3516. // Event receiving loop
  3517. std::string buffer;
  3518. SSEMessage current_msg;
  3519. while (running_.load() && result.next()) {
  3520. buffer.append(result.data(), result.size());
  3521. // Process complete lines in the buffer
  3522. size_t line_start = 0;
  3523. size_t newline_pos;
  3524. while ((newline_pos = buffer.find('\n', line_start)) !=
  3525. std::string::npos) {
  3526. auto line = buffer.substr(line_start, newline_pos - line_start);
  3527. line_start = newline_pos + 1;
  3528. // Parse the line and check if event is complete
  3529. auto event_complete =
  3530. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3531. if (event_complete && !current_msg.data.empty()) {
  3532. // Update last_event_id for reconnection
  3533. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3534. // Dispatch event to appropriate handler
  3535. dispatch_event(current_msg);
  3536. current_msg.clear();
  3537. }
  3538. }
  3539. // Keep unprocessed data in buffer
  3540. buffer.erase(0, line_start);
  3541. }
  3542. // Connection ended
  3543. connected_.store(false);
  3544. if (!running_.load()) { break; }
  3545. // Check for read errors
  3546. if (result.has_read_error()) {
  3547. if (on_error_) { on_error_(result.read_error()); }
  3548. }
  3549. if (!should_reconnect(reconnect_count)) { break; }
  3550. wait_for_reconnect();
  3551. reconnect_count++;
  3552. }
  3553. connected_.store(false);
  3554. }
  3555. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3556. // Check for specific event type handler first
  3557. auto it = event_handlers_.find(msg.event);
  3558. if (it != event_handlers_.end()) {
  3559. it->second(msg);
  3560. return;
  3561. }
  3562. // Fall back to generic message handler
  3563. if (on_message_) { on_message_(msg); }
  3564. }
  3565. inline bool SSEClient::should_reconnect(int count) const {
  3566. if (!running_.load()) { return false; }
  3567. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3568. return count < max_reconnect_attempts_;
  3569. }
  3570. inline void SSEClient::wait_for_reconnect() {
  3571. // Use small increments to check running_ flag frequently
  3572. auto waited = 0;
  3573. while (running_.load() && waited < reconnect_interval_ms_) {
  3574. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3575. waited += 100;
  3576. }
  3577. }
  3578. } // namespace sse
  3579. #ifdef CPPHTTPLIB_SSL_ENABLED
  3580. /*
  3581. * TLS abstraction layer - internal function declarations
  3582. * These are implementation details and not part of the public API.
  3583. */
  3584. namespace tls {
  3585. // Client context
  3586. ctx_t create_client_context();
  3587. void free_context(ctx_t ctx);
  3588. bool set_min_version(ctx_t ctx, Version version);
  3589. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3590. bool load_ca_file(ctx_t ctx, const char *file_path);
  3591. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3592. bool load_system_certs(ctx_t ctx);
  3593. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3594. const char *password);
  3595. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3596. const char *key_path, const char *password);
  3597. // Server context
  3598. ctx_t create_server_context();
  3599. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3600. const char *password);
  3601. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3602. const char *key_path, const char *password);
  3603. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3604. void set_verify_client(ctx_t ctx, bool require);
  3605. // Session management
  3606. session_t create_session(ctx_t ctx, socket_t sock);
  3607. void free_session(session_t session);
  3608. bool set_sni(session_t session, const char *hostname);
  3609. bool set_hostname(session_t session, const char *hostname);
  3610. // Handshake (non-blocking capable)
  3611. TlsError connect(session_t session);
  3612. TlsError accept(session_t session);
  3613. // Handshake with timeout (blocking until timeout)
  3614. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3615. time_t timeout_usec, TlsError *err);
  3616. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3617. time_t timeout_usec, TlsError *err);
  3618. // I/O (non-blocking capable)
  3619. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3620. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3621. int pending(const_session_t session);
  3622. void shutdown(session_t session, bool graceful);
  3623. // Connection state
  3624. bool is_peer_closed(session_t session, socket_t sock);
  3625. // Certificate verification
  3626. cert_t get_peer_cert(const_session_t session);
  3627. void free_cert(cert_t cert);
  3628. bool verify_hostname(cert_t cert, const char *hostname);
  3629. uint64_t hostname_mismatch_code();
  3630. long get_verify_result(const_session_t session);
  3631. // Certificate introspection
  3632. std::string get_cert_subject_cn(cert_t cert);
  3633. std::string get_cert_issuer_name(cert_t cert);
  3634. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3635. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3636. std::string get_cert_serial(cert_t cert);
  3637. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3638. const char *get_sni(const_session_t session);
  3639. // CA store management
  3640. ca_store_t create_ca_store(const char *pem, size_t len);
  3641. void free_ca_store(ca_store_t store);
  3642. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3643. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3644. std::vector<std::string> get_ca_names(ctx_t ctx);
  3645. // Dynamic certificate update (for servers)
  3646. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3647. const char *password);
  3648. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3649. // Certificate verification callback
  3650. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3651. long get_verify_error(const_session_t session);
  3652. std::string verify_error_string(long error_code);
  3653. // TlsError information
  3654. uint64_t peek_error();
  3655. uint64_t get_error();
  3656. std::string error_string(uint64_t code);
  3657. } // namespace tls
  3658. #endif // CPPHTTPLIB_SSL_ENABLED
  3659. /*
  3660. * Group 1: detail namespace - Non-SSL utilities
  3661. */
  3662. namespace detail {
  3663. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3664. const void *optval, socklen_t optlen) {
  3665. return setsockopt(sock, level, optname,
  3666. #ifdef _WIN32
  3667. reinterpret_cast<const char *>(optval),
  3668. #else
  3669. optval,
  3670. #endif
  3671. optlen) == 0;
  3672. }
  3673. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3674. time_t sec, time_t usec) {
  3675. #ifdef _WIN32
  3676. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3677. #else
  3678. timeval timeout;
  3679. timeout.tv_sec = static_cast<long>(sec);
  3680. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3681. #endif
  3682. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3683. }
  3684. inline bool is_hex(char c, int &v) {
  3685. if (is_ascii_digit(c)) {
  3686. v = c - '0';
  3687. return true;
  3688. } else if ('A' <= c && c <= 'F') {
  3689. v = c - 'A' + 10;
  3690. return true;
  3691. } else if ('a' <= c && c <= 'f') {
  3692. v = c - 'a' + 10;
  3693. return true;
  3694. }
  3695. return false;
  3696. }
  3697. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3698. int &val) {
  3699. if (i >= s.size()) { return false; }
  3700. val = 0;
  3701. for (; cnt; i++, cnt--) {
  3702. if (!s[i]) { return false; }
  3703. auto v = 0;
  3704. if (is_hex(s[i], v)) {
  3705. val = val * 16 + v;
  3706. } else {
  3707. return false;
  3708. }
  3709. }
  3710. return true;
  3711. }
  3712. inline std::string from_i_to_hex(size_t n) {
  3713. static const auto charset = "0123456789abcdef";
  3714. std::string ret;
  3715. do {
  3716. ret = charset[n & 15] + ret;
  3717. n >>= 4;
  3718. } while (n > 0);
  3719. return ret;
  3720. }
  3721. inline std::string compute_etag(const FileStat &fs) {
  3722. if (!fs.is_file()) { return std::string(); }
  3723. // If mtime cannot be determined (negative value indicates an error
  3724. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3725. // value like 0 could collide with a real file that legitimately has
  3726. // mtime == 0 (epoch) and lead to misleading validators.
  3727. auto mtime_raw = fs.mtime();
  3728. if (mtime_raw < 0) { return std::string(); }
  3729. auto mtime = static_cast<size_t>(mtime_raw);
  3730. auto size = fs.size();
  3731. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3732. from_i_to_hex(size) + "\"";
  3733. }
  3734. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3735. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3736. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3737. inline std::string file_mtime_to_http_date(time_t mtime) {
  3738. if (mtime < 0) { return std::string(); }
  3739. struct tm tm_buf;
  3740. #ifdef _WIN32
  3741. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3742. #else
  3743. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3744. #endif
  3745. char buf[64];
  3746. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3747. return std::string();
  3748. }
  3749. return std::string(buf);
  3750. }
  3751. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3752. inline time_t parse_http_date(const std::string &date_str) {
  3753. struct tm tm_buf;
  3754. // Create a classic locale object once for all parsing attempts
  3755. const std::locale classic_locale = std::locale::classic();
  3756. // Try to parse using std::get_time (C++11, cross-platform)
  3757. auto try_parse = [&](const char *fmt) -> bool {
  3758. std::istringstream ss(date_str);
  3759. ss.imbue(classic_locale);
  3760. memset(&tm_buf, 0, sizeof(tm_buf));
  3761. ss >> std::get_time(&tm_buf, fmt);
  3762. return !ss.fail();
  3763. };
  3764. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3765. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3766. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3767. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3768. // asctime format: "Sun Nov 6 08:49:37 1994"
  3769. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3770. return static_cast<time_t>(-1);
  3771. }
  3772. }
  3773. }
  3774. #ifdef _WIN32
  3775. return _mkgmtime(&tm_buf);
  3776. #elif defined _AIX
  3777. return mktime(&tm_buf);
  3778. #else
  3779. return timegm(&tm_buf);
  3780. #endif
  3781. }
  3782. inline bool is_weak_etag(const std::string &s) {
  3783. // Check if the string is a weak ETag (starts with 'W/"')
  3784. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3785. }
  3786. inline bool is_strong_etag(const std::string &s) {
  3787. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3788. // chars)
  3789. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3790. }
  3791. inline size_t to_utf8(int code, char *buff) {
  3792. if (code < 0x0080) {
  3793. buff[0] = static_cast<char>(code & 0x7F);
  3794. return 1;
  3795. } else if (code < 0x0800) {
  3796. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3797. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3798. return 2;
  3799. } else if (code < 0xD800) {
  3800. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3801. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3802. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3803. return 3;
  3804. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3805. return 0;
  3806. } else if (code < 0x10000) {
  3807. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3808. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3809. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3810. return 3;
  3811. } else if (code < 0x110000) {
  3812. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3813. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3814. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3815. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3816. return 4;
  3817. }
  3818. // NOTREACHED
  3819. return 0;
  3820. }
  3821. } // namespace detail
  3822. namespace ws {
  3823. namespace impl {
  3824. inline bool is_valid_utf8(const std::string &s) {
  3825. size_t i = 0;
  3826. auto n = s.size();
  3827. while (i < n) {
  3828. auto c = static_cast<unsigned char>(s[i]);
  3829. size_t len;
  3830. uint32_t cp;
  3831. if (c < 0x80) {
  3832. i++;
  3833. continue;
  3834. } else if ((c & 0xE0) == 0xC0) {
  3835. len = 2;
  3836. cp = c & 0x1F;
  3837. } else if ((c & 0xF0) == 0xE0) {
  3838. len = 3;
  3839. cp = c & 0x0F;
  3840. } else if ((c & 0xF8) == 0xF0) {
  3841. len = 4;
  3842. cp = c & 0x07;
  3843. } else {
  3844. return false;
  3845. }
  3846. if (i + len > n) { return false; }
  3847. for (size_t j = 1; j < len; j++) {
  3848. auto b = static_cast<unsigned char>(s[i + j]);
  3849. if ((b & 0xC0) != 0x80) { return false; }
  3850. cp = (cp << 6) | (b & 0x3F);
  3851. }
  3852. // Overlong encoding check
  3853. if (len == 2 && cp < 0x80) { return false; }
  3854. if (len == 3 && cp < 0x800) { return false; }
  3855. if (len == 4 && cp < 0x10000) { return false; }
  3856. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3857. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3858. if (cp > 0x10FFFF) { return false; }
  3859. i += len;
  3860. }
  3861. return true;
  3862. }
  3863. } // namespace impl
  3864. } // namespace ws
  3865. namespace detail {
  3866. // NOTE: This code came up with the following stackoverflow post:
  3867. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3868. inline std::string base64_encode(const std::string &in) {
  3869. static const auto lookup =
  3870. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3871. std::string out;
  3872. out.reserve(in.size());
  3873. // Unsigned: the accumulator is never masked, so with a signed int the
  3874. // `val << 8` below overflows once enough bytes are folded in (undefined
  3875. // behaviour before C++20). Only the low bits are ever emitted, so the
  3876. // wrap-around of an unsigned accumulator does not affect the output.
  3877. uint32_t val = 0;
  3878. auto valb = -6;
  3879. for (auto c : in) {
  3880. val = (val << 8) + static_cast<uint8_t>(c);
  3881. valb += 8;
  3882. while (valb >= 0) {
  3883. out.push_back(lookup[(val >> valb) & 0x3F]);
  3884. valb -= 6;
  3885. }
  3886. }
  3887. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3888. while (out.size() % 4) {
  3889. out.push_back('=');
  3890. }
  3891. return out;
  3892. }
  3893. inline std::string sha1(const std::string &input) {
  3894. // RFC 3174 SHA-1 implementation
  3895. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3896. return (x << n) | (x >> (32 - n));
  3897. };
  3898. uint32_t h0 = 0x67452301;
  3899. uint32_t h1 = 0xEFCDAB89;
  3900. uint32_t h2 = 0x98BADCFE;
  3901. uint32_t h3 = 0x10325476;
  3902. uint32_t h4 = 0xC3D2E1F0;
  3903. // Pre-processing: adding padding bits
  3904. std::string msg = input;
  3905. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3906. msg.push_back(static_cast<char>(0x80u));
  3907. while (msg.size() % 64 != 56) {
  3908. msg.push_back(0);
  3909. }
  3910. // Append original length in bits as 64-bit big-endian
  3911. for (int i = 56; i >= 0; i -= 8) {
  3912. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3913. }
  3914. // Process each 512-bit chunk
  3915. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3916. uint32_t w[80];
  3917. for (size_t i = 0; i < 16; i++) {
  3918. w[i] =
  3919. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3920. << 24) |
  3921. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3922. << 16) |
  3923. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3924. << 8) |
  3925. (static_cast<uint32_t>(
  3926. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3927. }
  3928. for (int i = 16; i < 80; i++) {
  3929. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3930. }
  3931. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3932. for (int i = 0; i < 80; i++) {
  3933. uint32_t f, k;
  3934. if (i < 20) {
  3935. f = (b & c) | ((~b) & d);
  3936. k = 0x5A827999;
  3937. } else if (i < 40) {
  3938. f = b ^ c ^ d;
  3939. k = 0x6ED9EBA1;
  3940. } else if (i < 60) {
  3941. f = (b & c) | (b & d) | (c & d);
  3942. k = 0x8F1BBCDC;
  3943. } else {
  3944. f = b ^ c ^ d;
  3945. k = 0xCA62C1D6;
  3946. }
  3947. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3948. e = d;
  3949. d = c;
  3950. c = left_rotate(b, 30);
  3951. b = a;
  3952. a = temp;
  3953. }
  3954. h0 += a;
  3955. h1 += b;
  3956. h2 += c;
  3957. h3 += d;
  3958. h4 += e;
  3959. }
  3960. // Produce the final hash as a 20-byte binary string
  3961. std::string hash(20, '\0');
  3962. for (size_t i = 0; i < 4; i++) {
  3963. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3964. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3965. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3966. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3967. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3968. }
  3969. return hash;
  3970. }
  3971. inline std::string websocket_accept_key(const std::string &client_key) {
  3972. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3973. return base64_encode(sha1(client_key + magic));
  3974. }
  3975. inline bool is_websocket_upgrade(const Request &req) {
  3976. if (req.method != "GET") { return false; }
  3977. // Check Upgrade: websocket (case-insensitive)
  3978. auto upgrade_it = req.headers.find("Upgrade");
  3979. if (upgrade_it == req.headers.end()) { return false; }
  3980. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3981. if (upgrade_val != "websocket") { return false; }
  3982. // Check Connection header contains "Upgrade"
  3983. auto connection_it = req.headers.find("Connection");
  3984. if (connection_it == req.headers.end()) { return false; }
  3985. auto connection_val = case_ignore::to_lower(connection_it->second);
  3986. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3987. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3988. // RFC 6455 Section 4.2.1
  3989. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3990. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3991. return false;
  3992. }
  3993. static const std::string b64chars =
  3994. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3995. for (size_t i = 0; i < 22; i++) {
  3996. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3997. }
  3998. // Check Sec-WebSocket-Version: 13
  3999. auto version = req.get_header_value("Sec-WebSocket-Version");
  4000. if (version != "13") { return false; }
  4001. return true;
  4002. }
  4003. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  4004. const char *data, size_t len, bool fin,
  4005. bool mask) {
  4006. // First byte: FIN + opcode
  4007. uint8_t header[2];
  4008. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  4009. (static_cast<uint8_t>(opcode) & 0x0F));
  4010. // Second byte: MASK + payload length
  4011. if (len < 126) {
  4012. header[1] = static_cast<uint8_t>(len);
  4013. if (mask) { header[1] |= 0x80; }
  4014. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4015. } else if (len <= 0xFFFF) {
  4016. header[1] = 126;
  4017. if (mask) { header[1] |= 0x80; }
  4018. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4019. uint8_t ext[2];
  4020. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4021. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4022. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4023. } else {
  4024. header[1] = 127;
  4025. if (mask) { header[1] |= 0x80; }
  4026. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4027. uint8_t ext[8];
  4028. for (int i = 7; i >= 0; i--) {
  4029. ext[7 - i] =
  4030. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4031. }
  4032. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4033. }
  4034. if (mask) {
  4035. // Generate random mask key
  4036. thread_local std::mt19937 rng(std::random_device{}());
  4037. uint8_t mask_key[4];
  4038. auto r = rng();
  4039. std::memcpy(mask_key, &r, 4);
  4040. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4041. // Write masked payload in chunks
  4042. const size_t chunk_size = 4096;
  4043. std::vector<char> buf((std::min)(len, chunk_size));
  4044. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4045. size_t n = (std::min)(chunk_size, len - offset);
  4046. for (size_t i = 0; i < n; i++) {
  4047. buf[i] =
  4048. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4049. }
  4050. if (strm.write(buf.data(), n) < 0) { return false; }
  4051. }
  4052. } else {
  4053. if (len > 0) {
  4054. if (strm.write(data, len) < 0) { return false; }
  4055. }
  4056. }
  4057. return true;
  4058. }
  4059. } // namespace detail
  4060. namespace ws {
  4061. namespace impl {
  4062. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4063. std::string &payload, bool &fin,
  4064. bool expect_masked, size_t max_len) {
  4065. // Read first 2 bytes
  4066. uint8_t header[2];
  4067. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4068. fin = (header[0] & 0x80) != 0;
  4069. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4070. if (header[0] & 0x70) { return false; }
  4071. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4072. bool masked = (header[1] & 0x80) != 0;
  4073. uint64_t payload_len = header[1] & 0x7F;
  4074. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4075. // MUST have a payload length of 125 bytes or less
  4076. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4077. if (is_control) {
  4078. if (!fin) { return false; }
  4079. if (payload_len > 125) { return false; }
  4080. }
  4081. if (masked != expect_masked) { return false; }
  4082. // Extended payload length
  4083. if (payload_len == 126) {
  4084. uint8_t ext[2];
  4085. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4086. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4087. } else if (payload_len == 127) {
  4088. uint8_t ext[8];
  4089. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4090. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4091. if (ext[0] & 0x80) { return false; }
  4092. payload_len = 0;
  4093. for (int i = 0; i < 8; i++) {
  4094. payload_len = (payload_len << 8) | ext[i];
  4095. }
  4096. }
  4097. if (payload_len > max_len) { return false; }
  4098. // Read mask key if present
  4099. uint8_t mask_key[4] = {0};
  4100. if (masked) {
  4101. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4102. }
  4103. // Read payload
  4104. payload.resize(static_cast<size_t>(payload_len));
  4105. if (payload_len > 0) {
  4106. size_t total_read = 0;
  4107. while (total_read < payload_len) {
  4108. auto n = strm.read(&payload[total_read],
  4109. static_cast<size_t>(payload_len - total_read));
  4110. if (n <= 0) { return false; }
  4111. total_read += static_cast<size_t>(n);
  4112. }
  4113. }
  4114. // Unmask if needed
  4115. if (masked) {
  4116. for (size_t i = 0; i < payload.size(); i++) {
  4117. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4118. }
  4119. }
  4120. return true;
  4121. }
  4122. } // namespace impl
  4123. } // namespace ws
  4124. namespace detail {
  4125. inline bool is_valid_path(const std::string &path) {
  4126. size_t level = 0;
  4127. size_t i = 0;
  4128. // Skip slash
  4129. while (i < path.size() && path[i] == '/') {
  4130. i++;
  4131. }
  4132. while (i < path.size()) {
  4133. // Read component
  4134. auto beg = i;
  4135. while (i < path.size() && path[i] != '/') {
  4136. if (path[i] == '\0') {
  4137. return false;
  4138. } else if (path[i] == '\\') {
  4139. return false;
  4140. }
  4141. i++;
  4142. }
  4143. auto len = i - beg;
  4144. assert(len > 0);
  4145. if (!path.compare(beg, len, ".")) {
  4146. ;
  4147. } else if (!path.compare(beg, len, "..")) {
  4148. if (level == 0) { return false; }
  4149. level--;
  4150. } else {
  4151. level++;
  4152. }
  4153. // Skip slash
  4154. while (i < path.size() && path[i] == '/') {
  4155. i++;
  4156. }
  4157. }
  4158. return true;
  4159. }
  4160. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4161. #if defined(_WIN32)
  4162. char buf[_MAX_PATH];
  4163. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4164. resolved = buf;
  4165. #elif defined(PATH_MAX)
  4166. char buf[PATH_MAX];
  4167. if (realpath(path, buf) == nullptr) { return false; }
  4168. resolved = buf;
  4169. #else
  4170. auto buf = realpath(path, nullptr);
  4171. auto guard = scope_exit([&]() { std::free(buf); });
  4172. if (buf == nullptr) { return false; }
  4173. resolved = buf;
  4174. #endif
  4175. return true;
  4176. }
  4177. inline bool is_path_within_base(const std::string &resolved_path,
  4178. const std::string &resolved_base) {
  4179. #if defined(_WIN32)
  4180. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4181. resolved_base.size()) == 0;
  4182. #else
  4183. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4184. resolved_base.size()) == 0;
  4185. #endif
  4186. }
  4187. inline FileStat::FileStat(const std::string &path) {
  4188. #if defined(_WIN32)
  4189. auto wpath = u8string_to_wstring(path.c_str());
  4190. ret_ = _wstat(wpath.c_str(), &st_);
  4191. #else
  4192. ret_ = stat(path.c_str(), &st_);
  4193. #endif
  4194. }
  4195. inline bool FileStat::is_file() const {
  4196. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4197. }
  4198. inline bool FileStat::is_dir() const {
  4199. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4200. }
  4201. inline time_t FileStat::mtime() const {
  4202. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4203. : static_cast<time_t>(-1);
  4204. }
  4205. inline size_t FileStat::size() const {
  4206. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4207. }
  4208. inline std::string encode_path(const std::string &s) {
  4209. std::string result;
  4210. result.reserve(s.size());
  4211. for (size_t i = 0; s[i]; i++) {
  4212. switch (s[i]) {
  4213. case ' ': result += "%20"; break;
  4214. case '+': result += "%2B"; break;
  4215. case '\r': result += "%0D"; break;
  4216. case '\n': result += "%0A"; break;
  4217. case '\'': result += "%27"; break;
  4218. case ',': result += "%2C"; break;
  4219. // case ':': result += "%3A"; break; // ok? probably...
  4220. case ';': result += "%3B"; break;
  4221. default:
  4222. auto c = static_cast<uint8_t>(s[i]);
  4223. if (c >= 0x80) {
  4224. result += '%';
  4225. char hex[4];
  4226. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4227. assert(len == 2);
  4228. result.append(hex, static_cast<size_t>(len));
  4229. } else {
  4230. result += s[i];
  4231. }
  4232. break;
  4233. }
  4234. }
  4235. return result;
  4236. }
  4237. inline std::string file_extension(const std::string &path) {
  4238. std::smatch m;
  4239. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4240. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4241. return std::string();
  4242. }
  4243. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4244. template <typename T>
  4245. inline bool parse_header(const char *beg, const char *end, T fn);
  4246. template <typename T>
  4247. inline bool parse_header(const char *beg, const char *end, T fn) {
  4248. // Skip trailing spaces and tabs.
  4249. while (beg < end && is_space_or_tab(end[-1])) {
  4250. end--;
  4251. }
  4252. auto p = beg;
  4253. while (p < end && *p != ':') {
  4254. p++;
  4255. }
  4256. auto name = std::string(beg, p);
  4257. if (!detail::fields::is_field_name(name)) { return false; }
  4258. if (p == end) { return false; }
  4259. auto key_end = p;
  4260. if (*p++ != ':') { return false; }
  4261. while (p < end && is_space_or_tab(*p)) {
  4262. p++;
  4263. }
  4264. if (p <= end) {
  4265. auto key_len = key_end - beg;
  4266. if (!key_len) { return false; }
  4267. auto key = std::string(beg, key_end);
  4268. auto val = std::string(p, end);
  4269. if (!detail::fields::is_field_value(val)) { return false; }
  4270. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4271. // percent-decoded by the recipient. Applications that need to interpret a
  4272. // value as a URI component should call httplib::decode_uri_component()
  4273. // (or decode_path_component()) explicitly.
  4274. fn(key, val);
  4275. return true;
  4276. }
  4277. return false;
  4278. }
  4279. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4280. const Headers &src_headers) {
  4281. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4282. // transfer coding is complete when a chunk with a chunk-size of zero is
  4283. // received, possibly followed by a trailer section, and finally terminated by
  4284. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4285. //
  4286. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4287. // doesn't care for the existence of the final CRLF. In other words, it seems
  4288. // to be ok whether the final CRLF exists or not in the chunked data.
  4289. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4290. //
  4291. // According to the reference code in RFC 9112, cpp-httplib now allows
  4292. // chunked transfer coding data without the final CRLF.
  4293. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4294. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4295. "transfer-encoding",
  4296. "content-length",
  4297. "host",
  4298. "authorization",
  4299. "www-authenticate",
  4300. "proxy-authenticate",
  4301. "proxy-authorization",
  4302. "cookie",
  4303. "set-cookie",
  4304. "cache-control",
  4305. "expect",
  4306. "max-forwards",
  4307. "pragma",
  4308. "range",
  4309. "te",
  4310. "age",
  4311. "expires",
  4312. "date",
  4313. "location",
  4314. "retry-after",
  4315. "vary",
  4316. "warning",
  4317. "content-encoding",
  4318. "content-type",
  4319. "content-range",
  4320. "trailer"};
  4321. case_ignore::unordered_set<std::string> declared_trailers;
  4322. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4323. if (trailer_header && std::strlen(trailer_header)) {
  4324. auto len = std::strlen(trailer_header);
  4325. split(trailer_header, trailer_header + len, ',',
  4326. [&](const char *b, const char *e) {
  4327. const char *kbeg = b;
  4328. const char *kend = e;
  4329. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4330. ++kbeg;
  4331. }
  4332. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4333. --kend;
  4334. }
  4335. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4336. if (!key.empty() &&
  4337. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4338. declared_trailers.insert(key);
  4339. }
  4340. });
  4341. }
  4342. size_t trailer_header_count = 0;
  4343. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4344. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4345. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4346. constexpr auto line_terminator_len = 2;
  4347. auto line_beg = line_reader.ptr();
  4348. auto line_end =
  4349. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4350. if (!parse_header(line_beg, line_end,
  4351. [&](const std::string &key, const std::string &val) {
  4352. if (declared_trailers.find(key) !=
  4353. declared_trailers.end()) {
  4354. dest.emplace(key, val);
  4355. trailer_header_count++;
  4356. }
  4357. })) {
  4358. return false;
  4359. }
  4360. if (!line_reader.getline()) { return false; }
  4361. }
  4362. return true;
  4363. }
  4364. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4365. size_t right) {
  4366. while (b + left < e && is_space_or_tab(b[left])) {
  4367. left++;
  4368. }
  4369. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4370. right--;
  4371. }
  4372. return std::make_pair(left, right);
  4373. }
  4374. inline std::string trim_copy(const std::string &s) {
  4375. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4376. return s.substr(r.first, r.second - r.first);
  4377. }
  4378. inline std::string trim_double_quotes_copy(const std::string &s) {
  4379. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4380. return s.substr(1, s.size() - 2);
  4381. }
  4382. return s;
  4383. }
  4384. inline void
  4385. divide(const char *data, std::size_t size, char d,
  4386. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4387. fn) {
  4388. const auto it = std::find(data, data + size, d);
  4389. const auto found = static_cast<std::size_t>(it != data + size);
  4390. const auto lhs_data = data;
  4391. const auto lhs_size = static_cast<std::size_t>(it - data);
  4392. const auto rhs_data = it + found;
  4393. const auto rhs_size = size - lhs_size - found;
  4394. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4395. }
  4396. inline void
  4397. divide(const std::string &str, char d,
  4398. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4399. fn) {
  4400. divide(str.data(), str.size(), d, std::move(fn));
  4401. }
  4402. inline void split(const char *b, const char *e, char d,
  4403. std::function<void(const char *, const char *)> fn) {
  4404. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4405. }
  4406. inline void split(const char *b, const char *e, char d, size_t m,
  4407. std::function<void(const char *, const char *)> fn) {
  4408. size_t i = 0;
  4409. size_t beg = 0;
  4410. size_t count = 1;
  4411. while (e ? (b + i < e) : (b[i] != '\0')) {
  4412. if (b[i] == d && count < m) {
  4413. auto r = trim(b, e, beg, i);
  4414. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4415. beg = i + 1;
  4416. count++;
  4417. }
  4418. i++;
  4419. }
  4420. if (i) {
  4421. auto r = trim(b, e, beg, i);
  4422. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4423. }
  4424. }
  4425. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4426. std::function<bool(const char *, const char *)> fn) {
  4427. size_t i = 0;
  4428. size_t beg = 0;
  4429. size_t count = 1;
  4430. while (e ? (b + i < e) : (b[i] != '\0')) {
  4431. if (b[i] == d && count < m) {
  4432. auto r = trim(b, e, beg, i);
  4433. if (r.first < r.second) {
  4434. auto found = fn(&b[r.first], &b[r.second]);
  4435. if (found) { return true; }
  4436. }
  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) {
  4445. auto found = fn(&b[r.first], &b[r.second]);
  4446. if (found) { return true; }
  4447. }
  4448. }
  4449. return false;
  4450. }
  4451. inline bool split_find(const char *b, const char *e, char d,
  4452. std::function<bool(const char *, const char *)> fn) {
  4453. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4454. std::move(fn));
  4455. }
  4456. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4457. size_t fixed_buffer_size)
  4458. : strm_(strm), fixed_buffer_(fixed_buffer),
  4459. fixed_buffer_size_(fixed_buffer_size) {}
  4460. inline const char *stream_line_reader::ptr() const {
  4461. if (growable_buffer_.empty()) {
  4462. return fixed_buffer_;
  4463. } else {
  4464. return growable_buffer_.data();
  4465. }
  4466. }
  4467. inline size_t stream_line_reader::size() const {
  4468. if (growable_buffer_.empty()) {
  4469. return fixed_buffer_used_size_;
  4470. } else {
  4471. return growable_buffer_.size();
  4472. }
  4473. }
  4474. inline bool stream_line_reader::end_with_crlf() const {
  4475. auto end = ptr() + size();
  4476. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4477. }
  4478. inline bool stream_line_reader::getline() {
  4479. fixed_buffer_used_size_ = 0;
  4480. growable_buffer_.clear();
  4481. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4482. char prev_byte = 0;
  4483. #endif
  4484. for (size_t i = 0;; i++) {
  4485. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4486. // Treat exceptionally long lines as an error to
  4487. // prevent infinite loops/memory exhaustion
  4488. return false;
  4489. }
  4490. char byte;
  4491. auto n = strm_.read(&byte, 1);
  4492. if (n < 0) {
  4493. return false;
  4494. } else if (n == 0) {
  4495. if (i == 0) {
  4496. return false;
  4497. } else {
  4498. break;
  4499. }
  4500. }
  4501. append(byte);
  4502. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4503. if (byte == '\n') { break; }
  4504. #else
  4505. if (prev_byte == '\r' && byte == '\n') { break; }
  4506. prev_byte = byte;
  4507. #endif
  4508. }
  4509. return true;
  4510. }
  4511. inline void stream_line_reader::append(char c) {
  4512. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4513. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4514. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4515. } else {
  4516. if (growable_buffer_.empty()) {
  4517. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4518. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4519. }
  4520. growable_buffer_ += c;
  4521. }
  4522. }
  4523. inline mmap::mmap(const char *path) { open(path); }
  4524. inline mmap::~mmap() { close(); }
  4525. inline bool mmap::open(const char *path) {
  4526. close();
  4527. #if defined(_WIN32)
  4528. auto wpath = u8string_to_wstring(path);
  4529. if (wpath.empty()) { return false; }
  4530. hFile_ =
  4531. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4532. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4533. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4534. LARGE_INTEGER size{};
  4535. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4536. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4537. // See:
  4538. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4539. if (static_cast<ULONGLONG>(size.QuadPart) >
  4540. (std::numeric_limits<decltype(size_)>::max)()) {
  4541. // `size_t` might be 32-bits, on 32-bits Windows.
  4542. return false;
  4543. }
  4544. size_ = static_cast<size_t>(size.QuadPart);
  4545. hMapping_ =
  4546. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4547. // Special treatment for an empty file...
  4548. if (hMapping_ == NULL && size_ == 0) {
  4549. close();
  4550. is_open_empty_file = true;
  4551. return true;
  4552. }
  4553. if (hMapping_ == NULL) {
  4554. close();
  4555. return false;
  4556. }
  4557. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4558. if (addr_ == nullptr) {
  4559. close();
  4560. return false;
  4561. }
  4562. #else
  4563. fd_ = ::open(path, O_RDONLY);
  4564. if (fd_ == -1) { return false; }
  4565. struct stat sb;
  4566. if (fstat(fd_, &sb) == -1) {
  4567. close();
  4568. return false;
  4569. }
  4570. size_ = static_cast<size_t>(sb.st_size);
  4571. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4572. // Special treatment for an empty file...
  4573. if (addr_ == MAP_FAILED && size_ == 0) {
  4574. close();
  4575. is_open_empty_file = true;
  4576. return false;
  4577. }
  4578. #endif
  4579. return true;
  4580. }
  4581. inline bool mmap::is_open() const {
  4582. return is_open_empty_file ? true : addr_ != nullptr;
  4583. }
  4584. inline size_t mmap::size() const { return size_; }
  4585. inline const char *mmap::data() const {
  4586. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4587. }
  4588. inline void mmap::close() {
  4589. #if defined(_WIN32)
  4590. if (addr_) {
  4591. ::UnmapViewOfFile(addr_);
  4592. addr_ = nullptr;
  4593. }
  4594. if (hMapping_) {
  4595. ::CloseHandle(hMapping_);
  4596. hMapping_ = NULL;
  4597. }
  4598. if (hFile_ != INVALID_HANDLE_VALUE) {
  4599. ::CloseHandle(hFile_);
  4600. hFile_ = INVALID_HANDLE_VALUE;
  4601. }
  4602. is_open_empty_file = false;
  4603. #else
  4604. if (addr_ != nullptr) {
  4605. munmap(addr_, size_);
  4606. addr_ = nullptr;
  4607. }
  4608. if (fd_ != -1) {
  4609. ::close(fd_);
  4610. fd_ = -1;
  4611. }
  4612. #endif
  4613. size_ = 0;
  4614. }
  4615. inline int close_socket(socket_t sock) noexcept {
  4616. #ifdef _WIN32
  4617. return closesocket(sock);
  4618. #else
  4619. return close(sock);
  4620. #endif
  4621. }
  4622. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4623. ssize_t res = 0;
  4624. while (true) {
  4625. res = fn();
  4626. if (res < 0 && errno == EINTR) {
  4627. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4628. continue;
  4629. }
  4630. break;
  4631. }
  4632. return res;
  4633. }
  4634. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4635. return handle_EINTR([&]() {
  4636. return recv(sock,
  4637. #ifdef _WIN32
  4638. static_cast<char *>(ptr), static_cast<int>(size),
  4639. #else
  4640. ptr, size,
  4641. #endif
  4642. flags);
  4643. });
  4644. }
  4645. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4646. int flags) {
  4647. return handle_EINTR([&]() {
  4648. return send(sock,
  4649. #ifdef _WIN32
  4650. static_cast<const char *>(ptr), static_cast<int>(size),
  4651. #else
  4652. ptr, size,
  4653. #endif
  4654. flags);
  4655. });
  4656. }
  4657. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4658. #ifdef _WIN32
  4659. return ::WSAPoll(fds, nfds, timeout);
  4660. #else
  4661. return ::poll(fds, nfds, timeout);
  4662. #endif
  4663. }
  4664. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4665. time_t usec) {
  4666. struct pollfd pfd;
  4667. pfd.fd = sock;
  4668. pfd.events = events;
  4669. pfd.revents = 0;
  4670. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4671. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4672. }
  4673. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4674. return select_impl(sock, POLLIN, sec, usec);
  4675. }
  4676. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4677. return select_impl(sock, POLLOUT, sec, usec);
  4678. }
  4679. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4680. time_t usec) {
  4681. struct pollfd pfd_read;
  4682. pfd_read.fd = sock;
  4683. pfd_read.events = POLLIN | POLLOUT;
  4684. pfd_read.revents = 0;
  4685. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4686. auto poll_res =
  4687. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4688. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4689. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4690. auto error = 0;
  4691. socklen_t len = sizeof(error);
  4692. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4693. reinterpret_cast<char *>(&error), &len);
  4694. auto successful = res >= 0 && !error;
  4695. return successful ? Error::Success : Error::Connection;
  4696. }
  4697. return Error::Connection;
  4698. }
  4699. inline bool is_socket_alive(socket_t sock) {
  4700. const auto val = detail::select_read(sock, 0, 0);
  4701. if (val == 0) {
  4702. return true;
  4703. } else if (val < 0 && errno == EBADF) {
  4704. return false;
  4705. }
  4706. char buf[1];
  4707. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4708. }
  4709. class SocketStream final : public Stream {
  4710. public:
  4711. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4712. time_t write_timeout_sec, time_t write_timeout_usec,
  4713. time_t max_timeout_msec = 0,
  4714. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4715. (std::chrono::steady_clock::time_point::min)());
  4716. ~SocketStream() override;
  4717. bool is_readable() const override;
  4718. bool wait_readable() const override;
  4719. bool wait_writable() const override;
  4720. bool is_peer_alive() const override;
  4721. ssize_t read(char *ptr, size_t size) override;
  4722. ssize_t write(const char *ptr, size_t size) override;
  4723. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4724. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4725. socket_t socket() const override;
  4726. time_t duration() const override;
  4727. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4728. private:
  4729. socket_t sock_;
  4730. time_t read_timeout_sec_;
  4731. time_t read_timeout_usec_;
  4732. time_t write_timeout_sec_;
  4733. time_t write_timeout_usec_;
  4734. time_t max_timeout_msec_;
  4735. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4736. std::vector<char> read_buff_;
  4737. size_t read_buff_off_ = 0;
  4738. size_t read_buff_content_size_ = 0;
  4739. static const size_t read_buff_size_ = 1024l * 4;
  4740. };
  4741. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4742. time_t keep_alive_timeout_sec) {
  4743. using namespace std::chrono;
  4744. const auto interval_usec =
  4745. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4746. // Avoid expensive `steady_clock::now()` call for the first time
  4747. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4748. const auto start = steady_clock::now() - microseconds{interval_usec};
  4749. const auto timeout = seconds{keep_alive_timeout_sec};
  4750. while (true) {
  4751. if (svr_sock == INVALID_SOCKET) {
  4752. break; // Server socket is closed
  4753. }
  4754. auto val = select_read(sock, 0, interval_usec);
  4755. if (val < 0) {
  4756. break; // Ssocket error
  4757. } else if (val == 0) {
  4758. if (steady_clock::now() - start > timeout) {
  4759. break; // Timeout
  4760. }
  4761. } else {
  4762. return true; // Ready for read
  4763. }
  4764. }
  4765. return false;
  4766. }
  4767. template <typename T>
  4768. inline bool
  4769. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4770. size_t keep_alive_max_count,
  4771. time_t keep_alive_timeout_sec, T callback) {
  4772. assert(keep_alive_max_count > 0);
  4773. auto ret = false;
  4774. auto count = keep_alive_max_count;
  4775. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4776. auto close_connection = count == 1;
  4777. auto connection_closed = false;
  4778. ret = callback(close_connection, connection_closed);
  4779. if (!ret || connection_closed) { break; }
  4780. count--;
  4781. }
  4782. return ret;
  4783. }
  4784. template <typename T>
  4785. inline bool
  4786. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4787. size_t keep_alive_max_count,
  4788. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4789. time_t read_timeout_usec, time_t write_timeout_sec,
  4790. time_t write_timeout_usec, T callback) {
  4791. return process_server_socket_core(
  4792. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4793. [&](bool close_connection, bool &connection_closed) {
  4794. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4795. write_timeout_sec, write_timeout_usec);
  4796. return callback(strm, close_connection, connection_closed);
  4797. });
  4798. }
  4799. inline bool process_client_socket(
  4800. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4801. time_t write_timeout_sec, time_t write_timeout_usec,
  4802. time_t max_timeout_msec,
  4803. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4804. std::function<bool(Stream &)> callback) {
  4805. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4806. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4807. start_time);
  4808. return callback(strm);
  4809. }
  4810. inline int shutdown_socket(socket_t sock) noexcept {
  4811. #ifdef _WIN32
  4812. return shutdown(sock, SD_BOTH);
  4813. #else
  4814. return shutdown(sock, SHUT_RDWR);
  4815. #endif
  4816. }
  4817. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4818. if (s.size() > 1 && s[0] == '\0') {
  4819. auto ret = s;
  4820. ret[0] = '@';
  4821. return ret;
  4822. }
  4823. return s;
  4824. }
  4825. inline std::string
  4826. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4827. if (s.size() > 1 && s[0] == '@') {
  4828. auto ret = s;
  4829. ret[0] = '\0';
  4830. return ret;
  4831. }
  4832. return s;
  4833. }
  4834. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4835. const struct addrinfo *hints,
  4836. struct addrinfo **res, time_t timeout_sec) {
  4837. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4838. if (timeout_sec <= 0) {
  4839. // No timeout specified, use standard getaddrinfo
  4840. return getaddrinfo(node, service, hints, res);
  4841. }
  4842. #ifdef _WIN32
  4843. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4844. OVERLAPPED overlapped = {};
  4845. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4846. if (!event) { return EAI_FAIL; }
  4847. overlapped.hEvent = event;
  4848. PADDRINFOEXW result_addrinfo = nullptr;
  4849. HANDLE cancel_handle = nullptr;
  4850. ADDRINFOEXW hints_ex = {};
  4851. if (hints) {
  4852. hints_ex.ai_flags = hints->ai_flags;
  4853. hints_ex.ai_family = hints->ai_family;
  4854. hints_ex.ai_socktype = hints->ai_socktype;
  4855. hints_ex.ai_protocol = hints->ai_protocol;
  4856. }
  4857. auto wnode = u8string_to_wstring(node);
  4858. auto wservice = u8string_to_wstring(service);
  4859. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4860. hints ? &hints_ex : nullptr, &result_addrinfo,
  4861. nullptr, &overlapped, nullptr, &cancel_handle);
  4862. if (ret == WSA_IO_PENDING) {
  4863. auto wait_result =
  4864. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4865. if (wait_result == WAIT_TIMEOUT) {
  4866. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4867. ::CloseHandle(event);
  4868. return EAI_AGAIN;
  4869. }
  4870. DWORD bytes_returned;
  4871. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4872. &bytes_returned, FALSE)) {
  4873. ::CloseHandle(event);
  4874. return ::WSAGetLastError();
  4875. }
  4876. }
  4877. ::CloseHandle(event);
  4878. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4879. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4880. return 0;
  4881. }
  4882. return ret;
  4883. #elif TARGET_OS_MAC && defined(__clang__)
  4884. if (!node) { return EAI_NONAME; }
  4885. // macOS implementation using CFHost API for asynchronous DNS resolution
  4886. CFStringRef hostname_ref = CFStringCreateWithCString(
  4887. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4888. if (!hostname_ref) { return EAI_MEMORY; }
  4889. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4890. CFRelease(hostname_ref);
  4891. if (!host_ref) { return EAI_MEMORY; }
  4892. // Set up context for callback
  4893. struct CFHostContext {
  4894. bool completed = false;
  4895. bool success = false;
  4896. CFArrayRef addresses = nullptr;
  4897. std::mutex mutex;
  4898. std::condition_variable cv;
  4899. } context;
  4900. CFHostClientContext client_context;
  4901. memset(&client_context, 0, sizeof(client_context));
  4902. client_context.info = &context;
  4903. // Set callback
  4904. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4905. const CFStreamError *error, void *info) {
  4906. auto ctx = static_cast<CFHostContext *>(info);
  4907. std::lock_guard<std::mutex> lock(ctx->mutex);
  4908. if (error && error->error != 0) {
  4909. ctx->success = false;
  4910. } else {
  4911. Boolean hasBeenResolved;
  4912. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4913. if (ctx->addresses && hasBeenResolved) {
  4914. CFRetain(ctx->addresses);
  4915. ctx->success = true;
  4916. } else {
  4917. ctx->success = false;
  4918. }
  4919. }
  4920. ctx->completed = true;
  4921. ctx->cv.notify_one();
  4922. };
  4923. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4924. CFRelease(host_ref);
  4925. return EAI_SYSTEM;
  4926. }
  4927. // Schedule on run loop
  4928. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4929. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4930. // Start resolution
  4931. CFStreamError stream_error;
  4932. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4933. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4934. CFRelease(host_ref);
  4935. return EAI_FAIL;
  4936. }
  4937. // Wait for completion with timeout
  4938. auto timeout_time =
  4939. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4940. bool timed_out = false;
  4941. {
  4942. std::unique_lock<std::mutex> lock(context.mutex);
  4943. while (!context.completed) {
  4944. auto now = std::chrono::steady_clock::now();
  4945. if (now >= timeout_time) {
  4946. timed_out = true;
  4947. break;
  4948. }
  4949. // Run the runloop for a short time
  4950. lock.unlock();
  4951. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4952. lock.lock();
  4953. }
  4954. }
  4955. // Clean up
  4956. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4957. CFHostSetClient(host_ref, nullptr, nullptr);
  4958. if (timed_out || !context.completed) {
  4959. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4960. CFRelease(host_ref);
  4961. return EAI_AGAIN;
  4962. }
  4963. if (!context.success || !context.addresses) {
  4964. CFRelease(host_ref);
  4965. return EAI_NODATA;
  4966. }
  4967. // Convert CFArray to addrinfo
  4968. CFIndex count = CFArrayGetCount(context.addresses);
  4969. if (count == 0) {
  4970. CFRelease(context.addresses);
  4971. CFRelease(host_ref);
  4972. return EAI_NODATA;
  4973. }
  4974. struct addrinfo *result_addrinfo = nullptr;
  4975. struct addrinfo **current = &result_addrinfo;
  4976. for (CFIndex i = 0; i < count; i++) {
  4977. CFDataRef addr_data =
  4978. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4979. if (!addr_data) continue;
  4980. const struct sockaddr *sockaddr_ptr =
  4981. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4982. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4983. // Allocate addrinfo structure
  4984. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4985. if (!*current) {
  4986. freeaddrinfo(result_addrinfo);
  4987. CFRelease(context.addresses);
  4988. CFRelease(host_ref);
  4989. return EAI_MEMORY;
  4990. }
  4991. memset(*current, 0, sizeof(struct addrinfo));
  4992. // Set up addrinfo fields
  4993. (*current)->ai_family = sockaddr_ptr->sa_family;
  4994. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4995. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4996. (*current)->ai_addrlen = sockaddr_len;
  4997. // Copy sockaddr
  4998. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4999. if (!(*current)->ai_addr) {
  5000. freeaddrinfo(result_addrinfo);
  5001. CFRelease(context.addresses);
  5002. CFRelease(host_ref);
  5003. return EAI_MEMORY;
  5004. }
  5005. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  5006. // Set port if service is specified
  5007. if (service && *service) {
  5008. int port = 0;
  5009. if (parse_port(service, strlen(service), port)) {
  5010. if (sockaddr_ptr->sa_family == AF_INET) {
  5011. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5012. ->sin_port = htons(static_cast<uint16_t>(port));
  5013. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5014. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5015. ->sin6_port = htons(static_cast<uint16_t>(port));
  5016. }
  5017. }
  5018. }
  5019. current = &((*current)->ai_next);
  5020. }
  5021. CFRelease(context.addresses);
  5022. CFRelease(host_ref);
  5023. *res = result_addrinfo;
  5024. return 0;
  5025. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5026. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5027. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5028. // the resolver worker still references the stack-local gaicb. The cancel
  5029. // path therefore waits (gai_suspend with no timeout) for the worker to
  5030. // actually finish before letting the stack frame go. The trade-off is that
  5031. // a wedged DNS server can hold this thread for the system resolver timeout
  5032. // (~30s by default) past the caller's connection timeout.
  5033. struct gaicb request {};
  5034. struct gaicb *requests[1] = {&request};
  5035. struct sigevent sevp {};
  5036. struct timespec timeout {
  5037. timeout_sec, 0
  5038. };
  5039. request.ar_name = node;
  5040. request.ar_service = service;
  5041. request.ar_request = hints;
  5042. sevp.sigev_notify = SIGEV_NONE;
  5043. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5044. if (rc != 0) { return rc; }
  5045. auto cleanup = scope_exit([&] {
  5046. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5047. });
  5048. int wait_result = gai_suspend(requests, 1, &timeout);
  5049. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5050. int gai_result = gai_error(&request);
  5051. if (gai_result == 0) {
  5052. *res = request.ar_result;
  5053. request.ar_result = nullptr;
  5054. return 0;
  5055. }
  5056. return gai_result;
  5057. }
  5058. gai_cancel(&request);
  5059. while (gai_error(&request) == EAI_INPROGRESS) {
  5060. gai_suspend(requests, 1, nullptr);
  5061. }
  5062. return wait_result;
  5063. #else
  5064. // Fallback implementation using thread-based timeout for other Unix systems.
  5065. struct GetAddrInfoState {
  5066. ~GetAddrInfoState() {
  5067. if (info) { freeaddrinfo(info); }
  5068. }
  5069. std::mutex mutex;
  5070. std::condition_variable result_cv;
  5071. bool completed = false;
  5072. int result = EAI_SYSTEM;
  5073. std::string node;
  5074. std::string service;
  5075. struct addrinfo hints;
  5076. struct addrinfo *info = nullptr;
  5077. };
  5078. // Allocate on the heap, so the resolver thread can keep using the data.
  5079. auto state = std::make_shared<GetAddrInfoState>();
  5080. if (node) { state->node = node; }
  5081. state->service = service;
  5082. state->hints = *hints;
  5083. std::thread resolve_thread([state]() {
  5084. auto thread_result =
  5085. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5086. &state->info);
  5087. std::lock_guard<std::mutex> lock(state->mutex);
  5088. state->result = thread_result;
  5089. state->completed = true;
  5090. state->result_cv.notify_one();
  5091. });
  5092. // Wait for completion or timeout
  5093. std::unique_lock<std::mutex> lock(state->mutex);
  5094. auto finished =
  5095. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5096. [&] { return state->completed; });
  5097. if (finished) {
  5098. // Operation completed within timeout
  5099. resolve_thread.join();
  5100. *res = state->info;
  5101. state->info = nullptr; // Pass ownership to caller
  5102. return state->result;
  5103. } else {
  5104. // Timeout occurred
  5105. resolve_thread.detach(); // Let the thread finish in background
  5106. return EAI_AGAIN; // Return timeout error
  5107. }
  5108. #endif
  5109. #else
  5110. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5111. return getaddrinfo(node, service, hints, res);
  5112. #endif
  5113. }
  5114. template <typename BindOrConnect>
  5115. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5116. int address_family, int socket_flags, bool tcp_nodelay,
  5117. bool ipv6_v6only, SocketOptions socket_options,
  5118. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5119. // Get address info
  5120. const char *node = nullptr;
  5121. struct addrinfo hints;
  5122. struct addrinfo *result;
  5123. memset(&hints, 0, sizeof(struct addrinfo));
  5124. hints.ai_socktype = SOCK_STREAM;
  5125. hints.ai_protocol = IPPROTO_IP;
  5126. if (!ip.empty()) {
  5127. node = ip.c_str();
  5128. // Ask getaddrinfo to convert IP in c-string to address
  5129. hints.ai_family = AF_UNSPEC;
  5130. hints.ai_flags = AI_NUMERICHOST;
  5131. } else {
  5132. if (!host.empty()) { node = host.c_str(); }
  5133. hints.ai_family = address_family;
  5134. hints.ai_flags = socket_flags;
  5135. }
  5136. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5137. if (hints.ai_family == AF_UNIX) {
  5138. const auto addrlen = host.length();
  5139. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5140. #ifdef SOCK_CLOEXEC
  5141. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5142. hints.ai_protocol);
  5143. #else
  5144. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5145. #endif
  5146. if (sock != INVALID_SOCKET) {
  5147. sockaddr_un addr{};
  5148. addr.sun_family = AF_UNIX;
  5149. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5150. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5151. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5152. hints.ai_addrlen = static_cast<socklen_t>(
  5153. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5154. #ifndef SOCK_CLOEXEC
  5155. #ifndef _WIN32
  5156. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5157. #endif
  5158. #endif
  5159. if (socket_options) { socket_options(sock); }
  5160. #ifdef _WIN32
  5161. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5162. // remove the option.
  5163. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5164. #endif
  5165. bool dummy;
  5166. if (!bind_or_connect(sock, hints, dummy)) {
  5167. close_socket(sock);
  5168. sock = INVALID_SOCKET;
  5169. }
  5170. }
  5171. return sock;
  5172. }
  5173. #endif
  5174. auto service = std::to_string(port);
  5175. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5176. timeout_sec)) {
  5177. #if defined __linux__ && !defined __ANDROID__
  5178. res_init();
  5179. #endif
  5180. return INVALID_SOCKET;
  5181. }
  5182. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5183. for (auto rp = result; rp; rp = rp->ai_next) {
  5184. // Create a socket
  5185. #ifdef _WIN32
  5186. auto sock =
  5187. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5188. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5189. /**
  5190. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5191. * and above the socket creation fails on older Windows Systems.
  5192. *
  5193. * Let's try to create a socket the old way in this case.
  5194. *
  5195. * Reference:
  5196. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5197. *
  5198. * WSA_FLAG_NO_HANDLE_INHERIT:
  5199. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5200. * SP1, and later
  5201. *
  5202. */
  5203. if (sock == INVALID_SOCKET) {
  5204. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5205. }
  5206. #else
  5207. #ifdef SOCK_CLOEXEC
  5208. auto sock =
  5209. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5210. #else
  5211. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5212. #endif
  5213. #endif
  5214. if (sock == INVALID_SOCKET) { continue; }
  5215. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5216. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5217. close_socket(sock);
  5218. continue;
  5219. }
  5220. #endif
  5221. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5222. if (rp->ai_family == AF_INET6) {
  5223. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5224. }
  5225. if (socket_options) { socket_options(sock); }
  5226. // bind or connect
  5227. auto quit = false;
  5228. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5229. close_socket(sock);
  5230. if (quit) { break; }
  5231. }
  5232. return INVALID_SOCKET;
  5233. }
  5234. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5235. #ifdef _WIN32
  5236. auto flags = nonblocking ? 1UL : 0UL;
  5237. ioctlsocket(sock, FIONBIO, &flags);
  5238. #else
  5239. auto flags = fcntl(sock, F_GETFL, 0);
  5240. fcntl(sock, F_SETFL,
  5241. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5242. #endif
  5243. }
  5244. inline bool is_connection_error() {
  5245. #ifdef _WIN32
  5246. return WSAGetLastError() != WSAEWOULDBLOCK;
  5247. #else
  5248. return errno != EINPROGRESS;
  5249. #endif
  5250. }
  5251. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5252. struct addrinfo hints;
  5253. struct addrinfo *result;
  5254. memset(&hints, 0, sizeof(struct addrinfo));
  5255. hints.ai_family = AF_UNSPEC;
  5256. hints.ai_socktype = SOCK_STREAM;
  5257. hints.ai_protocol = 0;
  5258. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5259. return false;
  5260. }
  5261. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5262. auto ret = false;
  5263. for (auto rp = result; rp; rp = rp->ai_next) {
  5264. const auto &ai = *rp;
  5265. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5266. ret = true;
  5267. break;
  5268. }
  5269. }
  5270. return ret;
  5271. }
  5272. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5273. #define USE_IF2IP
  5274. #endif
  5275. #ifdef USE_IF2IP
  5276. inline std::string if2ip(int address_family, const std::string &ifn) {
  5277. struct ifaddrs *ifap;
  5278. getifaddrs(&ifap);
  5279. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5280. std::string addr_candidate;
  5281. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5282. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5283. (AF_UNSPEC == address_family ||
  5284. ifa->ifa_addr->sa_family == address_family)) {
  5285. if (ifa->ifa_addr->sa_family == AF_INET) {
  5286. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5287. char buf[INET_ADDRSTRLEN];
  5288. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5289. return std::string(buf, INET_ADDRSTRLEN);
  5290. }
  5291. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5292. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5293. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5294. char buf[INET6_ADDRSTRLEN] = {};
  5295. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5296. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5297. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5298. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5299. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5300. } else {
  5301. return std::string(buf, INET6_ADDRSTRLEN);
  5302. }
  5303. }
  5304. }
  5305. }
  5306. }
  5307. }
  5308. return addr_candidate;
  5309. }
  5310. #endif
  5311. inline socket_t create_client_socket(
  5312. const std::string &host, const std::string &ip, int port,
  5313. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5314. SocketOptions socket_options, time_t connection_timeout_sec,
  5315. time_t connection_timeout_usec, time_t read_timeout_sec,
  5316. time_t read_timeout_usec, time_t write_timeout_sec,
  5317. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5318. auto sock = create_socket(
  5319. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5320. std::move(socket_options),
  5321. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5322. if (!intf.empty()) {
  5323. #ifdef USE_IF2IP
  5324. auto ip_from_if = if2ip(address_family, intf);
  5325. if (ip_from_if.empty()) { ip_from_if = intf; }
  5326. if (!bind_ip_address(sock2, ip_from_if)) {
  5327. error = Error::BindIPAddress;
  5328. return false;
  5329. }
  5330. #endif
  5331. }
  5332. set_nonblocking(sock2, true);
  5333. auto ret =
  5334. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5335. if (ret < 0) {
  5336. if (is_connection_error()) {
  5337. error = Error::Connection;
  5338. return false;
  5339. }
  5340. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5341. connection_timeout_usec);
  5342. if (error != Error::Success) {
  5343. if (error == Error::ConnectionTimeout) { quit = true; }
  5344. return false;
  5345. }
  5346. }
  5347. set_nonblocking(sock2, false);
  5348. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5349. read_timeout_usec);
  5350. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5351. write_timeout_usec);
  5352. error = Error::Success;
  5353. return true;
  5354. },
  5355. connection_timeout_sec); // Pass DNS timeout
  5356. if (sock != INVALID_SOCKET) {
  5357. error = Error::Success;
  5358. } else {
  5359. if (error == Error::Success) { error = Error::Connection; }
  5360. }
  5361. return sock;
  5362. }
  5363. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5364. socklen_t addr_len, std::string &ip, int &port) {
  5365. if (addr.ss_family == AF_INET) {
  5366. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5367. } else if (addr.ss_family == AF_INET6) {
  5368. port =
  5369. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5370. } else {
  5371. return false;
  5372. }
  5373. std::array<char, NI_MAXHOST> ipstr{};
  5374. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5375. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5376. 0, NI_NUMERICHOST)) {
  5377. return false;
  5378. }
  5379. ip = ipstr.data();
  5380. return true;
  5381. }
  5382. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5383. struct sockaddr_storage addr;
  5384. socklen_t addr_len = sizeof(addr);
  5385. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5386. &addr_len)) {
  5387. get_ip_and_port(addr, addr_len, ip, port);
  5388. }
  5389. }
  5390. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5391. struct sockaddr_storage addr;
  5392. socklen_t addr_len = sizeof(addr);
  5393. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5394. &addr_len)) {
  5395. #ifndef _WIN32
  5396. if (addr.ss_family == AF_UNIX) {
  5397. #if defined(__linux__)
  5398. struct ucred ucred;
  5399. socklen_t len = sizeof(ucred);
  5400. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5401. port = ucred.pid;
  5402. }
  5403. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5404. pid_t pid;
  5405. socklen_t len = sizeof(pid);
  5406. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5407. port = pid;
  5408. }
  5409. #endif
  5410. return;
  5411. }
  5412. #endif
  5413. get_ip_and_port(addr, addr_len, ip, port);
  5414. }
  5415. }
  5416. // Recursive form retained so operator""_t below can compute hashes for
  5417. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5418. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5419. // instead, which is iterative and stack-safe.
  5420. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5421. unsigned int h) {
  5422. return (l == 0)
  5423. ? h
  5424. : str2tag_core(
  5425. s + 1, l - 1,
  5426. // Unsets the 6 high bits of h, therefore no overflow happens
  5427. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5428. h * 33) ^
  5429. static_cast<unsigned char>(*s));
  5430. }
  5431. inline unsigned int str2tag(const std::string &s) {
  5432. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5433. // for compile-time UDL evaluation of short string literals, but at runtime
  5434. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5435. // would blow the stack with one frame per character.
  5436. unsigned int h = 0;
  5437. for (auto c : s) {
  5438. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5439. static_cast<unsigned char>(c);
  5440. }
  5441. return h;
  5442. }
  5443. namespace udl {
  5444. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5445. return str2tag_core(s, l, 0);
  5446. }
  5447. } // namespace udl
  5448. inline std::string
  5449. find_content_type(const std::string &path,
  5450. const std::map<std::string, std::string> &user_data,
  5451. const std::string &default_content_type) {
  5452. auto ext = file_extension(path);
  5453. auto it = user_data.find(ext);
  5454. if (it != user_data.end()) { return it->second; }
  5455. using udl::operator""_t;
  5456. switch (str2tag(ext)) {
  5457. default: return default_content_type;
  5458. case "css"_t: return "text/css";
  5459. case "csv"_t: return "text/csv";
  5460. case "htm"_t:
  5461. case "html"_t: return "text/html";
  5462. case "js"_t:
  5463. case "mjs"_t: return "text/javascript";
  5464. case "txt"_t: return "text/plain";
  5465. case "vtt"_t: return "text/vtt";
  5466. case "apng"_t: return "image/apng";
  5467. case "avif"_t: return "image/avif";
  5468. case "bmp"_t: return "image/bmp";
  5469. case "gif"_t: return "image/gif";
  5470. case "png"_t: return "image/png";
  5471. case "svg"_t: return "image/svg+xml";
  5472. case "webp"_t: return "image/webp";
  5473. case "ico"_t: return "image/x-icon";
  5474. case "tif"_t: return "image/tiff";
  5475. case "tiff"_t: return "image/tiff";
  5476. case "jpg"_t:
  5477. case "jpeg"_t: return "image/jpeg";
  5478. case "mp4"_t: return "video/mp4";
  5479. case "mpeg"_t: return "video/mpeg";
  5480. case "webm"_t: return "video/webm";
  5481. case "mp3"_t: return "audio/mp3";
  5482. case "mpga"_t: return "audio/mpeg";
  5483. case "weba"_t: return "audio/webm";
  5484. case "wav"_t: return "audio/wave";
  5485. case "otf"_t: return "font/otf";
  5486. case "ttf"_t: return "font/ttf";
  5487. case "woff"_t: return "font/woff";
  5488. case "woff2"_t: return "font/woff2";
  5489. case "7z"_t: return "application/x-7z-compressed";
  5490. case "atom"_t: return "application/atom+xml";
  5491. case "pdf"_t: return "application/pdf";
  5492. case "json"_t: return "application/json";
  5493. case "rss"_t: return "application/rss+xml";
  5494. case "tar"_t: return "application/x-tar";
  5495. case "xht"_t:
  5496. case "xhtml"_t: return "application/xhtml+xml";
  5497. case "xslt"_t: return "application/xslt+xml";
  5498. case "xml"_t: return "application/xml";
  5499. case "gz"_t: return "application/gzip";
  5500. case "zip"_t: return "application/zip";
  5501. case "wasm"_t: return "application/wasm";
  5502. }
  5503. }
  5504. inline std::string
  5505. extract_media_type(const std::string &content_type,
  5506. std::map<std::string, std::string> *params = nullptr) {
  5507. // Extract type/subtype from Content-Type value (RFC 2045)
  5508. // e.g. "application/json; charset=utf-8" -> "application/json"
  5509. auto media_type = content_type;
  5510. auto semicolon_pos = media_type.find(';');
  5511. if (semicolon_pos != std::string::npos) {
  5512. auto param_str = media_type.substr(semicolon_pos + 1);
  5513. media_type = media_type.substr(0, semicolon_pos);
  5514. if (params) {
  5515. // Parse parameters: key=value pairs separated by ';'
  5516. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5517. [&](const char *b, const char *e) {
  5518. std::string key;
  5519. std::string val;
  5520. split(b, e, '=', [&](const char *b2, const char *e2) {
  5521. if (key.empty()) {
  5522. key.assign(b2, e2);
  5523. } else {
  5524. val.assign(b2, e2);
  5525. }
  5526. });
  5527. if (!key.empty()) {
  5528. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5529. }
  5530. });
  5531. }
  5532. }
  5533. // Trim whitespace from media type
  5534. return trim_copy(media_type);
  5535. }
  5536. inline bool can_compress_content_type(const std::string &content_type) {
  5537. using udl::operator""_t;
  5538. auto mime_type = extract_media_type(content_type);
  5539. auto tag = str2tag(mime_type);
  5540. switch (tag) {
  5541. case "image/svg+xml"_t:
  5542. case "application/javascript"_t:
  5543. case "application/x-javascript"_t:
  5544. case "application/json"_t:
  5545. case "application/ld+json"_t:
  5546. case "application/xml"_t:
  5547. case "application/xhtml+xml"_t:
  5548. case "application/rss+xml"_t:
  5549. case "application/atom+xml"_t:
  5550. case "application/xslt+xml"_t:
  5551. case "application/protobuf"_t: return true;
  5552. case "text/event-stream"_t: return false;
  5553. default: return !mime_type.rfind("text/", 0);
  5554. }
  5555. }
  5556. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5557. double &quality) {
  5558. quality = 1.0;
  5559. token.clear();
  5560. // Split on first ';': left = token name, right = parameters
  5561. const char *params_b = nullptr;
  5562. std::size_t params_len = 0;
  5563. divide(
  5564. b, static_cast<std::size_t>(e - b), ';',
  5565. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5566. auto r = trim(lb, lb + llen, 0, llen);
  5567. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5568. params_b = rb;
  5569. params_len = rlen;
  5570. });
  5571. if (token.empty()) { return false; }
  5572. if (params_len == 0) { return true; }
  5573. // Scan parameters for q= (stops on first match)
  5574. bool invalid = false;
  5575. split_find(params_b, params_b + params_len, ';',
  5576. (std::numeric_limits<size_t>::max)(),
  5577. [&](const char *pb, const char *pe) -> bool {
  5578. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5579. auto len = static_cast<size_t>(pe - pb);
  5580. if (len < 2) { return false; }
  5581. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5582. return false;
  5583. }
  5584. // Trim the value portion
  5585. auto r = trim(pb, pe, 2, len);
  5586. if (r.first >= r.second) {
  5587. invalid = true;
  5588. return true;
  5589. }
  5590. double v = 0.0;
  5591. auto res = from_chars(pb + r.first, pb + r.second, v);
  5592. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5593. invalid = true;
  5594. return true;
  5595. }
  5596. quality = v;
  5597. return true;
  5598. });
  5599. return !invalid;
  5600. }
  5601. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5602. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5603. return EncodingType::None;
  5604. }
  5605. const auto &s = req.get_header_value("Accept-Encoding");
  5606. if (s.empty()) { return EncodingType::None; }
  5607. // Single-pass: iterate tokens and track the best supported encoding.
  5608. // Server preference breaks ties (br > gzip > zstd).
  5609. EncodingType best = EncodingType::None;
  5610. double best_q = 0.0; // q=0 means "not acceptable"
  5611. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5612. auto priority = [](EncodingType t) -> int {
  5613. switch (t) {
  5614. case EncodingType::Brotli: return 0;
  5615. case EncodingType::Gzip: return 1;
  5616. case EncodingType::Zstd: return 2;
  5617. default: return 3;
  5618. }
  5619. };
  5620. std::string name;
  5621. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5622. double quality = 1.0;
  5623. if (!parse_quality(b, e, name, quality)) { return; }
  5624. if (quality <= 0.0) { return; }
  5625. EncodingType type = EncodingType::None;
  5626. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5627. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5628. #endif
  5629. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5630. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5631. type = EncodingType::Gzip;
  5632. }
  5633. #endif
  5634. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5635. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5636. type = EncodingType::Zstd;
  5637. }
  5638. #endif
  5639. if (type == EncodingType::None) { return; }
  5640. // Higher q-value wins; for equal q, server preference breaks ties
  5641. if (quality > best_q ||
  5642. (quality == best_q && priority(type) < priority(best))) {
  5643. best_q = quality;
  5644. best = type;
  5645. }
  5646. });
  5647. return best;
  5648. }
  5649. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5650. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5651. if (type == EncodingType::Gzip) {
  5652. return detail::make_unique<gzip_compressor>();
  5653. }
  5654. #endif
  5655. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5656. if (type == EncodingType::Brotli) {
  5657. return detail::make_unique<brotli_compressor>();
  5658. }
  5659. #endif
  5660. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5661. if (type == EncodingType::Zstd) {
  5662. return detail::make_unique<zstd_compressor>();
  5663. }
  5664. #endif
  5665. (void)type;
  5666. return nullptr;
  5667. }
  5668. inline const char *encoding_name(EncodingType type) {
  5669. switch (type) {
  5670. case EncodingType::Gzip: return "gzip";
  5671. case EncodingType::Brotli: return "br";
  5672. case EncodingType::Zstd: return "zstd";
  5673. default: return "";
  5674. }
  5675. }
  5676. inline bool nocompressor::compress(const char *data, size_t data_length,
  5677. bool /*last*/, Callback callback) {
  5678. if (!data_length) { return true; }
  5679. return callback(data, data_length);
  5680. }
  5681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5682. inline gzip_compressor::gzip_compressor() {
  5683. std::memset(&strm_, 0, sizeof(strm_));
  5684. strm_.zalloc = Z_NULL;
  5685. strm_.zfree = Z_NULL;
  5686. strm_.opaque = Z_NULL;
  5687. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5688. Z_DEFAULT_STRATEGY) == Z_OK;
  5689. }
  5690. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5691. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5692. bool last, Callback callback) {
  5693. assert(is_valid_);
  5694. do {
  5695. constexpr size_t max_avail_in =
  5696. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5697. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5698. (std::min)(data_length, max_avail_in));
  5699. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5700. data_length -= strm_.avail_in;
  5701. data += strm_.avail_in;
  5702. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5703. auto ret = Z_OK;
  5704. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5705. do {
  5706. strm_.avail_out = static_cast<uInt>(buff.size());
  5707. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5708. ret = deflate(&strm_, flush);
  5709. if (ret == Z_STREAM_ERROR) { return false; }
  5710. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5711. return false;
  5712. }
  5713. } while (strm_.avail_out == 0);
  5714. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5715. (flush == Z_NO_FLUSH && ret == Z_OK));
  5716. assert(strm_.avail_in == 0);
  5717. } while (data_length > 0);
  5718. return true;
  5719. }
  5720. inline gzip_decompressor::gzip_decompressor() {
  5721. std::memset(&strm_, 0, sizeof(strm_));
  5722. strm_.zalloc = Z_NULL;
  5723. strm_.zfree = Z_NULL;
  5724. strm_.opaque = Z_NULL;
  5725. // 15 is the value of wbits, which should be at the maximum possible value
  5726. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5727. // that the stream type should be automatically detected either gzip or
  5728. // deflate.
  5729. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5730. }
  5731. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5732. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5733. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5734. Callback callback) {
  5735. assert(is_valid_);
  5736. auto ret = Z_OK;
  5737. do {
  5738. constexpr size_t max_avail_in =
  5739. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5740. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5741. (std::min)(data_length, max_avail_in));
  5742. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5743. data_length -= strm_.avail_in;
  5744. data += strm_.avail_in;
  5745. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5746. while (strm_.avail_in > 0 && ret == Z_OK) {
  5747. strm_.avail_out = static_cast<uInt>(buff.size());
  5748. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5749. ret = inflate(&strm_, Z_NO_FLUSH);
  5750. assert(ret != Z_STREAM_ERROR);
  5751. switch (ret) {
  5752. case Z_NEED_DICT:
  5753. case Z_DATA_ERROR:
  5754. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5755. }
  5756. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5757. return false;
  5758. }
  5759. }
  5760. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5761. } while (data_length > 0);
  5762. return true;
  5763. }
  5764. #endif
  5765. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5766. inline brotli_compressor::brotli_compressor() {
  5767. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5768. }
  5769. inline brotli_compressor::~brotli_compressor() {
  5770. BrotliEncoderDestroyInstance(state_);
  5771. }
  5772. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5773. bool last, Callback callback) {
  5774. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5775. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5776. auto available_in = data_length;
  5777. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5778. for (;;) {
  5779. if (last) {
  5780. if (BrotliEncoderIsFinished(state_)) { break; }
  5781. } else {
  5782. if (!available_in) { break; }
  5783. }
  5784. auto available_out = buff.size();
  5785. auto next_out = buff.data();
  5786. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5787. &available_out, &next_out, nullptr)) {
  5788. return false;
  5789. }
  5790. auto output_bytes = buff.size() - available_out;
  5791. if (output_bytes) {
  5792. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5793. }
  5794. }
  5795. return true;
  5796. }
  5797. inline brotli_decompressor::brotli_decompressor() {
  5798. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5799. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5800. : BROTLI_DECODER_RESULT_ERROR;
  5801. }
  5802. inline brotli_decompressor::~brotli_decompressor() {
  5803. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5804. }
  5805. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5806. inline bool brotli_decompressor::decompress(const char *data,
  5807. size_t data_length,
  5808. Callback callback) {
  5809. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5810. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5811. return 0;
  5812. }
  5813. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5814. size_t avail_in = data_length;
  5815. size_t total_out;
  5816. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5817. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5818. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5819. char *next_out = buff.data();
  5820. size_t avail_out = buff.size();
  5821. decoder_r = BrotliDecoderDecompressStream(
  5822. decoder_s, &avail_in, &next_in, &avail_out,
  5823. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5824. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5825. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5826. }
  5827. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5828. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5829. }
  5830. #endif
  5831. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5832. inline zstd_compressor::zstd_compressor() {
  5833. ctx_ = ZSTD_createCCtx();
  5834. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5835. }
  5836. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5837. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5838. bool last, Callback callback) {
  5839. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5840. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5841. ZSTD_inBuffer input = {data, data_length, 0};
  5842. bool finished;
  5843. do {
  5844. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5845. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5846. if (ZSTD_isError(remaining)) { return false; }
  5847. if (!callback(buff.data(), output.pos)) { return false; }
  5848. finished = last ? (remaining == 0) : (input.pos == input.size);
  5849. } while (!finished);
  5850. return true;
  5851. }
  5852. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5853. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5854. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5855. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5856. Callback callback) {
  5857. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5858. ZSTD_inBuffer input = {data, data_length, 0};
  5859. while (input.pos < input.size) {
  5860. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5861. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5862. if (ZSTD_isError(remaining)) { return false; }
  5863. if (!callback(buff.data(), output.pos)) { return false; }
  5864. }
  5865. return true;
  5866. }
  5867. #endif
  5868. inline std::unique_ptr<decompressor>
  5869. create_decompressor(const std::string &encoding) {
  5870. std::unique_ptr<decompressor> decompressor;
  5871. if (encoding == "gzip" || encoding == "deflate") {
  5872. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5873. decompressor = detail::make_unique<gzip_decompressor>();
  5874. #endif
  5875. } else if (encoding.find("br") != std::string::npos) {
  5876. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5877. decompressor = detail::make_unique<brotli_decompressor>();
  5878. #endif
  5879. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5880. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5881. decompressor = detail::make_unique<zstd_decompressor>();
  5882. #endif
  5883. }
  5884. return decompressor;
  5885. }
  5886. // Returns the best available compressor and its Content-Encoding name.
  5887. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5888. inline std::pair<std::unique_ptr<compressor>, const char *>
  5889. create_compressor() {
  5890. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5891. return {detail::make_unique<brotli_compressor>(), "br"};
  5892. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5893. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5894. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5895. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5896. #else
  5897. return {nullptr, nullptr};
  5898. #endif
  5899. }
  5900. inline bool is_prohibited_header_name(const std::string &name) {
  5901. using udl::operator""_t;
  5902. switch (str2tag(name)) {
  5903. case "REMOTE_ADDR"_t:
  5904. case "REMOTE_PORT"_t:
  5905. case "LOCAL_ADDR"_t:
  5906. case "LOCAL_PORT"_t: return true;
  5907. default: return false;
  5908. }
  5909. }
  5910. inline bool has_header(const Headers &headers, const std::string &key) {
  5911. if (is_prohibited_header_name(key)) { return false; }
  5912. return headers.find(key) != headers.end();
  5913. }
  5914. inline const char *get_header_value(const Headers &headers,
  5915. const std::string &key, const char *def,
  5916. size_t id) {
  5917. if (is_prohibited_header_name(key)) {
  5918. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5919. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5920. throw std::invalid_argument(msg);
  5921. #else
  5922. return "";
  5923. #endif
  5924. }
  5925. auto rng = headers.equal_range(key);
  5926. auto it = rng.first;
  5927. std::advance(it, static_cast<ssize_t>(id));
  5928. if (it != rng.second) { return it->second.c_str(); }
  5929. return def;
  5930. }
  5931. inline size_t get_header_value_count(const Headers &headers,
  5932. const std::string &key) {
  5933. auto r = headers.equal_range(key);
  5934. return static_cast<size_t>(std::distance(r.first, r.second));
  5935. }
  5936. template <typename Map>
  5937. inline typename Map::mapped_type
  5938. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5939. auto rng = m.equal_range(key);
  5940. auto it = rng.first;
  5941. std::advance(it, static_cast<ssize_t>(id));
  5942. if (it != rng.second) { return it->second; }
  5943. return typename Map::mapped_type();
  5944. }
  5945. inline void set_header(Headers &headers, const std::string &key,
  5946. const std::string &val) {
  5947. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5948. headers.emplace(key, val);
  5949. }
  5950. }
  5951. inline bool read_headers(Stream &strm, Headers &headers) {
  5952. const auto bufsiz = 2048;
  5953. char buf[bufsiz];
  5954. stream_line_reader line_reader(strm, buf, bufsiz);
  5955. size_t header_count = 0;
  5956. for (;;) {
  5957. if (!line_reader.getline()) { return false; }
  5958. // Check if the line ends with CRLF.
  5959. auto line_terminator_len = 2;
  5960. if (line_reader.end_with_crlf()) {
  5961. // Blank line indicates end of headers.
  5962. if (line_reader.size() == 2) { break; }
  5963. } else {
  5964. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5965. // Blank line indicates end of headers.
  5966. if (line_reader.size() == 1) { break; }
  5967. line_terminator_len = 1;
  5968. #else
  5969. continue; // Skip invalid line.
  5970. #endif
  5971. }
  5972. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5973. // Check header count limit
  5974. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5975. // Exclude line terminator
  5976. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5977. if (!parse_header(line_reader.ptr(), end,
  5978. [&](const std::string &key, const std::string &val) {
  5979. headers.emplace(key, val);
  5980. })) {
  5981. return false;
  5982. }
  5983. header_count++;
  5984. }
  5985. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5986. // headers that have different values to prevent request smuggling.
  5987. auto cl_range = headers.equal_range("Content-Length");
  5988. if (cl_range.first != cl_range.second) {
  5989. const auto &first_val = cl_range.first->second;
  5990. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5991. if (it->second != first_val) { return false; }
  5992. }
  5993. }
  5994. return true;
  5995. }
  5996. inline bool read_websocket_upgrade_response(Stream &strm,
  5997. const std::string &expected_accept,
  5998. std::string &selected_subprotocol) {
  5999. // Read status line
  6000. const auto bufsiz = 2048;
  6001. char buf[bufsiz];
  6002. stream_line_reader line_reader(strm, buf, bufsiz);
  6003. if (!line_reader.getline()) { return false; }
  6004. // Check for "HTTP/1.1 101"
  6005. auto line = std::string(line_reader.ptr(), line_reader.size());
  6006. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  6007. // Parse headers using existing read_headers
  6008. Headers headers;
  6009. if (!read_headers(strm, headers)) { return false; }
  6010. // Verify Upgrade: websocket (case-insensitive)
  6011. auto upgrade_it = headers.find("Upgrade");
  6012. if (upgrade_it == headers.end()) { return false; }
  6013. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  6014. if (upgrade_val != "websocket") { return false; }
  6015. // Verify Connection header contains "Upgrade" (case-insensitive)
  6016. auto connection_it = headers.find("Connection");
  6017. if (connection_it == headers.end()) { return false; }
  6018. auto connection_val = case_ignore::to_lower(connection_it->second);
  6019. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  6020. // Verify Sec-WebSocket-Accept header value
  6021. auto it = headers.find("Sec-WebSocket-Accept");
  6022. if (it == headers.end() || it->second != expected_accept) { return false; }
  6023. // Extract negotiated subprotocol
  6024. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6025. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6026. return true;
  6027. }
  6028. enum class ReadContentResult {
  6029. Success, // Successfully read the content
  6030. PayloadTooLarge, // The content exceeds the specified payload limit
  6031. Error // An error occurred while reading the content
  6032. };
  6033. inline ReadContentResult read_content_with_length(
  6034. Stream &strm, size_t len, DownloadProgress progress,
  6035. ContentReceiverWithProgress out,
  6036. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6037. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6038. detail::BodyReader br;
  6039. br.stream = &strm;
  6040. br.has_content_length = true;
  6041. br.content_length = len;
  6042. br.payload_max_length = payload_max_length;
  6043. br.chunked = false;
  6044. br.bytes_read = 0;
  6045. br.last_error = Error::Success;
  6046. size_t r = 0;
  6047. while (r < len) {
  6048. auto read_len = static_cast<size_t>(len - r);
  6049. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6050. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6051. if (n <= 0) {
  6052. // Check if it was a payload size error
  6053. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6054. return ReadContentResult::PayloadTooLarge;
  6055. }
  6056. return ReadContentResult::Error;
  6057. }
  6058. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6059. return ReadContentResult::Error;
  6060. }
  6061. r += static_cast<size_t>(n);
  6062. if (progress) {
  6063. if (!progress(r, len)) { return ReadContentResult::Error; }
  6064. }
  6065. }
  6066. return ReadContentResult::Success;
  6067. }
  6068. inline ReadContentResult
  6069. read_content_without_length(Stream &strm, size_t payload_max_length,
  6070. ContentReceiverWithProgress out) {
  6071. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6072. size_t r = 0;
  6073. for (;;) {
  6074. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6075. if (n == 0) { return ReadContentResult::Success; }
  6076. if (n < 0) { return ReadContentResult::Error; }
  6077. // Check if adding this data would exceed the payload limit
  6078. if (r > payload_max_length ||
  6079. payload_max_length - r < static_cast<size_t>(n)) {
  6080. return ReadContentResult::PayloadTooLarge;
  6081. }
  6082. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6083. return ReadContentResult::Error;
  6084. }
  6085. r += static_cast<size_t>(n);
  6086. }
  6087. return ReadContentResult::Success;
  6088. }
  6089. template <typename T>
  6090. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6091. size_t payload_max_length,
  6092. ContentReceiverWithProgress out) {
  6093. detail::ChunkedDecoder dec(strm);
  6094. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6095. size_t total_len = 0;
  6096. for (;;) {
  6097. size_t chunk_offset = 0;
  6098. size_t chunk_total = 0;
  6099. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6100. if (n < 0) { return ReadContentResult::Error; }
  6101. if (n == 0) {
  6102. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6103. return ReadContentResult::Error;
  6104. }
  6105. return ReadContentResult::Success;
  6106. }
  6107. if (total_len > payload_max_length ||
  6108. payload_max_length - total_len < static_cast<size_t>(n)) {
  6109. return ReadContentResult::PayloadTooLarge;
  6110. }
  6111. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6112. return ReadContentResult::Error;
  6113. }
  6114. total_len += static_cast<size_t>(n);
  6115. }
  6116. }
  6117. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6118. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  6119. // is the final transfer coding. A single field value may list several
  6120. // codings ("gzip, chunked"), and the list may be split across multiple
  6121. // Transfer-Encoding header lines (RFC 9110 5.3). Match the last coding token
  6122. // case-insensitively rather than comparing the whole value against "chunked".
  6123. //
  6124. // Security: reading a chunked message as unframed leaves its body in the
  6125. // socket, where a keep-alive connection parses it as a smuggled request.
  6126. // Headers is an unordered_multimap whose iteration order for duplicate keys
  6127. // is not portable, so when there is more than one Transfer-Encoding line we
  6128. // cannot tell which coding is truly final. In that ambiguous case we fail
  6129. // safe by treating the message as chunked (a mis-parse just closes the
  6130. // connection, whereas the opposite error enables smuggling).
  6131. auto rng = headers.equal_range("Transfer-Encoding");
  6132. size_t line_count = 0;
  6133. bool chunked_present = false;
  6134. bool last_line_ends_with_chunked = false;
  6135. for (auto it = rng.first; it != rng.second; ++it) {
  6136. line_count++;
  6137. const auto &value = it->second;
  6138. std::string last_coding;
  6139. bool line_has_chunked = false;
  6140. split(value.data(), value.data() + value.size(), ',',
  6141. [&](const char *b, const char *e) {
  6142. last_coding.assign(b, e);
  6143. if (case_ignore::equal(last_coding, "chunked")) {
  6144. line_has_chunked = true;
  6145. }
  6146. });
  6147. if (line_has_chunked) { chunked_present = true; }
  6148. last_line_ends_with_chunked = case_ignore::equal(last_coding, "chunked");
  6149. }
  6150. if (line_count == 0) { return false; }
  6151. if (line_count == 1) { return last_line_ends_with_chunked; }
  6152. return chunked_present;
  6153. }
  6154. template <typename T, typename U>
  6155. bool prepare_content_receiver(T &x, int &status,
  6156. ContentReceiverWithProgress receiver,
  6157. bool decompress, size_t payload_max_length,
  6158. bool &exceed_payload_max_length, U callback) {
  6159. if (decompress) {
  6160. std::string encoding = x.get_header_value("Content-Encoding");
  6161. std::unique_ptr<decompressor> decompressor;
  6162. if (!encoding.empty()) {
  6163. decompressor = detail::create_decompressor(encoding);
  6164. if (!decompressor) {
  6165. // Unsupported encoding or no support compiled in
  6166. status = StatusCode::UnsupportedMediaType_415;
  6167. return false;
  6168. }
  6169. }
  6170. if (decompressor) {
  6171. if (decompressor->is_valid()) {
  6172. size_t decompressed_size = 0;
  6173. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6174. size_t off, size_t len) {
  6175. return decompressor->decompress(
  6176. buf, n, [&](const char *buf2, size_t n2) {
  6177. // Guard against zip-bomb: check
  6178. // decompressed size against limit.
  6179. if (payload_max_length > 0 &&
  6180. (decompressed_size >= payload_max_length ||
  6181. n2 > payload_max_length - decompressed_size)) {
  6182. exceed_payload_max_length = true;
  6183. return false;
  6184. }
  6185. decompressed_size += n2;
  6186. return receiver(buf2, n2, off, len);
  6187. });
  6188. };
  6189. return callback(std::move(out));
  6190. } else {
  6191. status = StatusCode::InternalServerError_500;
  6192. return false;
  6193. }
  6194. }
  6195. }
  6196. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6197. size_t len) {
  6198. return receiver(buf, n, off, len);
  6199. };
  6200. return callback(std::move(out));
  6201. }
  6202. template <typename T>
  6203. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6204. DownloadProgress progress,
  6205. ContentReceiverWithProgress receiver, bool decompress) {
  6206. bool exceed_payload_max_length = false;
  6207. return prepare_content_receiver(
  6208. x, status, std::move(receiver), decompress, payload_max_length,
  6209. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6210. auto ret = true;
  6211. // Note: exceed_payload_max_length may also be set by the decompressor
  6212. // wrapper in prepare_content_receiver when the decompressed payload
  6213. // size exceeds the limit.
  6214. if (is_chunked_transfer_encoding(x.headers)) {
  6215. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6216. if (result == ReadContentResult::Success) {
  6217. ret = true;
  6218. } else if (result == ReadContentResult::PayloadTooLarge) {
  6219. exceed_payload_max_length = true;
  6220. ret = false;
  6221. } else {
  6222. ret = false;
  6223. }
  6224. } else if (!has_header(x.headers, "Content-Length")) {
  6225. auto result =
  6226. read_content_without_length(strm, payload_max_length, out);
  6227. if (result == ReadContentResult::Success) {
  6228. ret = true;
  6229. } else if (result == ReadContentResult::PayloadTooLarge) {
  6230. exceed_payload_max_length = true;
  6231. ret = false;
  6232. } else {
  6233. ret = false;
  6234. }
  6235. } else {
  6236. auto is_invalid_value = false;
  6237. auto len = get_header_value_u64(x.headers, "Content-Length",
  6238. (std::numeric_limits<size_t>::max)(),
  6239. 0, is_invalid_value);
  6240. if (is_invalid_value) {
  6241. ret = false;
  6242. } else if (len > 0) {
  6243. auto result = read_content_with_length(
  6244. strm, len, std::move(progress), out, payload_max_length);
  6245. ret = (result == ReadContentResult::Success);
  6246. if (result == ReadContentResult::PayloadTooLarge) {
  6247. exceed_payload_max_length = true;
  6248. }
  6249. }
  6250. }
  6251. if (!ret) {
  6252. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6253. : StatusCode::BadRequest_400;
  6254. }
  6255. return ret;
  6256. });
  6257. }
  6258. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6259. const std::string &path) {
  6260. // A request target must not carry CR/LF (or other control octets); otherwise
  6261. // a value smuggled into it splits the request line and injects headers or a
  6262. // whole request. The same field-value check already guards header values in
  6263. // check_and_write_headers and the request target in
  6264. // perform_websocket_handshake; apply it here too.
  6265. if (!fields::is_field_value(path)) { return -1; }
  6266. std::string s = method;
  6267. s += ' ';
  6268. s += path;
  6269. s += " HTTP/1.1\r\n";
  6270. return strm.write(s.data(), s.size());
  6271. }
  6272. inline ssize_t write_response_line(Stream &strm, int status) {
  6273. std::string s = "HTTP/1.1 ";
  6274. s += std::to_string(status);
  6275. s += ' ';
  6276. s += httplib::status_message(status);
  6277. s += "\r\n";
  6278. return strm.write(s.data(), s.size());
  6279. }
  6280. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6281. ssize_t write_len = 0;
  6282. for (const auto &x : headers) {
  6283. std::string s;
  6284. s = x.first;
  6285. s += ": ";
  6286. s += x.second;
  6287. s += "\r\n";
  6288. auto len = strm.write(s.data(), s.size());
  6289. if (len < 0) { return len; }
  6290. write_len += len;
  6291. }
  6292. auto len = strm.write("\r\n");
  6293. if (len < 0) { return len; }
  6294. write_len += len;
  6295. return write_len;
  6296. }
  6297. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6298. size_t offset = 0;
  6299. while (offset < l) {
  6300. auto length = strm.write(d + offset, l - offset);
  6301. if (length < 0) { return false; }
  6302. offset += static_cast<size_t>(length);
  6303. }
  6304. return true;
  6305. }
  6306. template <typename T>
  6307. inline bool write_content_with_progress(Stream &strm,
  6308. const ContentProvider &content_provider,
  6309. size_t offset, size_t length,
  6310. T is_shutting_down,
  6311. const UploadProgress &upload_progress,
  6312. Error &error) {
  6313. size_t end_offset = offset + length;
  6314. size_t start_offset = offset;
  6315. auto ok = true;
  6316. DataSink data_sink;
  6317. data_sink.write = [&](const char *d, size_t l) -> bool {
  6318. if (ok) {
  6319. if (write_data(strm, d, l)) {
  6320. offset += l;
  6321. if (upload_progress && length > 0) {
  6322. size_t current_written = offset - start_offset;
  6323. if (!upload_progress(current_written, length)) {
  6324. ok = false;
  6325. return false;
  6326. }
  6327. }
  6328. } else {
  6329. ok = false;
  6330. }
  6331. }
  6332. return ok;
  6333. };
  6334. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6335. while (offset < end_offset && !is_shutting_down()) {
  6336. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6337. error = Error::Write;
  6338. return false;
  6339. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6340. error = Error::Canceled;
  6341. return false;
  6342. } else if (!ok) {
  6343. error = Error::Write;
  6344. return false;
  6345. }
  6346. }
  6347. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6348. error = Error::Write;
  6349. return false;
  6350. }
  6351. error = Error::Success;
  6352. return true;
  6353. }
  6354. template <typename T>
  6355. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6356. size_t offset, size_t length, T is_shutting_down,
  6357. Error &error) {
  6358. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6359. is_shutting_down, nullptr, error);
  6360. }
  6361. template <typename T>
  6362. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6363. size_t offset, size_t length,
  6364. const T &is_shutting_down) {
  6365. auto error = Error::Success;
  6366. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6367. error);
  6368. }
  6369. template <typename T>
  6370. inline bool
  6371. write_content_without_length(Stream &strm,
  6372. const ContentProvider &content_provider,
  6373. const T &is_shutting_down) {
  6374. size_t offset = 0;
  6375. auto data_available = true;
  6376. auto ok = true;
  6377. DataSink data_sink;
  6378. data_sink.write = [&](const char *d, size_t l) -> bool {
  6379. if (ok) {
  6380. offset += l;
  6381. if (!write_data(strm, d, l)) { ok = false; }
  6382. }
  6383. return ok;
  6384. };
  6385. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6386. data_sink.done = [&](void) { data_available = false; };
  6387. while (data_available && !is_shutting_down()) {
  6388. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6389. return false;
  6390. } else if (!content_provider(offset, 0, data_sink)) {
  6391. return false;
  6392. } else if (!ok) {
  6393. return false;
  6394. }
  6395. }
  6396. return !data_available; // true only if done() was called, false if shutting
  6397. // down
  6398. }
  6399. template <typename T, typename U>
  6400. inline bool
  6401. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6402. const T &is_shutting_down, U &compressor, Error &error) {
  6403. size_t offset = 0;
  6404. auto data_available = true;
  6405. auto ok = true;
  6406. DataSink data_sink;
  6407. data_sink.write = [&](const char *d, size_t l) -> bool {
  6408. if (ok) {
  6409. data_available = l > 0;
  6410. offset += l;
  6411. std::string payload;
  6412. if (compressor.compress(d, l, false,
  6413. [&](const char *data, size_t data_len) {
  6414. payload.append(data, data_len);
  6415. return true;
  6416. })) {
  6417. if (!payload.empty()) {
  6418. // Emit chunked response header and footer for each chunk
  6419. auto chunk =
  6420. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6421. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6422. }
  6423. } else {
  6424. ok = false;
  6425. }
  6426. }
  6427. return ok;
  6428. };
  6429. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6430. auto done_with_trailer = [&](const Headers *trailer) {
  6431. if (!ok) { return; }
  6432. data_available = false;
  6433. std::string payload;
  6434. if (!compressor.compress(nullptr, 0, true,
  6435. [&](const char *data, size_t data_len) {
  6436. payload.append(data, data_len);
  6437. return true;
  6438. })) {
  6439. ok = false;
  6440. return;
  6441. }
  6442. if (!payload.empty()) {
  6443. // Emit chunked response header and footer for each chunk
  6444. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6445. if (!write_data(strm, chunk.data(), chunk.size())) {
  6446. ok = false;
  6447. return;
  6448. }
  6449. }
  6450. constexpr const char done_marker[] = "0\r\n";
  6451. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6452. // Trailer
  6453. if (trailer) {
  6454. for (const auto &kv : *trailer) {
  6455. // Skip fields with invalid names or values to prevent response
  6456. // splitting via CR/LF injection, matching set_header().
  6457. if (!fields::is_field_name(kv.first) ||
  6458. !fields::is_field_value(kv.second)) {
  6459. continue;
  6460. }
  6461. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6462. if (!write_data(strm, field_line.data(), field_line.size())) {
  6463. ok = false;
  6464. }
  6465. }
  6466. }
  6467. constexpr const char crlf[] = "\r\n";
  6468. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6469. };
  6470. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6471. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6472. done_with_trailer(&trailer);
  6473. };
  6474. while (data_available && !is_shutting_down()) {
  6475. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6476. error = Error::Write;
  6477. return false;
  6478. } else if (!content_provider(offset, 0, data_sink)) {
  6479. error = Error::Canceled;
  6480. return false;
  6481. } else if (!ok) {
  6482. error = Error::Write;
  6483. return false;
  6484. }
  6485. }
  6486. if (data_available) { // exited due to is_shutting_down(), not done()
  6487. error = Error::Write;
  6488. return false;
  6489. }
  6490. error = Error::Success;
  6491. return true;
  6492. }
  6493. template <typename T, typename U>
  6494. inline bool write_content_chunked(Stream &strm,
  6495. const ContentProvider &content_provider,
  6496. const T &is_shutting_down, U &compressor) {
  6497. auto error = Error::Success;
  6498. return write_content_chunked(strm, content_provider, is_shutting_down,
  6499. compressor, error);
  6500. }
  6501. template <typename T>
  6502. inline bool redirect(T &cli, Request &req, Response &res,
  6503. const std::string &path, const std::string &location,
  6504. Error &error) {
  6505. Request new_req = req;
  6506. new_req.path = path;
  6507. new_req.redirect_count_ -= 1;
  6508. if (res.status == StatusCode::SeeOther_303 &&
  6509. (req.method != "GET" && req.method != "HEAD")) {
  6510. new_req.method = "GET";
  6511. new_req.body.clear();
  6512. new_req.headers.clear();
  6513. }
  6514. Response new_res;
  6515. auto ret = cli.send(new_req, new_res, error);
  6516. if (ret) {
  6517. req = std::move(new_req);
  6518. res = std::move(new_res);
  6519. if (res.location.empty()) { res.location = location; }
  6520. }
  6521. return ret;
  6522. }
  6523. inline std::string params_to_query_str(const Params &params) {
  6524. std::string query;
  6525. for (auto it = params.begin(); it != params.end(); ++it) {
  6526. if (it != params.begin()) { query += '&'; }
  6527. query += encode_query_component(it->first);
  6528. query += '=';
  6529. query += encode_query_component(it->second);
  6530. }
  6531. return query;
  6532. }
  6533. inline void parse_query_text(const char *data, std::size_t size,
  6534. Params &params) {
  6535. std::set<std::string> cache;
  6536. split(data, data + size, '&', [&](const char *b, const char *e) {
  6537. std::string kv(b, e);
  6538. if (cache.find(kv) != cache.end()) { return; }
  6539. cache.insert(std::move(kv));
  6540. std::string key;
  6541. std::string val;
  6542. divide(b, static_cast<std::size_t>(e - b), '=',
  6543. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6544. std::size_t rhs_size) {
  6545. key.assign(lhs_data, lhs_size);
  6546. val.assign(rhs_data, rhs_size);
  6547. });
  6548. if (!key.empty()) {
  6549. params.emplace(decode_query_component(key), decode_query_component(val));
  6550. }
  6551. });
  6552. }
  6553. inline void parse_query_text(const std::string &s, Params &params) {
  6554. parse_query_text(s.data(), s.size(), params);
  6555. }
  6556. // Normalize a query string by decoding and re-encoding each key/value pair
  6557. // while preserving the original parameter order. This avoids double-encoding
  6558. // and ensures consistent encoding without reordering (unlike Params which
  6559. // uses std::multimap and sorts keys).
  6560. inline std::string normalize_query_string(const std::string &query) {
  6561. std::string result;
  6562. split(query.data(), query.data() + query.size(), '&',
  6563. [&](const char *b, const char *e) {
  6564. std::string key;
  6565. std::string val;
  6566. divide(b, static_cast<std::size_t>(e - b), '=',
  6567. [&](const char *lhs_data, std::size_t lhs_size,
  6568. const char *rhs_data, std::size_t rhs_size) {
  6569. key.assign(lhs_data, lhs_size);
  6570. val.assign(rhs_data, rhs_size);
  6571. });
  6572. if (!key.empty()) {
  6573. auto dec_key = decode_query_component(key);
  6574. auto dec_val = decode_query_component(val);
  6575. if (!result.empty()) { result += '&'; }
  6576. result += encode_query_component(dec_key);
  6577. if (!val.empty() || std::find(b, e, '=') != e) {
  6578. result += '=';
  6579. result += encode_query_component(dec_val);
  6580. }
  6581. }
  6582. });
  6583. return result;
  6584. }
  6585. inline bool parse_multipart_boundary(const std::string &content_type,
  6586. std::string &boundary) {
  6587. std::map<std::string, std::string> params;
  6588. extract_media_type(content_type, &params);
  6589. auto it = params.find("boundary");
  6590. if (it == params.end()) { return false; }
  6591. boundary = it->second;
  6592. return !boundary.empty();
  6593. }
  6594. inline void parse_disposition_params(const std::string &s, Params &params) {
  6595. std::set<std::string> cache;
  6596. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6597. std::string kv(b, e);
  6598. if (cache.find(kv) != cache.end()) { return; }
  6599. cache.insert(kv);
  6600. std::string key;
  6601. std::string val;
  6602. split(b, e, '=', [&](const char *b2, const char *e2) {
  6603. if (key.empty()) {
  6604. key.assign(b2, e2);
  6605. } else {
  6606. val.assign(b2, e2);
  6607. }
  6608. });
  6609. if (!key.empty()) {
  6610. params.emplace(trim_double_quotes_copy((key)),
  6611. trim_double_quotes_copy((val)));
  6612. }
  6613. });
  6614. }
  6615. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6616. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6617. #else
  6618. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6619. #endif
  6620. auto is_valid = [](const std::string &str) {
  6621. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6622. };
  6623. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6624. const auto pos = static_cast<size_t>(6);
  6625. const auto len = static_cast<size_t>(s.size() - 6);
  6626. auto all_valid_ranges = true;
  6627. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6628. if (!all_valid_ranges) { return; }
  6629. const auto it = std::find(b, e, '-');
  6630. if (it == e) {
  6631. all_valid_ranges = false;
  6632. return;
  6633. }
  6634. const auto lhs = std::string(b, it);
  6635. const auto rhs = std::string(it + 1, e);
  6636. if (!is_valid(lhs) || !is_valid(rhs)) {
  6637. all_valid_ranges = false;
  6638. return;
  6639. }
  6640. ssize_t first = -1;
  6641. if (!lhs.empty()) {
  6642. ssize_t v;
  6643. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6644. if (res.ec == std::errc{}) { first = v; }
  6645. }
  6646. ssize_t last = -1;
  6647. if (!rhs.empty()) {
  6648. ssize_t v;
  6649. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6650. if (res.ec == std::errc{}) { last = v; }
  6651. }
  6652. if ((first == -1 && last == -1) ||
  6653. (first != -1 && last != -1 && first > last)) {
  6654. all_valid_ranges = false;
  6655. return;
  6656. }
  6657. ranges.emplace_back(first, last);
  6658. });
  6659. return all_valid_ranges && !ranges.empty();
  6660. }
  6661. return false;
  6662. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6663. }
  6664. #else
  6665. } catch (...) { return false; }
  6666. #endif
  6667. inline bool parse_accept_header(const std::string &s,
  6668. std::vector<std::string> &content_types) {
  6669. content_types.clear();
  6670. // Empty string is considered valid (no preference)
  6671. if (s.empty()) { return true; }
  6672. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6673. if (s.front() == ',' || s.back() == ',' ||
  6674. s.find(",,") != std::string::npos) {
  6675. return false;
  6676. }
  6677. struct AcceptEntry {
  6678. std::string media_type;
  6679. double quality;
  6680. int order;
  6681. };
  6682. std::vector<AcceptEntry> entries;
  6683. int order = 0;
  6684. bool has_invalid_entry = false;
  6685. // Split by comma and parse each entry
  6686. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6687. std::string entry(b, e);
  6688. entry = trim_copy(entry);
  6689. if (entry.empty()) {
  6690. has_invalid_entry = true;
  6691. return;
  6692. }
  6693. AcceptEntry accept_entry;
  6694. accept_entry.order = order++;
  6695. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6696. accept_entry.media_type, accept_entry.quality)) {
  6697. has_invalid_entry = true;
  6698. return;
  6699. }
  6700. // Remove additional parameters from media type
  6701. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6702. // Basic validation of media type format
  6703. if (accept_entry.media_type.empty()) {
  6704. has_invalid_entry = true;
  6705. return;
  6706. }
  6707. // Check for basic media type format (should contain '/' or be '*')
  6708. if (accept_entry.media_type != "*" &&
  6709. accept_entry.media_type.find('/') == std::string::npos) {
  6710. has_invalid_entry = true;
  6711. return;
  6712. }
  6713. entries.push_back(std::move(accept_entry));
  6714. });
  6715. // Return false if any invalid entry was found
  6716. if (has_invalid_entry) { return false; }
  6717. // Sort by quality (descending), then by original order (ascending)
  6718. std::sort(entries.begin(), entries.end(),
  6719. [](const AcceptEntry &a, const AcceptEntry &b) {
  6720. if (a.quality != b.quality) {
  6721. return a.quality > b.quality; // Higher quality first
  6722. }
  6723. return a.order < b.order; // Earlier order first for same quality
  6724. });
  6725. // Extract sorted media types
  6726. content_types.reserve(entries.size());
  6727. for (auto &entry : entries) {
  6728. content_types.push_back(std::move(entry.media_type));
  6729. }
  6730. return true;
  6731. }
  6732. class FormDataParser {
  6733. public:
  6734. FormDataParser() = default;
  6735. void set_boundary(std::string &&boundary) {
  6736. boundary_ = std::move(boundary);
  6737. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6738. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6739. }
  6740. bool is_valid() const { return is_valid_; }
  6741. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6742. const ContentReceiver &content_callback) {
  6743. buf_append(buf, n);
  6744. while (buf_size() > 0) {
  6745. switch (state_) {
  6746. case 0: { // Initial boundary
  6747. auto pos = buf_find(dash_boundary_crlf_);
  6748. if (pos == buf_size()) { return true; }
  6749. buf_erase(pos + dash_boundary_crlf_.size());
  6750. state_ = 1;
  6751. break;
  6752. }
  6753. case 1: { // New entry
  6754. clear_file_info();
  6755. state_ = 2;
  6756. break;
  6757. }
  6758. case 2: { // Headers
  6759. auto pos = buf_find(crlf_);
  6760. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6761. while (pos < buf_size()) {
  6762. // Empty line
  6763. if (pos == 0) {
  6764. if (!header_callback(file_)) {
  6765. is_valid_ = false;
  6766. return false;
  6767. }
  6768. buf_erase(crlf_.size());
  6769. state_ = 3;
  6770. break;
  6771. }
  6772. const auto header = buf_head(pos);
  6773. if (!parse_header(header.data(), header.data() + header.size(),
  6774. [&](const std::string &, const std::string &) {})) {
  6775. is_valid_ = false;
  6776. return false;
  6777. }
  6778. // Parse and emplace space trimmed headers into a map
  6779. if (!parse_header(
  6780. header.data(), header.data() + header.size(),
  6781. [&](const std::string &key, const std::string &val) {
  6782. file_.headers.emplace(key, val);
  6783. })) {
  6784. is_valid_ = false;
  6785. return false;
  6786. }
  6787. constexpr const char header_content_type[] = "Content-Type:";
  6788. if (start_with_case_ignore(header, header_content_type)) {
  6789. file_.content_type =
  6790. trim_copy(header.substr(str_len(header_content_type)));
  6791. } else {
  6792. std::string disposition_params;
  6793. if (parse_content_disposition(header, disposition_params)) {
  6794. Params params;
  6795. parse_disposition_params(disposition_params, params);
  6796. auto it = params.find("name");
  6797. if (it != params.end()) {
  6798. file_.name = it->second;
  6799. } else {
  6800. is_valid_ = false;
  6801. return false;
  6802. }
  6803. it = params.find("filename");
  6804. if (it != params.end()) { file_.filename = it->second; }
  6805. it = params.find("filename*");
  6806. if (it != params.end()) {
  6807. // RFC 5987: only UTF-8 encoding is allowed
  6808. const auto &val = it->second;
  6809. constexpr const char utf8_prefix[] = "UTF-8''";
  6810. constexpr size_t prefix_len = str_len(utf8_prefix);
  6811. if (val.size() > prefix_len &&
  6812. start_with_case_ignore(val, utf8_prefix)) {
  6813. file_.filename = decode_path_component(
  6814. val.substr(prefix_len)); // override...
  6815. } else {
  6816. is_valid_ = false;
  6817. return false;
  6818. }
  6819. }
  6820. }
  6821. }
  6822. buf_erase(pos + crlf_.size());
  6823. pos = buf_find(crlf_);
  6824. }
  6825. if (state_ != 3) { return true; }
  6826. break;
  6827. }
  6828. case 3: { // Body
  6829. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6830. auto pos = buf_find(crlf_dash_boundary_);
  6831. if (pos < buf_size()) {
  6832. if (!content_callback(buf_data(), pos)) {
  6833. is_valid_ = false;
  6834. return false;
  6835. }
  6836. buf_erase(pos + crlf_dash_boundary_.size());
  6837. state_ = 4;
  6838. } else {
  6839. auto len = buf_size() - crlf_dash_boundary_.size();
  6840. if (len > 0) {
  6841. if (!content_callback(buf_data(), len)) {
  6842. is_valid_ = false;
  6843. return false;
  6844. }
  6845. buf_erase(len);
  6846. }
  6847. return true;
  6848. }
  6849. break;
  6850. }
  6851. case 4: { // Boundary
  6852. if (crlf_.size() > buf_size()) { return true; }
  6853. if (buf_start_with(crlf_)) {
  6854. buf_erase(crlf_.size());
  6855. state_ = 1;
  6856. } else {
  6857. if (dash_.size() > buf_size()) { return true; }
  6858. if (buf_start_with(dash_)) {
  6859. buf_erase(dash_.size());
  6860. is_valid_ = true;
  6861. buf_erase(buf_size()); // Remove epilogue
  6862. } else {
  6863. return true;
  6864. }
  6865. }
  6866. break;
  6867. }
  6868. }
  6869. }
  6870. return true;
  6871. }
  6872. private:
  6873. void clear_file_info() {
  6874. file_.name.clear();
  6875. file_.filename.clear();
  6876. file_.content_type.clear();
  6877. file_.headers.clear();
  6878. }
  6879. bool start_with_case_ignore(const std::string &a, const char *b,
  6880. size_t offset = 0) const {
  6881. const auto b_len = strlen(b);
  6882. if (a.size() < offset + b_len) { return false; }
  6883. for (size_t i = 0; i < b_len; i++) {
  6884. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6885. return false;
  6886. }
  6887. }
  6888. return true;
  6889. }
  6890. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6891. // Returns true if header matches, with the params portion in `params_out`.
  6892. bool parse_content_disposition(const std::string &header,
  6893. std::string &params_out) const {
  6894. constexpr const char prefix[] = "Content-Disposition:";
  6895. constexpr size_t prefix_len = str_len(prefix);
  6896. if (!start_with_case_ignore(header, prefix)) { return false; }
  6897. // Skip whitespace after "Content-Disposition:"
  6898. auto pos = prefix_len;
  6899. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6900. pos++;
  6901. }
  6902. // Match "form-data;" (case-insensitive)
  6903. constexpr const char form_data[] = "form-data;";
  6904. constexpr size_t form_data_len = str_len(form_data);
  6905. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6906. pos += form_data_len;
  6907. // Skip whitespace after "form-data;"
  6908. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6909. pos++;
  6910. }
  6911. params_out = header.substr(pos);
  6912. return true;
  6913. }
  6914. const std::string dash_ = "--";
  6915. const std::string crlf_ = "\r\n";
  6916. std::string boundary_;
  6917. std::string dash_boundary_crlf_;
  6918. std::string crlf_dash_boundary_;
  6919. size_t state_ = 0;
  6920. bool is_valid_ = false;
  6921. FormData file_;
  6922. // Buffer
  6923. bool start_with(const std::string &a, size_t spos, size_t epos,
  6924. const std::string &b) const {
  6925. if (epos - spos < b.size()) { return false; }
  6926. for (size_t i = 0; i < b.size(); i++) {
  6927. if (a[i + spos] != b[i]) { return false; }
  6928. }
  6929. return true;
  6930. }
  6931. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6932. const char *buf_data() const { return &buf_[buf_spos_]; }
  6933. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6934. bool buf_start_with(const std::string &s) const {
  6935. return start_with(buf_, buf_spos_, buf_epos_, s);
  6936. }
  6937. size_t buf_find(const std::string &s) const {
  6938. auto c = s.front();
  6939. size_t off = buf_spos_;
  6940. while (off < buf_epos_) {
  6941. auto pos = off;
  6942. while (true) {
  6943. if (pos == buf_epos_) { return buf_size(); }
  6944. if (buf_[pos] == c) { break; }
  6945. pos++;
  6946. }
  6947. auto remaining_size = buf_epos_ - pos;
  6948. if (s.size() > remaining_size) { return buf_size(); }
  6949. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6950. off = pos + 1;
  6951. }
  6952. return buf_size();
  6953. }
  6954. void buf_append(const char *data, size_t n) {
  6955. auto remaining_size = buf_size();
  6956. if (remaining_size > 0 && buf_spos_ > 0) {
  6957. for (size_t i = 0; i < remaining_size; i++) {
  6958. buf_[i] = buf_[buf_spos_ + i];
  6959. }
  6960. }
  6961. buf_spos_ = 0;
  6962. buf_epos_ = remaining_size;
  6963. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6964. for (size_t i = 0; i < n; i++) {
  6965. buf_[buf_epos_ + i] = data[i];
  6966. }
  6967. buf_epos_ += n;
  6968. }
  6969. void buf_erase(size_t size) { buf_spos_ += size; }
  6970. std::string buf_;
  6971. size_t buf_spos_ = 0;
  6972. size_t buf_epos_ = 0;
  6973. };
  6974. inline std::string random_string(size_t length) {
  6975. constexpr const char data[] =
  6976. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6977. thread_local auto engine([]() {
  6978. // std::random_device might actually be deterministic on some
  6979. // platforms, but due to lack of support in the c++ standard library,
  6980. // doing better requires either some ugly hacks or breaking portability.
  6981. std::random_device seed_gen;
  6982. // Request 128 bits of entropy for initialization
  6983. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6984. return std::mt19937(seed_sequence);
  6985. }());
  6986. std::string result;
  6987. for (size_t i = 0; i < length; i++) {
  6988. result += data[engine() % (sizeof(data) - 1)];
  6989. }
  6990. return result;
  6991. }
  6992. inline std::string make_multipart_data_boundary() {
  6993. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6994. }
  6995. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6996. auto valid = true;
  6997. for (size_t i = 0; i < boundary.size(); i++) {
  6998. auto c = boundary[i];
  6999. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  7000. valid = false;
  7001. break;
  7002. }
  7003. }
  7004. return valid;
  7005. }
  7006. // Escape a multipart field name/filename following the WHATWG HTML standard
  7007. // ("escape a multipart form-data name"), which is what browsers send:
  7008. // '"' -> %22, CR -> %0D, LF -> %0A
  7009. // With escape_quote = false, only CR and LF are escaped; this is for header
  7010. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  7011. inline std::string escape_multipart_field(const std::string &s,
  7012. bool escape_quote = true) {
  7013. std::string result;
  7014. result.reserve(s.size());
  7015. for (auto c : s) {
  7016. switch (c) {
  7017. case '"':
  7018. if (escape_quote) {
  7019. result += "%22";
  7020. } else {
  7021. result += c;
  7022. }
  7023. break;
  7024. case '\r': result += "%0D"; break;
  7025. case '\n': result += "%0A"; break;
  7026. default: result += c; break;
  7027. }
  7028. }
  7029. return result;
  7030. }
  7031. template <typename T>
  7032. inline std::string
  7033. serialize_multipart_formdata_item_begin(const T &item,
  7034. const std::string &boundary) {
  7035. std::string body = "--" + boundary + "\r\n";
  7036. body += "Content-Disposition: form-data; name=\"" +
  7037. escape_multipart_field(item.name) + "\"";
  7038. if (!item.filename.empty()) {
  7039. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  7040. }
  7041. body += "\r\n";
  7042. if (!item.content_type.empty()) {
  7043. body +=
  7044. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  7045. "\r\n";
  7046. }
  7047. body += "\r\n";
  7048. return body;
  7049. }
  7050. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  7051. inline std::string
  7052. serialize_multipart_formdata_finish(const std::string &boundary) {
  7053. return "--" + boundary + "--\r\n";
  7054. }
  7055. inline std::string
  7056. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7057. return "multipart/form-data; boundary=" + boundary;
  7058. }
  7059. inline std::string
  7060. serialize_multipart_formdata(const UploadFormDataItems &items,
  7061. const std::string &boundary, bool finish = true) {
  7062. std::string body;
  7063. for (const auto &item : items) {
  7064. body += serialize_multipart_formdata_item_begin(item, boundary);
  7065. body += item.content + serialize_multipart_formdata_item_end();
  7066. }
  7067. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7068. return body;
  7069. }
  7070. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7071. const std::string &boundary) {
  7072. size_t total = 0;
  7073. for (const auto &item : items) {
  7074. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7075. total += item.content.size();
  7076. total += serialize_multipart_formdata_item_end().size();
  7077. }
  7078. total += serialize_multipart_formdata_finish(boundary).size();
  7079. return total;
  7080. }
  7081. struct MultipartSegment {
  7082. const char *data;
  7083. size_t size;
  7084. };
  7085. // NOTE: items must outlive the returned ContentProvider
  7086. // (safe for synchronous use inside Post/Put/Patch)
  7087. inline ContentProvider
  7088. make_multipart_content_provider(const UploadFormDataItems &items,
  7089. const std::string &boundary) {
  7090. // Own the per-item header strings and the finish string
  7091. std::vector<std::string> owned;
  7092. owned.reserve(items.size() + 1);
  7093. for (const auto &item : items)
  7094. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7095. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7096. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7097. std::vector<MultipartSegment> segs;
  7098. segs.reserve(items.size() * 3 + 1);
  7099. static const char crlf[] = "\r\n";
  7100. for (size_t i = 0; i < items.size(); i++) {
  7101. segs.push_back({owned[i].data(), owned[i].size()});
  7102. segs.push_back({items[i].content.data(), items[i].content.size()});
  7103. segs.push_back({crlf, 2});
  7104. }
  7105. segs.push_back({owned.back().data(), owned.back().size()});
  7106. struct MultipartState {
  7107. std::vector<std::string> owned;
  7108. std::vector<MultipartSegment> segs;
  7109. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7110. };
  7111. auto state = std::make_shared<MultipartState>();
  7112. state->owned = std::move(owned);
  7113. // `segs` holds raw pointers into owned strings; std::string move preserves
  7114. // the data pointer, so these pointers remain valid after the move above.
  7115. state->segs = std::move(segs);
  7116. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7117. // Buffer multiple small segments into fewer, larger writes to avoid
  7118. // excessive TCP packets when there are many form data items (#2410)
  7119. auto &buf = state->buf;
  7120. auto buf_size = buf.size();
  7121. size_t buf_len = 0;
  7122. size_t remaining = length;
  7123. // Find the first segment containing 'offset'
  7124. size_t pos = 0;
  7125. size_t seg_idx = 0;
  7126. for (; seg_idx < state->segs.size(); seg_idx++) {
  7127. const auto &seg = state->segs[seg_idx];
  7128. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7129. pos += seg.size;
  7130. }
  7131. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7132. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7133. const auto &seg = state->segs[seg_idx];
  7134. size_t available = seg.size - seg_offset;
  7135. size_t to_copy = (std::min)(available, remaining);
  7136. const char *src = seg.data + seg_offset;
  7137. seg_offset = 0; // only the first segment has a non-zero offset
  7138. while (to_copy > 0) {
  7139. size_t space = buf_size - buf_len;
  7140. size_t chunk = (std::min)(to_copy, space);
  7141. std::memcpy(buf.data() + buf_len, src, chunk);
  7142. buf_len += chunk;
  7143. src += chunk;
  7144. to_copy -= chunk;
  7145. remaining -= chunk;
  7146. if (buf_len == buf_size) {
  7147. if (!sink.write(buf.data(), buf_len)) { return false; }
  7148. buf_len = 0;
  7149. }
  7150. }
  7151. }
  7152. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7153. return true;
  7154. };
  7155. }
  7156. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7157. if (ranges.size() <= 1) return;
  7158. // Sort ranges by start position
  7159. std::sort(ranges.begin(), ranges.end(),
  7160. [](const Range &a, const Range &b) { return a.first < b.first; });
  7161. Ranges coalesced;
  7162. coalesced.reserve(ranges.size());
  7163. for (auto &r : ranges) {
  7164. auto first_pos = r.first;
  7165. auto last_pos = r.second;
  7166. // Handle special cases like in range_error
  7167. if (first_pos == -1 && last_pos == -1) {
  7168. first_pos = 0;
  7169. last_pos = static_cast<ssize_t>(content_length);
  7170. }
  7171. if (first_pos == -1) {
  7172. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7173. last_pos = static_cast<ssize_t>(content_length) - 1;
  7174. }
  7175. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7176. last_pos = static_cast<ssize_t>(content_length) - 1;
  7177. }
  7178. // Skip invalid ranges
  7179. if (!(0 <= first_pos && first_pos <= last_pos &&
  7180. last_pos < static_cast<ssize_t>(content_length))) {
  7181. continue;
  7182. }
  7183. // Coalesce with previous range if overlapping or adjacent (but not
  7184. // identical)
  7185. if (!coalesced.empty()) {
  7186. auto &prev = coalesced.back();
  7187. // Check if current range overlaps or is adjacent to previous range
  7188. // but don't coalesce identical ranges (allow duplicates)
  7189. if (first_pos <= prev.second + 1 &&
  7190. !(first_pos == prev.first && last_pos == prev.second)) {
  7191. // Extend the previous range
  7192. prev.second = (std::max)(prev.second, last_pos);
  7193. continue;
  7194. }
  7195. }
  7196. // Add new range
  7197. coalesced.emplace_back(first_pos, last_pos);
  7198. }
  7199. ranges = std::move(coalesced);
  7200. }
  7201. inline bool range_error(Request &req, Response &res) {
  7202. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7203. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7204. req.ranges.clear();
  7205. if (res.status == StatusCode::PartialContent_206) {
  7206. res.status = StatusCode::OK_200;
  7207. }
  7208. return false;
  7209. }
  7210. ssize_t content_len = static_cast<ssize_t>(
  7211. res.content_length_ ? res.content_length_ : res.body.size());
  7212. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7213. size_t overwrapping_count = 0;
  7214. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7215. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7216. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7217. // Too many ranges
  7218. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7219. for (auto &r : req.ranges) {
  7220. auto &first_pos = r.first;
  7221. auto &last_pos = r.second;
  7222. if (first_pos == -1 && last_pos == -1) {
  7223. first_pos = 0;
  7224. last_pos = content_len;
  7225. }
  7226. if (first_pos == -1) {
  7227. first_pos = content_len - last_pos;
  7228. last_pos = content_len - 1;
  7229. }
  7230. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7231. // A client can limit the number of bytes requested without knowing the
  7232. // size of the selected representation. If the last-pos value is absent,
  7233. // or if the value is greater than or equal to the current length of the
  7234. // representation data, the byte range is interpreted as the remainder of
  7235. // the representation (i.e., the server replaces the value of last-pos
  7236. // with a value that is one less than the current length of the selected
  7237. // representation).
  7238. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7239. if (last_pos == -1 || last_pos >= content_len) {
  7240. last_pos = content_len - 1;
  7241. }
  7242. // Range must be within content length
  7243. if (!(0 <= first_pos && first_pos <= last_pos &&
  7244. last_pos <= content_len - 1)) {
  7245. return true;
  7246. }
  7247. // Request must not have more than two overlapping ranges
  7248. for (const auto &processed_range : processed_ranges) {
  7249. if (!(last_pos < processed_range.first ||
  7250. first_pos > processed_range.second)) {
  7251. overwrapping_count++;
  7252. if (overwrapping_count > 2) { return true; }
  7253. break; // Only count once per range
  7254. }
  7255. }
  7256. processed_ranges.emplace_back(first_pos, last_pos);
  7257. }
  7258. // After validation, coalesce overlapping ranges as per RFC 9110
  7259. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7260. }
  7261. return false;
  7262. }
  7263. inline std::pair<size_t, size_t>
  7264. get_range_offset_and_length(Range r, size_t content_length) {
  7265. assert(r.first != -1 && r.second != -1);
  7266. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7267. assert(r.first <= r.second &&
  7268. r.second < static_cast<ssize_t>(content_length));
  7269. (void)(content_length);
  7270. return std::make_pair(static_cast<size_t>(r.first),
  7271. static_cast<size_t>(r.second - r.first) + 1);
  7272. }
  7273. inline std::string make_content_range_header_field(
  7274. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7275. auto st = offset_and_length.first;
  7276. auto ed = st + offset_and_length.second - 1;
  7277. std::string field = "bytes ";
  7278. field += std::to_string(st);
  7279. field += '-';
  7280. field += std::to_string(ed);
  7281. field += '/';
  7282. field += std::to_string(content_length);
  7283. return field;
  7284. }
  7285. template <typename SToken, typename CToken, typename Content>
  7286. bool process_multipart_ranges_data(const Request &req,
  7287. const std::string &boundary,
  7288. const std::string &content_type,
  7289. size_t content_length, SToken stoken,
  7290. CToken ctoken, Content content) {
  7291. for (size_t i = 0; i < req.ranges.size(); i++) {
  7292. ctoken("--");
  7293. stoken(boundary);
  7294. ctoken("\r\n");
  7295. if (!content_type.empty()) {
  7296. ctoken("Content-Type: ");
  7297. stoken(content_type);
  7298. ctoken("\r\n");
  7299. }
  7300. auto offset_and_length =
  7301. get_range_offset_and_length(req.ranges[i], content_length);
  7302. ctoken("Content-Range: ");
  7303. stoken(make_content_range_header_field(offset_and_length, content_length));
  7304. ctoken("\r\n");
  7305. ctoken("\r\n");
  7306. if (!content(offset_and_length.first, offset_and_length.second)) {
  7307. return false;
  7308. }
  7309. ctoken("\r\n");
  7310. }
  7311. ctoken("--");
  7312. stoken(boundary);
  7313. ctoken("--");
  7314. return true;
  7315. }
  7316. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7317. const std::string &boundary,
  7318. const std::string &content_type,
  7319. size_t content_length,
  7320. std::string &data) {
  7321. process_multipart_ranges_data(
  7322. req, boundary, content_type, content_length,
  7323. [&](const std::string &token) { data += token; },
  7324. [&](const std::string &token) { data += token; },
  7325. [&](size_t offset, size_t length) {
  7326. assert(offset + length <= content_length);
  7327. data += res.body.substr(offset, length);
  7328. return true;
  7329. });
  7330. }
  7331. inline size_t get_multipart_ranges_data_length(const Request &req,
  7332. const std::string &boundary,
  7333. const std::string &content_type,
  7334. size_t content_length) {
  7335. size_t data_length = 0;
  7336. process_multipart_ranges_data(
  7337. req, boundary, content_type, content_length,
  7338. [&](const std::string &token) { data_length += token.size(); },
  7339. [&](const std::string &token) { data_length += token.size(); },
  7340. [&](size_t /*offset*/, size_t length) {
  7341. data_length += length;
  7342. return true;
  7343. });
  7344. return data_length;
  7345. }
  7346. template <typename T>
  7347. inline bool
  7348. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7349. const std::string &boundary,
  7350. const std::string &content_type,
  7351. size_t content_length, const T &is_shutting_down) {
  7352. return process_multipart_ranges_data(
  7353. req, boundary, content_type, content_length,
  7354. [&](const std::string &token) { strm.write(token); },
  7355. [&](const std::string &token) { strm.write(token); },
  7356. [&](size_t offset, size_t length) {
  7357. return write_content(strm, res.content_provider_, offset, length,
  7358. is_shutting_down);
  7359. });
  7360. }
  7361. inline bool has_framed_body(const Request &req) {
  7362. return is_chunked_transfer_encoding(req.headers) ||
  7363. req.get_header_value_u64("Content-Length") > 0;
  7364. }
  7365. inline bool is_connection_persistent(const Request &req) {
  7366. auto conn = req.get_header_value("Connection");
  7367. if (conn == "close") { return false; }
  7368. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7369. return true;
  7370. }
  7371. inline bool expect_content(const Request &req) {
  7372. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7373. req.method == "DELETE") {
  7374. return true;
  7375. }
  7376. return has_framed_body(req);
  7377. }
  7378. #ifdef _WIN32
  7379. class WSInit {
  7380. public:
  7381. WSInit() {
  7382. WSADATA wsaData;
  7383. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7384. }
  7385. ~WSInit() {
  7386. if (is_valid_) WSACleanup();
  7387. }
  7388. bool is_valid_ = false;
  7389. };
  7390. static WSInit wsinit_;
  7391. #endif
  7392. inline bool parse_www_authenticate(const Response &res,
  7393. std::map<std::string, std::string> &auth,
  7394. bool is_proxy) {
  7395. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7396. if (res.has_header(auth_key)) {
  7397. thread_local auto re =
  7398. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7399. auto s = res.get_header_value(auth_key);
  7400. auto pos = s.find(' ');
  7401. if (pos != std::string::npos) {
  7402. auto type = s.substr(0, pos);
  7403. if (type == "Basic") {
  7404. return false;
  7405. } else if (type == "Digest") {
  7406. s = s.substr(pos + 1);
  7407. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7408. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7409. const auto &m = *i;
  7410. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7411. static_cast<size_t>(m.length(1)));
  7412. auto val = m.length(2) > 0
  7413. ? s.substr(static_cast<size_t>(m.position(2)),
  7414. static_cast<size_t>(m.length(2)))
  7415. : s.substr(static_cast<size_t>(m.position(3)),
  7416. static_cast<size_t>(m.length(3)));
  7417. auth[std::move(key)] = std::move(val);
  7418. }
  7419. return true;
  7420. }
  7421. }
  7422. }
  7423. return false;
  7424. }
  7425. class ContentProviderAdapter {
  7426. public:
  7427. explicit ContentProviderAdapter(
  7428. ContentProviderWithoutLength &&content_provider)
  7429. : content_provider_(std::move(content_provider)) {}
  7430. bool operator()(size_t offset, size_t, DataSink &sink) {
  7431. return content_provider_(offset, sink);
  7432. }
  7433. private:
  7434. ContentProviderWithoutLength content_provider_;
  7435. };
  7436. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7437. namespace fields {
  7438. inline bool is_token_char(char c) {
  7439. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7440. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7441. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7442. }
  7443. inline bool is_token(const std::string &s) {
  7444. if (s.empty()) { return false; }
  7445. for (auto c : s) {
  7446. if (!is_token_char(c)) { return false; }
  7447. }
  7448. return true;
  7449. }
  7450. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7451. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7452. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7453. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7454. inline bool is_field_content(const std::string &s) {
  7455. if (s.empty()) { return true; }
  7456. if (s.size() == 1) {
  7457. return is_field_vchar(s[0]);
  7458. } else if (s.size() == 2) {
  7459. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7460. } else {
  7461. size_t i = 0;
  7462. if (!is_field_vchar(s[i])) { return false; }
  7463. i++;
  7464. while (i < s.size() - 1) {
  7465. auto c = s[i++];
  7466. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7467. } else {
  7468. return false;
  7469. }
  7470. }
  7471. return is_field_vchar(s[i]);
  7472. }
  7473. }
  7474. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7475. } // namespace fields
  7476. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7477. int port, bool is_ssl,
  7478. const std::string &path,
  7479. const Headers &headers,
  7480. std::string &selected_subprotocol) {
  7481. // Validate path and host
  7482. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7483. return false;
  7484. }
  7485. // Validate user-provided headers
  7486. for (const auto &h : headers) {
  7487. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7488. return false;
  7489. }
  7490. }
  7491. // Generate random Sec-WebSocket-Key
  7492. thread_local std::mt19937 rng(std::random_device{}());
  7493. std::string key_bytes(16, '\0');
  7494. for (size_t i = 0; i < 16; i += 4) {
  7495. auto r = rng();
  7496. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7497. }
  7498. auto client_key = base64_encode(key_bytes);
  7499. // Build upgrade request
  7500. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7501. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7502. req_str += "Upgrade: websocket\r\n";
  7503. req_str += "Connection: Upgrade\r\n";
  7504. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7505. req_str += "Sec-WebSocket-Version: 13\r\n";
  7506. for (const auto &h : headers) {
  7507. req_str += h.first + ": " + h.second + "\r\n";
  7508. }
  7509. req_str += "\r\n";
  7510. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7511. // Verify 101 response and Sec-WebSocket-Accept header
  7512. auto expected_accept = websocket_accept_key(client_key);
  7513. return read_websocket_upgrade_response(strm, expected_accept,
  7514. selected_subprotocol);
  7515. }
  7516. } // namespace detail
  7517. /*
  7518. * Group 2: detail namespace - SSL common utilities
  7519. */
  7520. #ifdef CPPHTTPLIB_SSL_ENABLED
  7521. namespace detail {
  7522. class SSLSocketStream final : public Stream {
  7523. public:
  7524. SSLSocketStream(
  7525. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7526. time_t read_timeout_usec, time_t write_timeout_sec,
  7527. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7528. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7529. (std::chrono::steady_clock::time_point::min)());
  7530. ~SSLSocketStream() override;
  7531. bool is_readable() const override;
  7532. bool wait_readable() const override;
  7533. bool wait_writable() const override;
  7534. bool is_peer_alive() const override;
  7535. ssize_t read(char *ptr, size_t size) override;
  7536. ssize_t write(const char *ptr, size_t size) override;
  7537. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7538. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7539. socket_t socket() const override;
  7540. time_t duration() const override;
  7541. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7542. private:
  7543. socket_t sock_;
  7544. tls::session_t session_;
  7545. time_t read_timeout_sec_;
  7546. time_t read_timeout_usec_;
  7547. time_t write_timeout_sec_;
  7548. time_t write_timeout_usec_;
  7549. time_t max_timeout_msec_;
  7550. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7551. };
  7552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7553. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7554. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7555. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7556. unsigned int hash_length = 0;
  7557. unsigned char hash[EVP_MAX_MD_SIZE];
  7558. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7559. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7560. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7561. std::stringstream ss;
  7562. for (auto i = 0u; i < hash_length; ++i) {
  7563. ss << std::hex << std::setw(2) << std::setfill('0')
  7564. << static_cast<unsigned int>(hash[i]);
  7565. }
  7566. return ss.str();
  7567. }
  7568. inline std::string MD5(const std::string &s) {
  7569. return message_digest(s, EVP_md5());
  7570. }
  7571. inline std::string SHA_256(const std::string &s) {
  7572. return message_digest(s, EVP_sha256());
  7573. }
  7574. inline std::string SHA_512(const std::string &s) {
  7575. return message_digest(s, EVP_sha512());
  7576. }
  7577. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7578. namespace {
  7579. template <size_t N>
  7580. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7581. std::stringstream ss;
  7582. for (size_t i = 0; i < N; ++i) {
  7583. ss << std::hex << std::setw(2) << std::setfill('0')
  7584. << static_cast<unsigned int>(hash[i]);
  7585. }
  7586. return ss.str();
  7587. }
  7588. } // namespace
  7589. inline std::string MD5(const std::string &s) {
  7590. unsigned char hash[16];
  7591. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7592. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7593. hash);
  7594. #else
  7595. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7596. hash);
  7597. #endif
  7598. return hash_to_hex(hash);
  7599. }
  7600. inline std::string SHA_256(const std::string &s) {
  7601. unsigned char hash[32];
  7602. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7603. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7604. hash, 0);
  7605. #else
  7606. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7607. s.size(), hash, 0);
  7608. #endif
  7609. return hash_to_hex(hash);
  7610. }
  7611. inline std::string SHA_512(const std::string &s) {
  7612. unsigned char hash[64];
  7613. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7614. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7615. hash, 0);
  7616. #else
  7617. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7618. s.size(), hash, 0);
  7619. #endif
  7620. return hash_to_hex(hash);
  7621. }
  7622. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7623. namespace {
  7624. template <size_t N>
  7625. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7626. std::stringstream ss;
  7627. for (size_t i = 0; i < N; ++i) {
  7628. ss << std::hex << std::setw(2) << std::setfill('0')
  7629. << static_cast<unsigned int>(hash[i]);
  7630. }
  7631. return ss.str();
  7632. }
  7633. } // namespace
  7634. inline std::string MD5(const std::string &s) {
  7635. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7636. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7637. static_cast<word32>(s.size()), hash);
  7638. return hash_to_hex(hash);
  7639. }
  7640. inline std::string SHA_256(const std::string &s) {
  7641. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7642. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7643. static_cast<word32>(s.size()), hash);
  7644. return hash_to_hex(hash);
  7645. }
  7646. inline std::string SHA_512(const std::string &s) {
  7647. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7648. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7649. static_cast<word32>(s.size()), hash);
  7650. return hash_to_hex(hash);
  7651. }
  7652. #endif
  7653. inline bool is_ip_address(const std::string &host) {
  7654. struct in_addr addr4;
  7655. struct in6_addr addr6;
  7656. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7657. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7658. }
  7659. template <typename T>
  7660. inline bool process_server_socket_ssl(
  7661. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7662. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7663. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7664. time_t write_timeout_usec, T callback) {
  7665. return process_server_socket_core(
  7666. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7667. [&](bool close_connection, bool &connection_closed) {
  7668. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7669. write_timeout_sec, write_timeout_usec);
  7670. return callback(strm, close_connection, connection_closed);
  7671. });
  7672. }
  7673. template <typename T>
  7674. inline bool process_client_socket_ssl(
  7675. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7676. time_t read_timeout_usec, time_t write_timeout_sec,
  7677. time_t write_timeout_usec, time_t max_timeout_msec,
  7678. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7679. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7680. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7681. start_time);
  7682. return callback(strm);
  7683. }
  7684. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7685. const Request &req, const std::map<std::string, std::string> &auth,
  7686. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7687. const std::string &password, bool is_proxy = false) {
  7688. std::string nc;
  7689. {
  7690. std::stringstream ss;
  7691. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7692. nc = ss.str();
  7693. }
  7694. std::string qop;
  7695. if (auth.find("qop") != auth.end()) {
  7696. qop = auth.at("qop");
  7697. if (qop.find("auth-int") != std::string::npos) {
  7698. qop = "auth-int";
  7699. } else if (qop.find("auth") != std::string::npos) {
  7700. qop = "auth";
  7701. } else {
  7702. qop.clear();
  7703. }
  7704. }
  7705. std::string algo = "MD5";
  7706. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7707. std::string response;
  7708. {
  7709. auto H = algo == "SHA-256" ? detail::SHA_256
  7710. : algo == "SHA-512" ? detail::SHA_512
  7711. : detail::MD5;
  7712. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7713. auto A2 = req.method + ":" + req.path;
  7714. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7715. if (qop.empty()) {
  7716. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7717. } else {
  7718. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7719. ":" + qop + ":" + H(A2));
  7720. }
  7721. }
  7722. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7723. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7724. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7725. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7726. (qop.empty() ? ", response=\""
  7727. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7728. cnonce + "\", response=\"") +
  7729. response + "\"" +
  7730. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7731. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7732. return std::make_pair(key, field);
  7733. }
  7734. inline bool match_hostname(const std::string &pattern,
  7735. const std::string &hostname) {
  7736. // Exact match (case-insensitive)
  7737. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7738. // Split both pattern and hostname into components by '.'
  7739. std::vector<std::string> pattern_components;
  7740. if (!pattern.empty()) {
  7741. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7742. [&](const char *b, const char *e) {
  7743. pattern_components.emplace_back(b, e);
  7744. });
  7745. }
  7746. std::vector<std::string> host_components;
  7747. if (!hostname.empty()) {
  7748. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7749. [&](const char *b, const char *e) {
  7750. host_components.emplace_back(b, e);
  7751. });
  7752. }
  7753. // Component count must match
  7754. if (host_components.size() != pattern_components.size()) { return false; }
  7755. // Compare each component with wildcard support
  7756. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7757. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7758. auto itr = pattern_components.begin();
  7759. for (const auto &h : host_components) {
  7760. auto &p = *itr;
  7761. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7762. bool partial_match = false;
  7763. if (!p.empty() && p[p.size() - 1] == '*') {
  7764. const auto prefix_length = p.size() - 1;
  7765. if (prefix_length == 0) {
  7766. partial_match = true;
  7767. } else if (h.size() >= prefix_length) {
  7768. partial_match =
  7769. std::equal(p.begin(),
  7770. p.begin() + static_cast<std::string::difference_type>(
  7771. prefix_length),
  7772. h.begin(), [](const char ca, const char cb) {
  7773. return detail::case_ignore::to_lower(ca) ==
  7774. detail::case_ignore::to_lower(cb);
  7775. });
  7776. }
  7777. }
  7778. if (!partial_match) { return false; }
  7779. }
  7780. ++itr;
  7781. }
  7782. return true;
  7783. }
  7784. #ifdef _WIN32
  7785. // Verify certificate using Windows CertGetCertificateChain API.
  7786. // This provides real-time certificate validation with Windows Update
  7787. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7788. inline bool
  7789. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7790. const std::string &hostname,
  7791. bool verify_hostname, uint64_t &out_error) {
  7792. if (der_cert.empty()) { return false; }
  7793. out_error = 0;
  7794. // Create Windows certificate context from DER data
  7795. auto cert_context = CertCreateCertificateContext(
  7796. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7797. static_cast<DWORD>(der_cert.size()));
  7798. if (!cert_context) {
  7799. out_error = GetLastError();
  7800. return false;
  7801. }
  7802. auto cert_guard =
  7803. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7804. // Setup chain parameters
  7805. CERT_CHAIN_PARA chain_para = {};
  7806. chain_para.cbSize = sizeof(chain_para);
  7807. // Build certificate chain with revocation checking
  7808. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7809. auto chain_result = CertGetCertificateChain(
  7810. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7811. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7812. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7813. nullptr, &chain_context);
  7814. if (!chain_result || !chain_context) {
  7815. out_error = GetLastError();
  7816. return false;
  7817. }
  7818. auto chain_guard =
  7819. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7820. // Check if chain has errors
  7821. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7822. out_error = chain_context->TrustStatus.dwErrorStatus;
  7823. return false;
  7824. }
  7825. // Verify SSL policy
  7826. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7827. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7828. #ifdef AUTHTYPE_SERVER
  7829. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7830. #endif
  7831. std::wstring whost;
  7832. if (verify_hostname) {
  7833. whost = u8string_to_wstring(hostname.c_str());
  7834. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7835. }
  7836. CERT_CHAIN_POLICY_PARA policy_para = {};
  7837. policy_para.cbSize = sizeof(policy_para);
  7838. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7839. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7840. #else
  7841. policy_para.dwFlags = 0;
  7842. #endif
  7843. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7844. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7845. policy_status.cbSize = sizeof(policy_status);
  7846. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7847. &policy_para, &policy_status)) {
  7848. out_error = GetLastError();
  7849. return false;
  7850. }
  7851. if (policy_status.dwError != 0) {
  7852. out_error = policy_status.dwError;
  7853. return false;
  7854. }
  7855. return true;
  7856. }
  7857. #endif // _WIN32
  7858. // Loads CA file/dir configuration and applies the system CA policy to a
  7859. // client TLS context. PEM data and native stores are applied to the context
  7860. // directly at set time; has_custom_store reflects them for the Auto policy
  7861. // decision.
  7862. inline bool load_client_ca_config(tls::ctx_t ctx,
  7863. const std::string &ca_cert_file_path,
  7864. const std::string &ca_cert_dir_path,
  7865. bool has_custom_store, SystemCAMode mode,
  7866. uint64_t &backend_error) {
  7867. auto ret = true;
  7868. if (!ca_cert_file_path.empty()) {
  7869. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7870. backend_error = tls::get_error();
  7871. ret = false;
  7872. }
  7873. } else if (!ca_cert_dir_path.empty()) {
  7874. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7875. backend_error = tls::get_error();
  7876. ret = false;
  7877. }
  7878. }
  7879. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7880. !ca_cert_dir_path.empty() || has_custom_store;
  7881. if (mode == SystemCAMode::Enabled ||
  7882. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7883. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7884. }
  7885. return ret;
  7886. }
  7887. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7888. tls::session_t &session, socket_t sock,
  7889. bool server_certificate_verification,
  7890. time_t timeout_sec, time_t timeout_usec) {
  7891. using namespace tls;
  7892. if (!ctx) { return false; }
  7893. bool is_ip = is_ip_address(host);
  7894. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7895. // Chain verification happens during the handshake even for IP hosts; the
  7896. // certificate identity is verified post-handshake via verify_hostname()
  7897. set_verify_client(ctx, server_certificate_verification);
  7898. #endif
  7899. session = create_session(ctx, sock);
  7900. if (!session) { return false; }
  7901. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7902. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7903. // their identity is checked post-handshake below instead.
  7904. if (!is_ip) {
  7905. if (server_certificate_verification) {
  7906. set_hostname(session, host.c_str());
  7907. } else {
  7908. set_sni(session, host.c_str());
  7909. }
  7910. }
  7911. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7912. return false;
  7913. }
  7914. if (server_certificate_verification) {
  7915. if (get_verify_result(session) != 0) { return false; }
  7916. // Identity check against the peer certificate, post-handshake for all
  7917. // backends (same as SSLClient). For IP hosts this is the only identity
  7918. // verification since no hostname is bound during the handshake.
  7919. auto server_cert = get_peer_cert(session);
  7920. if (!server_cert) { return false; }
  7921. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7922. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7923. }
  7924. return true;
  7925. }
  7926. } // namespace detail
  7927. #endif // CPPHTTPLIB_SSL_ENABLED
  7928. /*
  7929. * Group 3: httplib namespace - Non-SSL public API implementations
  7930. */
  7931. inline void default_socket_options(socket_t sock) {
  7932. set_socket_opt(sock, SOL_SOCKET,
  7933. #ifdef SO_REUSEPORT
  7934. SO_REUSEPORT,
  7935. #else
  7936. SO_REUSEADDR,
  7937. #endif
  7938. 1);
  7939. }
  7940. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7941. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7942. sizeof(optval));
  7943. }
  7944. inline std::string get_bearer_token_auth(const Request &req) {
  7945. if (req.has_header("Authorization")) {
  7946. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7947. return req.get_header_value("Authorization")
  7948. .substr(bearer_header_prefix_len);
  7949. }
  7950. return "";
  7951. }
  7952. inline const char *status_message(int status) {
  7953. switch (status) {
  7954. case StatusCode::Continue_100: return "Continue";
  7955. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7956. case StatusCode::Processing_102: return "Processing";
  7957. case StatusCode::EarlyHints_103: return "Early Hints";
  7958. case StatusCode::OK_200: return "OK";
  7959. case StatusCode::Created_201: return "Created";
  7960. case StatusCode::Accepted_202: return "Accepted";
  7961. case StatusCode::NonAuthoritativeInformation_203:
  7962. return "Non-Authoritative Information";
  7963. case StatusCode::NoContent_204: return "No Content";
  7964. case StatusCode::ResetContent_205: return "Reset Content";
  7965. case StatusCode::PartialContent_206: return "Partial Content";
  7966. case StatusCode::MultiStatus_207: return "Multi-Status";
  7967. case StatusCode::AlreadyReported_208: return "Already Reported";
  7968. case StatusCode::IMUsed_226: return "IM Used";
  7969. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7970. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7971. case StatusCode::Found_302: return "Found";
  7972. case StatusCode::SeeOther_303: return "See Other";
  7973. case StatusCode::NotModified_304: return "Not Modified";
  7974. case StatusCode::UseProxy_305: return "Use Proxy";
  7975. case StatusCode::unused_306: return "unused";
  7976. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7977. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7978. case StatusCode::BadRequest_400: return "Bad Request";
  7979. case StatusCode::Unauthorized_401: return "Unauthorized";
  7980. case StatusCode::PaymentRequired_402: return "Payment Required";
  7981. case StatusCode::Forbidden_403: return "Forbidden";
  7982. case StatusCode::NotFound_404: return "Not Found";
  7983. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7984. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7985. case StatusCode::ProxyAuthenticationRequired_407:
  7986. return "Proxy Authentication Required";
  7987. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7988. case StatusCode::Conflict_409: return "Conflict";
  7989. case StatusCode::Gone_410: return "Gone";
  7990. case StatusCode::LengthRequired_411: return "Length Required";
  7991. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7992. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7993. case StatusCode::UriTooLong_414: return "URI Too Long";
  7994. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7995. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7996. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7997. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7998. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7999. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  8000. case StatusCode::Locked_423: return "Locked";
  8001. case StatusCode::FailedDependency_424: return "Failed Dependency";
  8002. case StatusCode::TooEarly_425: return "Too Early";
  8003. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  8004. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  8005. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  8006. case StatusCode::RequestHeaderFieldsTooLarge_431:
  8007. return "Request Header Fields Too Large";
  8008. case StatusCode::UnavailableForLegalReasons_451:
  8009. return "Unavailable For Legal Reasons";
  8010. case StatusCode::NotImplemented_501: return "Not Implemented";
  8011. case StatusCode::BadGateway_502: return "Bad Gateway";
  8012. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  8013. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  8014. case StatusCode::HttpVersionNotSupported_505:
  8015. return "HTTP Version Not Supported";
  8016. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  8017. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  8018. case StatusCode::LoopDetected_508: return "Loop Detected";
  8019. case StatusCode::NotExtended_510: return "Not Extended";
  8020. case StatusCode::NetworkAuthenticationRequired_511:
  8021. return "Network Authentication Required";
  8022. default:
  8023. case StatusCode::InternalServerError_500: return "Internal Server Error";
  8024. }
  8025. }
  8026. inline std::string to_string(const Error error) {
  8027. switch (error) {
  8028. case Error::Success: return "Success (no error)";
  8029. case Error::Unknown: return "Unknown";
  8030. case Error::Connection: return "Could not establish connection";
  8031. case Error::BindIPAddress: return "Failed to bind IP address";
  8032. case Error::Read: return "Failed to read connection";
  8033. case Error::Write: return "Failed to write connection";
  8034. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  8035. case Error::Canceled: return "Connection handling canceled";
  8036. case Error::SSLConnection: return "SSL connection failed";
  8037. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  8038. case Error::SSLServerVerification: return "SSL server verification failed";
  8039. case Error::SSLServerHostnameVerification:
  8040. return "SSL server hostname verification failed";
  8041. case Error::UnsupportedMultipartBoundaryChars:
  8042. return "Unsupported HTTP multipart boundary characters";
  8043. case Error::Compression: return "Compression failed";
  8044. case Error::ConnectionTimeout: return "Connection timed out";
  8045. case Error::ProxyConnection: return "Proxy connection failed";
  8046. case Error::ConnectionClosed: return "Connection closed by server";
  8047. case Error::Timeout: return "Read timeout";
  8048. case Error::ResourceExhaustion: return "Resource exhaustion";
  8049. case Error::TooManyFormDataFiles: return "Too many form data files";
  8050. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  8051. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  8052. case Error::ExceedMaxSocketDescriptorCount:
  8053. return "Exceeded maximum socket descriptor count";
  8054. case Error::InvalidRequestLine: return "Invalid request line";
  8055. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8056. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8057. case Error::InvalidHeaders: return "Invalid headers";
  8058. case Error::MultipartParsing: return "Multipart parsing failed";
  8059. case Error::OpenFile: return "Failed to open file";
  8060. case Error::Listen: return "Failed to listen on socket";
  8061. case Error::GetSockName: return "Failed to get socket name";
  8062. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8063. case Error::HTTPParsing: return "HTTP parsing failed";
  8064. case Error::InvalidRangeHeader: return "Invalid Range header";
  8065. default: break;
  8066. }
  8067. return "Invalid";
  8068. }
  8069. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8070. os << to_string(obj);
  8071. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8072. return os;
  8073. }
  8074. inline std::string hosted_at(const std::string &hostname) {
  8075. std::vector<std::string> addrs;
  8076. hosted_at(hostname, addrs);
  8077. if (addrs.empty()) { return std::string(); }
  8078. return addrs[0];
  8079. }
  8080. inline void hosted_at(const std::string &hostname,
  8081. std::vector<std::string> &addrs) {
  8082. struct addrinfo hints;
  8083. struct addrinfo *result;
  8084. memset(&hints, 0, sizeof(struct addrinfo));
  8085. hints.ai_family = AF_UNSPEC;
  8086. hints.ai_socktype = SOCK_STREAM;
  8087. hints.ai_protocol = 0;
  8088. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8089. &result, 0)) {
  8090. #if defined __linux__ && !defined __ANDROID__
  8091. res_init();
  8092. #endif
  8093. return;
  8094. }
  8095. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8096. for (auto rp = result; rp; rp = rp->ai_next) {
  8097. const auto &addr =
  8098. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8099. std::string ip;
  8100. auto dummy = -1;
  8101. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8102. dummy)) {
  8103. addrs.emplace_back(std::move(ip));
  8104. }
  8105. }
  8106. }
  8107. inline std::string encode_uri_component(const std::string &value) {
  8108. std::ostringstream escaped;
  8109. escaped.fill('0');
  8110. escaped << std::hex;
  8111. for (auto c : value) {
  8112. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8113. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8114. escaped << c;
  8115. } else {
  8116. escaped << std::uppercase;
  8117. escaped << '%' << std::setw(2)
  8118. << static_cast<int>(static_cast<unsigned char>(c));
  8119. escaped << std::nouppercase;
  8120. }
  8121. }
  8122. return escaped.str();
  8123. }
  8124. inline std::string encode_uri(const std::string &value) {
  8125. std::ostringstream escaped;
  8126. escaped.fill('0');
  8127. escaped << std::hex;
  8128. for (auto c : value) {
  8129. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8130. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8131. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8132. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8133. escaped << c;
  8134. } else {
  8135. escaped << std::uppercase;
  8136. escaped << '%' << std::setw(2)
  8137. << static_cast<int>(static_cast<unsigned char>(c));
  8138. escaped << std::nouppercase;
  8139. }
  8140. }
  8141. return escaped.str();
  8142. }
  8143. inline std::string decode_uri_component(const std::string &value) {
  8144. std::string result;
  8145. for (size_t i = 0; i < value.size(); i++) {
  8146. if (value[i] == '%' && i + 2 < value.size()) {
  8147. auto val = 0;
  8148. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8149. result += static_cast<char>(val);
  8150. i += 2;
  8151. } else {
  8152. result += value[i];
  8153. }
  8154. } else {
  8155. result += value[i];
  8156. }
  8157. }
  8158. return result;
  8159. }
  8160. inline std::string decode_uri(const std::string &value) {
  8161. std::string result;
  8162. for (size_t i = 0; i < value.size(); i++) {
  8163. if (value[i] == '%' && i + 2 < value.size()) {
  8164. auto val = 0;
  8165. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8166. result += static_cast<char>(val);
  8167. i += 2;
  8168. } else {
  8169. result += value[i];
  8170. }
  8171. } else {
  8172. result += value[i];
  8173. }
  8174. }
  8175. return result;
  8176. }
  8177. inline std::string encode_path_component(const std::string &component) {
  8178. std::string result;
  8179. result.reserve(component.size() * 3);
  8180. for (size_t i = 0; i < component.size(); i++) {
  8181. auto c = static_cast<unsigned char>(component[i]);
  8182. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8183. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8184. c == '_' || c == '~') {
  8185. result += static_cast<char>(c);
  8186. }
  8187. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8188. // "," / ";" / "="
  8189. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8190. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8191. c == '=') {
  8192. result += static_cast<char>(c);
  8193. }
  8194. // Colon is allowed in path segments except first segment
  8195. else if (c == ':') {
  8196. result += static_cast<char>(c);
  8197. }
  8198. // @ is allowed in path
  8199. else if (c == '@') {
  8200. result += static_cast<char>(c);
  8201. } else {
  8202. result += '%';
  8203. char hex[3];
  8204. snprintf(hex, sizeof(hex), "%02X", c);
  8205. result.append(hex, 2);
  8206. }
  8207. }
  8208. return result;
  8209. }
  8210. inline std::string decode_path_component(const std::string &component) {
  8211. std::string result;
  8212. result.reserve(component.size());
  8213. for (size_t i = 0; i < component.size(); i++) {
  8214. if (component[i] == '%' && i + 1 < component.size()) {
  8215. if (component[i + 1] == 'u') {
  8216. // Unicode %uXXXX encoding
  8217. auto val = 0;
  8218. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8219. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8220. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8221. char buff[4];
  8222. size_t len = detail::to_utf8(val, buff);
  8223. if (len > 0) { result.append(buff, len); }
  8224. i += 5; // 'u0000'
  8225. } else {
  8226. result += component[i];
  8227. }
  8228. } else {
  8229. // Standard %XX encoding
  8230. auto val = 0;
  8231. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8232. // 2 digits hex codes
  8233. result += static_cast<char>(val);
  8234. i += 2; // 'XX'
  8235. } else {
  8236. result += component[i];
  8237. }
  8238. }
  8239. } else {
  8240. result += component[i];
  8241. }
  8242. }
  8243. return result;
  8244. }
  8245. inline std::string encode_query_component(const std::string &component,
  8246. bool space_as_plus) {
  8247. std::string result;
  8248. result.reserve(component.size() * 3);
  8249. for (size_t i = 0; i < component.size(); i++) {
  8250. auto c = static_cast<unsigned char>(component[i]);
  8251. // Unreserved characters per RFC 3986
  8252. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8253. c == '_' || c == '~') {
  8254. result += static_cast<char>(c);
  8255. }
  8256. // Space handling
  8257. else if (c == ' ') {
  8258. if (space_as_plus) {
  8259. result += '+';
  8260. } else {
  8261. result += "%20";
  8262. }
  8263. }
  8264. // Plus sign handling
  8265. else if (c == '+') {
  8266. if (space_as_plus) {
  8267. result += "%2B";
  8268. } else {
  8269. result += static_cast<char>(c);
  8270. }
  8271. }
  8272. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8273. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8274. c == '*' || c == ',' || c == ';') {
  8275. result += static_cast<char>(c);
  8276. }
  8277. // Colon and @ are allowed in query
  8278. else if (c == ':' || c == '@') {
  8279. result += static_cast<char>(c);
  8280. }
  8281. // Forward slash is allowed in query values
  8282. else if (c == '/') {
  8283. result += static_cast<char>(c);
  8284. }
  8285. // Question mark is allowed in query values (after first ?)
  8286. else if (c == '?') {
  8287. result += static_cast<char>(c);
  8288. } else {
  8289. result += '%';
  8290. char hex[3];
  8291. snprintf(hex, sizeof(hex), "%02X", c);
  8292. result.append(hex, 2);
  8293. }
  8294. }
  8295. return result;
  8296. }
  8297. inline std::string decode_query_component(const std::string &component,
  8298. bool plus_as_space) {
  8299. std::string result;
  8300. result.reserve(component.size());
  8301. for (size_t i = 0; i < component.size(); i++) {
  8302. if (component[i] == '%' && i + 2 < component.size()) {
  8303. auto val = 0;
  8304. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8305. result += static_cast<char>(val);
  8306. i += 2;
  8307. } else {
  8308. result += component[i];
  8309. }
  8310. } else if (component[i] == '+' && plus_as_space) {
  8311. result += ' '; // + becomes space in form-urlencoded
  8312. } else {
  8313. result += component[i];
  8314. }
  8315. }
  8316. return result;
  8317. }
  8318. inline std::string sanitize_filename(const std::string &filename) {
  8319. // Extract basename: find the last path separator (/ or \)
  8320. auto pos = filename.find_last_of("/\\");
  8321. auto result =
  8322. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8323. // Strip null bytes
  8324. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8325. // Trim whitespace
  8326. {
  8327. auto start = result.find_first_not_of(" \t");
  8328. auto end = result.find_last_not_of(" \t");
  8329. result = (start == std::string::npos)
  8330. ? ""
  8331. : result.substr(start, end - start + 1);
  8332. }
  8333. // Reject . and ..
  8334. if (result == "." || result == "..") { return ""; }
  8335. return result;
  8336. }
  8337. inline std::string append_query_params(const std::string &path,
  8338. const Params &params) {
  8339. std::string path_with_query = path;
  8340. thread_local const std::regex re("[^?]+\\?.*");
  8341. auto delm = std::regex_match(path, re) ? '&' : '?';
  8342. path_with_query += delm + detail::params_to_query_str(params);
  8343. return path_with_query;
  8344. }
  8345. // Header utilities
  8346. inline std::pair<std::string, std::string>
  8347. make_range_header(const Ranges &ranges) {
  8348. std::string field = "bytes=";
  8349. auto i = 0;
  8350. for (const auto &r : ranges) {
  8351. if (i != 0) { field += ", "; }
  8352. if (r.first != -1) { field += std::to_string(r.first); }
  8353. field += '-';
  8354. if (r.second != -1) { field += std::to_string(r.second); }
  8355. i++;
  8356. }
  8357. return std::make_pair("Range", std::move(field));
  8358. }
  8359. inline std::pair<std::string, std::string>
  8360. make_basic_authentication_header(const std::string &username,
  8361. const std::string &password, bool is_proxy) {
  8362. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8363. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8364. return std::make_pair(key, std::move(field));
  8365. }
  8366. inline std::pair<std::string, std::string>
  8367. make_bearer_token_authentication_header(const std::string &token,
  8368. bool is_proxy = false) {
  8369. auto field = "Bearer " + token;
  8370. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8371. return std::make_pair(key, std::move(field));
  8372. }
  8373. // Request implementation
  8374. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8375. size_t id) const {
  8376. return detail::get_header_value_u64(headers, key, def, id);
  8377. }
  8378. inline bool Request::has_header(const std::string &key) const {
  8379. return detail::has_header(headers, key);
  8380. }
  8381. inline std::string Request::get_header_value(const std::string &key,
  8382. const char *def, size_t id) const {
  8383. return detail::get_header_value(headers, key, def, id);
  8384. }
  8385. inline size_t Request::get_header_value_count(const std::string &key) const {
  8386. return detail::get_header_value_count(headers, key);
  8387. }
  8388. inline void Request::set_header(const std::string &key,
  8389. const std::string &val) {
  8390. detail::set_header(headers, key, val);
  8391. }
  8392. inline bool Request::has_trailer(const std::string &key) const {
  8393. return trailers.find(key) != trailers.end();
  8394. }
  8395. inline std::string Request::get_trailer_value(const std::string &key,
  8396. size_t id) const {
  8397. return detail::get_multimap_value(trailers, key, id);
  8398. }
  8399. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8400. auto r = trailers.equal_range(key);
  8401. return static_cast<size_t>(std::distance(r.first, r.second));
  8402. }
  8403. inline bool Request::has_param(const std::string &key) const {
  8404. return params.find(key) != params.end();
  8405. }
  8406. inline std::string Request::get_param_value(const std::string &key,
  8407. size_t id) const {
  8408. return detail::get_multimap_value(params, key, id);
  8409. }
  8410. inline std::vector<std::string>
  8411. Request::get_param_values(const std::string &key) const {
  8412. auto rng = params.equal_range(key);
  8413. std::vector<std::string> values;
  8414. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8415. for (auto it = rng.first; it != rng.second; ++it) {
  8416. values.push_back(it->second);
  8417. }
  8418. return values;
  8419. }
  8420. inline size_t Request::get_param_value_count(const std::string &key) const {
  8421. auto r = params.equal_range(key);
  8422. return static_cast<size_t>(std::distance(r.first, r.second));
  8423. }
  8424. inline bool Request::is_multipart_form_data() const {
  8425. const auto &content_type = get_header_value("Content-Type");
  8426. return detail::extract_media_type(content_type) == "multipart/form-data";
  8427. }
  8428. // Multipart FormData implementation
  8429. inline std::string MultipartFormData::get_field(const std::string &key,
  8430. size_t id) const {
  8431. auto rng = fields.equal_range(key);
  8432. auto it = rng.first;
  8433. std::advance(it, static_cast<ssize_t>(id));
  8434. if (it != rng.second) { return it->second.content; }
  8435. return std::string();
  8436. }
  8437. inline std::vector<std::string>
  8438. MultipartFormData::get_fields(const std::string &key) const {
  8439. std::vector<std::string> values;
  8440. auto rng = fields.equal_range(key);
  8441. for (auto it = rng.first; it != rng.second; it++) {
  8442. values.push_back(it->second.content);
  8443. }
  8444. return values;
  8445. }
  8446. inline bool MultipartFormData::has_field(const std::string &key) const {
  8447. return fields.find(key) != fields.end();
  8448. }
  8449. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8450. auto r = fields.equal_range(key);
  8451. return static_cast<size_t>(std::distance(r.first, r.second));
  8452. }
  8453. inline FormData MultipartFormData::get_file(const std::string &key,
  8454. size_t id) const {
  8455. return detail::get_multimap_value(files, key, id);
  8456. }
  8457. inline std::vector<FormData>
  8458. MultipartFormData::get_files(const std::string &key) const {
  8459. std::vector<FormData> values;
  8460. auto rng = files.equal_range(key);
  8461. for (auto it = rng.first; it != rng.second; it++) {
  8462. values.push_back(it->second);
  8463. }
  8464. return values;
  8465. }
  8466. inline bool MultipartFormData::has_file(const std::string &key) const {
  8467. return files.find(key) != files.end();
  8468. }
  8469. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8470. auto r = files.equal_range(key);
  8471. return static_cast<size_t>(std::distance(r.first, r.second));
  8472. }
  8473. // Multipart FormData writer implementation
  8474. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8475. return detail::is_multipart_boundary_chars_valid(boundary);
  8476. }
  8477. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8478. : boundary_(detail::make_multipart_data_boundary()) {}
  8479. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8480. : boundary_(std::move(boundary)) {}
  8481. inline const std::string &MultipartFormDataWriter::boundary() const {
  8482. return boundary_;
  8483. }
  8484. inline std::string MultipartFormDataWriter::content_type() const {
  8485. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8486. }
  8487. inline std::string
  8488. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8489. return detail::serialize_multipart_formdata(items, boundary_);
  8490. }
  8491. inline size_t MultipartFormDataWriter::content_length(
  8492. const UploadFormDataItems &items) const {
  8493. return detail::get_multipart_content_length(items, boundary_);
  8494. }
  8495. inline std::string
  8496. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8497. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8498. }
  8499. inline std::string MultipartFormDataWriter::item_end() {
  8500. return detail::serialize_multipart_formdata_item_end();
  8501. }
  8502. inline std::string MultipartFormDataWriter::finish() const {
  8503. return detail::serialize_multipart_formdata_finish(boundary_);
  8504. }
  8505. // Response implementation
  8506. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8507. size_t id) const {
  8508. return detail::get_header_value_u64(headers, key, def, id);
  8509. }
  8510. inline bool Response::has_header(const std::string &key) const {
  8511. return headers.find(key) != headers.end();
  8512. }
  8513. inline std::string Response::get_header_value(const std::string &key,
  8514. const char *def,
  8515. size_t id) const {
  8516. return detail::get_header_value(headers, key, def, id);
  8517. }
  8518. inline size_t Response::get_header_value_count(const std::string &key) const {
  8519. return detail::get_header_value_count(headers, key);
  8520. }
  8521. inline void Response::set_header(const std::string &key,
  8522. const std::string &val) {
  8523. detail::set_header(headers, key, val);
  8524. }
  8525. inline bool Response::has_trailer(const std::string &key) const {
  8526. return trailers.find(key) != trailers.end();
  8527. }
  8528. inline std::string Response::get_trailer_value(const std::string &key,
  8529. size_t id) const {
  8530. return detail::get_multimap_value(trailers, key, id);
  8531. }
  8532. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8533. auto r = trailers.equal_range(key);
  8534. return static_cast<size_t>(std::distance(r.first, r.second));
  8535. }
  8536. inline void Response::set_redirect(const std::string &url, int stat) {
  8537. if (detail::fields::is_field_value(url)) {
  8538. set_header("Location", url);
  8539. if (300 <= stat && stat < 400) {
  8540. this->status = stat;
  8541. } else {
  8542. this->status = StatusCode::Found_302;
  8543. }
  8544. }
  8545. }
  8546. inline void Response::set_content(const char *s, size_t n,
  8547. const std::string &content_type) {
  8548. body.assign(s, n);
  8549. auto rng = headers.equal_range("Content-Type");
  8550. headers.erase(rng.first, rng.second);
  8551. set_header("Content-Type", content_type);
  8552. }
  8553. inline void Response::set_content(const std::string &s,
  8554. const std::string &content_type) {
  8555. set_content(s.data(), s.size(), content_type);
  8556. }
  8557. inline void Response::set_content(std::string &&s,
  8558. const std::string &content_type) {
  8559. body = std::move(s);
  8560. auto rng = headers.equal_range("Content-Type");
  8561. headers.erase(rng.first, rng.second);
  8562. set_header("Content-Type", content_type);
  8563. }
  8564. inline void Response::set_content_provider(
  8565. size_t in_length, const std::string &content_type, ContentProvider provider,
  8566. ContentProviderResourceReleaser resource_releaser) {
  8567. set_header("Content-Type", content_type);
  8568. content_length_ = in_length;
  8569. if (in_length > 0) { content_provider_ = std::move(provider); }
  8570. content_provider_resource_releaser_ = std::move(resource_releaser);
  8571. is_chunked_content_provider_ = false;
  8572. }
  8573. inline void Response::set_content_provider(
  8574. const std::string &content_type, ContentProviderWithoutLength provider,
  8575. ContentProviderResourceReleaser resource_releaser) {
  8576. set_header("Content-Type", content_type);
  8577. content_length_ = 0;
  8578. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8579. content_provider_resource_releaser_ = std::move(resource_releaser);
  8580. is_chunked_content_provider_ = false;
  8581. }
  8582. inline void Response::set_chunked_content_provider(
  8583. const std::string &content_type, ContentProviderWithoutLength provider,
  8584. ContentProviderResourceReleaser resource_releaser) {
  8585. set_header("Content-Type", content_type);
  8586. content_length_ = 0;
  8587. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8588. content_provider_resource_releaser_ = std::move(resource_releaser);
  8589. is_chunked_content_provider_ = true;
  8590. }
  8591. inline void Response::set_file_content(const std::string &path,
  8592. const std::string &content_type) {
  8593. file_content_path_ = path;
  8594. file_content_content_type_ = content_type;
  8595. }
  8596. inline void Response::set_file_content(const std::string &path) {
  8597. file_content_path_ = path;
  8598. }
  8599. // Result implementation
  8600. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8601. size_t def,
  8602. size_t id) const {
  8603. return detail::get_header_value_u64(request_headers_, key, def, id);
  8604. }
  8605. inline bool Result::has_request_header(const std::string &key) const {
  8606. return request_headers_.find(key) != request_headers_.end();
  8607. }
  8608. inline std::string Result::get_request_header_value(const std::string &key,
  8609. const char *def,
  8610. size_t id) const {
  8611. return detail::get_header_value(request_headers_, key, def, id);
  8612. }
  8613. inline size_t
  8614. Result::get_request_header_value_count(const std::string &key) const {
  8615. auto r = request_headers_.equal_range(key);
  8616. return static_cast<size_t>(std::distance(r.first, r.second));
  8617. }
  8618. // Stream implementation
  8619. inline ssize_t Stream::write(const char *ptr) {
  8620. return write(ptr, strlen(ptr));
  8621. }
  8622. inline ssize_t Stream::write(const std::string &s) {
  8623. return write(s.data(), s.size());
  8624. }
  8625. // BodyReader implementation
  8626. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8627. if (!stream) {
  8628. last_error = Error::Connection;
  8629. return -1;
  8630. }
  8631. if (eof) { return 0; }
  8632. if (!chunked) {
  8633. // Content-Length based reading
  8634. if (has_content_length && bytes_read >= content_length) {
  8635. eof = true;
  8636. return 0;
  8637. }
  8638. auto to_read = len;
  8639. if (has_content_length) {
  8640. auto remaining = content_length - bytes_read;
  8641. to_read = (std::min)(len, remaining);
  8642. }
  8643. auto n = stream->read(buf, to_read);
  8644. if (n < 0) {
  8645. last_error = stream->get_error();
  8646. if (last_error == Error::Success) { last_error = Error::Read; }
  8647. eof = true;
  8648. return n;
  8649. }
  8650. if (n == 0) {
  8651. // Unexpected EOF before content_length
  8652. last_error = stream->get_error();
  8653. if (last_error == Error::Success) { last_error = Error::Read; }
  8654. eof = true;
  8655. return 0;
  8656. }
  8657. bytes_read += static_cast<size_t>(n);
  8658. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8659. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8660. last_error = Error::ExceedMaxPayloadSize;
  8661. eof = true;
  8662. return -1;
  8663. }
  8664. return n;
  8665. }
  8666. // Chunked transfer encoding: delegate to shared decoder instance.
  8667. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8668. size_t chunk_offset = 0;
  8669. size_t chunk_total = 0;
  8670. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8671. if (n < 0) {
  8672. last_error = stream->get_error();
  8673. if (last_error == Error::Success) { last_error = Error::Read; }
  8674. eof = true;
  8675. return n;
  8676. }
  8677. if (n == 0) {
  8678. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8679. eof = true;
  8680. return 0;
  8681. }
  8682. bytes_read += static_cast<size_t>(n);
  8683. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8684. last_error = Error::ExceedMaxPayloadSize;
  8685. eof = true;
  8686. return -1;
  8687. }
  8688. return n;
  8689. }
  8690. // ThreadPool implementation
  8691. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8692. time_t idle_timeout_sec)
  8693. : base_thread_count_(n), max_queued_requests_(mqr),
  8694. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8695. shutdown_(false) {
  8696. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8697. if (max_n != 0 && max_n < n) {
  8698. std::string msg = "max_threads must be >= base_threads";
  8699. throw std::invalid_argument(msg);
  8700. }
  8701. #endif
  8702. max_thread_count_ = max_n == 0 ? n : max_n;
  8703. threads_.reserve(base_thread_count_);
  8704. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8705. try {
  8706. #endif
  8707. for (size_t i = 0; i < base_thread_count_; i++) {
  8708. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8709. }
  8710. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8711. } catch (...) {
  8712. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8713. // signal the workers we already spawned to exit and join them so the
  8714. // vector destructor does not see joinable threads (which would call
  8715. // std::terminate). Then rethrow so the caller learns of the failure.
  8716. {
  8717. std::unique_lock<std::mutex> lock(mutex_);
  8718. shutdown_ = true;
  8719. }
  8720. cond_.notify_all();
  8721. for (auto &t : threads_) {
  8722. if (t.joinable()) { t.join(); }
  8723. }
  8724. throw;
  8725. }
  8726. #endif
  8727. }
  8728. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8729. {
  8730. std::unique_lock<std::mutex> lock(mutex_);
  8731. if (shutdown_) { return false; }
  8732. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8733. return false;
  8734. }
  8735. jobs_.push_back(std::move(fn));
  8736. // Spawn a dynamic thread if no idle threads and under max
  8737. if (idle_thread_count_ == 0 &&
  8738. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8739. cleanup_finished_threads();
  8740. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8741. }
  8742. }
  8743. cond_.notify_one();
  8744. return true;
  8745. }
  8746. inline void ThreadPool::shutdown() {
  8747. {
  8748. std::unique_lock<std::mutex> lock(mutex_);
  8749. shutdown_ = true;
  8750. }
  8751. cond_.notify_all();
  8752. for (auto &t : threads_) {
  8753. if (t.joinable()) { t.join(); }
  8754. }
  8755. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8756. // with worker threads that call move_to_finished() concurrently.
  8757. std::list<std::thread> remaining_dynamic;
  8758. {
  8759. std::unique_lock<std::mutex> lock(mutex_);
  8760. remaining_dynamic = std::move(dynamic_threads_);
  8761. }
  8762. for (auto &t : remaining_dynamic) {
  8763. if (t.joinable()) { t.join(); }
  8764. }
  8765. std::unique_lock<std::mutex> lock(mutex_);
  8766. cleanup_finished_threads();
  8767. }
  8768. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8769. // Must be called with mutex_ held
  8770. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8771. if (it->get_id() == id) {
  8772. finished_threads_.push_back(std::move(*it));
  8773. dynamic_threads_.erase(it);
  8774. return;
  8775. }
  8776. }
  8777. }
  8778. inline void ThreadPool::cleanup_finished_threads() {
  8779. // Must be called with mutex_ held
  8780. for (auto &t : finished_threads_) {
  8781. if (t.joinable()) { t.join(); }
  8782. }
  8783. finished_threads_.clear();
  8784. }
  8785. inline void ThreadPool::worker(bool is_dynamic) {
  8786. for (;;) {
  8787. std::function<void()> fn;
  8788. {
  8789. std::unique_lock<std::mutex> lock(mutex_);
  8790. idle_thread_count_++;
  8791. if (is_dynamic) {
  8792. auto has_work =
  8793. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8794. [&] { return !jobs_.empty() || shutdown_; });
  8795. if (!has_work) {
  8796. // Timed out with no work - exit this dynamic thread
  8797. idle_thread_count_--;
  8798. move_to_finished(std::this_thread::get_id());
  8799. break;
  8800. }
  8801. } else {
  8802. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8803. }
  8804. idle_thread_count_--;
  8805. if (shutdown_ && jobs_.empty()) { break; }
  8806. fn = std::move(jobs_.front());
  8807. jobs_.pop_front();
  8808. }
  8809. assert(true == static_cast<bool>(fn));
  8810. fn();
  8811. }
  8812. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8813. !defined(LIBRESSL_VERSION_NUMBER)
  8814. OPENSSL_thread_stop();
  8815. #endif
  8816. }
  8817. /*
  8818. * Group 1 (continued): detail namespace - Stream implementations
  8819. */
  8820. namespace detail {
  8821. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8822. time_t timeout_sec, time_t timeout_usec,
  8823. time_t &actual_timeout_sec,
  8824. time_t &actual_timeout_usec) {
  8825. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8826. auto actual_timeout_msec =
  8827. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8828. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8829. actual_timeout_sec = actual_timeout_msec / 1000;
  8830. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8831. }
  8832. // Socket stream implementation
  8833. inline SocketStream::SocketStream(
  8834. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8835. time_t write_timeout_sec, time_t write_timeout_usec,
  8836. time_t max_timeout_msec,
  8837. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8838. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8839. read_timeout_usec_(read_timeout_usec),
  8840. write_timeout_sec_(write_timeout_sec),
  8841. write_timeout_usec_(write_timeout_usec),
  8842. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8843. read_buff_(read_buff_size_, 0) {}
  8844. inline SocketStream::~SocketStream() = default;
  8845. inline bool SocketStream::is_readable() const {
  8846. return read_buff_off_ < read_buff_content_size_;
  8847. }
  8848. inline bool SocketStream::wait_readable() const {
  8849. if (max_timeout_msec_ <= 0) {
  8850. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8851. }
  8852. time_t read_timeout_sec;
  8853. time_t read_timeout_usec;
  8854. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8855. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8856. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8857. }
  8858. inline bool SocketStream::wait_writable() const {
  8859. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8860. }
  8861. inline bool SocketStream::is_peer_alive() const {
  8862. return detail::is_socket_alive(sock_);
  8863. }
  8864. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8865. #ifdef _WIN32
  8866. size =
  8867. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8868. #else
  8869. size = (std::min)(size,
  8870. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8871. #endif
  8872. if (read_buff_off_ < read_buff_content_size_) {
  8873. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8874. if (size <= remaining_size) {
  8875. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8876. read_buff_off_ += size;
  8877. return static_cast<ssize_t>(size);
  8878. } else {
  8879. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8880. read_buff_off_ += remaining_size;
  8881. return static_cast<ssize_t>(remaining_size);
  8882. }
  8883. }
  8884. if (!wait_readable()) {
  8885. error_ = Error::Timeout;
  8886. return -1;
  8887. }
  8888. read_buff_off_ = 0;
  8889. read_buff_content_size_ = 0;
  8890. if (size < read_buff_size_) {
  8891. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8892. CPPHTTPLIB_RECV_FLAGS);
  8893. if (n <= 0) {
  8894. if (n == 0) {
  8895. error_ = Error::ConnectionClosed;
  8896. } else {
  8897. error_ = Error::Read;
  8898. }
  8899. return n;
  8900. } else if (n <= static_cast<ssize_t>(size)) {
  8901. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8902. return n;
  8903. } else {
  8904. memcpy(ptr, read_buff_.data(), size);
  8905. read_buff_off_ = size;
  8906. read_buff_content_size_ = static_cast<size_t>(n);
  8907. return static_cast<ssize_t>(size);
  8908. }
  8909. } else {
  8910. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8911. if (n <= 0) {
  8912. if (n == 0) {
  8913. error_ = Error::ConnectionClosed;
  8914. } else {
  8915. error_ = Error::Read;
  8916. }
  8917. }
  8918. return n;
  8919. }
  8920. }
  8921. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8922. if (!wait_writable()) { return -1; }
  8923. #if defined(_WIN32) && !defined(_WIN64)
  8924. size =
  8925. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8926. #endif
  8927. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8928. }
  8929. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8930. int &port) const {
  8931. return detail::get_remote_ip_and_port(sock_, ip, port);
  8932. }
  8933. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8934. int &port) const {
  8935. return detail::get_local_ip_and_port(sock_, ip, port);
  8936. }
  8937. inline socket_t SocketStream::socket() const { return sock_; }
  8938. inline time_t SocketStream::duration() const {
  8939. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8940. std::chrono::steady_clock::now() - start_time_)
  8941. .count();
  8942. }
  8943. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8944. read_timeout_sec_ = sec;
  8945. read_timeout_usec_ = usec;
  8946. }
  8947. // Buffer stream implementation
  8948. inline bool BufferStream::is_readable() const { return true; }
  8949. inline bool BufferStream::wait_readable() const { return true; }
  8950. inline bool BufferStream::wait_writable() const { return true; }
  8951. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8952. #if defined(_MSC_VER) && _MSC_VER < 1910
  8953. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8954. #else
  8955. auto len_read = buffer.copy(ptr, size, position);
  8956. #endif
  8957. position += static_cast<size_t>(len_read);
  8958. return static_cast<ssize_t>(len_read);
  8959. }
  8960. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8961. buffer.append(ptr, size);
  8962. return static_cast<ssize_t>(size);
  8963. }
  8964. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8965. int & /*port*/) const {}
  8966. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8967. int & /*port*/) const {}
  8968. inline socket_t BufferStream::socket() const { return 0; }
  8969. inline time_t BufferStream::duration() const { return 0; }
  8970. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8971. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8972. : MatcherBase(pattern) {
  8973. constexpr const char marker[] = "/:";
  8974. // One past the last ending position of a path param substring
  8975. std::size_t last_param_end = 0;
  8976. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8977. // Needed to ensure that parameter names are unique during matcher
  8978. // construction
  8979. // If exceptions are disabled, only last duplicate path
  8980. // parameter will be set
  8981. std::unordered_set<std::string> param_name_set;
  8982. #endif
  8983. while (true) {
  8984. const auto marker_pos = pattern.find(
  8985. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8986. if (marker_pos == std::string::npos) { break; }
  8987. static_fragments_.push_back(
  8988. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8989. const auto param_name_start = marker_pos + str_len(marker);
  8990. auto sep_pos = pattern.find(separator, param_name_start);
  8991. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8992. auto param_name =
  8993. pattern.substr(param_name_start, sep_pos - param_name_start);
  8994. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8995. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8996. std::string msg = "Encountered path parameter '" + param_name +
  8997. "' multiple times in route pattern '" + pattern + "'.";
  8998. throw std::invalid_argument(msg);
  8999. }
  9000. #endif
  9001. param_names_.push_back(std::move(param_name));
  9002. last_param_end = sep_pos + 1;
  9003. }
  9004. if (last_param_end < pattern.length()) {
  9005. static_fragments_.push_back(pattern.substr(last_param_end));
  9006. }
  9007. }
  9008. inline bool PathParamsMatcher::match(Request &request) const {
  9009. request.matches = std::smatch();
  9010. request.path_params.clear();
  9011. request.path_params.reserve(param_names_.size());
  9012. // One past the position at which the path matched the pattern last time
  9013. std::size_t starting_pos = 0;
  9014. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  9015. const auto &fragment = static_fragments_[i];
  9016. if (starting_pos + fragment.length() > request.path.length()) {
  9017. return false;
  9018. }
  9019. // Avoid unnecessary allocation by using strncmp instead of substr +
  9020. // comparison
  9021. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  9022. fragment.length()) != 0) {
  9023. return false;
  9024. }
  9025. starting_pos += fragment.length();
  9026. // Should only happen when we have a static fragment after a param
  9027. // Example: '/users/:id/subscriptions'
  9028. // The 'subscriptions' fragment here does not have a corresponding param
  9029. if (i >= param_names_.size()) { continue; }
  9030. auto sep_pos = request.path.find(separator, starting_pos);
  9031. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  9032. const auto &param_name = param_names_[i];
  9033. request.path_params.emplace(
  9034. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  9035. // Mark everything up to '/' as matched
  9036. starting_pos = sep_pos + 1;
  9037. }
  9038. // Returns false if the path is longer than the pattern
  9039. return starting_pos >= request.path.length();
  9040. }
  9041. inline bool RegexMatcher::match(Request &request) const {
  9042. request.path_params.clear();
  9043. return std::regex_match(request.path, request.matches, regex_);
  9044. }
  9045. // Enclose IPv6 address in brackets if needed
  9046. inline std::string prepare_host_string(const std::string &host) {
  9047. // Enclose IPv6 address in brackets (but not if already enclosed)
  9048. if (host.find(':') == std::string::npos ||
  9049. (!host.empty() && host[0] == '[')) {
  9050. // IPv4, hostname, or already bracketed IPv6
  9051. return host;
  9052. } else {
  9053. // IPv6 address without brackets
  9054. return "[" + host + "]";
  9055. }
  9056. }
  9057. inline std::string make_host_and_port_string(const std::string &host, int port,
  9058. bool is_ssl) {
  9059. auto result = prepare_host_string(host);
  9060. // Append port if not default
  9061. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9062. ; // do nothing
  9063. } else {
  9064. result += ":" + std::to_string(port);
  9065. }
  9066. return result;
  9067. }
  9068. // Create "host:port" string always including port number (for CONNECT method)
  9069. inline std::string
  9070. make_host_and_port_string_always_port(const std::string &host, int port) {
  9071. return prepare_host_string(host) + ":" + std::to_string(port);
  9072. }
  9073. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9074. NormalizedTarget normalize_target(const std::string &host);
  9075. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9076. bool host_matches_no_proxy(const NormalizedTarget &target,
  9077. const std::vector<NoProxyEntry> &entries);
  9078. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9079. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9080. if (prefix_bits == 0) { return true; }
  9081. int full_bytes = prefix_bits / 8;
  9082. int rem_bits = prefix_bits % 8;
  9083. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9084. static_cast<size_t>(full_bytes)) != 0) {
  9085. return false;
  9086. }
  9087. if (rem_bits == 0) { return true; }
  9088. auto i = static_cast<size_t>(full_bytes);
  9089. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9090. return (ip[i] & mask) == (net[i] & mask);
  9091. }
  9092. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9093. if (token.empty()) { return false; }
  9094. if (token == "*") {
  9095. out.kind = NoProxyKind::Wildcard;
  9096. return true;
  9097. }
  9098. auto slash = token.find('/');
  9099. std::string addr_part =
  9100. (slash == std::string::npos) ? token : token.substr(0, slash);
  9101. std::string prefix_part =
  9102. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9103. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9104. // don't silently treat it as a /32 (or /128).
  9105. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9106. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9107. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9108. // when brackets are present.
  9109. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9110. addr_part.back() == ']';
  9111. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9112. if (!bracketed) {
  9113. struct in_addr v4;
  9114. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9115. int prefix = 32;
  9116. if (!prefix_part.empty()) {
  9117. auto r = from_chars(prefix_part.data(),
  9118. prefix_part.data() + prefix_part.size(), prefix);
  9119. if (r.ec != std::errc{} ||
  9120. r.ptr != prefix_part.data() + prefix_part.size()) {
  9121. return false;
  9122. }
  9123. if (prefix < 0 || prefix > 32) { return false; }
  9124. }
  9125. out.kind = NoProxyKind::IPv4Cidr;
  9126. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9127. out.prefix_bits = prefix;
  9128. return true;
  9129. }
  9130. }
  9131. struct in6_addr v6;
  9132. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9133. int prefix = 128;
  9134. if (!prefix_part.empty()) {
  9135. auto r = from_chars(prefix_part.data(),
  9136. prefix_part.data() + prefix_part.size(), prefix);
  9137. if (r.ec != std::errc{} ||
  9138. r.ptr != prefix_part.data() + prefix_part.size()) {
  9139. return false;
  9140. }
  9141. if (prefix < 0 || prefix > 128) { return false; }
  9142. }
  9143. out.kind = NoProxyKind::IPv6Cidr;
  9144. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9145. out.prefix_bits = prefix;
  9146. return true;
  9147. }
  9148. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9149. // the entry is malformed — don't fall through to the hostname branch.
  9150. if (bracketed) { return false; }
  9151. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9152. if (slash != std::string::npos) { return false; }
  9153. // Port-specific entries (host:port) are not supported.
  9154. if (token.find(':') != std::string::npos) { return false; }
  9155. std::string hostname = case_ignore::to_lower(token);
  9156. while (!hostname.empty() && hostname.front() == '.') {
  9157. hostname.erase(hostname.begin());
  9158. }
  9159. while (!hostname.empty() && hostname.back() == '.') {
  9160. hostname.pop_back();
  9161. }
  9162. if (hostname.empty()) { return false; }
  9163. out.kind = NoProxyKind::HostnameSuffix;
  9164. out.hostname_pattern = std::move(hostname);
  9165. return true;
  9166. }
  9167. inline NormalizedTarget normalize_target(const std::string &host) {
  9168. NormalizedTarget t;
  9169. std::string h = host;
  9170. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9171. h = h.substr(1, h.size() - 2);
  9172. }
  9173. // Strip a single trailing dot so "example.com." canonicalizes to
  9174. // "example.com".
  9175. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9176. t.hostname = case_ignore::to_lower(h);
  9177. if (!t.hostname.empty()) {
  9178. struct in_addr v4;
  9179. struct in6_addr v6;
  9180. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9181. t.is_ipv4 = true;
  9182. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9183. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9184. t.is_ipv6 = true;
  9185. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9186. }
  9187. }
  9188. return t;
  9189. }
  9190. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9191. const std::vector<NoProxyEntry> &entries) {
  9192. if (target.hostname.empty()) { return false; }
  9193. for (const auto &e : entries) {
  9194. switch (e.kind) {
  9195. case NoProxyKind::Wildcard: return true;
  9196. case NoProxyKind::IPv4Cidr:
  9197. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9198. return true;
  9199. }
  9200. break;
  9201. case NoProxyKind::IPv6Cidr:
  9202. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9203. return true;
  9204. }
  9205. break;
  9206. case NoProxyKind::HostnameSuffix:
  9207. if (target.is_ipv4 || target.is_ipv6) { break; }
  9208. if (target.hostname == e.hostname_pattern) { return true; }
  9209. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9210. // an entry of "example.com".
  9211. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9212. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9213. if (target.hostname[offset - 1] == '.' &&
  9214. target.hostname.compare(offset, e.hostname_pattern.size(),
  9215. e.hostname_pattern) == 0) {
  9216. return true;
  9217. }
  9218. }
  9219. break;
  9220. }
  9221. }
  9222. return false;
  9223. }
  9224. template <typename T>
  9225. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9226. T header_writer, Error &error) {
  9227. for (const auto &h : headers) {
  9228. if (!detail::fields::is_field_name(h.first) ||
  9229. !detail::fields::is_field_value(h.second)) {
  9230. error = Error::InvalidHeaders;
  9231. return false;
  9232. }
  9233. }
  9234. if (header_writer(strm, headers) <= 0) {
  9235. error = Error::Write;
  9236. return false;
  9237. }
  9238. return true;
  9239. }
  9240. } // namespace detail
  9241. /*
  9242. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9243. */
  9244. #ifdef CPPHTTPLIB_SSL_ENABLED
  9245. namespace detail {
  9246. // SSL socket stream implementation
  9247. inline SSLSocketStream::SSLSocketStream(
  9248. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9249. time_t read_timeout_usec, time_t write_timeout_sec,
  9250. time_t write_timeout_usec, time_t max_timeout_msec,
  9251. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9252. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9253. read_timeout_usec_(read_timeout_usec),
  9254. write_timeout_sec_(write_timeout_sec),
  9255. write_timeout_usec_(write_timeout_usec),
  9256. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9258. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9259. // Note: create_session() also clears this, but SSLClient currently
  9260. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9261. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9262. // SSL session was created.
  9263. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9264. #endif
  9265. }
  9266. inline SSLSocketStream::~SSLSocketStream() = default;
  9267. inline bool SSLSocketStream::is_readable() const {
  9268. return tls::pending(session_) > 0;
  9269. }
  9270. inline bool SSLSocketStream::wait_readable() const {
  9271. if (max_timeout_msec_ <= 0) {
  9272. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9273. }
  9274. time_t read_timeout_sec;
  9275. time_t read_timeout_usec;
  9276. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9277. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9278. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9279. }
  9280. inline bool SSLSocketStream::wait_writable() const {
  9281. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9282. !tls::is_peer_closed(session_, sock_);
  9283. }
  9284. inline bool SSLSocketStream::is_peer_alive() const {
  9285. return !tls::is_peer_closed(session_, sock_);
  9286. }
  9287. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9288. if (tls::pending(session_) > 0) {
  9289. tls::TlsError err;
  9290. auto ret = tls::read(session_, ptr, size, err);
  9291. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9292. error_ = Error::ConnectionClosed;
  9293. }
  9294. return ret;
  9295. } else if (wait_readable()) {
  9296. tls::TlsError err;
  9297. auto ret = tls::read(session_, ptr, size, err);
  9298. if (ret < 0) {
  9299. auto n = 1000;
  9300. #ifdef _WIN32
  9301. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9302. (err.code == tls::ErrorCode::SyscallError &&
  9303. WSAGetLastError() == WSAETIMEDOUT))) {
  9304. #else
  9305. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9306. #endif
  9307. if (tls::pending(session_) > 0) {
  9308. return tls::read(session_, ptr, size, err);
  9309. } else if (wait_readable()) {
  9310. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9311. ret = tls::read(session_, ptr, size, err);
  9312. if (ret >= 0) { return ret; }
  9313. } else {
  9314. break;
  9315. }
  9316. }
  9317. assert(ret < 0);
  9318. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9319. error_ = Error::ConnectionClosed;
  9320. }
  9321. return ret;
  9322. } else {
  9323. error_ = Error::Timeout;
  9324. return -1;
  9325. }
  9326. }
  9327. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9328. if (wait_writable()) {
  9329. auto handle_size =
  9330. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9331. tls::TlsError err;
  9332. auto ret = tls::write(session_, ptr, handle_size, err);
  9333. if (ret < 0) {
  9334. auto n = 1000;
  9335. #ifdef _WIN32
  9336. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9337. (err.code == tls::ErrorCode::SyscallError &&
  9338. WSAGetLastError() == WSAETIMEDOUT))) {
  9339. #else
  9340. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9341. #endif
  9342. if (wait_writable()) {
  9343. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9344. ret = tls::write(session_, ptr, handle_size, err);
  9345. if (ret >= 0) { return ret; }
  9346. } else {
  9347. break;
  9348. }
  9349. }
  9350. assert(ret < 0);
  9351. }
  9352. return ret;
  9353. }
  9354. return -1;
  9355. }
  9356. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9357. int &port) const {
  9358. detail::get_remote_ip_and_port(sock_, ip, port);
  9359. }
  9360. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9361. int &port) const {
  9362. detail::get_local_ip_and_port(sock_, ip, port);
  9363. }
  9364. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9365. inline time_t SSLSocketStream::duration() const {
  9366. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9367. std::chrono::steady_clock::now() - start_time_)
  9368. .count();
  9369. }
  9370. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9371. read_timeout_sec_ = sec;
  9372. read_timeout_usec_ = usec;
  9373. }
  9374. } // namespace detail
  9375. #endif // CPPHTTPLIB_SSL_ENABLED
  9376. /*
  9377. * Group 4: Server implementation
  9378. */
  9379. // HTTP server implementation
  9380. inline Server::Server()
  9381. : new_task_queue([] {
  9382. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9383. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9384. }) {
  9385. #ifndef _WIN32
  9386. signal(SIGPIPE, SIG_IGN);
  9387. #endif
  9388. }
  9389. inline Server::~Server() = default;
  9390. inline std::unique_ptr<detail::MatcherBase>
  9391. Server::make_matcher(const std::string &pattern) {
  9392. if (pattern.find("/:") != std::string::npos) {
  9393. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9394. } else {
  9395. return detail::make_unique<detail::RegexMatcher>(pattern);
  9396. }
  9397. }
  9398. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9399. return add_handler(get_handlers_, pattern, std::move(handler));
  9400. }
  9401. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9402. return add_handler(post_handlers_, pattern, std::move(handler));
  9403. }
  9404. inline Server &Server::Post(const std::string &pattern,
  9405. HandlerWithContentReader handler) {
  9406. return add_handler(post_handlers_for_content_reader_, pattern,
  9407. std::move(handler));
  9408. }
  9409. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9410. return add_handler(put_handlers_, pattern, std::move(handler));
  9411. }
  9412. inline Server &Server::Put(const std::string &pattern,
  9413. HandlerWithContentReader handler) {
  9414. return add_handler(put_handlers_for_content_reader_, pattern,
  9415. std::move(handler));
  9416. }
  9417. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9418. return add_handler(patch_handlers_, pattern, std::move(handler));
  9419. }
  9420. inline Server &Server::Patch(const std::string &pattern,
  9421. HandlerWithContentReader handler) {
  9422. return add_handler(patch_handlers_for_content_reader_, pattern,
  9423. std::move(handler));
  9424. }
  9425. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9426. return add_handler(delete_handlers_, pattern, std::move(handler));
  9427. }
  9428. inline Server &Server::Delete(const std::string &pattern,
  9429. HandlerWithContentReader handler) {
  9430. return add_handler(delete_handlers_for_content_reader_, pattern,
  9431. std::move(handler));
  9432. }
  9433. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9434. return add_handler(options_handlers_, pattern, std::move(handler));
  9435. }
  9436. inline Server &Server::WebSocket(const std::string &pattern,
  9437. WebSocketHandler handler) {
  9438. websocket_handlers_.push_back(
  9439. {make_matcher(pattern), std::move(handler), nullptr});
  9440. return *this;
  9441. }
  9442. inline Server &Server::WebSocket(const std::string &pattern,
  9443. WebSocketHandler handler,
  9444. SubProtocolSelector sub_protocol_selector) {
  9445. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9446. std::move(sub_protocol_selector)});
  9447. return *this;
  9448. }
  9449. inline bool Server::set_base_dir(const std::string &dir,
  9450. const std::string &mount_point) {
  9451. return set_mount_point(mount_point, dir);
  9452. }
  9453. inline bool Server::set_mount_point(const std::string &mount_point,
  9454. const std::string &dir, Headers headers) {
  9455. detail::FileStat stat(dir);
  9456. if (stat.is_dir()) {
  9457. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9458. if (!mnt.empty() && mnt[0] == '/') {
  9459. std::string resolved_base;
  9460. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9461. #if defined(_WIN32)
  9462. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9463. resolved_base += '\\';
  9464. }
  9465. #else
  9466. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9467. #endif
  9468. }
  9469. base_dirs_.push_back(
  9470. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9471. return true;
  9472. }
  9473. }
  9474. return false;
  9475. }
  9476. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9477. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9478. if (it->mount_point == mount_point) {
  9479. base_dirs_.erase(it);
  9480. return true;
  9481. }
  9482. }
  9483. return false;
  9484. }
  9485. inline Server &
  9486. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9487. const std::string &mime) {
  9488. file_extension_and_mimetype_map_[ext] = mime;
  9489. return *this;
  9490. }
  9491. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9492. default_file_mimetype_ = mime;
  9493. return *this;
  9494. }
  9495. inline Server &Server::set_file_request_handler(Handler handler) {
  9496. file_request_handler_ = std::move(handler);
  9497. return *this;
  9498. }
  9499. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9500. std::true_type) {
  9501. error_handler_ = std::move(handler);
  9502. return *this;
  9503. }
  9504. inline Server &Server::set_error_handler_core(Handler handler,
  9505. std::false_type) {
  9506. error_handler_ = [handler](const Request &req, Response &res) {
  9507. handler(req, res);
  9508. return HandlerResponse::Handled;
  9509. };
  9510. return *this;
  9511. }
  9512. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9513. exception_handler_ = std::move(handler);
  9514. return *this;
  9515. }
  9516. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9517. pre_routing_handler_ = std::move(handler);
  9518. return *this;
  9519. }
  9520. inline Server &Server::set_post_routing_handler(Handler handler) {
  9521. post_routing_handler_ = std::move(handler);
  9522. return *this;
  9523. }
  9524. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9525. pre_request_handler_ = std::move(handler);
  9526. return *this;
  9527. }
  9528. inline Server &Server::set_logger(Logger logger) {
  9529. logger_ = std::move(logger);
  9530. return *this;
  9531. }
  9532. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9533. error_logger_ = std::move(error_logger);
  9534. return *this;
  9535. }
  9536. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9537. pre_compression_logger_ = std::move(logger);
  9538. return *this;
  9539. }
  9540. inline Server &
  9541. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9542. expect_100_continue_handler_ = std::move(handler);
  9543. return *this;
  9544. }
  9545. inline Server &Server::set_start_handler(StartHandler handler) {
  9546. start_handler_ = std::move(handler);
  9547. return *this;
  9548. }
  9549. inline Server &Server::set_address_family(int family) {
  9550. address_family_ = family;
  9551. return *this;
  9552. }
  9553. inline Server &Server::set_tcp_nodelay(bool on) {
  9554. tcp_nodelay_ = on;
  9555. return *this;
  9556. }
  9557. inline Server &Server::set_ipv6_v6only(bool on) {
  9558. ipv6_v6only_ = on;
  9559. return *this;
  9560. }
  9561. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9562. socket_options_ = std::move(socket_options);
  9563. return *this;
  9564. }
  9565. inline Server &Server::set_default_headers(Headers headers) {
  9566. default_headers_ = std::move(headers);
  9567. return *this;
  9568. }
  9569. inline Server &Server::set_header_writer(
  9570. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9571. header_writer_ = writer;
  9572. return *this;
  9573. }
  9574. inline Server &
  9575. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9576. trusted_proxies_ = proxies;
  9577. return *this;
  9578. }
  9579. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9580. keep_alive_max_count_ = count;
  9581. return *this;
  9582. }
  9583. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9584. keep_alive_timeout_sec_ = sec;
  9585. return *this;
  9586. }
  9587. template <class Rep, class Period>
  9588. inline Server &Server::set_keep_alive_timeout(
  9589. const std::chrono::duration<Rep, Period> &duration) {
  9590. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9591. set_keep_alive_timeout(sec);
  9592. });
  9593. return *this;
  9594. }
  9595. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9596. read_timeout_sec_ = sec;
  9597. read_timeout_usec_ = usec;
  9598. return *this;
  9599. }
  9600. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9601. write_timeout_sec_ = sec;
  9602. write_timeout_usec_ = usec;
  9603. return *this;
  9604. }
  9605. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9606. idle_interval_sec_ = sec;
  9607. idle_interval_usec_ = usec;
  9608. return *this;
  9609. }
  9610. inline Server &Server::set_payload_max_length(size_t length) {
  9611. payload_max_length_ = length;
  9612. return *this;
  9613. }
  9614. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9615. websocket_max_missed_pongs_ = count;
  9616. return *this;
  9617. }
  9618. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9619. websocket_ping_interval_sec_ = sec;
  9620. return *this;
  9621. }
  9622. template <class Rep, class Period>
  9623. inline Server &Server::set_websocket_ping_interval(
  9624. const std::chrono::duration<Rep, Period> &duration) {
  9625. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9626. set_websocket_ping_interval(sec);
  9627. });
  9628. return *this;
  9629. }
  9630. inline bool Server::bind_to_port(const std::string &host, int port,
  9631. int socket_flags) {
  9632. auto ret = bind_internal(host, port, socket_flags);
  9633. if (ret == -1) { is_decommissioned = true; }
  9634. return ret >= 0;
  9635. }
  9636. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9637. auto ret = bind_internal(host, 0, socket_flags);
  9638. if (ret == -1) { is_decommissioned = true; }
  9639. return ret;
  9640. }
  9641. inline bool Server::listen_after_bind() { return listen_internal(); }
  9642. inline bool Server::listen(const std::string &host, int port,
  9643. int socket_flags) {
  9644. return bind_to_port(host, port, socket_flags) && listen_internal();
  9645. }
  9646. inline bool Server::is_running() const { return is_running_; }
  9647. inline void Server::wait_until_ready() const {
  9648. while (!is_running_ && !is_decommissioned) {
  9649. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9650. }
  9651. }
  9652. inline void Server::stop() noexcept {
  9653. if (is_running_) {
  9654. assert(svr_sock_ != INVALID_SOCKET);
  9655. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9656. detail::shutdown_socket(sock);
  9657. detail::close_socket(sock);
  9658. }
  9659. is_decommissioned = false;
  9660. }
  9661. inline void Server::decommission() { is_decommissioned = true; }
  9662. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9663. auto len = strlen(s);
  9664. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9665. len -= 2;
  9666. {
  9667. size_t count = 0;
  9668. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9669. switch (count) {
  9670. case 0: req.method = std::string(b, e); break;
  9671. case 1: req.target = std::string(b, e); break;
  9672. case 2: req.version = std::string(b, e); break;
  9673. default: break;
  9674. }
  9675. count++;
  9676. });
  9677. if (count != 3) { return false; }
  9678. }
  9679. thread_local const std::set<std::string> methods{
  9680. "GET", "HEAD", "POST", "PUT", "DELETE",
  9681. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9682. if (methods.find(req.method) == methods.end()) {
  9683. output_error_log(Error::InvalidHTTPMethod, &req);
  9684. return false;
  9685. }
  9686. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9687. output_error_log(Error::InvalidHTTPVersion, &req);
  9688. return false;
  9689. }
  9690. {
  9691. // Skip URL fragment
  9692. for (size_t i = 0; i < req.target.size(); i++) {
  9693. if (req.target[i] == '#') {
  9694. req.target.erase(i);
  9695. break;
  9696. }
  9697. }
  9698. detail::divide(req.target, '?',
  9699. [&](const char *lhs_data, std::size_t lhs_size,
  9700. const char *rhs_data, std::size_t rhs_size) {
  9701. req.path =
  9702. decode_path_component(std::string(lhs_data, lhs_size));
  9703. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9704. });
  9705. }
  9706. return true;
  9707. }
  9708. inline bool Server::write_response(Stream &strm, bool close_connection,
  9709. Request &req, Response &res) {
  9710. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9711. // incorrectly to the error content.
  9712. req.ranges.clear();
  9713. return write_response_core(strm, close_connection, req, res, false);
  9714. }
  9715. inline bool Server::write_response_with_content(Stream &strm,
  9716. bool close_connection,
  9717. const Request &req,
  9718. Response &res) {
  9719. return write_response_core(strm, close_connection, req, res, true);
  9720. }
  9721. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9722. const Request &req, Response &res,
  9723. bool need_apply_ranges) {
  9724. assert(res.status != -1);
  9725. if (400 <= res.status && error_handler_ &&
  9726. error_handler_(req, res) == HandlerResponse::Handled) {
  9727. need_apply_ranges = true;
  9728. }
  9729. std::string content_type;
  9730. std::string boundary;
  9731. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9732. // Prepare additional headers
  9733. if (close_connection || req.get_header_value("Connection") == "close" ||
  9734. 400 <= res.status) { // Don't leave connections open after errors
  9735. res.set_header("Connection", "close");
  9736. } else {
  9737. std::string s = "timeout=";
  9738. s += std::to_string(keep_alive_timeout_sec_);
  9739. s += ", max=";
  9740. s += std::to_string(keep_alive_max_count_);
  9741. res.set_header("Keep-Alive", s);
  9742. }
  9743. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9744. !res.has_header("Content-Type")) {
  9745. res.set_header("Content-Type", "text/plain");
  9746. }
  9747. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9748. !res.has_header("Content-Length")) {
  9749. res.set_header("Content-Length", "0");
  9750. }
  9751. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9752. res.set_header("Accept-Ranges", "bytes");
  9753. }
  9754. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9755. // Response line and headers
  9756. detail::BufferStream bstrm;
  9757. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9758. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9759. // Combine small body with headers to reduce write syscalls
  9760. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9761. bstrm.write(res.body.data(), res.body.size());
  9762. }
  9763. // Log before writing to avoid race condition with client-side code that
  9764. // accesses logger-captured data immediately after receiving the response.
  9765. output_log(req, res);
  9766. // Flush buffer
  9767. auto &data = bstrm.get_buffer();
  9768. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9769. // Streaming body
  9770. auto ret = true;
  9771. if (req.method != "HEAD" && res.content_provider_) {
  9772. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9773. res.content_provider_success_ = true;
  9774. } else {
  9775. ret = false;
  9776. }
  9777. }
  9778. return ret;
  9779. }
  9780. inline bool
  9781. Server::write_content_with_provider(Stream &strm, const Request &req,
  9782. Response &res, const std::string &boundary,
  9783. const std::string &content_type) {
  9784. auto is_shutting_down = [this]() {
  9785. return this->svr_sock_ == INVALID_SOCKET;
  9786. };
  9787. if (res.content_length_ > 0) {
  9788. if (req.ranges.empty()) {
  9789. return detail::write_content(strm, res.content_provider_, 0,
  9790. res.content_length_, is_shutting_down);
  9791. } else if (req.ranges.size() == 1) {
  9792. auto offset_and_length = detail::get_range_offset_and_length(
  9793. req.ranges[0], res.content_length_);
  9794. return detail::write_content(strm, res.content_provider_,
  9795. offset_and_length.first,
  9796. offset_and_length.second, is_shutting_down);
  9797. } else {
  9798. return detail::write_multipart_ranges_data(
  9799. strm, req, res, boundary, content_type, res.content_length_,
  9800. is_shutting_down);
  9801. }
  9802. } else {
  9803. if (res.is_chunked_content_provider_) {
  9804. auto type = detail::encoding_type(req, res);
  9805. auto compressor = detail::make_compressor(type);
  9806. if (!compressor) {
  9807. compressor = detail::make_unique<detail::nocompressor>();
  9808. }
  9809. return detail::write_content_chunked(strm, res.content_provider_,
  9810. is_shutting_down, *compressor);
  9811. } else {
  9812. return detail::write_content_without_length(strm, res.content_provider_,
  9813. is_shutting_down);
  9814. }
  9815. }
  9816. }
  9817. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9818. FormFields::iterator cur_field;
  9819. FormFiles::iterator cur_file;
  9820. auto is_text_field = false;
  9821. size_t count = 0;
  9822. if (read_content_core(
  9823. strm, req, res,
  9824. // Regular
  9825. [&](const char *buf, size_t n) {
  9826. // Prevent arithmetic overflow when checking sizes.
  9827. // Avoid computing (req.body.size() + n) directly because
  9828. // adding two unsigned `size_t` values can wrap around and
  9829. // produce a small result instead of indicating overflow.
  9830. // Instead, check using subtraction: ensure `n` does not
  9831. // exceed the remaining capacity `max_size() - size()`.
  9832. if (req.body.size() >= req.body.max_size() ||
  9833. n > req.body.max_size() - req.body.size()) {
  9834. return false;
  9835. }
  9836. // Limit decompressed body size to payload_max_length_ to protect
  9837. // against "zip bomb" attacks where a small compressed payload
  9838. // decompresses to a massive size.
  9839. if (payload_max_length_ > 0 &&
  9840. (req.body.size() >= payload_max_length_ ||
  9841. n > payload_max_length_ - req.body.size())) {
  9842. return false;
  9843. }
  9844. req.body.append(buf, n);
  9845. return true;
  9846. },
  9847. // Multipart FormData
  9848. [&](const FormData &file) {
  9849. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9850. output_error_log(Error::TooManyFormDataFiles, &req);
  9851. return false;
  9852. }
  9853. if (file.filename.empty()) {
  9854. cur_field = req.form.fields.emplace(
  9855. file.name, FormField{file.name, file.content, file.headers});
  9856. is_text_field = true;
  9857. } else {
  9858. cur_file = req.form.files.emplace(file.name, file);
  9859. is_text_field = false;
  9860. }
  9861. return true;
  9862. },
  9863. [&](const char *buf, size_t n) {
  9864. if (is_text_field) {
  9865. auto &content = cur_field->second.content;
  9866. if (content.size() + n > content.max_size()) { return false; }
  9867. content.append(buf, n);
  9868. } else {
  9869. auto &content = cur_file->second.content;
  9870. if (content.size() + n > content.max_size()) { return false; }
  9871. content.append(buf, n);
  9872. }
  9873. return true;
  9874. })) {
  9875. const auto &content_type = req.get_header_value("Content-Type");
  9876. if (detail::extract_media_type(content_type) ==
  9877. "application/x-www-form-urlencoded") {
  9878. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9879. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9880. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9881. return false;
  9882. }
  9883. detail::parse_query_text(req.body, req.params);
  9884. }
  9885. return true;
  9886. }
  9887. return false;
  9888. }
  9889. inline bool Server::read_content_with_content_receiver(
  9890. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9891. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9892. return read_content_core(strm, req, res, std::move(receiver),
  9893. std::move(multipart_header),
  9894. std::move(multipart_receiver));
  9895. }
  9896. inline bool Server::read_content_core(
  9897. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9898. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9899. detail::FormDataParser multipart_form_data_parser;
  9900. ContentReceiverWithProgress out;
  9901. if (req.is_multipart_form_data()) {
  9902. const auto &content_type = req.get_header_value("Content-Type");
  9903. std::string boundary;
  9904. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9905. res.status = StatusCode::BadRequest_400;
  9906. output_error_log(Error::MultipartParsing, &req);
  9907. return false;
  9908. }
  9909. multipart_form_data_parser.set_boundary(std::move(boundary));
  9910. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9911. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9912. multipart_receiver);
  9913. };
  9914. } else {
  9915. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9916. size_t /*len*/) { return receiver(buf, n); };
  9917. }
  9918. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9919. // For non-SSL builds we still scan non-persistent connections for stray
  9920. // body bytes so the payload limit is enforced (413). On keep-alive,
  9921. // pending bytes may be the next request (issue #2450), so skip.
  9922. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9923. if (!req.has_header("Content-Length") &&
  9924. !detail::is_chunked_transfer_encoding(req.headers)) {
  9925. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9926. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9927. auto has_data = strm.is_readable();
  9928. if (!has_data) {
  9929. auto s = strm.socket();
  9930. if (s != INVALID_SOCKET) {
  9931. has_data = detail::select_read(s, 0, 0) > 0;
  9932. }
  9933. }
  9934. if (has_data) {
  9935. auto result =
  9936. detail::read_content_without_length(strm, payload_max_length_, out);
  9937. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9938. res.status = StatusCode::PayloadTooLarge_413;
  9939. return false;
  9940. } else if (result != detail::ReadContentResult::Success) {
  9941. return false;
  9942. }
  9943. return true;
  9944. }
  9945. }
  9946. return true;
  9947. }
  9948. #else
  9949. if (!req.has_header("Content-Length") &&
  9950. !detail::is_chunked_transfer_encoding(req.headers)) {
  9951. return true;
  9952. }
  9953. #endif
  9954. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9955. out, true)) {
  9956. return false;
  9957. }
  9958. req.body_consumed_ = true;
  9959. if (req.is_multipart_form_data()) {
  9960. if (!multipart_form_data_parser.is_valid()) {
  9961. res.status = StatusCode::BadRequest_400;
  9962. output_error_log(Error::MultipartParsing, &req);
  9963. return false;
  9964. }
  9965. }
  9966. return true;
  9967. }
  9968. inline bool Server::handle_file_request(Request &req, Response &res) {
  9969. for (const auto &entry : base_dirs_) {
  9970. // Prefix match
  9971. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9972. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9973. if (detail::is_valid_path(sub_path)) {
  9974. auto path = entry.base_dir + sub_path;
  9975. if (path.back() == '/') { path += "index.html"; }
  9976. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9977. // but symlinks/junctions can still escape the base directory.
  9978. if (!entry.resolved_base_dir.empty()) {
  9979. std::string resolved_path;
  9980. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9981. !detail::is_path_within_base(resolved_path,
  9982. entry.resolved_base_dir)) {
  9983. res.status = StatusCode::Forbidden_403;
  9984. return true;
  9985. }
  9986. }
  9987. detail::FileStat stat(path);
  9988. if (stat.is_dir()) {
  9989. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9990. return true;
  9991. }
  9992. if (stat.is_file()) {
  9993. for (const auto &kv : entry.headers) {
  9994. res.set_header(kv.first, kv.second);
  9995. }
  9996. auto etag = detail::compute_etag(stat);
  9997. if (!etag.empty()) { res.set_header("ETag", etag); }
  9998. auto mtime = stat.mtime();
  9999. auto last_modified = detail::file_mtime_to_http_date(mtime);
  10000. if (!last_modified.empty()) {
  10001. res.set_header("Last-Modified", last_modified);
  10002. }
  10003. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  10004. check_if_range(req, etag, mtime);
  10005. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10006. if (!mm->is_open()) {
  10007. output_error_log(Error::OpenFile, &req);
  10008. return false;
  10009. }
  10010. res.set_content_provider(
  10011. mm->size(),
  10012. detail::find_content_type(path, file_extension_and_mimetype_map_,
  10013. default_file_mimetype_),
  10014. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10015. sink.write(mm->data() + offset, length);
  10016. return true;
  10017. });
  10018. if (req.method != "HEAD" && file_request_handler_) {
  10019. file_request_handler_(req, res);
  10020. }
  10021. return true;
  10022. } else {
  10023. output_error_log(Error::OpenFile, &req);
  10024. }
  10025. }
  10026. }
  10027. }
  10028. return false;
  10029. }
  10030. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  10031. const std::string &etag,
  10032. time_t mtime) const {
  10033. // Handle conditional GET:
  10034. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  10035. // 2. If-Modified-Since is checked only when If-None-Match is absent
  10036. if (req.has_header("If-None-Match")) {
  10037. if (!etag.empty()) {
  10038. auto val = req.get_header_value("If-None-Match");
  10039. // NOTE: We use exact string matching here. This works correctly
  10040. // because our server always generates weak ETags (W/"..."), and
  10041. // clients typically send back the same ETag they received.
  10042. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  10043. // If-None-Match, where W/"x" and "x" would match, but this
  10044. // simplified implementation requires exact matches.
  10045. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  10046. [&](const char *b, const char *e) {
  10047. auto seg_len = static_cast<size_t>(e - b);
  10048. return (seg_len == 1 && *b == '*') ||
  10049. (seg_len == etag.size() &&
  10050. std::equal(b, e, etag.begin()));
  10051. });
  10052. if (ret) {
  10053. res.status = StatusCode::NotModified_304;
  10054. return true;
  10055. }
  10056. }
  10057. } else if (req.has_header("If-Modified-Since")) {
  10058. auto val = req.get_header_value("If-Modified-Since");
  10059. auto t = detail::parse_http_date(val);
  10060. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10061. res.status = StatusCode::NotModified_304;
  10062. return true;
  10063. }
  10064. }
  10065. return false;
  10066. }
  10067. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10068. time_t mtime) const {
  10069. // Handle If-Range for partial content requests (RFC 9110
  10070. // Section 13.1.5). If-Range is only evaluated when Range header is
  10071. // present. If the validator matches, serve partial content; otherwise
  10072. // serve full content.
  10073. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10074. auto val = req.get_header_value("If-Range");
  10075. auto is_valid_range = [&]() {
  10076. if (detail::is_strong_etag(val)) {
  10077. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10078. // comparison.
  10079. return (!etag.empty() && val == etag);
  10080. } else if (detail::is_weak_etag(val)) {
  10081. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10082. return false;
  10083. } else {
  10084. // HTTP-date comparison
  10085. auto t = detail::parse_http_date(val);
  10086. return (t != static_cast<time_t>(-1) && mtime <= t);
  10087. }
  10088. };
  10089. if (!is_valid_range()) {
  10090. // Validator doesn't match: ignore Range and serve full content
  10091. req.ranges.clear();
  10092. return false;
  10093. }
  10094. }
  10095. return true;
  10096. }
  10097. inline socket_t
  10098. Server::create_server_socket(const std::string &host, int port,
  10099. int socket_flags,
  10100. SocketOptions socket_options) const {
  10101. return detail::create_socket(
  10102. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10103. ipv6_v6only_, std::move(socket_options),
  10104. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10105. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10106. output_error_log(Error::BindIPAddress, nullptr);
  10107. return false;
  10108. }
  10109. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10110. output_error_log(Error::Listen, nullptr);
  10111. return false;
  10112. }
  10113. return true;
  10114. });
  10115. }
  10116. inline int Server::bind_internal(const std::string &host, int port,
  10117. int socket_flags) {
  10118. if (is_decommissioned) { return -1; }
  10119. if (!is_valid()) { return -1; }
  10120. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10121. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10122. if (port == 0) {
  10123. struct sockaddr_storage addr;
  10124. socklen_t addr_len = sizeof(addr);
  10125. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10126. &addr_len) == -1) {
  10127. output_error_log(Error::GetSockName, nullptr);
  10128. return -1;
  10129. }
  10130. if (addr.ss_family == AF_INET) {
  10131. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10132. } else if (addr.ss_family == AF_INET6) {
  10133. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10134. } else {
  10135. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10136. return -1;
  10137. }
  10138. } else {
  10139. return port;
  10140. }
  10141. }
  10142. inline bool Server::listen_internal() {
  10143. if (is_decommissioned) { return false; }
  10144. auto ret = true;
  10145. is_running_ = true;
  10146. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10147. if (start_handler_) { start_handler_(); }
  10148. {
  10149. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10150. while (svr_sock_ != INVALID_SOCKET) {
  10151. #ifndef _WIN32
  10152. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10153. #endif
  10154. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10155. idle_interval_usec_);
  10156. if (val == 0) { // Timeout
  10157. task_queue->on_idle();
  10158. continue;
  10159. }
  10160. #ifndef _WIN32
  10161. }
  10162. #endif
  10163. #if defined _WIN32
  10164. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10165. // OVERLAPPED
  10166. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10167. #elif defined SOCK_CLOEXEC
  10168. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10169. #else
  10170. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10171. #endif
  10172. if (sock == INVALID_SOCKET) {
  10173. if (errno == EMFILE) {
  10174. // The per-process limit of open file descriptors has been reached.
  10175. // Try to accept new connections after a short sleep.
  10176. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10177. continue;
  10178. } else if (errno == EINTR || errno == EAGAIN) {
  10179. continue;
  10180. }
  10181. if (svr_sock_ != INVALID_SOCKET) {
  10182. detail::close_socket(svr_sock_);
  10183. ret = false;
  10184. output_error_log(Error::Connection, nullptr);
  10185. } else {
  10186. ; // The server socket was closed by user.
  10187. }
  10188. break;
  10189. }
  10190. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10191. read_timeout_sec_, read_timeout_usec_);
  10192. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10193. write_timeout_sec_, write_timeout_usec_);
  10194. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10195. if (!task_queue->enqueue(
  10196. [this, sock]() { process_and_close_socket(sock); })) {
  10197. output_error_log(Error::ResourceExhaustion, nullptr);
  10198. detail::shutdown_socket(sock);
  10199. detail::close_socket(sock);
  10200. }
  10201. }
  10202. task_queue->shutdown();
  10203. }
  10204. is_decommissioned = !ret;
  10205. return ret;
  10206. }
  10207. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10208. if (pre_routing_handler_ &&
  10209. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10210. return true;
  10211. }
  10212. // File handler
  10213. if ((req.method == "GET" || req.method == "HEAD") &&
  10214. handle_file_request(req, res)) {
  10215. return true;
  10216. }
  10217. if (detail::expect_content(req)) {
  10218. // Content reader handler
  10219. {
  10220. // Track whether the ContentReader was aborted due to the decompressed
  10221. // payload exceeding `payload_max_length_`.
  10222. // The user handler runs after the lambda returns, so we must restore the
  10223. // 413 status if the handler overwrites it.
  10224. bool content_reader_payload_too_large = false;
  10225. ContentReader reader(
  10226. [&](ContentReceiver receiver) {
  10227. auto result = read_content_with_content_receiver(
  10228. strm, req, res, std::move(receiver), nullptr, nullptr);
  10229. if (!result) {
  10230. output_error_log(Error::Read, &req);
  10231. if (res.status == StatusCode::PayloadTooLarge_413) {
  10232. content_reader_payload_too_large = true;
  10233. }
  10234. }
  10235. return result;
  10236. },
  10237. [&](FormDataHeader header, ContentReceiver receiver) {
  10238. auto result = read_content_with_content_receiver(
  10239. strm, req, res, nullptr, std::move(header),
  10240. std::move(receiver));
  10241. if (!result) {
  10242. output_error_log(Error::Read, &req);
  10243. if (res.status == StatusCode::PayloadTooLarge_413) {
  10244. content_reader_payload_too_large = true;
  10245. }
  10246. }
  10247. return result;
  10248. });
  10249. bool dispatched = false;
  10250. if (req.method == "POST") {
  10251. dispatched = dispatch_request_for_content_reader(
  10252. req, res, std::move(reader), post_handlers_for_content_reader_);
  10253. } else if (req.method == "PUT") {
  10254. dispatched = dispatch_request_for_content_reader(
  10255. req, res, std::move(reader), put_handlers_for_content_reader_);
  10256. } else if (req.method == "PATCH") {
  10257. dispatched = dispatch_request_for_content_reader(
  10258. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10259. } else if (req.method == "DELETE") {
  10260. dispatched = dispatch_request_for_content_reader(
  10261. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10262. }
  10263. if (dispatched) {
  10264. if (content_reader_payload_too_large) {
  10265. // Enforce the limit: override any status the handler may have set
  10266. // and return false so the error path sends a plain 413 response.
  10267. res.status = StatusCode::PayloadTooLarge_413;
  10268. res.body.clear();
  10269. res.content_length_ = 0;
  10270. res.content_provider_ = nullptr;
  10271. return false;
  10272. }
  10273. return true;
  10274. }
  10275. }
  10276. // NOTE: `req.body` is not read here. For a regular handler the body is
  10277. // read inside dispatch_request(), after the route has matched and the
  10278. // pre-request handler has approved the request, so that a rejected
  10279. // request (e.g. failed authentication) never forces us to buffer a
  10280. // potentially large body.
  10281. }
  10282. // Regular handler
  10283. if (req.method == "GET" || req.method == "HEAD") {
  10284. return dispatch_request(req, res, get_handlers_, strm);
  10285. } else if (req.method == "POST") {
  10286. return dispatch_request(req, res, post_handlers_, strm);
  10287. } else if (req.method == "PUT") {
  10288. return dispatch_request(req, res, put_handlers_, strm);
  10289. } else if (req.method == "DELETE") {
  10290. return dispatch_request(req, res, delete_handlers_, strm);
  10291. } else if (req.method == "OPTIONS") {
  10292. return dispatch_request(req, res, options_handlers_, strm);
  10293. } else if (req.method == "PATCH") {
  10294. return dispatch_request(req, res, patch_handlers_, strm);
  10295. }
  10296. res.status = StatusCode::BadRequest_400;
  10297. return false;
  10298. }
  10299. inline bool Server::dispatch_request(Request &req, Response &res,
  10300. const Handlers &handlers, Stream &strm) {
  10301. for (const auto &x : handlers) {
  10302. const auto &matcher = x.first;
  10303. const auto &handler = x.second;
  10304. if (matcher->match(req)) {
  10305. req.matched_route = matcher->pattern();
  10306. // Run the pre-request handler before reading the body so a rejected
  10307. // request (e.g. failed authentication) never forces us to buffer a
  10308. // potentially large body. `req.matched_route` is available here.
  10309. if (pre_request_handler_ &&
  10310. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10311. return true;
  10312. }
  10313. // The route matched and the request was approved; read the body now.
  10314. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10315. output_error_log(Error::Read, &req);
  10316. return false;
  10317. }
  10318. handler(req, res);
  10319. return true;
  10320. }
  10321. }
  10322. return false;
  10323. }
  10324. inline void Server::apply_ranges(const Request &req, Response &res,
  10325. std::string &content_type,
  10326. std::string &boundary) const {
  10327. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10328. auto it = res.headers.find("Content-Type");
  10329. if (it != res.headers.end()) {
  10330. content_type = it->second;
  10331. res.headers.erase(it);
  10332. }
  10333. boundary = detail::make_multipart_data_boundary();
  10334. res.set_header("Content-Type",
  10335. "multipart/byteranges; boundary=" + boundary);
  10336. }
  10337. auto type = detail::encoding_type(req, res);
  10338. if (res.body.empty()) {
  10339. if (res.content_length_ > 0) {
  10340. size_t length = 0;
  10341. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10342. length = res.content_length_;
  10343. } else if (req.ranges.size() == 1) {
  10344. auto offset_and_length = detail::get_range_offset_and_length(
  10345. req.ranges[0], res.content_length_);
  10346. length = offset_and_length.second;
  10347. auto content_range = detail::make_content_range_header_field(
  10348. offset_and_length, res.content_length_);
  10349. res.set_header("Content-Range", content_range);
  10350. } else {
  10351. length = detail::get_multipart_ranges_data_length(
  10352. req, boundary, content_type, res.content_length_);
  10353. }
  10354. res.set_header("Content-Length", std::to_string(length));
  10355. } else {
  10356. if (res.content_provider_) {
  10357. if (res.is_chunked_content_provider_) {
  10358. res.set_header("Transfer-Encoding", "chunked");
  10359. if (type != detail::EncodingType::None) {
  10360. res.set_header("Content-Encoding", detail::encoding_name(type));
  10361. res.set_header("Vary", "Accept-Encoding");
  10362. }
  10363. }
  10364. }
  10365. }
  10366. } else {
  10367. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10368. ;
  10369. } else if (req.ranges.size() == 1) {
  10370. auto offset_and_length =
  10371. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10372. auto offset = offset_and_length.first;
  10373. auto length = offset_and_length.second;
  10374. auto content_range = detail::make_content_range_header_field(
  10375. offset_and_length, res.body.size());
  10376. res.set_header("Content-Range", content_range);
  10377. assert(offset + length <= res.body.size());
  10378. res.body = res.body.substr(offset, length);
  10379. } else {
  10380. std::string data;
  10381. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10382. res.body.size(), data);
  10383. res.body.swap(data);
  10384. }
  10385. if (type != detail::EncodingType::None) {
  10386. output_pre_compression_log(req, res);
  10387. if (auto compressor = detail::make_compressor(type)) {
  10388. std::string compressed;
  10389. if (compressor->compress(res.body.data(), res.body.size(), true,
  10390. [&](const char *data, size_t data_len) {
  10391. compressed.append(data, data_len);
  10392. return true;
  10393. })) {
  10394. res.body.swap(compressed);
  10395. res.set_header("Content-Encoding", detail::encoding_name(type));
  10396. res.set_header("Vary", "Accept-Encoding");
  10397. }
  10398. }
  10399. }
  10400. res.content_length_ = res.body.size();
  10401. res.set_header("Content-Length", std::to_string(res.content_length_));
  10402. }
  10403. }
  10404. inline bool Server::dispatch_request_for_content_reader(
  10405. Request &req, Response &res, ContentReader content_reader,
  10406. const HandlersForContentReader &handlers) const {
  10407. for (const auto &x : handlers) {
  10408. const auto &matcher = x.first;
  10409. const auto &handler = x.second;
  10410. if (matcher->match(req)) {
  10411. req.matched_route = matcher->pattern();
  10412. if (!pre_request_handler_ ||
  10413. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10414. handler(req, res, content_reader);
  10415. }
  10416. return true;
  10417. }
  10418. }
  10419. return false;
  10420. }
  10421. inline std::string
  10422. get_client_ip(const std::string &x_forwarded_for,
  10423. const std::vector<std::string> &trusted_proxies) {
  10424. // X-Forwarded-For is a comma-separated list per RFC 7239
  10425. std::vector<std::string> ip_list;
  10426. detail::split(x_forwarded_for.data(),
  10427. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10428. [&](const char *b, const char *e) {
  10429. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10430. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10431. });
  10432. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10433. // no segments. Signal "no client IP derived" with an empty string so the
  10434. // caller can fall back to the connection-level remote address.
  10435. if (ip_list.empty()) { return std::string(); }
  10436. for (size_t i = 0; i < ip_list.size(); ++i) {
  10437. auto ip = ip_list[i];
  10438. auto is_trusted_proxy =
  10439. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10440. [&](const std::string &proxy) { return ip == proxy; });
  10441. if (is_trusted_proxy) {
  10442. if (i == 0) {
  10443. // If the trusted proxy is the first IP, there's no preceding client IP
  10444. return ip;
  10445. } else {
  10446. // Return the IP immediately before the trusted proxy
  10447. return ip_list[i - 1];
  10448. }
  10449. }
  10450. }
  10451. // If no trusted proxy is found, return the first IP in the list
  10452. return ip_list.front();
  10453. }
  10454. inline bool
  10455. Server::process_request(Stream &strm, const std::string &remote_addr,
  10456. int remote_port, const std::string &local_addr,
  10457. int local_port, bool close_connection,
  10458. bool &connection_closed,
  10459. const std::function<void(Request &)> &setup_request,
  10460. bool *websocket_upgraded) {
  10461. std::array<char, 2048> buf{};
  10462. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10463. // Connection has been closed on client
  10464. if (!line_reader.getline()) { return false; }
  10465. Request req;
  10466. req.start_time_ = std::chrono::steady_clock::now();
  10467. req.remote_addr = remote_addr;
  10468. req.remote_port = remote_port;
  10469. req.local_addr = local_addr;
  10470. req.local_port = local_port;
  10471. Response res;
  10472. res.version = "HTTP/1.1";
  10473. res.headers = default_headers_;
  10474. // Request line and headers
  10475. if (!parse_request_line(line_reader.ptr(), req)) {
  10476. res.status = StatusCode::BadRequest_400;
  10477. output_error_log(Error::InvalidRequestLine, &req);
  10478. return write_response(strm, close_connection, req, res);
  10479. }
  10480. // Request headers
  10481. if (!detail::read_headers(strm, req.headers)) {
  10482. res.status = StatusCode::BadRequest_400;
  10483. output_error_log(Error::InvalidHeaders, &req);
  10484. return write_response(strm, close_connection, req, res);
  10485. }
  10486. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10487. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10488. // tolerated for compatibility with existing clients.
  10489. if (req.get_header_value_u64("Content-Length") > 0 &&
  10490. req.has_header("Transfer-Encoding")) {
  10491. connection_closed = true;
  10492. res.status = StatusCode::BadRequest_400;
  10493. return write_response(strm, close_connection, req, res);
  10494. }
  10495. // Check if the request URI doesn't exceed the limit
  10496. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10497. connection_closed = true;
  10498. res.status = StatusCode::UriTooLong_414;
  10499. output_error_log(Error::ExceedUriMaxLength, &req);
  10500. return write_response(strm, close_connection, req, res);
  10501. }
  10502. if (req.get_header_value("Connection") == "close") {
  10503. connection_closed = true;
  10504. }
  10505. if (req.version == "HTTP/1.0" &&
  10506. req.get_header_value("Connection") != "Keep-Alive") {
  10507. connection_closed = true;
  10508. }
  10509. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10510. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10511. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10512. req.remote_addr = derived.empty() ? remote_addr : derived;
  10513. } else {
  10514. req.remote_addr = remote_addr;
  10515. }
  10516. req.remote_port = remote_port;
  10517. req.local_addr = local_addr;
  10518. req.local_port = local_port;
  10519. if (req.has_header("Accept")) {
  10520. const auto &accept_header = req.get_header_value("Accept");
  10521. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10522. connection_closed = true;
  10523. res.status = StatusCode::BadRequest_400;
  10524. output_error_log(Error::HTTPParsing, &req);
  10525. return write_response(strm, close_connection, req, res);
  10526. }
  10527. }
  10528. if (req.has_header("Range")) {
  10529. const auto &range_header_value = req.get_header_value("Range");
  10530. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10531. connection_closed = true;
  10532. res.status = StatusCode::RangeNotSatisfiable_416;
  10533. output_error_log(Error::InvalidRangeHeader, &req);
  10534. return write_response(strm, close_connection, req, res);
  10535. }
  10536. }
  10537. if (setup_request) { setup_request(req); }
  10538. if (req.get_header_value("Expect") == "100-continue") {
  10539. int status = StatusCode::Continue_100;
  10540. if (expect_100_continue_handler_) {
  10541. status = expect_100_continue_handler_(req, res);
  10542. }
  10543. switch (status) {
  10544. case StatusCode::Continue_100:
  10545. case StatusCode::ExpectationFailed_417:
  10546. detail::write_response_line(strm, status);
  10547. strm.write("\r\n");
  10548. break;
  10549. default:
  10550. connection_closed = true;
  10551. return write_response(strm, true, req, res);
  10552. }
  10553. }
  10554. // Setup `is_connection_closed` method
  10555. auto sock = strm.socket();
  10556. req.is_connection_closed = [sock]() {
  10557. return !detail::is_socket_alive(sock);
  10558. };
  10559. // WebSocket upgrade
  10560. // Check pre_routing_handler_ before upgrading so that authentication
  10561. // and other middleware can reject the request with an HTTP response
  10562. // (e.g., 401) before the protocol switches.
  10563. if (detail::is_websocket_upgrade(req)) {
  10564. if (pre_routing_handler_ &&
  10565. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10566. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10567. return write_response(strm, close_connection, req, res);
  10568. }
  10569. // Find matching WebSocket handler
  10570. for (const auto &entry : websocket_handlers_) {
  10571. if (entry.matcher->match(req)) {
  10572. // Compute accept key
  10573. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10574. auto accept_key = detail::websocket_accept_key(client_key);
  10575. // Negotiate subprotocol
  10576. std::string selected_subprotocol;
  10577. if (entry.sub_protocol_selector) {
  10578. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10579. if (!protocol_header.empty()) {
  10580. std::vector<std::string> protocols;
  10581. std::istringstream iss(protocol_header);
  10582. std::string token;
  10583. while (std::getline(iss, token, ',')) {
  10584. // Trim whitespace
  10585. auto start = token.find_first_not_of(' ');
  10586. auto end = token.find_last_not_of(' ');
  10587. if (start != std::string::npos) {
  10588. protocols.push_back(token.substr(start, end - start + 1));
  10589. }
  10590. }
  10591. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10592. }
  10593. }
  10594. // Send 101 Switching Protocols
  10595. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10596. "Upgrade: websocket\r\n"
  10597. "Connection: Upgrade\r\n"
  10598. "Sec-WebSocket-Accept: " +
  10599. accept_key + "\r\n";
  10600. if (!selected_subprotocol.empty()) {
  10601. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10602. return false;
  10603. }
  10604. handshake_response +=
  10605. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10606. }
  10607. handshake_response += "\r\n";
  10608. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10609. 0) {
  10610. return false;
  10611. }
  10612. connection_closed = true;
  10613. if (websocket_upgraded) { *websocket_upgraded = true; }
  10614. {
  10615. // Use WebSocket-specific read timeout instead of HTTP timeout
  10616. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10617. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10618. websocket_max_missed_pongs_);
  10619. entry.handler(req, ws);
  10620. }
  10621. return true;
  10622. }
  10623. }
  10624. // No matching handler - fall through to 404
  10625. }
  10626. // Routing
  10627. auto routed = false;
  10628. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10629. routed = routing(req, res, strm);
  10630. #else
  10631. try {
  10632. routed = routing(req, res, strm);
  10633. } catch (std::exception &) {
  10634. if (exception_handler_) {
  10635. auto ep = std::current_exception();
  10636. exception_handler_(req, res, ep);
  10637. routed = true;
  10638. } else {
  10639. res.status = StatusCode::InternalServerError_500;
  10640. }
  10641. } catch (...) {
  10642. if (exception_handler_) {
  10643. auto ep = std::current_exception();
  10644. exception_handler_(req, res, ep);
  10645. routed = true;
  10646. } else {
  10647. res.status = StatusCode::InternalServerError_500;
  10648. }
  10649. }
  10650. #endif
  10651. auto ret = false;
  10652. if (routed) {
  10653. if (res.status == -1) {
  10654. res.status = req.ranges.empty() ? StatusCode::OK_200
  10655. : StatusCode::PartialContent_206;
  10656. }
  10657. // Serve file content by using a content provider
  10658. auto file_open_error = false;
  10659. if (!res.file_content_path_.empty()) {
  10660. const auto &path = res.file_content_path_;
  10661. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10662. if (!mm->is_open()) {
  10663. res.body.clear();
  10664. res.content_length_ = 0;
  10665. res.content_provider_ = nullptr;
  10666. res.status = StatusCode::NotFound_404;
  10667. output_error_log(Error::OpenFile, &req);
  10668. file_open_error = true;
  10669. } else {
  10670. auto content_type = res.file_content_content_type_;
  10671. if (content_type.empty()) {
  10672. content_type = detail::find_content_type(
  10673. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10674. }
  10675. res.set_content_provider(
  10676. mm->size(), content_type,
  10677. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10678. sink.write(mm->data() + offset, length);
  10679. return true;
  10680. });
  10681. }
  10682. }
  10683. if (file_open_error) {
  10684. ret = write_response(strm, close_connection, req, res);
  10685. } else if (detail::range_error(req, res)) {
  10686. res.body.clear();
  10687. res.content_length_ = 0;
  10688. res.content_provider_ = nullptr;
  10689. res.status = StatusCode::RangeNotSatisfiable_416;
  10690. ret = write_response(strm, close_connection, req, res);
  10691. } else {
  10692. ret = write_response_with_content(strm, close_connection, req, res);
  10693. }
  10694. } else {
  10695. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10696. ret = write_response(strm, close_connection, req, res);
  10697. }
  10698. // Drain any unconsumed framed body to prevent request smuggling on
  10699. // keep-alive. Without framing there is no body to drain — reading would
  10700. // consume the next request (issue #2450). If the response has committed the
  10701. // connection to close, there is no next request to protect.
  10702. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10703. if (res.get_header_value("Connection") == "close") {
  10704. connection_closed = true;
  10705. } else {
  10706. int dummy_status;
  10707. if (!detail::read_content(
  10708. strm, req, payload_max_length_, dummy_status, nullptr,
  10709. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10710. connection_closed = true;
  10711. }
  10712. }
  10713. }
  10714. return ret;
  10715. }
  10716. inline bool Server::is_valid() const { return true; }
  10717. inline bool Server::process_and_close_socket(socket_t sock) {
  10718. std::string remote_addr;
  10719. int remote_port = 0;
  10720. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10721. std::string local_addr;
  10722. int local_port = 0;
  10723. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10724. bool websocket_upgraded = false;
  10725. auto ret = detail::process_server_socket(
  10726. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10727. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10728. write_timeout_usec_,
  10729. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10730. return process_request(strm, remote_addr, remote_port, local_addr,
  10731. local_port, close_connection, connection_closed,
  10732. nullptr, &websocket_upgraded);
  10733. });
  10734. detail::shutdown_socket(sock);
  10735. detail::close_socket(sock);
  10736. return ret;
  10737. }
  10738. inline void Server::output_log(const Request &req, const Response &res) const {
  10739. if (logger_) {
  10740. std::lock_guard<std::mutex> guard(logger_mutex_);
  10741. logger_(req, res);
  10742. }
  10743. }
  10744. inline void Server::output_pre_compression_log(const Request &req,
  10745. const Response &res) const {
  10746. if (pre_compression_logger_) {
  10747. std::lock_guard<std::mutex> guard(logger_mutex_);
  10748. pre_compression_logger_(req, res);
  10749. }
  10750. }
  10751. inline void Server::output_error_log(const Error &err,
  10752. const Request *req) const {
  10753. if (error_logger_) {
  10754. std::lock_guard<std::mutex> guard(logger_mutex_);
  10755. error_logger_(err, req);
  10756. }
  10757. }
  10758. /*
  10759. * Group 5: ClientImpl and Client (Universal) implementation
  10760. */
  10761. // HTTP client implementation
  10762. inline ClientImpl::ClientImpl(const std::string &host)
  10763. : ClientImpl(host, 80, std::string(), std::string()) {}
  10764. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10765. : ClientImpl(host, port, std::string(), std::string()) {}
  10766. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10767. const std::string &client_cert_path,
  10768. const std::string &client_key_path)
  10769. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10770. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10771. inline ClientImpl::~ClientImpl() {
  10772. // Wait until all the requests in flight are handled.
  10773. size_t retry_count = 10;
  10774. while (retry_count-- > 0) {
  10775. {
  10776. std::lock_guard<std::mutex> guard(socket_mutex_);
  10777. if (socket_requests_in_flight_ == 0) { break; }
  10778. }
  10779. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10780. }
  10781. std::lock_guard<std::mutex> guard(socket_mutex_);
  10782. shutdown_socket(socket_);
  10783. close_socket(socket_);
  10784. }
  10785. inline bool ClientImpl::is_valid() const { return true; }
  10786. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10787. client_cert_path_ = rhs.client_cert_path_;
  10788. client_key_path_ = rhs.client_key_path_;
  10789. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10790. read_timeout_sec_ = rhs.read_timeout_sec_;
  10791. read_timeout_usec_ = rhs.read_timeout_usec_;
  10792. write_timeout_sec_ = rhs.write_timeout_sec_;
  10793. write_timeout_usec_ = rhs.write_timeout_usec_;
  10794. max_timeout_msec_ = rhs.max_timeout_msec_;
  10795. basic_auth_username_ = rhs.basic_auth_username_;
  10796. basic_auth_password_ = rhs.basic_auth_password_;
  10797. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10798. keep_alive_ = rhs.keep_alive_;
  10799. follow_location_ = rhs.follow_location_;
  10800. path_encode_ = rhs.path_encode_;
  10801. address_family_ = rhs.address_family_;
  10802. tcp_nodelay_ = rhs.tcp_nodelay_;
  10803. ipv6_v6only_ = rhs.ipv6_v6only_;
  10804. socket_options_ = rhs.socket_options_;
  10805. compress_ = rhs.compress_;
  10806. decompress_ = rhs.decompress_;
  10807. payload_max_length_ = rhs.payload_max_length_;
  10808. has_payload_max_length_ = rhs.has_payload_max_length_;
  10809. interface_ = rhs.interface_;
  10810. proxy_host_ = rhs.proxy_host_;
  10811. proxy_port_ = rhs.proxy_port_;
  10812. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10813. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10814. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10815. no_proxy_entries_ = rhs.no_proxy_entries_;
  10816. logger_ = rhs.logger_;
  10817. error_logger_ = rhs.error_logger_;
  10818. #ifdef CPPHTTPLIB_SSL_ENABLED
  10819. digest_auth_username_ = rhs.digest_auth_username_;
  10820. digest_auth_password_ = rhs.digest_auth_password_;
  10821. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10822. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10823. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10824. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10825. server_certificate_verification_ = rhs.server_certificate_verification_;
  10826. server_hostname_verification_ = rhs.server_hostname_verification_;
  10827. system_ca_mode_ = rhs.system_ca_mode_;
  10828. #endif
  10829. }
  10830. inline bool
  10831. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10832. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10833. if (no_proxy_entries_.empty()) { return true; }
  10834. // host_ is const so its normalized form is invariant; cache it. The
  10835. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10836. if (host == host_) {
  10837. if (!host_normalized_valid_) {
  10838. host_normalized_ = detail::normalize_target(host_);
  10839. host_normalized_valid_ = true;
  10840. }
  10841. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10842. }
  10843. auto target = detail::normalize_target(host);
  10844. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10845. }
  10846. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10847. if (is_proxy_enabled_for_host(host_)) {
  10848. return detail::create_client_socket(
  10849. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10850. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10851. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10852. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10853. }
  10854. // Check is custom IP specified for host_
  10855. std::string ip;
  10856. auto it = addr_map_.find(host_);
  10857. if (it != addr_map_.end()) { ip = it->second; }
  10858. return detail::create_client_socket(
  10859. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10860. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10861. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10862. write_timeout_usec_, interface_, error);
  10863. }
  10864. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10865. Error &error) {
  10866. auto sock = create_client_socket(error);
  10867. if (sock == INVALID_SOCKET) { return false; }
  10868. socket.sock = sock;
  10869. return true;
  10870. }
  10871. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10872. return create_and_connect_socket(socket, error);
  10873. }
  10874. inline bool ClientImpl::setup_proxy_connection(
  10875. Socket & /*socket*/,
  10876. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10877. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10878. return true;
  10879. }
  10880. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10881. bool /*shutdown_gracefully*/) {
  10882. // If there are any requests in flight from threads other than us, then it's
  10883. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10884. assert(socket_requests_in_flight_ == 0 ||
  10885. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10886. }
  10887. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10888. if (socket.sock == INVALID_SOCKET) { return; }
  10889. detail::shutdown_socket(socket.sock);
  10890. }
  10891. inline void ClientImpl::close_socket(Socket &socket) {
  10892. // If there are requests in flight in another thread, usually closing
  10893. // the socket will be fine and they will simply receive an error when
  10894. // using the closed socket, but it is still a bug since rarely the OS
  10895. // may reassign the socket id to be used for a new socket, and then
  10896. // suddenly they will be operating on a live socket that is different
  10897. // than the one they intended!
  10898. assert(socket_requests_in_flight_ == 0 ||
  10899. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10900. // It is also a bug if this happens while SSL is still active
  10901. #ifdef CPPHTTPLIB_SSL_ENABLED
  10902. assert(socket.ssl == nullptr);
  10903. #endif
  10904. if (socket.sock == INVALID_SOCKET) { return; }
  10905. detail::close_socket(socket.sock);
  10906. socket.sock = INVALID_SOCKET;
  10907. }
  10908. inline void ClientImpl::disconnect(bool gracefully) {
  10909. shutdown_ssl(socket_, gracefully);
  10910. shutdown_socket(socket_);
  10911. close_socket(socket_);
  10912. }
  10913. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10914. Response &res,
  10915. bool skip_100_continue) const {
  10916. std::array<char, 2048> buf{};
  10917. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10918. if (!line_reader.getline()) { return false; }
  10919. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10920. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10921. #else
  10922. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10923. #endif
  10924. std::cmatch m;
  10925. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10926. return req.method == "CONNECT";
  10927. }
  10928. res.version = std::string(m[1]);
  10929. res.status = std::stoi(std::string(m[2]));
  10930. res.reason = std::string(m[3]);
  10931. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10932. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10933. if (!line_reader.getline()) { return false; } // CRLF
  10934. if (!line_reader.getline()) { return false; } // next response line
  10935. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10936. res.version = std::string(m[1]);
  10937. res.status = std::stoi(std::string(m[2]));
  10938. res.reason = std::string(m[3]);
  10939. }
  10940. return true;
  10941. }
  10942. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10943. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10944. auto ret = send_(req, res, error);
  10945. if (error == Error::SSLPeerCouldBeClosed_) {
  10946. assert(!ret);
  10947. ret = send_(req, res, error);
  10948. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10949. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10950. }
  10951. return ret;
  10952. }
  10953. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10954. {
  10955. std::lock_guard<std::mutex> guard(socket_mutex_);
  10956. // Set this to false immediately - if it ever gets set to true by the end
  10957. // of the request, we know another thread instructed us to close the
  10958. // socket.
  10959. socket_should_be_closed_when_request_is_done_ = false;
  10960. auto is_alive = false;
  10961. if (socket_.is_open()) {
  10962. is_alive = detail::is_socket_alive(socket_.sock);
  10963. #ifdef CPPHTTPLIB_SSL_ENABLED
  10964. if (is_alive && is_ssl()) {
  10965. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10966. is_alive = false;
  10967. }
  10968. }
  10969. #endif
  10970. if (!is_alive) {
  10971. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10972. disconnect(/*gracefully=*/false);
  10973. }
  10974. }
  10975. if (!is_alive) {
  10976. if (!ensure_socket_connection(socket_, error)) {
  10977. output_error_log(error, &req);
  10978. return false;
  10979. }
  10980. {
  10981. auto success = true;
  10982. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10983. error)) {
  10984. if (!success) { output_error_log(error, &req); }
  10985. return success;
  10986. }
  10987. }
  10988. }
  10989. // Mark the current socket as being in use so that it cannot be closed by
  10990. // anyone else while this request is ongoing, even though we will be
  10991. // releasing the mutex.
  10992. if (socket_requests_in_flight_ > 1) {
  10993. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10994. }
  10995. socket_requests_in_flight_ += 1;
  10996. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10997. }
  10998. for (const auto &header : default_headers_) {
  10999. if (req.headers.find(header.first) == req.headers.end()) {
  11000. req.headers.insert(header);
  11001. }
  11002. }
  11003. auto ret = false;
  11004. auto close_connection = !keep_alive_;
  11005. auto se = detail::scope_exit([&]() {
  11006. // Briefly lock mutex in order to mark that a request is no longer ongoing
  11007. std::lock_guard<std::mutex> guard(socket_mutex_);
  11008. socket_requests_in_flight_ -= 1;
  11009. if (socket_requests_in_flight_ <= 0) {
  11010. assert(socket_requests_in_flight_ == 0);
  11011. socket_requests_are_from_thread_ = std::thread::id();
  11012. }
  11013. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  11014. !ret) {
  11015. disconnect(/*gracefully=*/true);
  11016. }
  11017. });
  11018. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  11019. return handle_request(strm, req, res, close_connection, error);
  11020. });
  11021. if (!ret) {
  11022. if (error == Error::Success) {
  11023. error = Error::Unknown;
  11024. output_error_log(error, &req);
  11025. }
  11026. }
  11027. return ret;
  11028. }
  11029. inline Result ClientImpl::send(const Request &req) {
  11030. auto req2 = req;
  11031. return send_(std::move(req2));
  11032. }
  11033. inline Result ClientImpl::send_(Request &&req) {
  11034. auto res = detail::make_unique<Response>();
  11035. auto error = Error::Success;
  11036. auto ret = send(req, *res, error);
  11037. #ifdef CPPHTTPLIB_SSL_ENABLED
  11038. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  11039. last_ssl_error_, last_backend_error_};
  11040. #else
  11041. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  11042. #endif
  11043. }
  11044. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  11045. const std::string &ct) {
  11046. (void)for_stream;
  11047. for (const auto &header : default_headers_) {
  11048. if (!r.has_header(header.first)) { r.headers.insert(header); }
  11049. }
  11050. if (!r.has_header("Host")) {
  11051. if (address_family_ == AF_UNIX) {
  11052. r.headers.emplace("Host", "localhost");
  11053. } else {
  11054. r.headers.emplace(
  11055. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  11056. }
  11057. }
  11058. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  11059. if (!r.content_receiver) {
  11060. if (!r.has_header("Accept-Encoding")) {
  11061. std::string accept_encoding;
  11062. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11063. accept_encoding = "br";
  11064. #endif
  11065. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11066. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11067. accept_encoding += "gzip, deflate";
  11068. #endif
  11069. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11070. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11071. accept_encoding += "zstd";
  11072. #endif
  11073. r.set_header("Accept-Encoding", accept_encoding);
  11074. }
  11075. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11076. if (!r.has_header("User-Agent")) {
  11077. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11078. r.set_header("User-Agent", agent);
  11079. }
  11080. #endif
  11081. }
  11082. if (!r.body.empty()) {
  11083. if (!ct.empty() && !r.has_header("Content-Type")) {
  11084. r.headers.emplace("Content-Type", ct);
  11085. }
  11086. if (!r.has_header("Content-Length")) {
  11087. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11088. }
  11089. }
  11090. }
  11091. inline ClientImpl::StreamHandle
  11092. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11093. const Params &params, const Headers &headers,
  11094. const std::string &body,
  11095. const std::string &content_type) {
  11096. StreamHandle handle;
  11097. handle.response = detail::make_unique<Response>();
  11098. handle.error = Error::Success;
  11099. auto query_path = params.empty() ? path : append_query_params(path, params);
  11100. handle.connection_ = detail::make_unique<ClientConnection>();
  11101. {
  11102. std::lock_guard<std::mutex> guard(socket_mutex_);
  11103. auto is_alive = false;
  11104. if (socket_.is_open()) {
  11105. is_alive = detail::is_socket_alive(socket_.sock);
  11106. #ifdef CPPHTTPLIB_SSL_ENABLED
  11107. if (is_alive && is_ssl()) {
  11108. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11109. is_alive = false;
  11110. }
  11111. }
  11112. #endif
  11113. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11114. }
  11115. if (!is_alive) {
  11116. if (!ensure_socket_connection(socket_, handle.error)) {
  11117. handle.response.reset();
  11118. return handle;
  11119. }
  11120. {
  11121. auto success = true;
  11122. auto start_time = std::chrono::steady_clock::now();
  11123. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11124. success, handle.error)) {
  11125. if (!success) { handle.response.reset(); }
  11126. return handle;
  11127. }
  11128. }
  11129. }
  11130. transfer_socket_ownership_to_handle(handle);
  11131. }
  11132. #ifdef CPPHTTPLIB_SSL_ENABLED
  11133. if (is_ssl() && handle.connection_->session) {
  11134. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11135. handle.connection_->sock, handle.connection_->session,
  11136. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11137. write_timeout_usec_);
  11138. } else {
  11139. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11140. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11141. write_timeout_sec_, write_timeout_usec_);
  11142. }
  11143. #else
  11144. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11145. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11146. write_timeout_sec_, write_timeout_usec_);
  11147. #endif
  11148. handle.stream_ = handle.socket_stream_.get();
  11149. Request req;
  11150. req.method = method;
  11151. req.path = query_path;
  11152. req.headers = headers;
  11153. req.body = body;
  11154. prepare_default_headers(req, true, content_type);
  11155. auto &strm = *handle.stream_;
  11156. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11157. handle.error = Error::Write;
  11158. handle.response.reset();
  11159. return handle;
  11160. }
  11161. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11162. handle.error)) {
  11163. handle.response.reset();
  11164. return handle;
  11165. }
  11166. if (!body.empty()) {
  11167. if (strm.write(body.data(), body.size()) < 0) {
  11168. handle.error = Error::Write;
  11169. handle.response.reset();
  11170. return handle;
  11171. }
  11172. }
  11173. if (!read_response_line(strm, req, *handle.response) ||
  11174. !detail::read_headers(strm, handle.response->headers)) {
  11175. handle.error = Error::Read;
  11176. handle.response.reset();
  11177. return handle;
  11178. }
  11179. handle.body_reader_.stream = handle.stream_;
  11180. handle.body_reader_.payload_max_length = payload_max_length_;
  11181. if (handle.response->has_header("Content-Length")) {
  11182. bool is_invalid = false;
  11183. auto content_length = detail::get_header_value_u64(
  11184. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11185. if (is_invalid) {
  11186. handle.error = Error::Read;
  11187. handle.response.reset();
  11188. return handle;
  11189. }
  11190. handle.body_reader_.has_content_length = true;
  11191. handle.body_reader_.content_length = content_length;
  11192. }
  11193. handle.body_reader_.chunked =
  11194. detail::is_chunked_transfer_encoding(handle.response->headers);
  11195. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11196. if (!content_encoding.empty()) {
  11197. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11198. }
  11199. return handle;
  11200. }
  11201. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11202. if (!is_valid() || !response) { return -1; }
  11203. if (decompressor_) { return read_with_decompression(buf, len); }
  11204. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11205. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11206. trailers_parsed_ = true;
  11207. if (body_reader_.chunked_decoder) {
  11208. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11209. response->trailers, response->headers)) {
  11210. return n;
  11211. }
  11212. } else {
  11213. detail::ChunkedDecoder dec(*stream_);
  11214. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11215. return n;
  11216. }
  11217. }
  11218. }
  11219. return n;
  11220. }
  11221. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11222. size_t len) {
  11223. if (decompress_offset_ < decompress_buffer_.size()) {
  11224. auto available = decompress_buffer_.size() - decompress_offset_;
  11225. auto to_copy = (std::min)(len, available);
  11226. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11227. decompress_offset_ += to_copy;
  11228. decompressed_bytes_read_ += to_copy;
  11229. return static_cast<ssize_t>(to_copy);
  11230. }
  11231. decompress_buffer_.clear();
  11232. decompress_offset_ = 0;
  11233. constexpr size_t kDecompressionBufferSize = 8192;
  11234. char compressed_buf[kDecompressionBufferSize];
  11235. while (true) {
  11236. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11237. sizeof(compressed_buf));
  11238. if (n <= 0) { return n; }
  11239. bool decompress_ok = decompressor_->decompress(
  11240. compressed_buf, static_cast<size_t>(n),
  11241. [this](const char *data, size_t data_len) {
  11242. decompress_buffer_.append(data, data_len);
  11243. auto limit = body_reader_.payload_max_length;
  11244. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11245. return false;
  11246. }
  11247. return true;
  11248. });
  11249. if (!decompress_ok) {
  11250. body_reader_.last_error = Error::Read;
  11251. return -1;
  11252. }
  11253. if (!decompress_buffer_.empty()) { break; }
  11254. }
  11255. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11256. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11257. decompress_offset_ = to_copy;
  11258. decompressed_bytes_read_ += to_copy;
  11259. return static_cast<ssize_t>(to_copy);
  11260. }
  11261. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11262. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11263. return;
  11264. }
  11265. trailers_parsed_ = true;
  11266. const auto bufsiz = 128;
  11267. char line_buf[bufsiz];
  11268. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11269. if (!line_reader.getline()) { return; }
  11270. if (!detail::parse_trailers(line_reader, response->trailers,
  11271. response->headers)) {
  11272. return;
  11273. }
  11274. }
  11275. namespace detail {
  11276. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11277. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11278. size_t &out_chunk_offset,
  11279. size_t &out_chunk_total) {
  11280. if (finished) { return 0; }
  11281. if (chunk_remaining == 0) {
  11282. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11283. if (!lr.getline()) { return -1; }
  11284. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11285. const char *p = lr.ptr();
  11286. int v = 0;
  11287. if (!is_hex(*p, v)) { return -1; }
  11288. size_t chunk_len = 0;
  11289. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11290. for (; is_hex(*p, v); ++p) {
  11291. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11292. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11293. }
  11294. while (is_space_or_tab(*p)) {
  11295. ++p;
  11296. }
  11297. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11298. if (chunk_len == 0) {
  11299. chunk_remaining = 0;
  11300. finished = true;
  11301. out_chunk_offset = 0;
  11302. out_chunk_total = 0;
  11303. return 0;
  11304. }
  11305. chunk_remaining = chunk_len;
  11306. last_chunk_total = chunk_remaining;
  11307. last_chunk_offset = 0;
  11308. }
  11309. auto to_read = (std::min)(chunk_remaining, len);
  11310. auto n = strm.read(buf, to_read);
  11311. if (n <= 0) { return -1; }
  11312. auto offset_before = last_chunk_offset;
  11313. last_chunk_offset += static_cast<size_t>(n);
  11314. chunk_remaining -= static_cast<size_t>(n);
  11315. out_chunk_offset = offset_before;
  11316. out_chunk_total = last_chunk_total;
  11317. if (chunk_remaining == 0) {
  11318. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11319. if (!lr.getline()) { return -1; }
  11320. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11321. }
  11322. return n;
  11323. }
  11324. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11325. const Headers &src_headers) {
  11326. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11327. if (!lr.getline()) { return false; }
  11328. return parse_trailers(lr, dest, src_headers);
  11329. }
  11330. } // namespace detail
  11331. inline void
  11332. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11333. handle.connection_->sock = socket_.sock;
  11334. #ifdef CPPHTTPLIB_SSL_ENABLED
  11335. handle.connection_->session = socket_.ssl;
  11336. socket_.ssl = nullptr;
  11337. #endif
  11338. socket_.sock = INVALID_SOCKET;
  11339. }
  11340. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11341. Response &res, bool close_connection,
  11342. Error &error) {
  11343. if (req.path.empty()) {
  11344. error = Error::Connection;
  11345. output_error_log(error, &req);
  11346. return false;
  11347. }
  11348. auto req_save = req;
  11349. bool ret;
  11350. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11351. auto req2 = req;
  11352. req2.path = "http://" +
  11353. detail::make_host_and_port_string(host_, port_, false) +
  11354. req.path;
  11355. ret = process_request(strm, req2, res, close_connection, error);
  11356. req = std::move(req2);
  11357. req.path = req_save.path;
  11358. } else {
  11359. ret = process_request(strm, req, res, close_connection, error);
  11360. }
  11361. if (!ret) { return false; }
  11362. if (res.get_header_value("Connection") == "close" ||
  11363. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11364. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11365. // for this to be safe.
  11366. // This is safe to call because handle_request is only called by send_
  11367. // which locks the request mutex during the process. It would be a bug
  11368. // to call it from a different thread since it's a thread-safety issue
  11369. // to do these things to the socket if another thread is using the socket.
  11370. std::lock_guard<std::mutex> guard(socket_mutex_);
  11371. disconnect(/*gracefully=*/true);
  11372. }
  11373. if (300 < res.status && res.status < 400 && follow_location_) {
  11374. req = std::move(req_save);
  11375. ret = redirect(req, res, error);
  11376. }
  11377. #ifdef CPPHTTPLIB_SSL_ENABLED
  11378. if ((res.status == StatusCode::Unauthorized_401 ||
  11379. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11380. req.authorization_count_ < 5) {
  11381. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11382. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11383. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11384. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11385. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11386. return ret;
  11387. }
  11388. const auto &username =
  11389. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11390. const auto &password =
  11391. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11392. if (!username.empty() && !password.empty()) {
  11393. std::map<std::string, std::string> auth;
  11394. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11395. Request new_req = req;
  11396. new_req.authorization_count_ += 1;
  11397. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11398. : "Authorization");
  11399. new_req.headers.insert(detail::make_digest_authentication_header(
  11400. req, auth, new_req.authorization_count_, detail::random_string(10),
  11401. username, password, is_proxy));
  11402. Response new_res;
  11403. ret = send(new_req, new_res, error);
  11404. if (ret) { res = std::move(new_res); }
  11405. }
  11406. }
  11407. }
  11408. #endif
  11409. return ret;
  11410. }
  11411. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11412. if (req.redirect_count_ == 0) {
  11413. error = Error::ExceedRedirectCount;
  11414. output_error_log(error, &req);
  11415. return false;
  11416. }
  11417. auto location = res.get_header_value("location");
  11418. if (location.empty()) { return false; }
  11419. detail::UrlComponents uc;
  11420. if (!detail::parse_url(location, uc)) { return false; }
  11421. // Only follow http/https redirects
  11422. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11423. return false;
  11424. }
  11425. auto scheme = is_ssl() ? "https" : "http";
  11426. auto next_scheme = std::move(uc.scheme);
  11427. auto next_host = std::move(uc.host);
  11428. auto port_str = std::move(uc.port);
  11429. auto next_path = std::move(uc.path);
  11430. auto next_query = std::move(uc.query);
  11431. auto next_port = port_;
  11432. if (!port_str.empty()) {
  11433. if (!detail::parse_port(port_str, next_port)) { return false; }
  11434. } else if (!next_scheme.empty()) {
  11435. next_port = next_scheme == "https" ? 443 : 80;
  11436. }
  11437. if (next_scheme.empty()) { next_scheme = scheme; }
  11438. if (next_host.empty()) { next_host = host_; }
  11439. if (next_path.empty()) { next_path = "/"; }
  11440. auto path = decode_path_component(next_path) + next_query;
  11441. // Same host redirect - use current client
  11442. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11443. return detail::redirect(*this, req, res, path, location, error);
  11444. }
  11445. // Cross-host/scheme redirect - create new client with robust setup
  11446. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11447. path, location, error);
  11448. }
  11449. // New method for robust redirect client creation
  11450. inline bool ClientImpl::create_redirect_client(
  11451. const std::string &scheme, const std::string &host, int port, Request &req,
  11452. Response &res, const std::string &path, const std::string &location,
  11453. Error &error) {
  11454. // Determine if we need SSL
  11455. auto need_ssl = (scheme == "https");
  11456. // Clean up request headers that are host/client specific
  11457. // Remove headers that should not be carried over to new host
  11458. auto headers_to_remove = std::vector<std::string>{
  11459. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  11460. for (const auto &header_name : headers_to_remove) {
  11461. auto it = req.headers.find(header_name);
  11462. while (it != req.headers.end()) {
  11463. it = req.headers.erase(it);
  11464. it = req.headers.find(header_name);
  11465. }
  11466. }
  11467. // Create appropriate client type and handle redirect
  11468. if (need_ssl) {
  11469. #ifdef CPPHTTPLIB_SSL_ENABLED
  11470. // Create SSL client for HTTPS redirect
  11471. SSLClient redirect_client(host, port);
  11472. // Setup basic client configuration first
  11473. setup_redirect_client(redirect_client);
  11474. redirect_client.enable_server_certificate_verification(
  11475. server_certificate_verification_);
  11476. redirect_client.enable_server_hostname_verification(
  11477. server_hostname_verification_);
  11478. redirect_client.system_ca_mode_ = system_ca_mode_;
  11479. // Transfer CA certificate to redirect client
  11480. if (!ca_cert_pem_.empty()) {
  11481. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11482. ca_cert_pem_.size());
  11483. }
  11484. if (!ca_cert_file_path_.empty()) {
  11485. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11486. }
  11487. // Client certificates are set through constructor for SSLClient
  11488. // NOTE: SSLClient constructor already takes client_cert_path and
  11489. // client_key_path so we need to create it properly if client certs are
  11490. // needed
  11491. // Execute the redirect
  11492. return detail::redirect(redirect_client, req, res, path, location, error);
  11493. #else
  11494. // SSL not supported - set appropriate error
  11495. error = Error::SSLConnection;
  11496. output_error_log(error, &req);
  11497. return false;
  11498. #endif
  11499. } else {
  11500. // HTTP redirect
  11501. ClientImpl redirect_client(host, port);
  11502. // Setup client with robust configuration
  11503. setup_redirect_client(redirect_client);
  11504. // Execute the redirect
  11505. return detail::redirect(redirect_client, req, res, path, location, error);
  11506. }
  11507. }
  11508. // New method for robust client setup (based on basic_manual_redirect.cpp
  11509. // logic)
  11510. template <typename ClientType>
  11511. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11512. // Copy basic settings first
  11513. client.set_connection_timeout(connection_timeout_sec_);
  11514. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11515. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11516. client.set_keep_alive(keep_alive_);
  11517. client.set_follow_location(
  11518. true); // Enable redirects to handle multi-step redirects
  11519. client.set_path_encode(path_encode_);
  11520. client.set_compress(compress_);
  11521. client.set_decompress(decompress_);
  11522. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11523. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11524. // 15.4, credentials must not be forwarded when redirecting to a different
  11525. // host. This function is only called for cross-host redirects; same-host
  11526. // redirects are handled directly in ClientImpl::redirect().
  11527. // Copy the proxy configuration unconditionally; the per-target bypass is
  11528. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11529. // still use the proxy.
  11530. client.no_proxy_entries_ = no_proxy_entries_;
  11531. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11532. client.set_proxy(proxy_host_, proxy_port_);
  11533. if (!proxy_basic_auth_username_.empty()) {
  11534. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11535. proxy_basic_auth_password_);
  11536. }
  11537. if (!proxy_bearer_token_auth_token_.empty()) {
  11538. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11539. }
  11540. #ifdef CPPHTTPLIB_SSL_ENABLED
  11541. if (!proxy_digest_auth_username_.empty()) {
  11542. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11543. proxy_digest_auth_password_);
  11544. }
  11545. #endif
  11546. }
  11547. // Copy network and socket settings
  11548. client.set_address_family(address_family_);
  11549. client.set_tcp_nodelay(tcp_nodelay_);
  11550. client.set_ipv6_v6only(ipv6_v6only_);
  11551. if (socket_options_) { client.set_socket_options(socket_options_); }
  11552. if (!interface_.empty()) { client.set_interface(interface_); }
  11553. // Copy logging and headers
  11554. if (logger_) { client.set_logger(logger_); }
  11555. if (error_logger_) { client.set_error_logger(error_logger_); }
  11556. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11557. // Each new client should generate its own headers based on its target host
  11558. }
  11559. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11560. const Request &req,
  11561. Error &error) const {
  11562. auto is_shutting_down = []() { return false; };
  11563. if (req.is_chunked_content_provider_) {
  11564. auto compressor = compress_ ? detail::create_compressor().first
  11565. : std::unique_ptr<detail::compressor>();
  11566. if (!compressor) {
  11567. compressor = detail::make_unique<detail::nocompressor>();
  11568. }
  11569. return detail::write_content_chunked(strm, req.content_provider_,
  11570. is_shutting_down, *compressor, error);
  11571. } else {
  11572. return detail::write_content_with_progress(
  11573. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11574. req.upload_progress, error);
  11575. }
  11576. }
  11577. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11578. bool close_connection, Error &error,
  11579. bool skip_body) {
  11580. // Prepare additional headers
  11581. if (close_connection) {
  11582. if (!req.has_header("Connection")) {
  11583. req.set_header("Connection", "close");
  11584. }
  11585. }
  11586. std::string ct_for_defaults;
  11587. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11588. ct_for_defaults = "text/plain";
  11589. }
  11590. prepare_default_headers(req, false, ct_for_defaults);
  11591. if (req.body.empty()) {
  11592. if (req.content_provider_) {
  11593. if (!req.is_chunked_content_provider_) {
  11594. if (!req.has_header("Content-Length")) {
  11595. auto length = std::to_string(req.content_length_);
  11596. req.set_header("Content-Length", length);
  11597. }
  11598. }
  11599. } else {
  11600. if (req.method == "POST" || req.method == "PUT" ||
  11601. req.method == "PATCH") {
  11602. req.set_header("Content-Length", "0");
  11603. }
  11604. }
  11605. }
  11606. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11607. if (!req.has_header("Authorization")) {
  11608. req.headers.insert(make_basic_authentication_header(
  11609. basic_auth_username_, basic_auth_password_, false));
  11610. }
  11611. }
  11612. if (!bearer_token_auth_token_.empty()) {
  11613. if (!req.has_header("Authorization")) {
  11614. req.headers.insert(make_bearer_token_authentication_header(
  11615. bearer_token_auth_token_, false));
  11616. }
  11617. }
  11618. // Proxy-Authorization is only sent when the proxy is actually used for
  11619. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11620. // credentials directly to the destination server.
  11621. if (is_proxy_enabled_for_host(host_)) {
  11622. if (!proxy_basic_auth_username_.empty() &&
  11623. !proxy_basic_auth_password_.empty() &&
  11624. !req.has_header("Proxy-Authorization")) {
  11625. req.headers.insert(make_basic_authentication_header(
  11626. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11627. }
  11628. if (!proxy_bearer_token_auth_token_.empty() &&
  11629. !req.has_header("Proxy-Authorization")) {
  11630. req.headers.insert(make_bearer_token_authentication_header(
  11631. proxy_bearer_token_auth_token_, true));
  11632. }
  11633. }
  11634. // Request line and headers
  11635. {
  11636. detail::BufferStream bstrm;
  11637. // Extract path and query from req.path
  11638. std::string path_part, query_part;
  11639. auto query_pos = req.path.find('?');
  11640. if (query_pos != std::string::npos) {
  11641. path_part = req.path.substr(0, query_pos);
  11642. query_part = req.path.substr(query_pos + 1);
  11643. } else {
  11644. path_part = req.path;
  11645. query_part = "";
  11646. }
  11647. // Encode path part. If the original `req.path` already contained a
  11648. // query component, preserve its raw query string (including parameter
  11649. // order) instead of reparsing and reassembling it which may reorder
  11650. // parameters due to container ordering (e.g. `Params` uses
  11651. // `std::multimap`). When there is no query in `req.path`, fall back to
  11652. // building a query from `req.params` so existing callers that pass
  11653. // `Params` continue to work.
  11654. auto path_with_query =
  11655. path_encode_ ? detail::encode_path(path_part) : path_part;
  11656. if (!query_part.empty()) {
  11657. // Normalize the query string (decode then re-encode) while preserving
  11658. // the original parameter order. When path encoding is disabled the
  11659. // caller has supplied an already-encoded target and expects the exact
  11660. // bytes to be sent on the wire, so skip normalization for the query
  11661. // too. Normalizing here would decode-then-re-encode the query and
  11662. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11663. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11664. if (path_encode_) {
  11665. auto normalized = detail::normalize_query_string(query_part);
  11666. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11667. } else {
  11668. path_with_query += '?' + query_part;
  11669. }
  11670. // Still populate req.params for handlers/users who read them.
  11671. detail::parse_query_text(query_part, req.params);
  11672. } else {
  11673. // No query in path; parse any query_part (empty) and append params
  11674. // from `req.params` when present (preserves prior behavior for
  11675. // callers who provide Params separately).
  11676. detail::parse_query_text(query_part, req.params);
  11677. if (!req.params.empty()) {
  11678. path_with_query = append_query_params(path_with_query, req.params);
  11679. }
  11680. }
  11681. // Write request line and headers
  11682. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  11683. // A rejected target (e.g. CR/LF smuggled in via a decoded redirect
  11684. // Location under set_path_encode(false)) must fail the request cleanly
  11685. // instead of emitting a request-line-less, header-injecting request.
  11686. error = Error::Write;
  11687. output_error_log(error, &req);
  11688. return false;
  11689. }
  11690. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11691. error)) {
  11692. output_error_log(error, &req);
  11693. return false;
  11694. }
  11695. // Flush buffer
  11696. auto &data = bstrm.get_buffer();
  11697. if (!detail::write_data(strm, data.data(), data.size())) {
  11698. error = Error::Write;
  11699. output_error_log(error, &req);
  11700. return false;
  11701. }
  11702. }
  11703. // After sending request line and headers, wait briefly for an early server
  11704. // response (e.g. 4xx) and avoid sending a potentially large request body
  11705. // unnecessarily. This workaround is only enabled on Windows because Unix
  11706. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11707. // buffering can accept large writes even when the peer already responded.
  11708. // Check the stream first (which covers SSL via `is_readable()`), then
  11709. // fall back to select on the socket. Only perform the wait for very large
  11710. // request bodies to avoid interfering with normal small requests and
  11711. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11712. // response. Skip this check when using Expect: 100-continue, as the protocol
  11713. // handles early responses properly.
  11714. #if defined(_WIN32)
  11715. if (!skip_body &&
  11716. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11717. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11718. auto start = std::chrono::high_resolution_clock::now();
  11719. for (;;) {
  11720. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11721. // from SSL internals. If the underlying socket is readable, assume an
  11722. // early response may be present.
  11723. auto sock = strm.socket();
  11724. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11725. return false;
  11726. }
  11727. // Fallback to stream-level check for non-socket streams or when the
  11728. // socket isn't reporting readable. Avoid using `is_readable()` for
  11729. // SSL, since `SSL_pending()` may report buffered records that do not
  11730. // indicate a complete application-level response yet.
  11731. if (!is_ssl() && strm.is_readable()) { return false; }
  11732. auto now = std::chrono::high_resolution_clock::now();
  11733. auto elapsed =
  11734. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11735. .count();
  11736. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11737. break;
  11738. }
  11739. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11740. }
  11741. }
  11742. #endif
  11743. // Body
  11744. if (skip_body) { return true; }
  11745. return write_request_body(strm, req, error);
  11746. }
  11747. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11748. Error &error) {
  11749. if (req.body.empty()) {
  11750. return write_content_with_provider(strm, req, error);
  11751. }
  11752. if (req.upload_progress) {
  11753. auto body_size = req.body.size();
  11754. size_t written = 0;
  11755. auto data = req.body.data();
  11756. while (written < body_size) {
  11757. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11758. if (!detail::write_data(strm, data + written, to_write)) {
  11759. error = Error::Write;
  11760. output_error_log(error, &req);
  11761. return false;
  11762. }
  11763. written += to_write;
  11764. if (!req.upload_progress(written, body_size)) {
  11765. error = Error::Canceled;
  11766. output_error_log(error, &req);
  11767. return false;
  11768. }
  11769. }
  11770. } else {
  11771. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11772. error = Error::Write;
  11773. output_error_log(error, &req);
  11774. return false;
  11775. }
  11776. }
  11777. return true;
  11778. }
  11779. inline std::unique_ptr<Response>
  11780. ClientImpl::send_with_content_provider_and_receiver(
  11781. Request &req, const char *body, size_t content_length,
  11782. ContentProvider content_provider,
  11783. ContentProviderWithoutLength content_provider_without_length,
  11784. const std::string &content_type, ContentReceiver content_receiver,
  11785. Error &error) {
  11786. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11787. auto enc = compress_
  11788. ? detail::create_compressor()
  11789. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11790. nullptr, nullptr);
  11791. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11792. if (enc.first && !content_provider_without_length) {
  11793. auto &compressor = enc.first;
  11794. if (content_provider) {
  11795. auto ok = true;
  11796. size_t offset = 0;
  11797. DataSink data_sink;
  11798. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11799. if (ok) {
  11800. auto last = offset + data_len == content_length;
  11801. auto ret = compressor->compress(
  11802. data, data_len, last,
  11803. [&](const char *compressed_data, size_t compressed_data_len) {
  11804. req.body.append(compressed_data, compressed_data_len);
  11805. return true;
  11806. });
  11807. if (ret) {
  11808. offset += data_len;
  11809. } else {
  11810. ok = false;
  11811. }
  11812. }
  11813. return ok;
  11814. };
  11815. while (ok && offset < content_length) {
  11816. if (!content_provider(offset, content_length - offset, data_sink)) {
  11817. error = Error::Canceled;
  11818. output_error_log(error, &req);
  11819. return nullptr;
  11820. }
  11821. }
  11822. } else {
  11823. if (!compressor->compress(body, content_length, true,
  11824. [&](const char *data, size_t data_len) {
  11825. req.body.append(data, data_len);
  11826. return true;
  11827. })) {
  11828. error = Error::Compression;
  11829. output_error_log(error, &req);
  11830. return nullptr;
  11831. }
  11832. }
  11833. } else {
  11834. if (content_provider) {
  11835. req.content_length_ = content_length;
  11836. req.content_provider_ = std::move(content_provider);
  11837. req.is_chunked_content_provider_ = false;
  11838. } else if (content_provider_without_length) {
  11839. req.content_length_ = 0;
  11840. req.content_provider_ = detail::ContentProviderAdapter(
  11841. std::move(content_provider_without_length));
  11842. req.is_chunked_content_provider_ = true;
  11843. req.set_header("Transfer-Encoding", "chunked");
  11844. } else {
  11845. req.body.assign(body, content_length);
  11846. }
  11847. }
  11848. if (content_receiver) {
  11849. req.content_receiver =
  11850. [content_receiver](const char *data, size_t data_length,
  11851. size_t /*offset*/, size_t /*total_length*/) {
  11852. return content_receiver(data, data_length);
  11853. };
  11854. }
  11855. auto res = detail::make_unique<Response>();
  11856. return send(req, *res, error) ? std::move(res) : nullptr;
  11857. }
  11858. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11859. const std::string &method, const std::string &path, const Headers &headers,
  11860. const char *body, size_t content_length, ContentProvider content_provider,
  11861. ContentProviderWithoutLength content_provider_without_length,
  11862. const std::string &content_type, ContentReceiver content_receiver,
  11863. UploadProgress progress) {
  11864. Request req;
  11865. req.method = method;
  11866. req.headers = headers;
  11867. req.path = path;
  11868. req.upload_progress = std::move(progress);
  11869. if (max_timeout_msec_ > 0) {
  11870. req.start_time_ = std::chrono::steady_clock::now();
  11871. }
  11872. auto error = Error::Success;
  11873. auto res = send_with_content_provider_and_receiver(
  11874. req, body, content_length, std::move(content_provider),
  11875. std::move(content_provider_without_length), content_type,
  11876. std::move(content_receiver), error);
  11877. #ifdef CPPHTTPLIB_SSL_ENABLED
  11878. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11879. last_backend_error_};
  11880. #else
  11881. return Result{std::move(res), error, std::move(req.headers)};
  11882. #endif
  11883. }
  11884. inline void ClientImpl::output_log(const Request &req,
  11885. const Response &res) const {
  11886. if (logger_) {
  11887. std::lock_guard<std::mutex> guard(logger_mutex_);
  11888. logger_(req, res);
  11889. }
  11890. }
  11891. inline void ClientImpl::output_error_log(const Error &err,
  11892. const Request *req) const {
  11893. if (error_logger_) {
  11894. std::lock_guard<std::mutex> guard(logger_mutex_);
  11895. error_logger_(err, req);
  11896. }
  11897. }
  11898. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11899. Response &res, bool close_connection,
  11900. Error &error) {
  11901. // Auto-add Expect: 100-continue for large bodies
  11902. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11903. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11904. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11905. req.set_header("Expect", "100-continue");
  11906. }
  11907. }
  11908. // Check for Expect: 100-continue
  11909. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11910. // Send request (skip body if using Expect: 100-continue)
  11911. auto write_request_success =
  11912. write_request(strm, req, close_connection, error, expect_100_continue);
  11913. #ifdef CPPHTTPLIB_SSL_ENABLED
  11914. if (is_ssl() && !expect_100_continue) {
  11915. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11916. if (!is_proxy_enabled) {
  11917. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11918. error = Error::SSLPeerCouldBeClosed_;
  11919. output_error_log(error, &req);
  11920. return false;
  11921. }
  11922. }
  11923. }
  11924. #endif
  11925. // Handle Expect: 100-continue.
  11926. //
  11927. // Wait for an interim/early response by attempting to read the status line
  11928. // under a short timeout, instead of trusting raw socket readability. Over
  11929. // TLS, post-handshake records (e.g. session tickets) make the socket
  11930. // readable without any HTTP response being available; relying on
  11931. // `select_read` there caused the body to be withheld forever and the
  11932. // request to fail with `Read` (#2458). If no status line arrives within the
  11933. // timeout, send the body anyway (matching curl's behavior).
  11934. auto status_line_read = false;
  11935. if (expect_100_continue && write_request_success) {
  11936. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11937. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11938. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11939. strm.set_read_timeout(sec, usec);
  11940. status_line_read = read_response_line(strm, req, res, false);
  11941. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11942. }
  11943. if (!status_line_read) {
  11944. // No interim response within the timeout: send the body and handle the
  11945. // response as usual.
  11946. if (!write_request_body(strm, req, error)) { return false; }
  11947. expect_100_continue = false; // Switch to normal response handling
  11948. }
  11949. }
  11950. // Receive response and headers
  11951. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11952. if ((!status_line_read &&
  11953. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11954. !detail::read_headers(strm, res.headers)) {
  11955. if (write_request_success) { error = Error::Read; }
  11956. output_error_log(error, &req);
  11957. return false;
  11958. }
  11959. if (!write_request_success) { return false; }
  11960. // Handle Expect: 100-continue response
  11961. if (expect_100_continue) {
  11962. if (res.status == StatusCode::Continue_100) {
  11963. // Server accepted, send the body
  11964. if (!write_request_body(strm, req, error)) { return false; }
  11965. // Read the actual response
  11966. res.headers.clear();
  11967. res.body.clear();
  11968. if (!read_response_line(strm, req, res) ||
  11969. !detail::read_headers(strm, res.headers)) {
  11970. error = Error::Read;
  11971. output_error_log(error, &req);
  11972. return false;
  11973. }
  11974. }
  11975. // If not 100 Continue, server returned an error; proceed with that response
  11976. }
  11977. // Body
  11978. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11979. req.method != "CONNECT") {
  11980. auto redirect = 300 < res.status && res.status < 400 &&
  11981. res.status != StatusCode::NotModified_304 &&
  11982. follow_location_;
  11983. if (req.response_handler && !redirect) {
  11984. if (!req.response_handler(res)) {
  11985. error = Error::Canceled;
  11986. output_error_log(error, &req);
  11987. return false;
  11988. }
  11989. }
  11990. auto out =
  11991. req.content_receiver
  11992. ? static_cast<ContentReceiverWithProgress>(
  11993. [&](const char *buf, size_t n, size_t off, size_t len) {
  11994. if (redirect) { return true; }
  11995. auto ret = req.content_receiver(buf, n, off, len);
  11996. if (!ret) {
  11997. error = Error::Canceled;
  11998. output_error_log(error, &req);
  11999. }
  12000. return ret;
  12001. })
  12002. : static_cast<ContentReceiverWithProgress>(
  12003. [&](const char *buf, size_t n, size_t /*off*/,
  12004. size_t /*len*/) {
  12005. assert(res.body.size() + n <= res.body.max_size());
  12006. if (payload_max_length_ > 0 &&
  12007. (res.body.size() >= payload_max_length_ ||
  12008. n > payload_max_length_ - res.body.size())) {
  12009. return false;
  12010. }
  12011. res.body.append(buf, n);
  12012. return true;
  12013. });
  12014. auto progress = [&](size_t current, size_t total) {
  12015. if (!req.download_progress || redirect) { return true; }
  12016. auto ret = req.download_progress(current, total);
  12017. if (!ret) {
  12018. error = Error::Canceled;
  12019. output_error_log(error, &req);
  12020. }
  12021. return ret;
  12022. };
  12023. if (res.has_header("Content-Length")) {
  12024. if (!req.content_receiver) {
  12025. auto len = res.get_header_value_u64("Content-Length");
  12026. if (len > res.body.max_size()) {
  12027. error = Error::Read;
  12028. output_error_log(error, &req);
  12029. return false;
  12030. }
  12031. // Cap the reservation by payload_max_length_ to avoid OOM when a
  12032. // hostile or malformed server sends an enormous Content-Length.
  12033. // The actual body read below is bounded by payload_max_length_,
  12034. // so reserving more than that is never useful.
  12035. auto reserve_len = static_cast<size_t>(len);
  12036. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  12037. reserve_len = payload_max_length_;
  12038. }
  12039. res.body.reserve(reserve_len);
  12040. }
  12041. }
  12042. if (res.status != StatusCode::NotModified_304) {
  12043. int dummy_status;
  12044. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  12045. ? (std::numeric_limits<size_t>::max)()
  12046. : payload_max_length_;
  12047. if (!detail::read_content(strm, res, max_length, dummy_status,
  12048. std::move(progress), std::move(out),
  12049. decompress_)) {
  12050. if (error != Error::Canceled) { error = Error::Read; }
  12051. output_error_log(error, &req);
  12052. return false;
  12053. }
  12054. }
  12055. }
  12056. // Log
  12057. output_log(req, res);
  12058. return true;
  12059. }
  12060. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  12061. const std::string &boundary, const UploadFormDataItems &items,
  12062. const FormDataProviderItems &provider_items) const {
  12063. size_t cur_item = 0;
  12064. size_t cur_start = 0;
  12065. // cur_item and cur_start are copied to within the std::function and
  12066. // maintain state between successive calls
  12067. return [&, cur_item, cur_start](size_t offset,
  12068. DataSink &sink) mutable -> bool {
  12069. if (!offset && !items.empty()) {
  12070. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12071. return true;
  12072. } else if (cur_item < provider_items.size()) {
  12073. if (!cur_start) {
  12074. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12075. provider_items[cur_item], boundary);
  12076. offset += begin.size();
  12077. cur_start = offset;
  12078. sink.os << begin;
  12079. }
  12080. DataSink cur_sink;
  12081. auto has_data = true;
  12082. cur_sink.write = sink.write;
  12083. cur_sink.done = [&]() { has_data = false; };
  12084. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12085. return false;
  12086. }
  12087. if (!has_data) {
  12088. sink.os << detail::serialize_multipart_formdata_item_end();
  12089. cur_item++;
  12090. cur_start = 0;
  12091. }
  12092. return true;
  12093. } else {
  12094. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12095. sink.done();
  12096. return true;
  12097. }
  12098. };
  12099. }
  12100. inline bool ClientImpl::process_socket(
  12101. const Socket &socket,
  12102. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12103. std::function<bool(Stream &strm)> callback) {
  12104. return detail::process_client_socket(
  12105. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12106. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12107. }
  12108. inline bool ClientImpl::is_ssl() const { return false; }
  12109. inline Result ClientImpl::Get(const std::string &path,
  12110. DownloadProgress progress) {
  12111. return Get(path, Headers(), std::move(progress));
  12112. }
  12113. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12114. DownloadProgress progress) {
  12115. return Get(path, params, Headers(), std::move(progress));
  12116. }
  12117. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12118. const Headers &headers,
  12119. DownloadProgress progress) {
  12120. if (params.empty()) { return Get(path, headers); }
  12121. std::string path_with_query = append_query_params(path, params);
  12122. return Get(path_with_query, headers, std::move(progress));
  12123. }
  12124. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12125. DownloadProgress progress) {
  12126. Request req;
  12127. req.method = "GET";
  12128. req.path = path;
  12129. req.headers = headers;
  12130. req.download_progress = std::move(progress);
  12131. if (max_timeout_msec_ > 0) {
  12132. req.start_time_ = std::chrono::steady_clock::now();
  12133. }
  12134. return send_(std::move(req));
  12135. }
  12136. inline Result ClientImpl::Get(const std::string &path,
  12137. ContentReceiver content_receiver,
  12138. DownloadProgress progress) {
  12139. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12140. std::move(progress));
  12141. }
  12142. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12143. ContentReceiver content_receiver,
  12144. DownloadProgress progress) {
  12145. return Get(path, headers, nullptr, std::move(content_receiver),
  12146. std::move(progress));
  12147. }
  12148. inline Result ClientImpl::Get(const std::string &path,
  12149. ResponseHandler response_handler,
  12150. ContentReceiver content_receiver,
  12151. DownloadProgress progress) {
  12152. return Get(path, Headers(), std::move(response_handler),
  12153. std::move(content_receiver), std::move(progress));
  12154. }
  12155. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12156. ResponseHandler response_handler,
  12157. ContentReceiver content_receiver,
  12158. DownloadProgress progress) {
  12159. Request req;
  12160. req.method = "GET";
  12161. req.path = path;
  12162. req.headers = headers;
  12163. req.response_handler = std::move(response_handler);
  12164. req.content_receiver =
  12165. [content_receiver](const char *data, size_t data_length,
  12166. size_t /*offset*/, size_t /*total_length*/) {
  12167. return content_receiver(data, data_length);
  12168. };
  12169. req.download_progress = std::move(progress);
  12170. if (max_timeout_msec_ > 0) {
  12171. req.start_time_ = std::chrono::steady_clock::now();
  12172. }
  12173. return send_(std::move(req));
  12174. }
  12175. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12176. const Headers &headers,
  12177. ContentReceiver content_receiver,
  12178. DownloadProgress progress) {
  12179. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12180. std::move(progress));
  12181. }
  12182. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12183. const Headers &headers,
  12184. ResponseHandler response_handler,
  12185. ContentReceiver content_receiver,
  12186. DownloadProgress progress) {
  12187. if (params.empty()) {
  12188. return Get(path, headers, std::move(response_handler),
  12189. std::move(content_receiver), std::move(progress));
  12190. }
  12191. std::string path_with_query = append_query_params(path, params);
  12192. return Get(path_with_query, headers, std::move(response_handler),
  12193. std::move(content_receiver), std::move(progress));
  12194. }
  12195. inline Result ClientImpl::Head(const std::string &path) {
  12196. return Head(path, Headers());
  12197. }
  12198. inline Result ClientImpl::Head(const std::string &path,
  12199. const Headers &headers) {
  12200. Request req;
  12201. req.method = "HEAD";
  12202. req.headers = headers;
  12203. req.path = path;
  12204. if (max_timeout_msec_ > 0) {
  12205. req.start_time_ = std::chrono::steady_clock::now();
  12206. }
  12207. return send_(std::move(req));
  12208. }
  12209. inline Result ClientImpl::Post(const std::string &path) {
  12210. return Post(path, std::string(), std::string());
  12211. }
  12212. inline Result ClientImpl::Post(const std::string &path,
  12213. const Headers &headers) {
  12214. return Post(path, headers, nullptr, 0, std::string());
  12215. }
  12216. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12217. size_t content_length,
  12218. const std::string &content_type,
  12219. UploadProgress progress) {
  12220. return Post(path, Headers(), body, content_length, content_type, progress);
  12221. }
  12222. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12223. const std::string &content_type,
  12224. UploadProgress progress) {
  12225. return Post(path, Headers(), body, content_type, progress);
  12226. }
  12227. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12228. return Post(path, Headers(), params);
  12229. }
  12230. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12231. ContentProvider content_provider,
  12232. const std::string &content_type,
  12233. UploadProgress progress) {
  12234. return Post(path, Headers(), content_length, std::move(content_provider),
  12235. content_type, progress);
  12236. }
  12237. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12238. ContentProvider content_provider,
  12239. const std::string &content_type,
  12240. ContentReceiver content_receiver,
  12241. UploadProgress progress) {
  12242. return Post(path, Headers(), content_length, std::move(content_provider),
  12243. content_type, std::move(content_receiver), progress);
  12244. }
  12245. inline Result ClientImpl::Post(const std::string &path,
  12246. ContentProviderWithoutLength content_provider,
  12247. const std::string &content_type,
  12248. UploadProgress progress) {
  12249. return Post(path, Headers(), std::move(content_provider), content_type,
  12250. progress);
  12251. }
  12252. inline Result ClientImpl::Post(const std::string &path,
  12253. ContentProviderWithoutLength content_provider,
  12254. const std::string &content_type,
  12255. ContentReceiver content_receiver,
  12256. UploadProgress progress) {
  12257. return Post(path, Headers(), std::move(content_provider), content_type,
  12258. std::move(content_receiver), progress);
  12259. }
  12260. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12261. const Params &params) {
  12262. auto query = detail::params_to_query_str(params);
  12263. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12264. }
  12265. inline Result ClientImpl::Post(const std::string &path,
  12266. const UploadFormDataItems &items,
  12267. UploadProgress progress) {
  12268. return Post(path, Headers(), items, progress);
  12269. }
  12270. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12271. const UploadFormDataItems &items,
  12272. UploadProgress progress) {
  12273. const auto &boundary = detail::make_multipart_data_boundary();
  12274. const auto &content_type =
  12275. detail::serialize_multipart_formdata_get_content_type(boundary);
  12276. auto content_length = detail::get_multipart_content_length(items, boundary);
  12277. return Post(path, headers, content_length,
  12278. detail::make_multipart_content_provider(items, boundary),
  12279. content_type, progress);
  12280. }
  12281. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12282. const UploadFormDataItems &items,
  12283. const std::string &boundary,
  12284. UploadProgress progress) {
  12285. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12286. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12287. }
  12288. const auto &content_type =
  12289. detail::serialize_multipart_formdata_get_content_type(boundary);
  12290. auto content_length = detail::get_multipart_content_length(items, boundary);
  12291. return Post(path, headers, content_length,
  12292. detail::make_multipart_content_provider(items, boundary),
  12293. content_type, progress);
  12294. }
  12295. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12296. const char *body, size_t content_length,
  12297. const std::string &content_type,
  12298. UploadProgress progress) {
  12299. return send_with_content_provider_and_receiver(
  12300. "POST", path, headers, body, content_length, nullptr, nullptr,
  12301. content_type, nullptr, progress);
  12302. }
  12303. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12304. const std::string &body,
  12305. const std::string &content_type,
  12306. UploadProgress progress) {
  12307. return send_with_content_provider_and_receiver(
  12308. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12309. content_type, nullptr, progress);
  12310. }
  12311. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12312. size_t content_length,
  12313. ContentProvider content_provider,
  12314. const std::string &content_type,
  12315. UploadProgress progress) {
  12316. return send_with_content_provider_and_receiver(
  12317. "POST", path, headers, nullptr, content_length,
  12318. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12319. }
  12320. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12321. size_t content_length,
  12322. ContentProvider content_provider,
  12323. const std::string &content_type,
  12324. ContentReceiver content_receiver,
  12325. DownloadProgress progress) {
  12326. return send_with_content_provider_and_receiver(
  12327. "POST", path, headers, nullptr, content_length,
  12328. std::move(content_provider), nullptr, content_type,
  12329. std::move(content_receiver), std::move(progress));
  12330. }
  12331. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12332. ContentProviderWithoutLength content_provider,
  12333. const std::string &content_type,
  12334. UploadProgress progress) {
  12335. return send_with_content_provider_and_receiver(
  12336. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12337. content_type, nullptr, progress);
  12338. }
  12339. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12340. ContentProviderWithoutLength content_provider,
  12341. const std::string &content_type,
  12342. ContentReceiver content_receiver,
  12343. DownloadProgress progress) {
  12344. return send_with_content_provider_and_receiver(
  12345. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12346. content_type, std::move(content_receiver), std::move(progress));
  12347. }
  12348. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12349. const UploadFormDataItems &items,
  12350. const FormDataProviderItems &provider_items,
  12351. UploadProgress progress) {
  12352. const auto &boundary = detail::make_multipart_data_boundary();
  12353. const auto &content_type =
  12354. detail::serialize_multipart_formdata_get_content_type(boundary);
  12355. return send_with_content_provider_and_receiver(
  12356. "POST", path, headers, nullptr, 0, nullptr,
  12357. get_multipart_content_provider(boundary, items, provider_items),
  12358. content_type, nullptr, progress);
  12359. }
  12360. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12361. const std::string &body,
  12362. const std::string &content_type,
  12363. ContentReceiver content_receiver,
  12364. DownloadProgress progress) {
  12365. Request req;
  12366. req.method = "POST";
  12367. req.path = path;
  12368. req.headers = headers;
  12369. req.body = body;
  12370. req.content_receiver =
  12371. [content_receiver](const char *data, size_t data_length,
  12372. size_t /*offset*/, size_t /*total_length*/) {
  12373. return content_receiver(data, data_length);
  12374. };
  12375. req.download_progress = std::move(progress);
  12376. if (max_timeout_msec_ > 0) {
  12377. req.start_time_ = std::chrono::steady_clock::now();
  12378. }
  12379. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12380. return send_(std::move(req));
  12381. }
  12382. inline Result ClientImpl::Put(const std::string &path) {
  12383. return Put(path, std::string(), std::string());
  12384. }
  12385. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12386. return Put(path, headers, nullptr, 0, std::string());
  12387. }
  12388. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12389. size_t content_length,
  12390. const std::string &content_type,
  12391. UploadProgress progress) {
  12392. return Put(path, Headers(), body, content_length, content_type, progress);
  12393. }
  12394. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12395. const std::string &content_type,
  12396. UploadProgress progress) {
  12397. return Put(path, Headers(), body, content_type, progress);
  12398. }
  12399. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12400. return Put(path, Headers(), params);
  12401. }
  12402. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12403. ContentProvider content_provider,
  12404. const std::string &content_type,
  12405. UploadProgress progress) {
  12406. return Put(path, Headers(), content_length, std::move(content_provider),
  12407. content_type, progress);
  12408. }
  12409. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12410. ContentProvider content_provider,
  12411. const std::string &content_type,
  12412. ContentReceiver content_receiver,
  12413. UploadProgress progress) {
  12414. return Put(path, Headers(), content_length, std::move(content_provider),
  12415. content_type, std::move(content_receiver), progress);
  12416. }
  12417. inline Result ClientImpl::Put(const std::string &path,
  12418. ContentProviderWithoutLength content_provider,
  12419. const std::string &content_type,
  12420. UploadProgress progress) {
  12421. return Put(path, Headers(), std::move(content_provider), content_type,
  12422. progress);
  12423. }
  12424. inline Result ClientImpl::Put(const std::string &path,
  12425. ContentProviderWithoutLength content_provider,
  12426. const std::string &content_type,
  12427. ContentReceiver content_receiver,
  12428. UploadProgress progress) {
  12429. return Put(path, Headers(), std::move(content_provider), content_type,
  12430. std::move(content_receiver), progress);
  12431. }
  12432. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12433. const Params &params) {
  12434. auto query = detail::params_to_query_str(params);
  12435. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12436. }
  12437. inline Result ClientImpl::Put(const std::string &path,
  12438. const UploadFormDataItems &items,
  12439. UploadProgress progress) {
  12440. return Put(path, Headers(), items, progress);
  12441. }
  12442. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12443. const UploadFormDataItems &items,
  12444. UploadProgress progress) {
  12445. const auto &boundary = detail::make_multipart_data_boundary();
  12446. const auto &content_type =
  12447. detail::serialize_multipart_formdata_get_content_type(boundary);
  12448. auto content_length = detail::get_multipart_content_length(items, boundary);
  12449. return Put(path, headers, content_length,
  12450. detail::make_multipart_content_provider(items, boundary),
  12451. content_type, progress);
  12452. }
  12453. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12454. const UploadFormDataItems &items,
  12455. const std::string &boundary,
  12456. UploadProgress progress) {
  12457. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12458. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12459. }
  12460. const auto &content_type =
  12461. detail::serialize_multipart_formdata_get_content_type(boundary);
  12462. auto content_length = detail::get_multipart_content_length(items, boundary);
  12463. return Put(path, headers, content_length,
  12464. detail::make_multipart_content_provider(items, boundary),
  12465. content_type, progress);
  12466. }
  12467. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12468. const char *body, size_t content_length,
  12469. const std::string &content_type,
  12470. UploadProgress progress) {
  12471. return send_with_content_provider_and_receiver(
  12472. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12473. content_type, nullptr, progress);
  12474. }
  12475. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12476. const std::string &body,
  12477. const std::string &content_type,
  12478. UploadProgress progress) {
  12479. return send_with_content_provider_and_receiver(
  12480. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12481. content_type, nullptr, progress);
  12482. }
  12483. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12484. size_t content_length,
  12485. ContentProvider content_provider,
  12486. const std::string &content_type,
  12487. UploadProgress progress) {
  12488. return send_with_content_provider_and_receiver(
  12489. "PUT", path, headers, nullptr, content_length,
  12490. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12491. }
  12492. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12493. size_t content_length,
  12494. ContentProvider content_provider,
  12495. const std::string &content_type,
  12496. ContentReceiver content_receiver,
  12497. UploadProgress progress) {
  12498. return send_with_content_provider_and_receiver(
  12499. "PUT", path, headers, nullptr, content_length,
  12500. std::move(content_provider), nullptr, content_type,
  12501. std::move(content_receiver), progress);
  12502. }
  12503. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12504. ContentProviderWithoutLength content_provider,
  12505. const std::string &content_type,
  12506. UploadProgress progress) {
  12507. return send_with_content_provider_and_receiver(
  12508. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12509. content_type, nullptr, progress);
  12510. }
  12511. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12512. ContentProviderWithoutLength content_provider,
  12513. const std::string &content_type,
  12514. ContentReceiver content_receiver,
  12515. UploadProgress progress) {
  12516. return send_with_content_provider_and_receiver(
  12517. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12518. content_type, std::move(content_receiver), progress);
  12519. }
  12520. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12521. const UploadFormDataItems &items,
  12522. const FormDataProviderItems &provider_items,
  12523. UploadProgress progress) {
  12524. const auto &boundary = detail::make_multipart_data_boundary();
  12525. const auto &content_type =
  12526. detail::serialize_multipart_formdata_get_content_type(boundary);
  12527. return send_with_content_provider_and_receiver(
  12528. "PUT", path, headers, nullptr, 0, nullptr,
  12529. get_multipart_content_provider(boundary, items, provider_items),
  12530. content_type, nullptr, progress);
  12531. }
  12532. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12533. const std::string &body,
  12534. const std::string &content_type,
  12535. ContentReceiver content_receiver,
  12536. DownloadProgress progress) {
  12537. Request req;
  12538. req.method = "PUT";
  12539. req.path = path;
  12540. req.headers = headers;
  12541. req.body = body;
  12542. req.content_receiver =
  12543. [content_receiver](const char *data, size_t data_length,
  12544. size_t /*offset*/, size_t /*total_length*/) {
  12545. return content_receiver(data, data_length);
  12546. };
  12547. req.download_progress = std::move(progress);
  12548. if (max_timeout_msec_ > 0) {
  12549. req.start_time_ = std::chrono::steady_clock::now();
  12550. }
  12551. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12552. return send_(std::move(req));
  12553. }
  12554. inline Result ClientImpl::Patch(const std::string &path) {
  12555. return Patch(path, std::string(), std::string());
  12556. }
  12557. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12558. UploadProgress progress) {
  12559. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12560. }
  12561. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12562. size_t content_length,
  12563. const std::string &content_type,
  12564. UploadProgress progress) {
  12565. return Patch(path, Headers(), body, content_length, content_type, progress);
  12566. }
  12567. inline Result ClientImpl::Patch(const std::string &path,
  12568. const std::string &body,
  12569. const std::string &content_type,
  12570. UploadProgress progress) {
  12571. return Patch(path, Headers(), body, content_type, progress);
  12572. }
  12573. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12574. return Patch(path, Headers(), params);
  12575. }
  12576. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12577. ContentProvider content_provider,
  12578. const std::string &content_type,
  12579. UploadProgress progress) {
  12580. return Patch(path, Headers(), content_length, std::move(content_provider),
  12581. content_type, progress);
  12582. }
  12583. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12584. ContentProvider content_provider,
  12585. const std::string &content_type,
  12586. ContentReceiver content_receiver,
  12587. UploadProgress progress) {
  12588. return Patch(path, Headers(), content_length, std::move(content_provider),
  12589. content_type, std::move(content_receiver), progress);
  12590. }
  12591. inline Result ClientImpl::Patch(const std::string &path,
  12592. ContentProviderWithoutLength content_provider,
  12593. const std::string &content_type,
  12594. UploadProgress progress) {
  12595. return Patch(path, Headers(), std::move(content_provider), content_type,
  12596. progress);
  12597. }
  12598. inline Result ClientImpl::Patch(const std::string &path,
  12599. ContentProviderWithoutLength content_provider,
  12600. const std::string &content_type,
  12601. ContentReceiver content_receiver,
  12602. UploadProgress progress) {
  12603. return Patch(path, Headers(), std::move(content_provider), content_type,
  12604. std::move(content_receiver), progress);
  12605. }
  12606. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12607. const Params &params) {
  12608. auto query = detail::params_to_query_str(params);
  12609. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12610. }
  12611. inline Result ClientImpl::Patch(const std::string &path,
  12612. const UploadFormDataItems &items,
  12613. UploadProgress progress) {
  12614. return Patch(path, Headers(), items, progress);
  12615. }
  12616. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12617. const UploadFormDataItems &items,
  12618. UploadProgress progress) {
  12619. const auto &boundary = detail::make_multipart_data_boundary();
  12620. const auto &content_type =
  12621. detail::serialize_multipart_formdata_get_content_type(boundary);
  12622. auto content_length = detail::get_multipart_content_length(items, boundary);
  12623. return Patch(path, headers, content_length,
  12624. detail::make_multipart_content_provider(items, boundary),
  12625. content_type, progress);
  12626. }
  12627. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12628. const UploadFormDataItems &items,
  12629. const std::string &boundary,
  12630. UploadProgress progress) {
  12631. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12632. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12633. }
  12634. const auto &content_type =
  12635. detail::serialize_multipart_formdata_get_content_type(boundary);
  12636. auto content_length = detail::get_multipart_content_length(items, boundary);
  12637. return Patch(path, headers, content_length,
  12638. detail::make_multipart_content_provider(items, boundary),
  12639. content_type, progress);
  12640. }
  12641. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12642. const char *body, size_t content_length,
  12643. const std::string &content_type,
  12644. UploadProgress progress) {
  12645. return send_with_content_provider_and_receiver(
  12646. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12647. content_type, nullptr, progress);
  12648. }
  12649. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12650. const std::string &body,
  12651. const std::string &content_type,
  12652. UploadProgress progress) {
  12653. return send_with_content_provider_and_receiver(
  12654. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12655. content_type, nullptr, progress);
  12656. }
  12657. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12658. size_t content_length,
  12659. ContentProvider content_provider,
  12660. const std::string &content_type,
  12661. UploadProgress progress) {
  12662. return send_with_content_provider_and_receiver(
  12663. "PATCH", path, headers, nullptr, content_length,
  12664. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12665. }
  12666. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12667. size_t content_length,
  12668. ContentProvider content_provider,
  12669. const std::string &content_type,
  12670. ContentReceiver content_receiver,
  12671. UploadProgress progress) {
  12672. return send_with_content_provider_and_receiver(
  12673. "PATCH", path, headers, nullptr, content_length,
  12674. std::move(content_provider), nullptr, content_type,
  12675. std::move(content_receiver), progress);
  12676. }
  12677. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12678. ContentProviderWithoutLength content_provider,
  12679. const std::string &content_type,
  12680. UploadProgress progress) {
  12681. return send_with_content_provider_and_receiver(
  12682. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12683. content_type, nullptr, progress);
  12684. }
  12685. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12686. ContentProviderWithoutLength content_provider,
  12687. const std::string &content_type,
  12688. ContentReceiver content_receiver,
  12689. UploadProgress progress) {
  12690. return send_with_content_provider_and_receiver(
  12691. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12692. content_type, std::move(content_receiver), progress);
  12693. }
  12694. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12695. const UploadFormDataItems &items,
  12696. const FormDataProviderItems &provider_items,
  12697. UploadProgress progress) {
  12698. const auto &boundary = detail::make_multipart_data_boundary();
  12699. const auto &content_type =
  12700. detail::serialize_multipart_formdata_get_content_type(boundary);
  12701. return send_with_content_provider_and_receiver(
  12702. "PATCH", path, headers, nullptr, 0, nullptr,
  12703. get_multipart_content_provider(boundary, items, provider_items),
  12704. content_type, nullptr, progress);
  12705. }
  12706. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12707. const std::string &body,
  12708. const std::string &content_type,
  12709. ContentReceiver content_receiver,
  12710. DownloadProgress progress) {
  12711. Request req;
  12712. req.method = "PATCH";
  12713. req.path = path;
  12714. req.headers = headers;
  12715. req.body = body;
  12716. req.content_receiver =
  12717. [content_receiver](const char *data, size_t data_length,
  12718. size_t /*offset*/, size_t /*total_length*/) {
  12719. return content_receiver(data, data_length);
  12720. };
  12721. req.download_progress = std::move(progress);
  12722. if (max_timeout_msec_ > 0) {
  12723. req.start_time_ = std::chrono::steady_clock::now();
  12724. }
  12725. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12726. return send_(std::move(req));
  12727. }
  12728. inline Result ClientImpl::Delete(const std::string &path,
  12729. DownloadProgress progress) {
  12730. return Delete(path, Headers(), std::string(), std::string(), progress);
  12731. }
  12732. inline Result ClientImpl::Delete(const std::string &path,
  12733. const Headers &headers,
  12734. DownloadProgress progress) {
  12735. return Delete(path, headers, std::string(), std::string(), progress);
  12736. }
  12737. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12738. size_t content_length,
  12739. const std::string &content_type,
  12740. DownloadProgress progress) {
  12741. return Delete(path, Headers(), body, content_length, content_type, progress);
  12742. }
  12743. inline Result ClientImpl::Delete(const std::string &path,
  12744. const std::string &body,
  12745. const std::string &content_type,
  12746. DownloadProgress progress) {
  12747. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12748. progress);
  12749. }
  12750. inline Result ClientImpl::Delete(const std::string &path,
  12751. const Headers &headers,
  12752. const std::string &body,
  12753. const std::string &content_type,
  12754. DownloadProgress progress) {
  12755. return Delete(path, headers, body.data(), body.size(), content_type,
  12756. progress);
  12757. }
  12758. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12759. DownloadProgress progress) {
  12760. return Delete(path, Headers(), params, progress);
  12761. }
  12762. inline Result ClientImpl::Delete(const std::string &path,
  12763. const Headers &headers, const Params &params,
  12764. DownloadProgress progress) {
  12765. auto query = detail::params_to_query_str(params);
  12766. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12767. progress);
  12768. }
  12769. inline Result ClientImpl::Delete(const std::string &path,
  12770. const Headers &headers, const char *body,
  12771. size_t content_length,
  12772. const std::string &content_type,
  12773. DownloadProgress progress) {
  12774. Request req;
  12775. req.method = "DELETE";
  12776. req.headers = headers;
  12777. req.path = path;
  12778. req.download_progress = std::move(progress);
  12779. if (max_timeout_msec_ > 0) {
  12780. req.start_time_ = std::chrono::steady_clock::now();
  12781. }
  12782. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12783. req.body.assign(body, content_length);
  12784. return send_(std::move(req));
  12785. }
  12786. inline Result ClientImpl::Options(const std::string &path) {
  12787. return Options(path, Headers());
  12788. }
  12789. inline Result ClientImpl::Options(const std::string &path,
  12790. const Headers &headers) {
  12791. Request req;
  12792. req.method = "OPTIONS";
  12793. req.headers = headers;
  12794. req.path = path;
  12795. if (max_timeout_msec_ > 0) {
  12796. req.start_time_ = std::chrono::steady_clock::now();
  12797. }
  12798. return send_(std::move(req));
  12799. }
  12800. inline void ClientImpl::stop() {
  12801. std::lock_guard<std::mutex> guard(socket_mutex_);
  12802. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12803. // do is to shutdown_socket, so that threads using this socket suddenly
  12804. // discover they can't read/write any more and error out. Everything else
  12805. // (closing the socket, shutting ssl down) is unsafe because these actions
  12806. // are not thread-safe.
  12807. if (socket_requests_in_flight_ > 0) {
  12808. shutdown_socket(socket_);
  12809. // Aside from that, we set a flag for the socket to be closed when we're
  12810. // done.
  12811. socket_should_be_closed_when_request_is_done_ = true;
  12812. return;
  12813. }
  12814. disconnect(/*gracefully=*/true);
  12815. }
  12816. inline std::string ClientImpl::host() const { return host_; }
  12817. inline int ClientImpl::port() const { return port_; }
  12818. inline size_t ClientImpl::is_socket_open() const {
  12819. std::lock_guard<std::mutex> guard(socket_mutex_);
  12820. return socket_.is_open();
  12821. }
  12822. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12823. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12824. connection_timeout_sec_ = sec;
  12825. connection_timeout_usec_ = usec;
  12826. }
  12827. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12828. read_timeout_sec_ = sec;
  12829. read_timeout_usec_ = usec;
  12830. }
  12831. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12832. write_timeout_sec_ = sec;
  12833. write_timeout_usec_ = usec;
  12834. }
  12835. inline void ClientImpl::set_max_timeout(time_t msec) {
  12836. max_timeout_msec_ = msec;
  12837. }
  12838. inline void ClientImpl::set_basic_auth(const std::string &username,
  12839. const std::string &password) {
  12840. basic_auth_username_ = username;
  12841. basic_auth_password_ = password;
  12842. }
  12843. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12844. bearer_token_auth_token_ = token;
  12845. }
  12846. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12847. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12848. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12849. inline void
  12850. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12851. addr_map_ = std::move(addr_map);
  12852. }
  12853. inline void ClientImpl::set_default_headers(Headers headers) {
  12854. default_headers_ = std::move(headers);
  12855. }
  12856. inline void ClientImpl::set_header_writer(
  12857. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12858. header_writer_ = writer;
  12859. }
  12860. inline void ClientImpl::set_address_family(int family) {
  12861. address_family_ = family;
  12862. }
  12863. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12864. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12865. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12866. socket_options_ = std::move(socket_options);
  12867. }
  12868. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12869. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12870. inline void ClientImpl::set_payload_max_length(size_t length) {
  12871. payload_max_length_ = length;
  12872. has_payload_max_length_ = true;
  12873. }
  12874. inline void ClientImpl::set_interface(const std::string &intf) {
  12875. interface_ = intf;
  12876. }
  12877. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12878. proxy_host_ = host;
  12879. proxy_port_ = port;
  12880. std::lock_guard<std::mutex> guard(socket_mutex_);
  12881. disconnect(/*gracefully=*/true);
  12882. }
  12883. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12884. const std::string &password) {
  12885. proxy_basic_auth_username_ = username;
  12886. proxy_basic_auth_password_ = password;
  12887. }
  12888. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12889. proxy_bearer_token_auth_token_ = token;
  12890. }
  12891. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12892. std::vector<detail::NoProxyEntry> parsed;
  12893. parsed.reserve(patterns.size());
  12894. for (const auto &p : patterns) {
  12895. auto trimmed = detail::trim_copy(p);
  12896. if (trimmed.empty()) { continue; }
  12897. detail::NoProxyEntry entry;
  12898. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12899. parsed.push_back(std::move(entry));
  12900. }
  12901. }
  12902. no_proxy_entries_ = std::move(parsed);
  12903. std::lock_guard<std::mutex> guard(socket_mutex_);
  12904. disconnect(/*gracefully=*/true);
  12905. }
  12906. #ifdef CPPHTTPLIB_SSL_ENABLED
  12907. inline void ClientImpl::set_digest_auth(const std::string &username,
  12908. const std::string &password) {
  12909. digest_auth_username_ = username;
  12910. digest_auth_password_ = password;
  12911. }
  12912. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12913. const std::string &ca_cert_dir_path) {
  12914. ca_cert_file_path_ = ca_cert_file_path;
  12915. ca_cert_dir_path_ = ca_cert_dir_path;
  12916. }
  12917. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12918. const std::string &password) {
  12919. proxy_digest_auth_username_ = username;
  12920. proxy_digest_auth_password_ = password;
  12921. }
  12922. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12923. server_certificate_verification_ = enabled;
  12924. }
  12925. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12926. server_hostname_verification_ = enabled;
  12927. }
  12928. inline void ClientImpl::enable_system_ca(bool enabled) {
  12929. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12930. }
  12931. #endif
  12932. inline void ClientImpl::set_logger(Logger logger) {
  12933. logger_ = std::move(logger);
  12934. }
  12935. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12936. error_logger_ = std::move(error_logger);
  12937. }
  12938. /*
  12939. * SSL/TLS Common Implementation
  12940. */
  12941. inline ClientConnection::~ClientConnection() {
  12942. #ifdef CPPHTTPLIB_SSL_ENABLED
  12943. if (session) {
  12944. tls::shutdown(session, true);
  12945. tls::free_session(session);
  12946. session = nullptr;
  12947. }
  12948. #endif
  12949. if (sock != INVALID_SOCKET) {
  12950. detail::close_socket(sock);
  12951. sock = INVALID_SOCKET;
  12952. }
  12953. }
  12954. // Universal client implementation
  12955. inline Client::Client(const std::string &scheme_host_port)
  12956. : Client(scheme_host_port, std::string(), std::string()) {}
  12957. inline Client::Client(const std::string &scheme_host_port,
  12958. const std::string &client_cert_path,
  12959. const std::string &client_key_path) {
  12960. detail::UrlComponents uc;
  12961. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12962. auto &scheme = uc.scheme;
  12963. #ifdef CPPHTTPLIB_SSL_ENABLED
  12964. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12965. #else
  12966. if (!scheme.empty() && scheme != "http") {
  12967. #endif
  12968. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12969. std::string msg = "'" + scheme + "' scheme is not supported.";
  12970. throw std::invalid_argument(msg);
  12971. #endif
  12972. return;
  12973. }
  12974. auto is_ssl = scheme == "https";
  12975. auto host = std::move(uc.host);
  12976. auto port = is_ssl ? 443 : 80;
  12977. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12978. if (is_ssl) {
  12979. #ifdef CPPHTTPLIB_SSL_ENABLED
  12980. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12981. client_key_path);
  12982. is_ssl_ = is_ssl;
  12983. #endif
  12984. } else {
  12985. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12986. client_key_path);
  12987. }
  12988. } else {
  12989. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12990. // if port param below changes.
  12991. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12992. client_cert_path, client_key_path);
  12993. }
  12994. }
  12995. inline Client::Client(const std::string &host, int port)
  12996. : Client(host, port, std::string(), std::string()) {}
  12997. inline Client::Client(const std::string &host, int port,
  12998. const std::string &client_cert_path,
  12999. const std::string &client_key_path)
  13000. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13001. client_key_path)) {}
  13002. inline Client::~Client() = default;
  13003. inline bool Client::is_valid() const {
  13004. return cli_ != nullptr && cli_->is_valid();
  13005. }
  13006. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  13007. return cli_->Get(path, std::move(progress));
  13008. }
  13009. inline Result Client::Get(const std::string &path, const Headers &headers,
  13010. DownloadProgress progress) {
  13011. return cli_->Get(path, headers, std::move(progress));
  13012. }
  13013. inline Result Client::Get(const std::string &path,
  13014. ContentReceiver content_receiver,
  13015. DownloadProgress progress) {
  13016. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  13017. }
  13018. inline Result Client::Get(const std::string &path, const Headers &headers,
  13019. ContentReceiver content_receiver,
  13020. DownloadProgress progress) {
  13021. return cli_->Get(path, headers, std::move(content_receiver),
  13022. std::move(progress));
  13023. }
  13024. inline Result Client::Get(const std::string &path,
  13025. ResponseHandler response_handler,
  13026. ContentReceiver content_receiver,
  13027. DownloadProgress progress) {
  13028. return cli_->Get(path, std::move(response_handler),
  13029. std::move(content_receiver), std::move(progress));
  13030. }
  13031. inline Result Client::Get(const std::string &path, const Headers &headers,
  13032. ResponseHandler response_handler,
  13033. ContentReceiver content_receiver,
  13034. DownloadProgress progress) {
  13035. return cli_->Get(path, headers, std::move(response_handler),
  13036. std::move(content_receiver), std::move(progress));
  13037. }
  13038. inline Result Client::Get(const std::string &path, const Params &params,
  13039. DownloadProgress progress) {
  13040. return cli_->Get(path, params, std::move(progress));
  13041. }
  13042. inline Result Client::Get(const std::string &path, const Params &params,
  13043. const Headers &headers, DownloadProgress progress) {
  13044. return cli_->Get(path, params, headers, std::move(progress));
  13045. }
  13046. inline Result Client::Get(const std::string &path, const Params &params,
  13047. const Headers &headers,
  13048. ContentReceiver content_receiver,
  13049. DownloadProgress progress) {
  13050. return cli_->Get(path, params, headers, std::move(content_receiver),
  13051. std::move(progress));
  13052. }
  13053. inline Result Client::Get(const std::string &path, const Params &params,
  13054. const Headers &headers,
  13055. ResponseHandler response_handler,
  13056. ContentReceiver content_receiver,
  13057. DownloadProgress progress) {
  13058. return cli_->Get(path, params, headers, std::move(response_handler),
  13059. std::move(content_receiver), std::move(progress));
  13060. }
  13061. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  13062. inline Result Client::Head(const std::string &path, const Headers &headers) {
  13063. return cli_->Head(path, headers);
  13064. }
  13065. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  13066. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13067. return cli_->Post(path, headers);
  13068. }
  13069. inline Result Client::Post(const std::string &path, const char *body,
  13070. size_t content_length,
  13071. const std::string &content_type,
  13072. UploadProgress progress) {
  13073. return cli_->Post(path, body, content_length, content_type, progress);
  13074. }
  13075. inline Result Client::Post(const std::string &path, const Headers &headers,
  13076. const char *body, size_t content_length,
  13077. const std::string &content_type,
  13078. UploadProgress progress) {
  13079. return cli_->Post(path, headers, body, content_length, content_type,
  13080. progress);
  13081. }
  13082. inline Result Client::Post(const std::string &path, const std::string &body,
  13083. const std::string &content_type,
  13084. UploadProgress progress) {
  13085. return cli_->Post(path, body, content_type, progress);
  13086. }
  13087. inline Result Client::Post(const std::string &path, const Headers &headers,
  13088. const std::string &body,
  13089. const std::string &content_type,
  13090. UploadProgress progress) {
  13091. return cli_->Post(path, headers, body, content_type, progress);
  13092. }
  13093. inline Result Client::Post(const std::string &path, size_t content_length,
  13094. ContentProvider content_provider,
  13095. const std::string &content_type,
  13096. UploadProgress progress) {
  13097. return cli_->Post(path, content_length, std::move(content_provider),
  13098. content_type, progress);
  13099. }
  13100. inline Result Client::Post(const std::string &path, size_t content_length,
  13101. ContentProvider content_provider,
  13102. const std::string &content_type,
  13103. ContentReceiver content_receiver,
  13104. UploadProgress progress) {
  13105. return cli_->Post(path, content_length, std::move(content_provider),
  13106. content_type, std::move(content_receiver), progress);
  13107. }
  13108. inline Result Client::Post(const std::string &path,
  13109. ContentProviderWithoutLength content_provider,
  13110. const std::string &content_type,
  13111. UploadProgress progress) {
  13112. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13113. }
  13114. inline Result Client::Post(const std::string &path,
  13115. ContentProviderWithoutLength content_provider,
  13116. const std::string &content_type,
  13117. ContentReceiver content_receiver,
  13118. UploadProgress progress) {
  13119. return cli_->Post(path, std::move(content_provider), content_type,
  13120. std::move(content_receiver), progress);
  13121. }
  13122. inline Result Client::Post(const std::string &path, const Headers &headers,
  13123. size_t content_length,
  13124. ContentProvider content_provider,
  13125. const std::string &content_type,
  13126. UploadProgress progress) {
  13127. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13128. content_type, progress);
  13129. }
  13130. inline Result Client::Post(const std::string &path, const Headers &headers,
  13131. size_t content_length,
  13132. ContentProvider content_provider,
  13133. const std::string &content_type,
  13134. ContentReceiver content_receiver,
  13135. DownloadProgress progress) {
  13136. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13137. content_type, std::move(content_receiver), progress);
  13138. }
  13139. inline Result Client::Post(const std::string &path, const Headers &headers,
  13140. ContentProviderWithoutLength content_provider,
  13141. const std::string &content_type,
  13142. UploadProgress progress) {
  13143. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13144. progress);
  13145. }
  13146. inline Result Client::Post(const std::string &path, const Headers &headers,
  13147. ContentProviderWithoutLength content_provider,
  13148. const std::string &content_type,
  13149. ContentReceiver content_receiver,
  13150. DownloadProgress progress) {
  13151. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13152. std::move(content_receiver), progress);
  13153. }
  13154. inline Result Client::Post(const std::string &path, const Params &params) {
  13155. return cli_->Post(path, params);
  13156. }
  13157. inline Result Client::Post(const std::string &path, const Headers &headers,
  13158. const Params &params) {
  13159. return cli_->Post(path, headers, params);
  13160. }
  13161. inline Result Client::Post(const std::string &path,
  13162. const UploadFormDataItems &items,
  13163. UploadProgress progress) {
  13164. return cli_->Post(path, items, progress);
  13165. }
  13166. inline Result Client::Post(const std::string &path, const Headers &headers,
  13167. const UploadFormDataItems &items,
  13168. UploadProgress progress) {
  13169. return cli_->Post(path, headers, items, progress);
  13170. }
  13171. inline Result Client::Post(const std::string &path, const Headers &headers,
  13172. const UploadFormDataItems &items,
  13173. const std::string &boundary,
  13174. UploadProgress progress) {
  13175. return cli_->Post(path, headers, items, boundary, progress);
  13176. }
  13177. inline Result Client::Post(const std::string &path, const Headers &headers,
  13178. const UploadFormDataItems &items,
  13179. const FormDataProviderItems &provider_items,
  13180. UploadProgress progress) {
  13181. return cli_->Post(path, headers, items, provider_items, progress);
  13182. }
  13183. inline Result Client::Post(const std::string &path, const Headers &headers,
  13184. const std::string &body,
  13185. const std::string &content_type,
  13186. ContentReceiver content_receiver,
  13187. DownloadProgress progress) {
  13188. return cli_->Post(path, headers, body, content_type,
  13189. std::move(content_receiver), progress);
  13190. }
  13191. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13192. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13193. return cli_->Put(path, headers);
  13194. }
  13195. inline Result Client::Put(const std::string &path, const char *body,
  13196. size_t content_length,
  13197. const std::string &content_type,
  13198. UploadProgress progress) {
  13199. return cli_->Put(path, body, content_length, content_type, progress);
  13200. }
  13201. inline Result Client::Put(const std::string &path, const Headers &headers,
  13202. const char *body, size_t content_length,
  13203. const std::string &content_type,
  13204. UploadProgress progress) {
  13205. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13206. }
  13207. inline Result Client::Put(const std::string &path, const std::string &body,
  13208. const std::string &content_type,
  13209. UploadProgress progress) {
  13210. return cli_->Put(path, body, content_type, progress);
  13211. }
  13212. inline Result Client::Put(const std::string &path, const Headers &headers,
  13213. const std::string &body,
  13214. const std::string &content_type,
  13215. UploadProgress progress) {
  13216. return cli_->Put(path, headers, body, content_type, progress);
  13217. }
  13218. inline Result Client::Put(const std::string &path, size_t content_length,
  13219. ContentProvider content_provider,
  13220. const std::string &content_type,
  13221. UploadProgress progress) {
  13222. return cli_->Put(path, content_length, std::move(content_provider),
  13223. content_type, progress);
  13224. }
  13225. inline Result Client::Put(const std::string &path, size_t content_length,
  13226. ContentProvider content_provider,
  13227. const std::string &content_type,
  13228. ContentReceiver content_receiver,
  13229. UploadProgress progress) {
  13230. return cli_->Put(path, content_length, std::move(content_provider),
  13231. content_type, std::move(content_receiver), progress);
  13232. }
  13233. inline Result Client::Put(const std::string &path,
  13234. ContentProviderWithoutLength content_provider,
  13235. const std::string &content_type,
  13236. UploadProgress progress) {
  13237. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13238. }
  13239. inline Result Client::Put(const std::string &path,
  13240. ContentProviderWithoutLength content_provider,
  13241. const std::string &content_type,
  13242. ContentReceiver content_receiver,
  13243. UploadProgress progress) {
  13244. return cli_->Put(path, std::move(content_provider), content_type,
  13245. std::move(content_receiver), progress);
  13246. }
  13247. inline Result Client::Put(const std::string &path, const Headers &headers,
  13248. size_t content_length,
  13249. ContentProvider content_provider,
  13250. const std::string &content_type,
  13251. UploadProgress progress) {
  13252. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13253. content_type, progress);
  13254. }
  13255. inline Result Client::Put(const std::string &path, const Headers &headers,
  13256. size_t content_length,
  13257. ContentProvider content_provider,
  13258. const std::string &content_type,
  13259. ContentReceiver content_receiver,
  13260. UploadProgress progress) {
  13261. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13262. content_type, std::move(content_receiver), progress);
  13263. }
  13264. inline Result Client::Put(const std::string &path, const Headers &headers,
  13265. ContentProviderWithoutLength content_provider,
  13266. const std::string &content_type,
  13267. UploadProgress progress) {
  13268. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13269. progress);
  13270. }
  13271. inline Result Client::Put(const std::string &path, const Headers &headers,
  13272. ContentProviderWithoutLength content_provider,
  13273. const std::string &content_type,
  13274. ContentReceiver content_receiver,
  13275. UploadProgress progress) {
  13276. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13277. std::move(content_receiver), progress);
  13278. }
  13279. inline Result Client::Put(const std::string &path, const Params &params) {
  13280. return cli_->Put(path, params);
  13281. }
  13282. inline Result Client::Put(const std::string &path, const Headers &headers,
  13283. const Params &params) {
  13284. return cli_->Put(path, headers, params);
  13285. }
  13286. inline Result Client::Put(const std::string &path,
  13287. const UploadFormDataItems &items,
  13288. UploadProgress progress) {
  13289. return cli_->Put(path, items, progress);
  13290. }
  13291. inline Result Client::Put(const std::string &path, const Headers &headers,
  13292. const UploadFormDataItems &items,
  13293. UploadProgress progress) {
  13294. return cli_->Put(path, headers, items, progress);
  13295. }
  13296. inline Result Client::Put(const std::string &path, const Headers &headers,
  13297. const UploadFormDataItems &items,
  13298. const std::string &boundary,
  13299. UploadProgress progress) {
  13300. return cli_->Put(path, headers, items, boundary, progress);
  13301. }
  13302. inline Result Client::Put(const std::string &path, const Headers &headers,
  13303. const UploadFormDataItems &items,
  13304. const FormDataProviderItems &provider_items,
  13305. UploadProgress progress) {
  13306. return cli_->Put(path, headers, items, provider_items, progress);
  13307. }
  13308. inline Result Client::Put(const std::string &path, const Headers &headers,
  13309. const std::string &body,
  13310. const std::string &content_type,
  13311. ContentReceiver content_receiver,
  13312. DownloadProgress progress) {
  13313. return cli_->Put(path, headers, body, content_type, content_receiver,
  13314. progress);
  13315. }
  13316. inline Result Client::Patch(const std::string &path) {
  13317. return cli_->Patch(path);
  13318. }
  13319. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13320. return cli_->Patch(path, headers);
  13321. }
  13322. inline Result Client::Patch(const std::string &path, const char *body,
  13323. size_t content_length,
  13324. const std::string &content_type,
  13325. UploadProgress progress) {
  13326. return cli_->Patch(path, body, content_length, content_type, progress);
  13327. }
  13328. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13329. const char *body, size_t content_length,
  13330. const std::string &content_type,
  13331. UploadProgress progress) {
  13332. return cli_->Patch(path, headers, body, content_length, content_type,
  13333. progress);
  13334. }
  13335. inline Result Client::Patch(const std::string &path, const std::string &body,
  13336. const std::string &content_type,
  13337. UploadProgress progress) {
  13338. return cli_->Patch(path, body, content_type, progress);
  13339. }
  13340. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13341. const std::string &body,
  13342. const std::string &content_type,
  13343. UploadProgress progress) {
  13344. return cli_->Patch(path, headers, body, content_type, progress);
  13345. }
  13346. inline Result Client::Patch(const std::string &path, size_t content_length,
  13347. ContentProvider content_provider,
  13348. const std::string &content_type,
  13349. UploadProgress progress) {
  13350. return cli_->Patch(path, content_length, std::move(content_provider),
  13351. content_type, progress);
  13352. }
  13353. inline Result Client::Patch(const std::string &path, size_t content_length,
  13354. ContentProvider content_provider,
  13355. const std::string &content_type,
  13356. ContentReceiver content_receiver,
  13357. UploadProgress progress) {
  13358. return cli_->Patch(path, content_length, std::move(content_provider),
  13359. content_type, std::move(content_receiver), progress);
  13360. }
  13361. inline Result Client::Patch(const std::string &path,
  13362. ContentProviderWithoutLength content_provider,
  13363. const std::string &content_type,
  13364. UploadProgress progress) {
  13365. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13366. }
  13367. inline Result Client::Patch(const std::string &path,
  13368. ContentProviderWithoutLength content_provider,
  13369. const std::string &content_type,
  13370. ContentReceiver content_receiver,
  13371. UploadProgress progress) {
  13372. return cli_->Patch(path, std::move(content_provider), content_type,
  13373. std::move(content_receiver), progress);
  13374. }
  13375. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13376. size_t content_length,
  13377. ContentProvider content_provider,
  13378. const std::string &content_type,
  13379. UploadProgress progress) {
  13380. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13381. content_type, progress);
  13382. }
  13383. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13384. size_t content_length,
  13385. ContentProvider content_provider,
  13386. const std::string &content_type,
  13387. ContentReceiver content_receiver,
  13388. UploadProgress progress) {
  13389. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13390. content_type, std::move(content_receiver), progress);
  13391. }
  13392. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13393. ContentProviderWithoutLength content_provider,
  13394. const std::string &content_type,
  13395. UploadProgress progress) {
  13396. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13397. progress);
  13398. }
  13399. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13400. ContentProviderWithoutLength content_provider,
  13401. const std::string &content_type,
  13402. ContentReceiver content_receiver,
  13403. UploadProgress progress) {
  13404. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13405. std::move(content_receiver), progress);
  13406. }
  13407. inline Result Client::Patch(const std::string &path, const Params &params) {
  13408. return cli_->Patch(path, params);
  13409. }
  13410. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13411. const Params &params) {
  13412. return cli_->Patch(path, headers, params);
  13413. }
  13414. inline Result Client::Patch(const std::string &path,
  13415. const UploadFormDataItems &items,
  13416. UploadProgress progress) {
  13417. return cli_->Patch(path, items, progress);
  13418. }
  13419. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13420. const UploadFormDataItems &items,
  13421. UploadProgress progress) {
  13422. return cli_->Patch(path, headers, items, progress);
  13423. }
  13424. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13425. const UploadFormDataItems &items,
  13426. const std::string &boundary,
  13427. UploadProgress progress) {
  13428. return cli_->Patch(path, headers, items, boundary, progress);
  13429. }
  13430. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13431. const UploadFormDataItems &items,
  13432. const FormDataProviderItems &provider_items,
  13433. UploadProgress progress) {
  13434. return cli_->Patch(path, headers, items, provider_items, progress);
  13435. }
  13436. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13437. const std::string &body,
  13438. const std::string &content_type,
  13439. ContentReceiver content_receiver,
  13440. DownloadProgress progress) {
  13441. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13442. progress);
  13443. }
  13444. inline Result Client::Delete(const std::string &path,
  13445. DownloadProgress progress) {
  13446. return cli_->Delete(path, progress);
  13447. }
  13448. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13449. DownloadProgress progress) {
  13450. return cli_->Delete(path, headers, progress);
  13451. }
  13452. inline Result Client::Delete(const std::string &path, const char *body,
  13453. size_t content_length,
  13454. const std::string &content_type,
  13455. DownloadProgress progress) {
  13456. return cli_->Delete(path, body, content_length, content_type, progress);
  13457. }
  13458. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13459. const char *body, size_t content_length,
  13460. const std::string &content_type,
  13461. DownloadProgress progress) {
  13462. return cli_->Delete(path, headers, body, content_length, content_type,
  13463. progress);
  13464. }
  13465. inline Result Client::Delete(const std::string &path, const std::string &body,
  13466. const std::string &content_type,
  13467. DownloadProgress progress) {
  13468. return cli_->Delete(path, body, content_type, progress);
  13469. }
  13470. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13471. const std::string &body,
  13472. const std::string &content_type,
  13473. DownloadProgress progress) {
  13474. return cli_->Delete(path, headers, body, content_type, progress);
  13475. }
  13476. inline Result Client::Delete(const std::string &path, const Params &params,
  13477. DownloadProgress progress) {
  13478. return cli_->Delete(path, params, progress);
  13479. }
  13480. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13481. const Params &params, DownloadProgress progress) {
  13482. return cli_->Delete(path, headers, params, progress);
  13483. }
  13484. inline Result Client::Options(const std::string &path) {
  13485. return cli_->Options(path);
  13486. }
  13487. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13488. return cli_->Options(path, headers);
  13489. }
  13490. inline ClientImpl::StreamHandle
  13491. Client::open_stream(const std::string &method, const std::string &path,
  13492. const Params &params, const Headers &headers,
  13493. const std::string &body, const std::string &content_type) {
  13494. return cli_->open_stream(method, path, params, headers, body, content_type);
  13495. }
  13496. inline bool Client::send(Request &req, Response &res, Error &error) {
  13497. return cli_->send(req, res, error);
  13498. }
  13499. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13500. inline void Client::stop() { cli_->stop(); }
  13501. inline std::string Client::host() const { return cli_->host(); }
  13502. inline int Client::port() const { return cli_->port(); }
  13503. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13504. inline socket_t Client::socket() const { return cli_->socket(); }
  13505. inline void
  13506. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13507. cli_->set_hostname_addr_map(std::move(addr_map));
  13508. }
  13509. inline void Client::set_default_headers(Headers headers) {
  13510. cli_->set_default_headers(std::move(headers));
  13511. }
  13512. inline void Client::set_header_writer(
  13513. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13514. cli_->set_header_writer(writer);
  13515. }
  13516. inline void Client::set_address_family(int family) {
  13517. cli_->set_address_family(family);
  13518. }
  13519. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13520. inline void Client::set_socket_options(SocketOptions socket_options) {
  13521. cli_->set_socket_options(std::move(socket_options));
  13522. }
  13523. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13524. cli_->set_connection_timeout(sec, usec);
  13525. }
  13526. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13527. cli_->set_read_timeout(sec, usec);
  13528. }
  13529. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13530. cli_->set_write_timeout(sec, usec);
  13531. }
  13532. inline void Client::set_basic_auth(const std::string &username,
  13533. const std::string &password) {
  13534. cli_->set_basic_auth(username, password);
  13535. }
  13536. inline void Client::set_bearer_token_auth(const std::string &token) {
  13537. cli_->set_bearer_token_auth(token);
  13538. }
  13539. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13540. inline void Client::set_follow_location(bool on) {
  13541. cli_->set_follow_location(on);
  13542. }
  13543. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13544. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13545. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13546. inline void Client::set_payload_max_length(size_t length) {
  13547. cli_->set_payload_max_length(length);
  13548. }
  13549. inline void Client::set_interface(const std::string &intf) {
  13550. cli_->set_interface(intf);
  13551. }
  13552. inline void Client::set_proxy(const std::string &host, int port) {
  13553. cli_->set_proxy(host, port);
  13554. }
  13555. inline void Client::set_proxy_basic_auth(const std::string &username,
  13556. const std::string &password) {
  13557. cli_->set_proxy_basic_auth(username, password);
  13558. }
  13559. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13560. cli_->set_proxy_bearer_token_auth(token);
  13561. }
  13562. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13563. cli_->set_no_proxy(patterns);
  13564. }
  13565. inline void Client::set_logger(Logger logger) {
  13566. cli_->set_logger(std::move(logger));
  13567. }
  13568. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13569. cli_->set_error_logger(std::move(error_logger));
  13570. }
  13571. /*
  13572. * Group 6: SSL Server and Client implementation
  13573. */
  13574. #ifdef CPPHTTPLIB_SSL_ENABLED
  13575. // SSL HTTP server implementation
  13576. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13577. const char *client_ca_cert_file_path,
  13578. const char *client_ca_cert_dir_path,
  13579. const char *private_key_password) {
  13580. using namespace tls;
  13581. ctx_ = create_server_context();
  13582. if (!ctx_) { return; }
  13583. // Load server certificate and private key
  13584. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13585. private_key_password)) {
  13586. last_ssl_error_ = static_cast<int>(get_error());
  13587. free_context(ctx_);
  13588. ctx_ = nullptr;
  13589. return;
  13590. }
  13591. // Load client CA certificates for client authentication
  13592. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13593. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13594. client_ca_cert_dir_path)) {
  13595. last_ssl_error_ = static_cast<int>(get_error());
  13596. free_context(ctx_);
  13597. ctx_ = nullptr;
  13598. return;
  13599. }
  13600. // Enable client certificate verification
  13601. set_verify_client(ctx_, true);
  13602. }
  13603. }
  13604. inline SSLServer::SSLServer(const PemMemory &pem) {
  13605. using namespace tls;
  13606. ctx_ = create_server_context();
  13607. if (ctx_) {
  13608. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13609. pem.private_key_password)) {
  13610. last_ssl_error_ = static_cast<int>(get_error());
  13611. free_context(ctx_);
  13612. ctx_ = nullptr;
  13613. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13614. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13615. last_ssl_error_ = static_cast<int>(get_error());
  13616. free_context(ctx_);
  13617. ctx_ = nullptr;
  13618. } else {
  13619. set_verify_client(ctx_, true);
  13620. }
  13621. }
  13622. }
  13623. }
  13624. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13625. using namespace tls;
  13626. ctx_ = create_server_context();
  13627. if (ctx_) {
  13628. if (!setup_callback(ctx_)) {
  13629. free_context(ctx_);
  13630. ctx_ = nullptr;
  13631. }
  13632. }
  13633. }
  13634. inline SSLServer::~SSLServer() {
  13635. if (ctx_) { tls::free_context(ctx_); }
  13636. }
  13637. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13638. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13639. using namespace tls;
  13640. // Create TLS session with mutex protection
  13641. session_t session = nullptr;
  13642. {
  13643. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13644. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13645. }
  13646. if (!session) {
  13647. last_ssl_error_ = static_cast<int>(get_error());
  13648. detail::shutdown_socket(sock);
  13649. detail::close_socket(sock);
  13650. return false;
  13651. }
  13652. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13653. bool handshake_done = false;
  13654. bool ret = false;
  13655. bool websocket_upgraded = false;
  13656. auto cleanup = detail::scope_exit([&] {
  13657. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13658. free_session(session);
  13659. detail::shutdown_socket(sock);
  13660. detail::close_socket(sock);
  13661. });
  13662. // Perform TLS accept handshake with timeout
  13663. TlsError tls_err;
  13664. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13665. &tls_err)) {
  13666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13667. // Map TlsError to legacy ssl_error for backward compatibility
  13668. if (tls_err.code == ErrorCode::WantRead) {
  13669. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13670. } else if (tls_err.code == ErrorCode::WantWrite) {
  13671. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13672. } else {
  13673. last_ssl_error_ = SSL_ERROR_SSL;
  13674. }
  13675. #else
  13676. last_ssl_error_ = static_cast<int>(get_error());
  13677. #endif
  13678. return false;
  13679. }
  13680. handshake_done = true;
  13681. std::string remote_addr;
  13682. int remote_port = 0;
  13683. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13684. std::string local_addr;
  13685. int local_port = 0;
  13686. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13687. ret = detail::process_server_socket_ssl(
  13688. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13689. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13690. write_timeout_usec_,
  13691. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13692. return process_request(
  13693. strm, remote_addr, remote_port, local_addr, local_port,
  13694. close_connection, connection_closed,
  13695. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13696. });
  13697. return ret;
  13698. }
  13699. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13700. const char *key_pem,
  13701. const char *client_ca_pem,
  13702. const char *password) {
  13703. if (!ctx_) { return false; }
  13704. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13705. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13706. return false;
  13707. }
  13708. if (client_ca_pem) {
  13709. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13710. }
  13711. return true;
  13712. }
  13713. // SSL HTTP client implementation
  13714. inline SSLClient::~SSLClient() {
  13715. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13716. // base function rather than the derived function once we get to the
  13717. // base class destructor, and won't free the SSL (causing a leak).
  13718. // This must happen before the context is freed below: some backends
  13719. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  13720. // context, so freeing the context first leaves close_notify reading
  13721. // freed memory.
  13722. shutdown_ssl_impl(socket_, true);
  13723. if (ctx_) {
  13724. tls::free_context(ctx_);
  13725. ctx_ = nullptr;
  13726. }
  13727. }
  13728. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13729. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13730. shutdown_ssl_impl(socket, shutdown_gracefully);
  13731. }
  13732. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13733. bool shutdown_gracefully) {
  13734. if (socket.sock == INVALID_SOCKET) {
  13735. assert(socket.ssl == nullptr);
  13736. return;
  13737. }
  13738. if (socket.ssl) {
  13739. tls::shutdown(socket.ssl, shutdown_gracefully);
  13740. {
  13741. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13742. tls::free_session(socket.ssl);
  13743. }
  13744. socket.ssl = nullptr;
  13745. }
  13746. assert(socket.ssl == nullptr);
  13747. }
  13748. inline bool SSLClient::process_socket(
  13749. const Socket &socket,
  13750. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13751. std::function<bool(Stream &strm)> callback) {
  13752. assert(socket.ssl);
  13753. return detail::process_client_socket_ssl(
  13754. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13755. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13756. std::move(callback));
  13757. }
  13758. inline bool SSLClient::is_ssl() const { return true; }
  13759. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13760. if (!is_valid()) {
  13761. error = Error::SSLConnection;
  13762. return false;
  13763. }
  13764. return ClientImpl::create_and_connect_socket(socket, error);
  13765. }
  13766. inline bool SSLClient::setup_proxy_connection(
  13767. Socket &socket,
  13768. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13769. Response &res, bool &success, Error &error) {
  13770. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13771. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13772. return false;
  13773. }
  13774. if (!initialize_ssl(socket, error)) {
  13775. success = false;
  13776. return false;
  13777. }
  13778. return true;
  13779. }
  13780. // Assumes that socket_mutex_ is locked and that there are no requests in
  13781. // flight
  13782. inline bool SSLClient::connect_with_proxy(
  13783. Socket &socket,
  13784. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13785. Response &res, bool &success, Error &error) {
  13786. success = true;
  13787. Response proxy_res;
  13788. if (!detail::process_client_socket(
  13789. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13790. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13791. start_time, [&](Stream &strm) {
  13792. Request req2;
  13793. req2.method = "CONNECT";
  13794. req2.path =
  13795. detail::make_host_and_port_string_always_port(host_, port_);
  13796. if (max_timeout_msec_ > 0) {
  13797. req2.start_time_ = std::chrono::steady_clock::now();
  13798. }
  13799. return process_request(strm, req2, proxy_res, false, error);
  13800. })) {
  13801. // Thread-safe to close everything because we are assuming there are no
  13802. // requests in flight
  13803. shutdown_ssl(socket, true);
  13804. shutdown_socket(socket);
  13805. close_socket(socket);
  13806. success = false;
  13807. return false;
  13808. }
  13809. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13810. if (!proxy_digest_auth_username_.empty() &&
  13811. !proxy_digest_auth_password_.empty()) {
  13812. std::map<std::string, std::string> auth;
  13813. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13814. // Close the current socket and create a new one for the authenticated
  13815. // request
  13816. shutdown_ssl(socket, true);
  13817. shutdown_socket(socket);
  13818. close_socket(socket);
  13819. // Create a new socket for the authenticated CONNECT request
  13820. if (!ensure_socket_connection(socket, error)) {
  13821. success = false;
  13822. output_error_log(error, nullptr);
  13823. return false;
  13824. }
  13825. proxy_res = Response();
  13826. if (!detail::process_client_socket(
  13827. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13828. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13829. start_time, [&](Stream &strm) {
  13830. Request req3;
  13831. req3.method = "CONNECT";
  13832. req3.path = detail::make_host_and_port_string_always_port(
  13833. host_, port_);
  13834. req3.headers.insert(detail::make_digest_authentication_header(
  13835. req3, auth, 1, detail::random_string(10),
  13836. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13837. true));
  13838. if (max_timeout_msec_ > 0) {
  13839. req3.start_time_ = std::chrono::steady_clock::now();
  13840. }
  13841. return process_request(strm, req3, proxy_res, false, error);
  13842. })) {
  13843. // Thread-safe to close everything because we are assuming there are
  13844. // no requests in flight
  13845. shutdown_ssl(socket, true);
  13846. shutdown_socket(socket);
  13847. close_socket(socket);
  13848. success = false;
  13849. return false;
  13850. }
  13851. }
  13852. }
  13853. }
  13854. // If status code is not 200, proxy request is failed.
  13855. // Set error to ProxyConnection and return proxy response
  13856. // as the response of the request
  13857. if (proxy_res.status != StatusCode::OK_200) {
  13858. error = Error::ProxyConnection;
  13859. output_error_log(error, nullptr);
  13860. res = std::move(proxy_res);
  13861. // Thread-safe to close everything because we are assuming there are
  13862. // no requests in flight
  13863. shutdown_ssl(socket, true);
  13864. shutdown_socket(socket);
  13865. close_socket(socket);
  13866. return false;
  13867. }
  13868. return true;
  13869. }
  13870. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13871. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13872. if (is_proxy_enabled_for_host(host_)) { return true; }
  13873. if (!initialize_ssl(socket, error)) {
  13874. shutdown_socket(socket);
  13875. close_socket(socket);
  13876. return false;
  13877. }
  13878. return true;
  13879. }
  13880. // SSL HTTP client implementation
  13881. inline SSLClient::SSLClient(const std::string &host)
  13882. : SSLClient(host, 443, std::string(), std::string()) {}
  13883. inline SSLClient::SSLClient(const std::string &host, int port)
  13884. : SSLClient(host, port, std::string(), std::string()) {}
  13885. inline void SSLClient::init_ctx() {
  13886. ctx_ = tls::create_client_context();
  13887. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13888. }
  13889. inline void SSLClient::reset_ctx_on_error() {
  13890. last_backend_error_ = tls::get_error();
  13891. tls::free_context(ctx_);
  13892. ctx_ = nullptr;
  13893. }
  13894. inline SSLClient::SSLClient(const std::string &host, int port,
  13895. const std::string &client_cert_path,
  13896. const std::string &client_key_path,
  13897. const std::string &private_key_password)
  13898. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13899. init_ctx();
  13900. if (!ctx_) { return; }
  13901. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13902. const char *password =
  13903. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13904. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13905. client_key_path.c_str(), password)) {
  13906. reset_ctx_on_error();
  13907. }
  13908. }
  13909. }
  13910. inline SSLClient::SSLClient(const std::string &host, int port,
  13911. const PemMemory &pem)
  13912. : ClientImpl(host, port) {
  13913. init_ctx();
  13914. if (!ctx_) { return; }
  13915. if (pem.cert_pem && pem.key_pem) {
  13916. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13917. pem.private_key_password)) {
  13918. reset_ctx_on_error();
  13919. }
  13920. }
  13921. }
  13922. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13923. if (ca_cert_store && ctx_) {
  13924. // set_ca_store takes ownership of ca_cert_store
  13925. tls::set_ca_store(ctx_, ca_cert_store);
  13926. ca_cert_store_set_ = true;
  13927. } else if (ca_cert_store) {
  13928. tls::free_ca_store(ca_cert_store);
  13929. }
  13930. }
  13931. inline void
  13932. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13933. if (!ctx_) { return; }
  13934. tls::set_verify_callback(ctx_, verifier);
  13935. }
  13936. inline void SSLClient::set_session_verifier(
  13937. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13938. session_verifier_ = std::move(verifier);
  13939. }
  13940. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13941. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13942. enable_windows_cert_verification_ = enabled;
  13943. }
  13944. #endif
  13945. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13946. std::size_t size) {
  13947. if (ctx_ && ca_cert && size > 0) {
  13948. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13949. tls::load_ca_pem(ctx_, ca_cert, size);
  13950. }
  13951. }
  13952. inline bool SSLClient::load_certs() {
  13953. auto ret = true;
  13954. std::call_once(initialize_cert_, [&]() {
  13955. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13956. ret = detail::load_client_ca_config(
  13957. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13958. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13959. last_backend_error_);
  13960. });
  13961. return ret;
  13962. }
  13963. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13964. using namespace tls;
  13965. // Load CA certificates if server verification is enabled
  13966. if (server_certificate_verification_) {
  13967. if (!load_certs()) {
  13968. error = Error::SSLLoadingCerts;
  13969. output_error_log(error, nullptr);
  13970. return false;
  13971. }
  13972. }
  13973. bool is_ip = detail::is_ip_address(host_);
  13974. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13975. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13976. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13977. // Chain verification happens during the handshake even for IP hosts; the
  13978. // certificate identity is verified post-handshake via verify_hostname().
  13979. set_verify_client(ctx_, server_certificate_verification_);
  13980. #endif
  13981. // Create TLS session
  13982. session_t session = nullptr;
  13983. {
  13984. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13985. session = create_session(ctx_, socket.sock);
  13986. }
  13987. if (!session) {
  13988. error = Error::SSLConnection;
  13989. last_backend_error_ = get_error();
  13990. return false;
  13991. }
  13992. // Use scope_exit to ensure session is freed on error paths
  13993. bool success = false;
  13994. auto session_guard = detail::scope_exit([&] {
  13995. if (!success) { free_session(session); }
  13996. });
  13997. // Set SNI extension (skip for IP addresses per RFC 6066).
  13998. // On MbedTLS, set_sni also enables hostname verification internally.
  13999. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  14000. if (!is_ip) {
  14001. if (!set_sni(session, host_.c_str())) {
  14002. error = Error::SSLConnection;
  14003. last_backend_error_ = get_error();
  14004. return false;
  14005. }
  14006. }
  14007. // Perform non-blocking TLS handshake with timeout
  14008. TlsError tls_err;
  14009. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  14010. connection_timeout_usec_, &tls_err)) {
  14011. last_ssl_error_ = static_cast<int>(tls_err.code);
  14012. last_backend_error_ = tls_err.backend_code;
  14013. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  14014. error = Error::SSLServerVerification;
  14015. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  14016. error = Error::SSLServerHostnameVerification;
  14017. } else {
  14018. error = Error::SSLConnection;
  14019. }
  14020. output_error_log(error, nullptr);
  14021. return false;
  14022. }
  14023. // Post-handshake session verifier callback
  14024. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  14025. if (session_verifier_) { verification_status = session_verifier_(session); }
  14026. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  14027. last_backend_error_ = get_error();
  14028. error = Error::SSLServerVerification;
  14029. output_error_log(error, nullptr);
  14030. return false;
  14031. }
  14032. // Default server certificate verification
  14033. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  14034. server_certificate_verification_) {
  14035. verify_result_ = tls::get_verify_result(session);
  14036. if (verify_result_ != 0) {
  14037. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  14038. error = Error::SSLServerVerification;
  14039. output_error_log(error, nullptr);
  14040. return false;
  14041. }
  14042. auto server_cert = get_peer_cert(session);
  14043. if (!server_cert) {
  14044. last_backend_error_ = get_error();
  14045. error = Error::SSLServerVerification;
  14046. output_error_log(error, nullptr);
  14047. return false;
  14048. }
  14049. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  14050. // Hostname verification (post-handshake for all cases).
  14051. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  14052. // On MbedTLS, set_sni already enabled hostname verification during
  14053. // handshake for non-IP hosts, but this check is still needed for IP
  14054. // addresses where SNI is not set.
  14055. if (server_hostname_verification_) {
  14056. if (!verify_hostname(server_cert, host_.c_str())) {
  14057. last_backend_error_ = hostname_mismatch_code();
  14058. error = Error::SSLServerHostnameVerification;
  14059. output_error_log(error, nullptr);
  14060. return false;
  14061. }
  14062. }
  14063. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14064. // Additional Windows Schannel verification.
  14065. // This provides real-time certificate validation with Windows Update
  14066. // integration, working with both OpenSSL and MbedTLS backends.
  14067. // Skip when a custom CA cert is specified, as the Windows certificate
  14068. // store would not know about user-provided CA certificates. Also skip
  14069. // when system CA trust is explicitly disabled.
  14070. if (enable_windows_cert_verification_ &&
  14071. system_ca_mode_ != SystemCAMode::Disabled &&
  14072. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  14073. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  14074. std::vector<unsigned char> der;
  14075. if (get_cert_der(server_cert, der)) {
  14076. uint64_t wincrypt_error = 0;
  14077. if (!detail::verify_cert_with_windows_schannel(
  14078. der, host_, server_hostname_verification_, wincrypt_error)) {
  14079. last_backend_error_ = wincrypt_error;
  14080. error = Error::SSLServerVerification;
  14081. output_error_log(error, nullptr);
  14082. return false;
  14083. }
  14084. }
  14085. }
  14086. #endif
  14087. }
  14088. success = true;
  14089. socket.ssl = session;
  14090. return true;
  14091. }
  14092. inline void Client::set_digest_auth(const std::string &username,
  14093. const std::string &password) {
  14094. cli_->set_digest_auth(username, password);
  14095. }
  14096. inline void Client::set_proxy_digest_auth(const std::string &username,
  14097. const std::string &password) {
  14098. cli_->set_proxy_digest_auth(username, password);
  14099. }
  14100. inline void Client::enable_server_certificate_verification(bool enabled) {
  14101. cli_->enable_server_certificate_verification(enabled);
  14102. }
  14103. inline void Client::enable_server_hostname_verification(bool enabled) {
  14104. cli_->enable_server_hostname_verification(enabled);
  14105. }
  14106. inline void Client::enable_system_ca(bool enabled) {
  14107. cli_->enable_system_ca(enabled);
  14108. }
  14109. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14110. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14111. if (is_ssl_) {
  14112. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14113. enabled);
  14114. }
  14115. }
  14116. #endif
  14117. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14118. const std::string &ca_cert_dir_path) {
  14119. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14120. }
  14121. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14122. if (is_ssl_) {
  14123. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14124. } else if (ca_cert_store) {
  14125. tls::free_ca_store(ca_cert_store);
  14126. }
  14127. }
  14128. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14129. if (is_ssl_) {
  14130. // Use the PEM-based path so the CA data is retained for redirect transfer
  14131. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14132. }
  14133. }
  14134. inline void
  14135. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14136. if (is_ssl_) {
  14137. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14138. std::move(verifier));
  14139. }
  14140. }
  14141. inline void Client::set_session_verifier(
  14142. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14143. if (is_ssl_) {
  14144. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14145. }
  14146. }
  14147. inline tls::ctx_t Client::tls_context() const {
  14148. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14149. return nullptr;
  14150. }
  14151. #endif // CPPHTTPLIB_SSL_ENABLED
  14152. /*
  14153. * Group 7: TLS abstraction layer - Common API
  14154. */
  14155. #ifdef CPPHTTPLIB_SSL_ENABLED
  14156. namespace tls {
  14157. // Helper for PeerCert construction
  14158. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14159. return PeerCert(get_peer_cert(session));
  14160. }
  14161. namespace impl {
  14162. inline VerifyCallback &get_verify_callback() {
  14163. static thread_local VerifyCallback callback;
  14164. return callback;
  14165. }
  14166. inline VerifyCallback &get_mbedtls_verify_callback() {
  14167. static thread_local VerifyCallback callback;
  14168. return callback;
  14169. }
  14170. // Check if a string is an IPv4 address
  14171. inline bool is_ipv4_address(const std::string &str) {
  14172. int dots = 0;
  14173. for (char c : str) {
  14174. if (c == '.') {
  14175. dots++;
  14176. } else if (!detail::is_ascii_digit(c)) {
  14177. return false;
  14178. }
  14179. }
  14180. return dots == 3;
  14181. }
  14182. // Parse IPv4 address string to bytes
  14183. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14184. const char *p = str.c_str();
  14185. for (int i = 0; i < 4; i++) {
  14186. if (i > 0) {
  14187. if (*p != '.') { return false; }
  14188. p++;
  14189. }
  14190. int val = 0;
  14191. int digits = 0;
  14192. while (detail::is_ascii_digit(*p)) {
  14193. val = val * 10 + (*p - '0');
  14194. if (val > 255) { return false; }
  14195. p++;
  14196. digits++;
  14197. }
  14198. if (digits == 0) { return false; }
  14199. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14200. if (digits > 1 && *(p - digits) == '0') { return false; }
  14201. out[i] = static_cast<unsigned char>(val);
  14202. }
  14203. return *p == '\0';
  14204. }
  14205. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14206. // `out` must have room for at least 16 bytes. Returns the address length
  14207. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14208. // literal. Used to match a host against iPAddress SANs the same way the
  14209. // OpenSSL backend does via X509_check_ip.
  14210. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14211. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14212. struct in6_addr addr6 = {};
  14213. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14214. memcpy(out, &addr6, 16);
  14215. return 16;
  14216. }
  14217. return 0;
  14218. }
  14219. #ifdef _WIN32
  14220. // Enumerate Windows system certificates and call callback with DER data
  14221. template <typename Callback>
  14222. inline bool enumerate_windows_system_certs(Callback cb) {
  14223. bool loaded = false;
  14224. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14225. for (auto store_name : store_names) {
  14226. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14227. if (hStore) {
  14228. PCCERT_CONTEXT pContext = nullptr;
  14229. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14230. nullptr) {
  14231. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14232. loaded = true;
  14233. }
  14234. }
  14235. CertCloseStore(hStore, 0);
  14236. }
  14237. }
  14238. return loaded;
  14239. }
  14240. #endif
  14241. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14242. // Enumerate macOS Keychain certificates and call callback with DER data
  14243. template <typename Callback>
  14244. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14245. bool loaded = false;
  14246. const SecTrustSettingsDomain domains[] = {
  14247. kSecTrustSettingsDomainSystem,
  14248. kSecTrustSettingsDomainAdmin,
  14249. kSecTrustSettingsDomainUser,
  14250. };
  14251. for (auto domain : domains) {
  14252. CFArrayRef certs = nullptr;
  14253. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14254. if (status != errSecSuccess || !certs) {
  14255. if (certs) CFRelease(certs);
  14256. continue;
  14257. }
  14258. CFIndex count = CFArrayGetCount(certs);
  14259. for (CFIndex i = 0; i < count; i++) {
  14260. SecCertificateRef cert =
  14261. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14262. CFDataRef data = SecCertificateCopyData(cert);
  14263. if (data) {
  14264. if (cb(CFDataGetBytePtr(data),
  14265. static_cast<size_t>(CFDataGetLength(data)))) {
  14266. loaded = true;
  14267. }
  14268. CFRelease(data);
  14269. }
  14270. }
  14271. CFRelease(certs);
  14272. }
  14273. return loaded;
  14274. }
  14275. #endif
  14276. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14277. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14278. // Common CA certificate file paths on Linux/Unix
  14279. inline const char **system_ca_paths() {
  14280. static const char *paths[] = {
  14281. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14282. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14283. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14284. "/etc/pki/tls/cacert.pem", // OpenELEC
  14285. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14286. nullptr};
  14287. return paths;
  14288. }
  14289. // Common CA certificate directory paths on Linux/Unix
  14290. inline const char **system_ca_dirs() {
  14291. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14292. "/etc/pki/tls/certs", // RHEL/CentOS
  14293. "/usr/share/ca-certificates", // Other
  14294. nullptr};
  14295. return dirs;
  14296. }
  14297. #endif
  14298. } // namespace impl
  14299. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14300. const char *ca_dir) {
  14301. if (!ctx) { return false; }
  14302. bool success = true;
  14303. if (ca_file && *ca_file) {
  14304. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14305. }
  14306. if (ca_dir && *ca_dir) {
  14307. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14308. }
  14309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14310. // Set CA list for client certificate request (CertificateRequest message)
  14311. if (ca_file && *ca_file) {
  14312. auto list = SSL_load_client_CA_file(ca_file);
  14313. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14314. }
  14315. #endif
  14316. return success;
  14317. }
  14318. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14319. const char *password) {
  14320. return set_client_cert_pem(ctx, cert, key, password);
  14321. }
  14322. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14323. const char *key_path, const char *password) {
  14324. return set_client_cert_file(ctx, cert_path, key_path, password);
  14325. }
  14326. // PeerCert implementation
  14327. inline PeerCert::PeerCert() = default;
  14328. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14329. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14330. other.cert_ = nullptr;
  14331. }
  14332. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14333. if (this != &other) {
  14334. if (cert_) { free_cert(cert_); }
  14335. cert_ = other.cert_;
  14336. other.cert_ = nullptr;
  14337. }
  14338. return *this;
  14339. }
  14340. inline PeerCert::~PeerCert() {
  14341. if (cert_) { free_cert(cert_); }
  14342. }
  14343. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14344. inline std::string PeerCert::subject_cn() const {
  14345. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14346. }
  14347. inline std::string PeerCert::issuer_name() const {
  14348. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14349. }
  14350. inline bool PeerCert::check_hostname(const char *hostname) const {
  14351. return cert_ ? verify_hostname(cert_, hostname) : false;
  14352. }
  14353. inline std::vector<SanEntry> PeerCert::sans() const {
  14354. std::vector<SanEntry> result;
  14355. if (cert_) { get_cert_sans(cert_, result); }
  14356. return result;
  14357. }
  14358. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14359. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14360. }
  14361. inline std::string PeerCert::serial() const {
  14362. return cert_ ? get_cert_serial(cert_) : std::string();
  14363. }
  14364. // VerifyContext method implementations
  14365. inline std::string VerifyContext::subject_cn() const {
  14366. return cert ? get_cert_subject_cn(cert) : std::string();
  14367. }
  14368. inline std::string VerifyContext::issuer_name() const {
  14369. return cert ? get_cert_issuer_name(cert) : std::string();
  14370. }
  14371. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14372. return cert ? verify_hostname(cert, hostname) : false;
  14373. }
  14374. inline std::vector<SanEntry> VerifyContext::sans() const {
  14375. std::vector<SanEntry> result;
  14376. if (cert) { get_cert_sans(cert, result); }
  14377. return result;
  14378. }
  14379. inline bool VerifyContext::validity(time_t &not_before,
  14380. time_t &not_after) const {
  14381. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14382. }
  14383. inline std::string VerifyContext::serial() const {
  14384. return cert ? get_cert_serial(cert) : std::string();
  14385. }
  14386. // TlsError static method implementation
  14387. inline std::string TlsError::verify_error_to_string(long error_code) {
  14388. return verify_error_string(error_code);
  14389. }
  14390. } // namespace tls
  14391. // Request::peer_cert() implementation
  14392. inline tls::PeerCert Request::peer_cert() const {
  14393. return tls::get_peer_cert_from_session(ssl);
  14394. }
  14395. // Request::sni() implementation
  14396. inline std::string Request::sni() const {
  14397. if (!ssl) { return std::string(); }
  14398. const char *s = tls::get_sni(ssl);
  14399. return s ? std::string(s) : std::string();
  14400. }
  14401. #endif // CPPHTTPLIB_SSL_ENABLED
  14402. /*
  14403. * Group 8: TLS abstraction layer - OpenSSL backend
  14404. */
  14405. /*
  14406. * OpenSSL Backend Implementation
  14407. */
  14408. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14409. namespace tls {
  14410. namespace impl {
  14411. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14412. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14413. switch (ssl_error) {
  14414. case SSL_ERROR_NONE: return ErrorCode::Success;
  14415. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14416. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14417. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14418. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14419. case SSL_ERROR_SSL:
  14420. default: return ErrorCode::Fatal;
  14421. }
  14422. }
  14423. // Helper: Create client CA list from PEM string
  14424. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14425. // Caller takes ownership of returned list
  14426. inline STACK_OF(X509_NAME) *
  14427. create_client_ca_list_from_pem(const char *ca_pem) {
  14428. if (!ca_pem) { return nullptr; }
  14429. auto ca_list = sk_X509_NAME_new_null();
  14430. if (!ca_list) { return nullptr; }
  14431. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14432. if (!bio) {
  14433. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14434. return nullptr;
  14435. }
  14436. X509 *cert = nullptr;
  14437. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14438. nullptr) {
  14439. const X509_NAME *name = X509_get_subject_name(cert);
  14440. if (name) {
  14441. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14442. }
  14443. X509_free(cert);
  14444. }
  14445. BIO_free(bio);
  14446. return ca_list;
  14447. }
  14448. // OpenSSL verify callback wrapper
  14449. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14450. auto &callback = get_verify_callback();
  14451. if (!callback) { return preverify_ok; }
  14452. // Get SSL object from X509_STORE_CTX
  14453. auto ssl = static_cast<SSL *>(
  14454. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14455. if (!ssl) { return preverify_ok; }
  14456. // Get current certificate and depth
  14457. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14458. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14459. int error = X509_STORE_CTX_get_error(ctx);
  14460. // Build context
  14461. VerifyContext verify_ctx;
  14462. verify_ctx.session = static_cast<session_t>(ssl);
  14463. verify_ctx.cert = static_cast<cert_t>(cert);
  14464. verify_ctx.depth = depth;
  14465. verify_ctx.preverify_ok = (preverify_ok != 0);
  14466. verify_ctx.error_code = error;
  14467. verify_ctx.error_string =
  14468. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14469. return callback(verify_ctx) ? 1 : 0;
  14470. }
  14471. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14472. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14473. // that must be released with release_store_objects
  14474. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14475. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14476. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14477. #endif
  14478. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14479. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14480. return X509_STORE_get1_objects(store);
  14481. #else
  14482. return X509_STORE_get0_objects(store);
  14483. #endif
  14484. }
  14485. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14486. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14487. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14488. #else
  14489. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14490. #endif
  14491. }
  14492. } // namespace impl
  14493. inline ctx_t create_client_context() {
  14494. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14495. if (ctx) {
  14496. // Disable auto-retry to properly handle non-blocking I/O
  14497. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14498. // Set minimum TLS version
  14499. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14500. }
  14501. return static_cast<ctx_t>(ctx);
  14502. }
  14503. inline void free_context(ctx_t ctx) {
  14504. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14505. }
  14506. inline bool set_min_version(ctx_t ctx, Version version) {
  14507. if (!ctx) return false;
  14508. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14509. static_cast<int>(version)) == 1;
  14510. }
  14511. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14512. if (!ctx || !pem || len == 0) return false;
  14513. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14514. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14515. if (!store) return false;
  14516. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14517. if (!bio) return false;
  14518. bool ok = true;
  14519. X509 *cert = nullptr;
  14520. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14521. nullptr) {
  14522. if (X509_STORE_add_cert(store, cert) != 1) {
  14523. // Ignore duplicate errors
  14524. auto err = ERR_peek_last_error();
  14525. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14526. ok = false;
  14527. }
  14528. }
  14529. X509_free(cert);
  14530. if (!ok) break;
  14531. }
  14532. BIO_free(bio);
  14533. // Clear any "no more certificates" errors
  14534. ERR_clear_error();
  14535. return ok;
  14536. }
  14537. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14538. if (!ctx || !file_path) return false;
  14539. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14540. nullptr) == 1;
  14541. }
  14542. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14543. if (!ctx || !dir_path) return false;
  14544. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14545. dir_path) == 1;
  14546. }
  14547. inline bool load_system_certs(ctx_t ctx) {
  14548. if (!ctx) return false;
  14549. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14550. #ifdef _WIN32
  14551. // Windows: Load from system certificate store (ROOT and CA)
  14552. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14553. if (!store) return false;
  14554. bool loaded_any = false;
  14555. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14556. for (auto store_name : store_names) {
  14557. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14558. if (!hStore) continue;
  14559. PCCERT_CONTEXT pContext = nullptr;
  14560. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14561. nullptr) {
  14562. const unsigned char *data = pContext->pbCertEncoded;
  14563. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14564. if (x509) {
  14565. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14566. X509_free(x509);
  14567. }
  14568. }
  14569. CertCloseStore(hStore, 0);
  14570. }
  14571. return loaded_any;
  14572. #elif defined(__APPLE__)
  14573. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14574. // macOS: Load from Keychain
  14575. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14576. if (!store) return false;
  14577. bool loaded_any = false;
  14578. const SecTrustSettingsDomain domains[] = {
  14579. kSecTrustSettingsDomainSystem,
  14580. kSecTrustSettingsDomainAdmin,
  14581. kSecTrustSettingsDomainUser,
  14582. };
  14583. for (auto domain : domains) {
  14584. CFArrayRef certs = nullptr;
  14585. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14586. !certs) {
  14587. if (certs) CFRelease(certs);
  14588. continue;
  14589. }
  14590. auto count = CFArrayGetCount(certs);
  14591. for (CFIndex i = 0; i < count; i++) {
  14592. auto cert = reinterpret_cast<SecCertificateRef>(
  14593. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14594. CFDataRef der = SecCertificateCopyData(cert);
  14595. if (der) {
  14596. const unsigned char *data = CFDataGetBytePtr(der);
  14597. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14598. if (x509) {
  14599. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14600. X509_free(x509);
  14601. }
  14602. CFRelease(der);
  14603. }
  14604. }
  14605. CFRelease(certs);
  14606. }
  14607. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14608. #else
  14609. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14610. #endif
  14611. #else
  14612. // Other Unix: use default verify paths
  14613. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14614. #endif
  14615. }
  14616. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14617. const char *password) {
  14618. if (!ctx || !cert || !key) return false;
  14619. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14620. // Load certificate
  14621. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14622. if (!cert_bio) return false;
  14623. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14624. BIO_free(cert_bio);
  14625. if (!x509) return false;
  14626. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14627. X509_free(x509);
  14628. if (!cert_ok) return false;
  14629. // Load private key
  14630. auto key_bio = BIO_new_mem_buf(key, -1);
  14631. if (!key_bio) return false;
  14632. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14633. password ? const_cast<char *>(password)
  14634. : nullptr);
  14635. BIO_free(key_bio);
  14636. if (!pkey) return false;
  14637. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14638. EVP_PKEY_free(pkey);
  14639. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14640. }
  14641. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14642. const char *key_path, const char *password) {
  14643. if (!ctx || !cert_path || !key_path) return false;
  14644. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14645. if (password && password[0] != '\0') {
  14646. SSL_CTX_set_default_passwd_cb_userdata(
  14647. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14648. }
  14649. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14650. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14651. }
  14652. inline ctx_t create_server_context() {
  14653. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14654. if (ctx) {
  14655. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14656. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14657. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14658. }
  14659. return static_cast<ctx_t>(ctx);
  14660. }
  14661. inline void set_verify_client(ctx_t ctx, bool require) {
  14662. if (!ctx) return;
  14663. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14664. require
  14665. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14666. : SSL_VERIFY_NONE,
  14667. nullptr);
  14668. }
  14669. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14670. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14671. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14672. SSL *ssl = SSL_new(ssl_ctx);
  14673. if (!ssl) return nullptr;
  14674. // Disable auto-retry for proper non-blocking I/O handling
  14675. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14676. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14677. if (!bio) {
  14678. SSL_free(ssl);
  14679. return nullptr;
  14680. }
  14681. SSL_set_bio(ssl, bio, bio);
  14682. return static_cast<session_t>(ssl);
  14683. }
  14684. inline void free_session(session_t session) {
  14685. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14686. }
  14687. inline bool set_sni(session_t session, const char *hostname) {
  14688. if (!session || !hostname) return false;
  14689. auto ssl = static_cast<SSL *>(session);
  14690. // Set SNI (Server Name Indication) only - does not enable verification
  14691. #if defined(OPENSSL_IS_BORINGSSL)
  14692. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14693. #else
  14694. // Direct call instead of macro to suppress -Wold-style-cast warning
  14695. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14696. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14697. #endif
  14698. }
  14699. inline bool set_hostname(session_t session, const char *hostname) {
  14700. if (!session || !hostname) return false;
  14701. auto ssl = static_cast<SSL *>(session);
  14702. // Enable hostname verification
  14703. auto param = SSL_get0_param(ssl);
  14704. if (!param) return false;
  14705. if (detail::is_ip_address(hostname)) {
  14706. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14707. // certificate's IP SANs instead of its DNS names
  14708. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14709. } else {
  14710. // Set SNI (Server Name Indication)
  14711. if (!set_sni(session, hostname)) { return false; }
  14712. X509_VERIFY_PARAM_set_hostflags(param,
  14713. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14714. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14715. }
  14716. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14717. return true;
  14718. }
  14719. inline TlsError connect(session_t session) {
  14720. if (!session) { return TlsError(); }
  14721. auto ssl = static_cast<SSL *>(session);
  14722. auto ret = SSL_connect(ssl);
  14723. TlsError err;
  14724. if (ret == 1) {
  14725. err.code = ErrorCode::Success;
  14726. } else {
  14727. auto ssl_err = SSL_get_error(ssl, ret);
  14728. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14729. err.backend_code = ERR_get_error();
  14730. }
  14731. return err;
  14732. }
  14733. inline TlsError accept(session_t session) {
  14734. if (!session) { return TlsError(); }
  14735. auto ssl = static_cast<SSL *>(session);
  14736. auto ret = SSL_accept(ssl);
  14737. TlsError err;
  14738. if (ret == 1) {
  14739. err.code = ErrorCode::Success;
  14740. } else {
  14741. auto ssl_err = SSL_get_error(ssl, ret);
  14742. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14743. err.backend_code = ERR_get_error();
  14744. }
  14745. return err;
  14746. }
  14747. inline bool connect_nonblocking(session_t session, socket_t sock,
  14748. time_t timeout_sec, time_t timeout_usec,
  14749. TlsError *err) {
  14750. if (!session) {
  14751. if (err) { err->code = ErrorCode::Fatal; }
  14752. return false;
  14753. }
  14754. auto ssl = static_cast<SSL *>(session);
  14755. auto bio = SSL_get_rbio(ssl);
  14756. // Set non-blocking mode for handshake
  14757. detail::set_nonblocking(sock, true);
  14758. if (bio) { BIO_set_nbio(bio, 1); }
  14759. auto cleanup = detail::scope_exit([&]() {
  14760. // Restore blocking mode after handshake
  14761. if (bio) { BIO_set_nbio(bio, 0); }
  14762. detail::set_nonblocking(sock, false);
  14763. });
  14764. auto res = 0;
  14765. while ((res = SSL_connect(ssl)) != 1) {
  14766. auto ssl_err = SSL_get_error(ssl, res);
  14767. switch (ssl_err) {
  14768. case SSL_ERROR_WANT_READ:
  14769. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14770. continue;
  14771. }
  14772. break;
  14773. case SSL_ERROR_WANT_WRITE:
  14774. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14775. continue;
  14776. }
  14777. break;
  14778. default: break;
  14779. }
  14780. if (err) {
  14781. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14782. err->backend_code = ERR_get_error();
  14783. }
  14784. return false;
  14785. }
  14786. if (err) { err->code = ErrorCode::Success; }
  14787. return true;
  14788. }
  14789. inline bool accept_nonblocking(session_t session, socket_t sock,
  14790. time_t timeout_sec, time_t timeout_usec,
  14791. TlsError *err) {
  14792. if (!session) {
  14793. if (err) { err->code = ErrorCode::Fatal; }
  14794. return false;
  14795. }
  14796. auto ssl = static_cast<SSL *>(session);
  14797. auto bio = SSL_get_rbio(ssl);
  14798. // Set non-blocking mode for handshake
  14799. detail::set_nonblocking(sock, true);
  14800. if (bio) { BIO_set_nbio(bio, 1); }
  14801. auto cleanup = detail::scope_exit([&]() {
  14802. // Restore blocking mode after handshake
  14803. if (bio) { BIO_set_nbio(bio, 0); }
  14804. detail::set_nonblocking(sock, false);
  14805. });
  14806. auto res = 0;
  14807. while ((res = SSL_accept(ssl)) != 1) {
  14808. auto ssl_err = SSL_get_error(ssl, res);
  14809. switch (ssl_err) {
  14810. case SSL_ERROR_WANT_READ:
  14811. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14812. continue;
  14813. }
  14814. break;
  14815. case SSL_ERROR_WANT_WRITE:
  14816. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14817. continue;
  14818. }
  14819. break;
  14820. default: break;
  14821. }
  14822. if (err) {
  14823. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14824. err->backend_code = ERR_get_error();
  14825. }
  14826. return false;
  14827. }
  14828. if (err) { err->code = ErrorCode::Success; }
  14829. return true;
  14830. }
  14831. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14832. if (!session || !buf) {
  14833. err.code = ErrorCode::Fatal;
  14834. return -1;
  14835. }
  14836. auto ssl = static_cast<SSL *>(session);
  14837. constexpr auto max_len =
  14838. static_cast<size_t>((std::numeric_limits<int>::max)());
  14839. if (len > max_len) { len = max_len; }
  14840. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14841. if (ret > 0) {
  14842. err.code = ErrorCode::Success;
  14843. return ret;
  14844. }
  14845. auto ssl_err = SSL_get_error(ssl, ret);
  14846. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14847. if (err.code == ErrorCode::PeerClosed) {
  14848. return 0;
  14849. } // Gracefully handle the peer closed state.
  14850. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14851. return -1;
  14852. }
  14853. inline ssize_t write(session_t session, const void *buf, size_t len,
  14854. TlsError &err) {
  14855. if (!session || !buf) {
  14856. err.code = ErrorCode::Fatal;
  14857. return -1;
  14858. }
  14859. auto ssl = static_cast<SSL *>(session);
  14860. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14861. if (ret > 0) {
  14862. err.code = ErrorCode::Success;
  14863. return ret;
  14864. }
  14865. auto ssl_err = SSL_get_error(ssl, ret);
  14866. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14867. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14868. return -1;
  14869. }
  14870. inline int pending(const_session_t session) {
  14871. if (!session) return 0;
  14872. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14873. }
  14874. inline void shutdown(session_t session, bool graceful) {
  14875. if (!session) return;
  14876. auto ssl = static_cast<SSL *>(session);
  14877. if (graceful) {
  14878. // First call sends close_notify
  14879. if (SSL_shutdown(ssl) == 0) {
  14880. // Second call waits for peer's close_notify
  14881. SSL_shutdown(ssl);
  14882. }
  14883. }
  14884. }
  14885. inline bool is_peer_closed(session_t session, socket_t sock) {
  14886. if (!session) return true;
  14887. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14888. detail::set_nonblocking(sock, true);
  14889. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14890. auto ssl = static_cast<SSL *>(session);
  14891. char buf;
  14892. auto ret = SSL_peek(ssl, &buf, 1);
  14893. if (ret > 0) return false;
  14894. auto err = SSL_get_error(ssl, ret);
  14895. return err == SSL_ERROR_ZERO_RETURN;
  14896. }
  14897. inline cert_t get_peer_cert(const_session_t session) {
  14898. if (!session) return nullptr;
  14899. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14900. static_cast<SSL *>(const_cast<void *>(session))));
  14901. }
  14902. inline void free_cert(cert_t cert) {
  14903. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14904. }
  14905. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14906. if (!cert || !hostname) return false;
  14907. auto x509 = static_cast<X509 *>(cert);
  14908. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14909. if (detail::is_ip_address(hostname)) {
  14910. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14911. }
  14912. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14913. }
  14914. inline uint64_t hostname_mismatch_code() {
  14915. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14916. }
  14917. inline long get_verify_result(const_session_t session) {
  14918. if (!session) return X509_V_ERR_UNSPECIFIED;
  14919. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14920. }
  14921. inline std::string get_cert_subject_cn(cert_t cert) {
  14922. if (!cert) return "";
  14923. auto x509 = static_cast<X509 *>(cert);
  14924. auto subject_name = X509_get_subject_name(x509);
  14925. if (!subject_name) return "";
  14926. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14927. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14928. if (idx < 0) return "";
  14929. auto entry = X509_NAME_get_entry(subject_name, idx);
  14930. if (!entry) return "";
  14931. auto data = X509_NAME_ENTRY_get_data(entry);
  14932. if (!data) return "";
  14933. return std::string(
  14934. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14935. static_cast<size_t>(ASN1_STRING_length(data)));
  14936. }
  14937. inline std::string get_cert_issuer_name(cert_t cert) {
  14938. if (!cert) return "";
  14939. auto x509 = static_cast<X509 *>(cert);
  14940. auto issuer_name = X509_get_issuer_name(x509);
  14941. if (!issuer_name) return "";
  14942. char buf[256];
  14943. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14944. return std::string(buf);
  14945. }
  14946. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14947. sans.clear();
  14948. if (!cert) return false;
  14949. auto x509 = static_cast<X509 *>(cert);
  14950. auto names = static_cast<GENERAL_NAMES *>(
  14951. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14952. if (!names) return true; // No SANs is valid
  14953. auto count = sk_GENERAL_NAME_num(names);
  14954. for (decltype(count) i = 0; i < count; i++) {
  14955. auto gen = sk_GENERAL_NAME_value(names, i);
  14956. if (!gen) continue;
  14957. SanEntry entry;
  14958. switch (gen->type) {
  14959. case GEN_DNS:
  14960. entry.type = SanType::DNS;
  14961. if (gen->d.dNSName) {
  14962. entry.value = std::string(
  14963. reinterpret_cast<const char *>(
  14964. ASN1_STRING_get0_data(gen->d.dNSName)),
  14965. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14966. }
  14967. break;
  14968. case GEN_IPADD:
  14969. entry.type = SanType::IP;
  14970. if (gen->d.iPAddress) {
  14971. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14972. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14973. if (len == 4) {
  14974. // IPv4
  14975. char buf[INET_ADDRSTRLEN];
  14976. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14977. entry.value = buf;
  14978. } else if (len == 16) {
  14979. // IPv6
  14980. char buf[INET6_ADDRSTRLEN];
  14981. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14982. entry.value = buf;
  14983. }
  14984. }
  14985. break;
  14986. case GEN_EMAIL:
  14987. entry.type = SanType::EMAIL;
  14988. if (gen->d.rfc822Name) {
  14989. entry.value = std::string(
  14990. reinterpret_cast<const char *>(
  14991. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14992. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14993. }
  14994. break;
  14995. case GEN_URI:
  14996. entry.type = SanType::URI;
  14997. if (gen->d.uniformResourceIdentifier) {
  14998. entry.value = std::string(
  14999. reinterpret_cast<const char *>(
  15000. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  15001. static_cast<size_t>(
  15002. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  15003. }
  15004. break;
  15005. default: entry.type = SanType::OTHER; break;
  15006. }
  15007. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15008. }
  15009. GENERAL_NAMES_free(names);
  15010. return true;
  15011. }
  15012. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15013. time_t &not_after) {
  15014. if (!cert) return false;
  15015. auto x509 = static_cast<X509 *>(cert);
  15016. auto nb = X509_get0_notBefore(x509);
  15017. auto na = X509_get0_notAfter(x509);
  15018. if (!nb || !na) return false;
  15019. ASN1_TIME *epoch = ASN1_TIME_new();
  15020. if (!epoch) return false;
  15021. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  15022. if (!ASN1_TIME_set(epoch, 0)) return false;
  15023. int pday, psec;
  15024. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  15025. not_before = 86400 * (time_t)pday + psec;
  15026. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  15027. not_after = 86400 * (time_t)pday + psec;
  15028. return true;
  15029. }
  15030. inline std::string get_cert_serial(cert_t cert) {
  15031. if (!cert) return "";
  15032. auto x509 = static_cast<X509 *>(cert);
  15033. auto serial = X509_get_serialNumber(x509);
  15034. if (!serial) return "";
  15035. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  15036. if (!bn) return "";
  15037. auto hex = BN_bn2hex(bn);
  15038. BN_free(bn);
  15039. if (!hex) return "";
  15040. std::string result(hex);
  15041. OPENSSL_free(hex);
  15042. return result;
  15043. }
  15044. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15045. if (!cert) return false;
  15046. auto x509 = static_cast<X509 *>(cert);
  15047. auto len = i2d_X509(x509, nullptr);
  15048. if (len < 0) return false;
  15049. der.resize(static_cast<size_t>(len));
  15050. auto p = der.data();
  15051. i2d_X509(x509, &p);
  15052. return true;
  15053. }
  15054. inline const char *get_sni(const_session_t session) {
  15055. if (!session) return nullptr;
  15056. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15057. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15058. }
  15059. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  15060. inline uint64_t get_error() { return ERR_get_error(); }
  15061. inline std::string error_string(uint64_t code) {
  15062. char buf[256];
  15063. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  15064. return std::string(buf);
  15065. }
  15066. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15067. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  15068. if (!mem) { return nullptr; }
  15069. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  15070. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  15071. if (!inf) { return nullptr; }
  15072. auto store = X509_STORE_new();
  15073. if (store) {
  15074. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  15075. auto itmp = sk_X509_INFO_value(inf, i);
  15076. if (!itmp) { continue; }
  15077. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  15078. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  15079. }
  15080. }
  15081. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  15082. return static_cast<ca_store_t>(store);
  15083. }
  15084. inline void free_ca_store(ca_store_t store) {
  15085. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15086. }
  15087. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15088. if (!ctx || !store) { return false; }
  15089. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15090. auto x509_store = static_cast<X509_STORE *>(store);
  15091. // Check if same store is already set
  15092. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15093. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15094. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15095. return true;
  15096. }
  15097. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15098. certs.clear();
  15099. if (!ctx) { return 0; }
  15100. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15101. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15102. if (!store) { return 0; }
  15103. auto objs = impl::get_store_objects(store);
  15104. if (!objs) { return 0; }
  15105. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15106. auto count = sk_X509_OBJECT_num(objs);
  15107. for (decltype(count) i = 0; i < count; i++) {
  15108. auto obj = sk_X509_OBJECT_value(objs, i);
  15109. if (!obj) { continue; }
  15110. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15111. auto x509 = X509_OBJECT_get0_X509(obj);
  15112. if (x509) {
  15113. // Increment reference count so caller can free it
  15114. X509_up_ref(x509);
  15115. certs.push_back(static_cast<cert_t>(x509));
  15116. }
  15117. }
  15118. }
  15119. return certs.size();
  15120. }
  15121. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15122. std::vector<std::string> names;
  15123. if (!ctx) { return names; }
  15124. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15125. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15126. if (!store) { return names; }
  15127. auto objs = impl::get_store_objects(store);
  15128. if (!objs) { return names; }
  15129. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15130. auto count = sk_X509_OBJECT_num(objs);
  15131. for (decltype(count) i = 0; i < count; i++) {
  15132. auto obj = sk_X509_OBJECT_value(objs, i);
  15133. if (!obj) { continue; }
  15134. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15135. auto x509 = X509_OBJECT_get0_X509(obj);
  15136. if (x509) {
  15137. auto subject = X509_get_subject_name(x509);
  15138. if (subject) {
  15139. char buf[512];
  15140. X509_NAME_oneline(subject, buf, sizeof(buf));
  15141. names.push_back(buf);
  15142. }
  15143. }
  15144. }
  15145. }
  15146. return names;
  15147. }
  15148. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15149. const char *key_pem, const char *password) {
  15150. if (!ctx || !cert_pem || !key_pem) { return false; }
  15151. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15152. // Load certificate from PEM
  15153. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15154. if (!cert_bio) { return false; }
  15155. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15156. BIO_free(cert_bio);
  15157. if (!cert) { return false; }
  15158. // Load private key from PEM
  15159. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15160. if (!key_bio) {
  15161. X509_free(cert);
  15162. return false;
  15163. }
  15164. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15165. password ? const_cast<char *>(password)
  15166. : nullptr);
  15167. BIO_free(key_bio);
  15168. if (!key) {
  15169. X509_free(cert);
  15170. return false;
  15171. }
  15172. // Update certificate and key
  15173. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15174. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15175. X509_free(cert);
  15176. EVP_PKEY_free(key);
  15177. return ret;
  15178. }
  15179. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15180. if (!ctx || !ca_pem) { return false; }
  15181. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15182. // Create new X509_STORE from PEM
  15183. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15184. if (!store) { return false; }
  15185. // SSL_CTX_set_cert_store takes ownership
  15186. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15187. // Set client CA list for client certificate request
  15188. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15189. if (ca_list) {
  15190. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15191. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15192. }
  15193. return true;
  15194. }
  15195. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15196. if (!ctx) { return false; }
  15197. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15198. impl::get_verify_callback() = std::move(callback);
  15199. if (impl::get_verify_callback()) {
  15200. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15201. } else {
  15202. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15203. }
  15204. return true;
  15205. }
  15206. inline long get_verify_error(const_session_t session) {
  15207. if (!session) { return -1; }
  15208. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15209. return SSL_get_verify_result(ssl);
  15210. }
  15211. inline std::string verify_error_string(long error_code) {
  15212. if (error_code == X509_V_OK) { return ""; }
  15213. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15214. return str ? str : "unknown error";
  15215. }
  15216. } // namespace tls
  15217. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15218. /*
  15219. * Group 9: TLS abstraction layer - Mbed TLS backend
  15220. */
  15221. /*
  15222. * Mbed TLS Backend Implementation
  15223. */
  15224. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15225. namespace tls {
  15226. namespace impl {
  15227. // Mbed TLS session wrapper
  15228. struct MbedTlsSession {
  15229. mbedtls_ssl_context ssl;
  15230. socket_t sock = INVALID_SOCKET;
  15231. std::string hostname; // For client: set via set_sni
  15232. std::string sni_hostname; // For server: received from client via SNI callback
  15233. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15234. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15235. MbedTlsSession(const MbedTlsSession &) = delete;
  15236. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15237. };
  15238. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15239. // queue)
  15240. inline int &mbedtls_last_error() {
  15241. static thread_local int err = 0;
  15242. return err;
  15243. }
  15244. // Helper to map Mbed TLS error to ErrorCode
  15245. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15246. if (ret == 0) { return ErrorCode::Success; }
  15247. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15248. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15249. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15250. return ErrorCode::PeerClosed;
  15251. }
  15252. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15253. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15254. out_errno = errno;
  15255. return ErrorCode::SyscallError;
  15256. }
  15257. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15258. return ErrorCode::CertVerifyFailed;
  15259. }
  15260. return ErrorCode::Fatal;
  15261. }
  15262. // BIO-like send callback for Mbed TLS
  15263. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15264. size_t len) {
  15265. auto sock = *static_cast<socket_t *>(ctx);
  15266. #ifdef _WIN32
  15267. auto ret =
  15268. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15269. if (ret == SOCKET_ERROR) {
  15270. int err = WSAGetLastError();
  15271. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15272. return MBEDTLS_ERR_NET_SEND_FAILED;
  15273. }
  15274. #else
  15275. auto ret = send(sock, buf, len, 0);
  15276. if (ret < 0) {
  15277. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15278. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15279. }
  15280. return MBEDTLS_ERR_NET_SEND_FAILED;
  15281. }
  15282. #endif
  15283. return static_cast<int>(ret);
  15284. }
  15285. // BIO-like recv callback for Mbed TLS
  15286. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15287. auto sock = *static_cast<socket_t *>(ctx);
  15288. #ifdef _WIN32
  15289. auto ret =
  15290. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15291. if (ret == SOCKET_ERROR) {
  15292. int err = WSAGetLastError();
  15293. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15294. return MBEDTLS_ERR_NET_RECV_FAILED;
  15295. }
  15296. #else
  15297. auto ret = recv(sock, buf, len, 0);
  15298. if (ret < 0) {
  15299. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15300. return MBEDTLS_ERR_SSL_WANT_READ;
  15301. }
  15302. return MBEDTLS_ERR_NET_RECV_FAILED;
  15303. }
  15304. #endif
  15305. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15306. return static_cast<int>(ret);
  15307. }
  15308. // MbedTlsContext constructor/destructor implementations
  15309. inline MbedTlsContext::MbedTlsContext() {
  15310. mbedtls_ssl_config_init(&conf);
  15311. mbedtls_entropy_init(&entropy);
  15312. mbedtls_ctr_drbg_init(&ctr_drbg);
  15313. mbedtls_x509_crt_init(&ca_chain);
  15314. mbedtls_x509_crt_init(&own_cert);
  15315. mbedtls_pk_init(&own_key);
  15316. }
  15317. inline MbedTlsContext::~MbedTlsContext() {
  15318. mbedtls_pk_free(&own_key);
  15319. mbedtls_x509_crt_free(&own_cert);
  15320. mbedtls_x509_crt_free(&ca_chain);
  15321. mbedtls_ctr_drbg_free(&ctr_drbg);
  15322. mbedtls_entropy_free(&entropy);
  15323. mbedtls_ssl_config_free(&conf);
  15324. }
  15325. // Thread-local storage for SNI captured during handshake
  15326. // This is needed because the SNI callback doesn't have a way to pass
  15327. // session-specific data before the session is fully set up
  15328. inline std::string &mbedpending_sni() {
  15329. static thread_local std::string sni;
  15330. return sni;
  15331. }
  15332. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15333. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15334. const unsigned char *name, size_t name_len) {
  15335. (void)p_ctx;
  15336. (void)ssl;
  15337. // Store SNI name in thread-local storage
  15338. // It will be retrieved and stored in the session after handshake
  15339. if (name && name_len > 0) {
  15340. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15341. } else {
  15342. mbedpending_sni().clear();
  15343. }
  15344. return 0; // Accept any SNI
  15345. }
  15346. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15347. int cert_depth, uint32_t *flags);
  15348. // MbedTLS verify callback wrapper
  15349. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15350. int cert_depth, uint32_t *flags) {
  15351. auto &callback = get_verify_callback();
  15352. if (!callback) { return 0; } // Continue with default verification
  15353. // data points to the MbedTlsSession
  15354. auto *session = static_cast<MbedTlsSession *>(data);
  15355. // Build context
  15356. VerifyContext verify_ctx;
  15357. verify_ctx.session = static_cast<session_t>(session);
  15358. verify_ctx.cert = static_cast<cert_t>(crt);
  15359. verify_ctx.depth = cert_depth;
  15360. verify_ctx.preverify_ok = (*flags == 0);
  15361. verify_ctx.error_code = static_cast<long>(*flags);
  15362. // Convert Mbed TLS flags to error string
  15363. static thread_local char error_buf[256];
  15364. if (*flags != 0) {
  15365. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15366. verify_ctx.error_string = error_buf;
  15367. } else {
  15368. verify_ctx.error_string = nullptr;
  15369. }
  15370. bool accepted = callback(verify_ctx);
  15371. if (accepted) {
  15372. *flags = 0; // Clear all error flags
  15373. return 0;
  15374. }
  15375. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15376. }
  15377. } // namespace impl
  15378. inline ctx_t create_client_context() {
  15379. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15380. if (!ctx) { return nullptr; }
  15381. ctx->is_server = false;
  15382. // Seed the random number generator
  15383. const char *pers = "httplib_client";
  15384. int ret = mbedtls_ctr_drbg_seed(
  15385. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15386. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15387. if (ret != 0) {
  15388. impl::mbedtls_last_error() = ret;
  15389. delete ctx;
  15390. return nullptr;
  15391. }
  15392. // Set up SSL config for client
  15393. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15394. MBEDTLS_SSL_TRANSPORT_STREAM,
  15395. MBEDTLS_SSL_PRESET_DEFAULT);
  15396. if (ret != 0) {
  15397. impl::mbedtls_last_error() = ret;
  15398. delete ctx;
  15399. return nullptr;
  15400. }
  15401. // Set random number generator
  15402. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15403. // Default: verify peer certificate
  15404. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15405. // Set minimum TLS version to 1.2
  15406. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15407. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15408. #else
  15409. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15410. MBEDTLS_SSL_MINOR_VERSION_3);
  15411. #endif
  15412. return static_cast<ctx_t>(ctx);
  15413. }
  15414. inline ctx_t create_server_context() {
  15415. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15416. if (!ctx) { return nullptr; }
  15417. ctx->is_server = true;
  15418. // Seed the random number generator
  15419. const char *pers = "httplib_server";
  15420. int ret = mbedtls_ctr_drbg_seed(
  15421. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15422. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15423. if (ret != 0) {
  15424. impl::mbedtls_last_error() = ret;
  15425. delete ctx;
  15426. return nullptr;
  15427. }
  15428. // Set up SSL config for server
  15429. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15430. MBEDTLS_SSL_TRANSPORT_STREAM,
  15431. MBEDTLS_SSL_PRESET_DEFAULT);
  15432. if (ret != 0) {
  15433. impl::mbedtls_last_error() = ret;
  15434. delete ctx;
  15435. return nullptr;
  15436. }
  15437. // Set random number generator
  15438. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15439. // Default: don't verify client
  15440. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15441. // Set minimum TLS version to 1.2
  15442. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15443. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15444. #else
  15445. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15446. MBEDTLS_SSL_MINOR_VERSION_3);
  15447. #endif
  15448. // Set SNI callback to capture client's SNI hostname
  15449. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15450. return static_cast<ctx_t>(ctx);
  15451. }
  15452. inline void free_context(ctx_t ctx) {
  15453. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15454. }
  15455. inline bool set_min_version(ctx_t ctx, Version version) {
  15456. if (!ctx) { return false; }
  15457. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15458. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15459. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15460. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15461. if (version >= Version::TLS1_3) {
  15462. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15463. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15464. #endif
  15465. }
  15466. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15467. #else
  15468. // Mbed TLS 2.x uses major/minor version numbers
  15469. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15470. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15471. if (version >= Version::TLS1_3) {
  15472. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15473. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15474. #else
  15475. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15476. #endif
  15477. }
  15478. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15479. #endif
  15480. return true;
  15481. }
  15482. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15483. if (!ctx || !pem) { return false; }
  15484. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15485. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15486. // Add null terminator if not present
  15487. std::string pem_str(pem, len);
  15488. int ret = mbedtls_x509_crt_parse(
  15489. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15490. pem_str.size() + 1);
  15491. if (ret != 0) {
  15492. impl::mbedtls_last_error() = ret;
  15493. return false;
  15494. }
  15495. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15496. return true;
  15497. }
  15498. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15499. if (!ctx || !file_path) { return false; }
  15500. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15501. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15502. if (ret != 0) {
  15503. impl::mbedtls_last_error() = ret;
  15504. return false;
  15505. }
  15506. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15507. return true;
  15508. }
  15509. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15510. if (!ctx || !dir_path) { return false; }
  15511. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15512. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15513. if (ret < 0) { // Returns number of certs on success, negative on error
  15514. impl::mbedtls_last_error() = ret;
  15515. return false;
  15516. }
  15517. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15518. return true;
  15519. }
  15520. inline bool load_system_certs(ctx_t ctx) {
  15521. if (!ctx) { return false; }
  15522. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15523. bool loaded = false;
  15524. #ifdef _WIN32
  15525. loaded = impl::enumerate_windows_system_certs(
  15526. [&](const unsigned char *data, size_t len) {
  15527. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15528. });
  15529. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15530. loaded = impl::enumerate_macos_keychain_certs(
  15531. [&](const unsigned char *data, size_t len) {
  15532. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15533. });
  15534. #else
  15535. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15536. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15537. loaded = true;
  15538. break;
  15539. }
  15540. }
  15541. if (!loaded) {
  15542. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15543. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15544. loaded = true;
  15545. break;
  15546. }
  15547. }
  15548. }
  15549. #endif
  15550. if (loaded) {
  15551. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15552. }
  15553. return loaded;
  15554. }
  15555. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15556. const char *password) {
  15557. if (!ctx || !cert || !key) { return false; }
  15558. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15559. // Parse certificate
  15560. std::string cert_str(cert);
  15561. int ret = mbedtls_x509_crt_parse(
  15562. &mctx->own_cert,
  15563. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15564. cert_str.size() + 1);
  15565. if (ret != 0) {
  15566. impl::mbedtls_last_error() = ret;
  15567. return false;
  15568. }
  15569. // Parse private key
  15570. std::string key_str(key);
  15571. const unsigned char *pwd =
  15572. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15573. size_t pwd_len = password ? strlen(password) : 0;
  15574. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15575. ret = mbedtls_pk_parse_key(
  15576. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15577. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15578. &mctx->ctr_drbg);
  15579. #else
  15580. ret = mbedtls_pk_parse_key(
  15581. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15582. key_str.size() + 1, pwd, pwd_len);
  15583. #endif
  15584. if (ret != 0) {
  15585. impl::mbedtls_last_error() = ret;
  15586. return false;
  15587. }
  15588. // Verify that the certificate and private key match
  15589. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15590. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15591. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15592. #else
  15593. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15594. #endif
  15595. if (ret != 0) {
  15596. impl::mbedtls_last_error() = ret;
  15597. return false;
  15598. }
  15599. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15600. if (ret != 0) {
  15601. impl::mbedtls_last_error() = ret;
  15602. return false;
  15603. }
  15604. return true;
  15605. }
  15606. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15607. const char *key_path, const char *password) {
  15608. if (!ctx || !cert_path || !key_path) { return false; }
  15609. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15610. // Parse certificate file
  15611. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15612. if (ret != 0) {
  15613. impl::mbedtls_last_error() = ret;
  15614. return false;
  15615. }
  15616. // Parse private key file
  15617. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15618. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15619. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15620. #else
  15621. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15622. #endif
  15623. if (ret != 0) {
  15624. impl::mbedtls_last_error() = ret;
  15625. return false;
  15626. }
  15627. // Verify that the certificate and private key match
  15628. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15629. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15630. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15631. #else
  15632. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15633. #endif
  15634. if (ret != 0) {
  15635. impl::mbedtls_last_error() = ret;
  15636. return false;
  15637. }
  15638. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15639. if (ret != 0) {
  15640. impl::mbedtls_last_error() = ret;
  15641. return false;
  15642. }
  15643. return true;
  15644. }
  15645. inline void set_verify_client(ctx_t ctx, bool require) {
  15646. if (!ctx) { return; }
  15647. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15648. mctx->verify_client = require;
  15649. if (require) {
  15650. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15651. } else {
  15652. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15653. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15654. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15655. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15656. : MBEDTLS_SSL_VERIFY_NONE);
  15657. }
  15658. }
  15659. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15660. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15661. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15662. auto session = new (std::nothrow) impl::MbedTlsSession();
  15663. if (!session) { return nullptr; }
  15664. session->sock = sock;
  15665. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15666. if (ret != 0) {
  15667. impl::mbedtls_last_error() = ret;
  15668. delete session;
  15669. return nullptr;
  15670. }
  15671. // Explicitly opt out of in-handshake hostname verification by default;
  15672. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15673. // fails outright when no hostname was set. set_sni() installs the real
  15674. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15675. // caller verifies the certificate identity post-handshake via
  15676. // verify_hostname().
  15677. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15678. // Set BIO callbacks
  15679. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15680. impl::mbedtls_net_recv_cb, nullptr);
  15681. // Set per-session verify callback with session pointer if callback is
  15682. // registered
  15683. if (mctx->has_verify_callback) {
  15684. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15685. session);
  15686. }
  15687. return static_cast<session_t>(session);
  15688. }
  15689. inline void free_session(session_t session) {
  15690. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15691. }
  15692. inline bool set_sni(session_t session, const char *hostname) {
  15693. if (!session || !hostname) { return false; }
  15694. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15695. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15696. if (ret != 0) {
  15697. impl::mbedtls_last_error() = ret;
  15698. return false;
  15699. }
  15700. msession->hostname = hostname;
  15701. return true;
  15702. }
  15703. inline bool set_hostname(session_t session, const char *hostname) {
  15704. // In Mbed TLS, set_hostname also sets up hostname verification
  15705. return set_sni(session, hostname);
  15706. }
  15707. inline TlsError connect(session_t session) {
  15708. TlsError err;
  15709. if (!session) {
  15710. err.code = ErrorCode::Fatal;
  15711. return err;
  15712. }
  15713. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15714. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15715. if (ret == 0) {
  15716. err.code = ErrorCode::Success;
  15717. } else {
  15718. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15719. err.backend_code = static_cast<uint64_t>(-ret);
  15720. impl::mbedtls_last_error() = ret;
  15721. }
  15722. return err;
  15723. }
  15724. inline TlsError accept(session_t session) {
  15725. // Same as connect for Mbed TLS - handshake works for both client and server
  15726. auto result = connect(session);
  15727. // After successful handshake, capture SNI from thread-local storage
  15728. if (result.code == ErrorCode::Success && session) {
  15729. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15730. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15731. impl::mbedpending_sni().clear();
  15732. }
  15733. return result;
  15734. }
  15735. inline bool connect_nonblocking(session_t session, socket_t sock,
  15736. time_t timeout_sec, time_t timeout_usec,
  15737. TlsError *err) {
  15738. if (!session) {
  15739. if (err) { err->code = ErrorCode::Fatal; }
  15740. return false;
  15741. }
  15742. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15743. // Set socket to non-blocking mode
  15744. detail::set_nonblocking(sock, true);
  15745. auto cleanup =
  15746. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15747. int ret;
  15748. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15749. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15750. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15751. continue;
  15752. }
  15753. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15754. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15755. continue;
  15756. }
  15757. }
  15758. // TlsError or timeout
  15759. if (err) {
  15760. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15761. err->backend_code = static_cast<uint64_t>(-ret);
  15762. }
  15763. impl::mbedtls_last_error() = ret;
  15764. return false;
  15765. }
  15766. if (err) { err->code = ErrorCode::Success; }
  15767. return true;
  15768. }
  15769. inline bool accept_nonblocking(session_t session, socket_t sock,
  15770. time_t timeout_sec, time_t timeout_usec,
  15771. TlsError *err) {
  15772. // Same implementation as connect for Mbed TLS
  15773. bool result =
  15774. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15775. // After successful handshake, capture SNI from thread-local storage
  15776. if (result && session) {
  15777. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15778. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15779. impl::mbedpending_sni().clear();
  15780. }
  15781. return result;
  15782. }
  15783. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15784. if (!session || !buf) {
  15785. err.code = ErrorCode::Fatal;
  15786. return -1;
  15787. }
  15788. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15789. int ret =
  15790. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15791. if (ret > 0) {
  15792. err.code = ErrorCode::Success;
  15793. return static_cast<ssize_t>(ret);
  15794. }
  15795. if (ret == 0) {
  15796. err.code = ErrorCode::PeerClosed;
  15797. return 0;
  15798. }
  15799. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15800. err.backend_code = static_cast<uint64_t>(-ret);
  15801. impl::mbedtls_last_error() = ret;
  15802. // mbedTLS signals a clean close_notify via a negative error code rather
  15803. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15804. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15805. return -1;
  15806. }
  15807. inline ssize_t write(session_t session, const void *buf, size_t len,
  15808. TlsError &err) {
  15809. if (!session || !buf) {
  15810. err.code = ErrorCode::Fatal;
  15811. return -1;
  15812. }
  15813. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15814. int ret = mbedtls_ssl_write(&msession->ssl,
  15815. static_cast<const unsigned char *>(buf), len);
  15816. if (ret > 0) {
  15817. err.code = ErrorCode::Success;
  15818. return static_cast<ssize_t>(ret);
  15819. }
  15820. if (ret == 0) {
  15821. err.code = ErrorCode::PeerClosed;
  15822. return 0;
  15823. }
  15824. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15825. err.backend_code = static_cast<uint64_t>(-ret);
  15826. impl::mbedtls_last_error() = ret;
  15827. return -1;
  15828. }
  15829. inline int pending(const_session_t session) {
  15830. if (!session) { return 0; }
  15831. auto msession =
  15832. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15833. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15834. }
  15835. inline void shutdown(session_t session, bool graceful) {
  15836. if (!session) { return; }
  15837. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15838. if (graceful) {
  15839. // Try to send close_notify, but don't block forever
  15840. int ret;
  15841. int attempts = 0;
  15842. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15843. attempts < 3) {
  15844. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15845. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15846. break;
  15847. }
  15848. attempts++;
  15849. }
  15850. }
  15851. }
  15852. inline bool is_peer_closed(session_t session, socket_t sock) {
  15853. if (!session || sock == INVALID_SOCKET) { return true; }
  15854. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15855. // Check if there's already decrypted data available in the TLS buffer
  15856. // If so, the connection is definitely alive
  15857. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15858. // Set socket to non-blocking to avoid blocking on read
  15859. detail::set_nonblocking(sock, true);
  15860. auto cleanup =
  15861. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15862. // Try a 1-byte read to check connection status
  15863. // Note: This will consume the byte if data is available, but for the
  15864. // purpose of checking if peer is closed, this should be acceptable
  15865. // since we're only called when we expect the connection might be closing
  15866. unsigned char buf;
  15867. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15868. // If we got data or WANT_READ (would block), connection is alive
  15869. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15870. // If we get a peer close notify or a connection reset, the peer is closed
  15871. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15872. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15873. }
  15874. inline cert_t get_peer_cert(const_session_t session) {
  15875. if (!session) { return nullptr; }
  15876. auto msession =
  15877. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15878. // Mbed TLS returns a pointer to the internal peer cert chain.
  15879. // WARNING: This pointer is only valid while the session is active.
  15880. // Do not use the certificate after calling free_session().
  15881. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15882. return const_cast<mbedtls_x509_crt *>(cert);
  15883. }
  15884. inline void free_cert(cert_t cert) {
  15885. // Mbed TLS: peer certificate is owned by the SSL context.
  15886. // No-op here, but callers should still call this for cross-backend
  15887. // portability.
  15888. (void)cert;
  15889. }
  15890. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15891. if (!cert || !hostname) { return false; }
  15892. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15893. std::string host_str(hostname);
  15894. // Check if hostname is an IP address (IPv4 or IPv6)
  15895. unsigned char ip_bytes[16];
  15896. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15897. auto is_ip = ip_len > 0;
  15898. // Check Subject Alternative Names (SAN)
  15899. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15900. // - DNS names: raw string bytes
  15901. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15902. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15903. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15904. const unsigned char *p = san->buf.p;
  15905. size_t len = san->buf.len;
  15906. if (is_ip) {
  15907. // For an IP host, only a matching iPAddress SAN of the same family
  15908. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15909. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15910. } else {
  15911. // Check if this SAN is a DNS name (printable ASCII string)
  15912. bool is_dns = len > 0;
  15913. for (size_t i = 0; i < len && is_dns; i++) {
  15914. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15915. }
  15916. if (is_dns) {
  15917. std::string san_name(reinterpret_cast<const char *>(p), len);
  15918. if (detail::match_hostname(san_name, host_str)) { return true; }
  15919. }
  15920. }
  15921. san = san->next;
  15922. }
  15923. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15924. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15925. // the OpenSSL backend's X509_check_ip behaves the same way).
  15926. if (!is_ip) {
  15927. char cn[256];
  15928. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15929. if (ret > 0) {
  15930. std::string cn_str(cn);
  15931. // Look for "CN=" in the DN string
  15932. size_t cn_pos = cn_str.find("CN=");
  15933. if (cn_pos != std::string::npos) {
  15934. size_t start = cn_pos + 3;
  15935. size_t end = cn_str.find(',', start);
  15936. std::string cn_value =
  15937. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15938. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15939. }
  15940. }
  15941. }
  15942. return false;
  15943. }
  15944. inline uint64_t hostname_mismatch_code() {
  15945. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15946. }
  15947. inline long get_verify_result(const_session_t session) {
  15948. if (!session) { return -1; }
  15949. auto msession =
  15950. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15951. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15952. // Return 0 (X509_V_OK equivalent) if verification passed
  15953. return flags == 0 ? 0 : static_cast<long>(flags);
  15954. }
  15955. inline std::string get_cert_subject_cn(cert_t cert) {
  15956. if (!cert) return "";
  15957. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15958. // Find the CN in the subject
  15959. const mbedtls_x509_name *name = &x509->subject;
  15960. while (name != nullptr) {
  15961. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15962. return std::string(reinterpret_cast<const char *>(name->val.p),
  15963. name->val.len);
  15964. }
  15965. name = name->next;
  15966. }
  15967. return "";
  15968. }
  15969. inline std::string get_cert_issuer_name(cert_t cert) {
  15970. if (!cert) return "";
  15971. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15972. // Build a human-readable issuer name string
  15973. char buf[512];
  15974. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15975. if (ret < 0) return "";
  15976. return std::string(buf);
  15977. }
  15978. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15979. sans.clear();
  15980. if (!cert) return false;
  15981. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15982. // Parse the Subject Alternative Name extension
  15983. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15984. while (cur != nullptr) {
  15985. if (cur->buf.len > 0) {
  15986. // Mbed TLS stores SAN as ASN.1 sequences
  15987. // The tag byte indicates the type
  15988. const unsigned char *p = cur->buf.p;
  15989. size_t len = cur->buf.len;
  15990. // First byte is the tag
  15991. unsigned char tag = *p;
  15992. p++;
  15993. len--;
  15994. // Parse length (simple single-byte length assumed)
  15995. if (len > 0 && *p < 0x80) {
  15996. size_t value_len = *p;
  15997. p++;
  15998. len--;
  15999. if (value_len <= len) {
  16000. SanEntry entry;
  16001. // ASN.1 context tags for GeneralName
  16002. switch (tag & 0x1F) {
  16003. case 2: // dNSName
  16004. entry.type = SanType::DNS;
  16005. entry.value =
  16006. std::string(reinterpret_cast<const char *>(p), value_len);
  16007. break;
  16008. case 7: // iPAddress
  16009. entry.type = SanType::IP;
  16010. if (value_len == 4) {
  16011. // IPv4
  16012. char buf[16];
  16013. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  16014. entry.value = buf;
  16015. } else if (value_len == 16) {
  16016. // IPv6
  16017. char buf[64];
  16018. snprintf(buf, sizeof(buf),
  16019. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16020. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16021. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  16022. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  16023. entry.value = buf;
  16024. }
  16025. break;
  16026. case 1: // rfc822Name (email)
  16027. entry.type = SanType::EMAIL;
  16028. entry.value =
  16029. std::string(reinterpret_cast<const char *>(p), value_len);
  16030. break;
  16031. case 6: // uniformResourceIdentifier
  16032. entry.type = SanType::URI;
  16033. entry.value =
  16034. std::string(reinterpret_cast<const char *>(p), value_len);
  16035. break;
  16036. default: entry.type = SanType::OTHER; break;
  16037. }
  16038. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16039. }
  16040. }
  16041. }
  16042. cur = cur->next;
  16043. }
  16044. return true;
  16045. }
  16046. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16047. time_t &not_after) {
  16048. if (!cert) return false;
  16049. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16050. // Convert mbedtls_x509_time to time_t
  16051. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  16052. struct tm tm_time = {};
  16053. tm_time.tm_year = t.year - 1900;
  16054. tm_time.tm_mon = t.mon - 1;
  16055. tm_time.tm_mday = t.day;
  16056. tm_time.tm_hour = t.hour;
  16057. tm_time.tm_min = t.min;
  16058. tm_time.tm_sec = t.sec;
  16059. #ifdef _WIN32
  16060. return _mkgmtime(&tm_time);
  16061. #else
  16062. return timegm(&tm_time);
  16063. #endif
  16064. };
  16065. not_before = to_time_t(x509->valid_from);
  16066. not_after = to_time_t(x509->valid_to);
  16067. return true;
  16068. }
  16069. inline std::string get_cert_serial(cert_t cert) {
  16070. if (!cert) return "";
  16071. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16072. // Convert serial number to hex string
  16073. std::string result;
  16074. result.reserve(x509->serial.len * 2);
  16075. for (size_t i = 0; i < x509->serial.len; i++) {
  16076. char hex[3];
  16077. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  16078. result += hex;
  16079. }
  16080. return result;
  16081. }
  16082. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16083. if (!cert) return false;
  16084. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16085. if (!crt->raw.p || crt->raw.len == 0) return false;
  16086. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16087. return true;
  16088. }
  16089. inline const char *get_sni(const_session_t session) {
  16090. if (!session) return nullptr;
  16091. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16092. // For server: return SNI received from client during handshake
  16093. if (!msession->sni_hostname.empty()) {
  16094. return msession->sni_hostname.c_str();
  16095. }
  16096. // For client: return the hostname set via set_sni
  16097. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16098. return nullptr;
  16099. }
  16100. inline uint64_t peek_error() {
  16101. // Mbed TLS doesn't have an error queue, return the last error
  16102. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16103. }
  16104. inline uint64_t get_error() {
  16105. // Mbed TLS doesn't have an error queue, return and clear the last error
  16106. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16107. impl::mbedtls_last_error() = 0;
  16108. return err;
  16109. }
  16110. inline std::string error_string(uint64_t code) {
  16111. char buf[256];
  16112. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16113. return std::string(buf);
  16114. }
  16115. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16116. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16117. if (!ca_chain) { return nullptr; }
  16118. mbedtls_x509_crt_init(ca_chain);
  16119. // mbedtls_x509_crt_parse expects null-terminated PEM
  16120. int ret = mbedtls_x509_crt_parse(ca_chain,
  16121. reinterpret_cast<const unsigned char *>(pem),
  16122. len + 1); // +1 for null terminator
  16123. if (ret != 0) {
  16124. // Try without +1 in case PEM is already null-terminated
  16125. ret = mbedtls_x509_crt_parse(
  16126. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16127. if (ret != 0) {
  16128. mbedtls_x509_crt_free(ca_chain);
  16129. delete ca_chain;
  16130. return nullptr;
  16131. }
  16132. }
  16133. return static_cast<ca_store_t>(ca_chain);
  16134. }
  16135. inline void free_ca_store(ca_store_t store) {
  16136. if (store) {
  16137. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16138. mbedtls_x509_crt_free(ca_chain);
  16139. delete ca_chain;
  16140. }
  16141. }
  16142. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16143. if (!ctx || !store) { return false; }
  16144. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16145. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16146. // Free existing CA chain
  16147. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16148. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16149. // Copy the CA chain (deep copy)
  16150. // Parse from the raw data of the source cert
  16151. mbedtls_x509_crt *src = ca_chain;
  16152. while (src != nullptr) {
  16153. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16154. src->raw.len);
  16155. if (ret != 0) {
  16156. free_ca_store(store);
  16157. return false;
  16158. }
  16159. src = src->next;
  16160. }
  16161. // This function takes ownership of the store; the chain was deep-copied
  16162. // above, so release the source
  16163. free_ca_store(store);
  16164. // Update the SSL config to use the new CA chain
  16165. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16166. return true;
  16167. }
  16168. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16169. certs.clear();
  16170. if (!ctx) { return 0; }
  16171. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16172. // Iterate through the CA chain
  16173. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16174. while (cert != nullptr && cert->raw.len > 0) {
  16175. // Create a copy of the certificate for the caller
  16176. auto *copy = new mbedtls_x509_crt;
  16177. mbedtls_x509_crt_init(copy);
  16178. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16179. if (ret == 0) {
  16180. certs.push_back(static_cast<cert_t>(copy));
  16181. } else {
  16182. mbedtls_x509_crt_free(copy);
  16183. delete copy;
  16184. }
  16185. cert = cert->next;
  16186. }
  16187. return certs.size();
  16188. }
  16189. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16190. std::vector<std::string> names;
  16191. if (!ctx) { return names; }
  16192. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16193. // Iterate through the CA chain
  16194. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16195. while (cert != nullptr && cert->raw.len > 0) {
  16196. char buf[512];
  16197. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16198. if (ret > 0) { names.push_back(buf); }
  16199. cert = cert->next;
  16200. }
  16201. return names;
  16202. }
  16203. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16204. const char *key_pem, const char *password) {
  16205. if (!ctx || !cert_pem || !key_pem) { return false; }
  16206. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16207. // Free existing certificate and key
  16208. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16209. mbedtls_pk_free(&mbed_ctx->own_key);
  16210. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16211. mbedtls_pk_init(&mbed_ctx->own_key);
  16212. // Parse certificate PEM
  16213. int ret = mbedtls_x509_crt_parse(
  16214. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16215. strlen(cert_pem) + 1);
  16216. if (ret != 0) {
  16217. impl::mbedtls_last_error() = ret;
  16218. return false;
  16219. }
  16220. // Parse private key PEM
  16221. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16222. ret = mbedtls_pk_parse_key(
  16223. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16224. strlen(key_pem) + 1,
  16225. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16226. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16227. &mbed_ctx->ctr_drbg);
  16228. #else
  16229. ret = mbedtls_pk_parse_key(
  16230. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16231. strlen(key_pem) + 1,
  16232. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16233. password ? strlen(password) : 0);
  16234. #endif
  16235. if (ret != 0) {
  16236. impl::mbedtls_last_error() = ret;
  16237. return false;
  16238. }
  16239. // Configure SSL to use the new certificate and key
  16240. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16241. &mbed_ctx->own_key);
  16242. if (ret != 0) {
  16243. impl::mbedtls_last_error() = ret;
  16244. return false;
  16245. }
  16246. return true;
  16247. }
  16248. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16249. if (!ctx || !ca_pem) { return false; }
  16250. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16251. // Free existing CA chain
  16252. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16253. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16254. // Parse CA PEM
  16255. int ret = mbedtls_x509_crt_parse(
  16256. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16257. strlen(ca_pem) + 1);
  16258. if (ret != 0) {
  16259. impl::mbedtls_last_error() = ret;
  16260. return false;
  16261. }
  16262. // Update SSL config to use new CA chain
  16263. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16264. return true;
  16265. }
  16266. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16267. if (!ctx) { return false; }
  16268. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16269. impl::get_verify_callback() = std::move(callback);
  16270. mbed_ctx->has_verify_callback =
  16271. static_cast<bool>(impl::get_verify_callback());
  16272. if (mbed_ctx->has_verify_callback) {
  16273. // Set OPTIONAL mode to ensure callback is called even when verification
  16274. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16275. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16276. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16277. nullptr);
  16278. } else {
  16279. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16280. }
  16281. return true;
  16282. }
  16283. inline long get_verify_error(const_session_t session) {
  16284. if (!session) { return -1; }
  16285. auto *msession =
  16286. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16287. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16288. }
  16289. inline std::string verify_error_string(long error_code) {
  16290. if (error_code == 0) { return ""; }
  16291. char buf[256];
  16292. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16293. static_cast<uint32_t>(error_code));
  16294. // Remove trailing newline if present
  16295. std::string result(buf);
  16296. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16297. result.pop_back();
  16298. }
  16299. return result;
  16300. }
  16301. } // namespace tls
  16302. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16303. /*
  16304. * Group 10: TLS abstraction layer - wolfSSL backend
  16305. */
  16306. /*
  16307. * wolfSSL Backend Implementation
  16308. */
  16309. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16310. namespace tls {
  16311. namespace impl {
  16312. // wolfSSL session wrapper
  16313. struct WolfSSLSession {
  16314. WOLFSSL *ssl = nullptr;
  16315. socket_t sock = INVALID_SOCKET;
  16316. std::string hostname; // For client: set via set_sni
  16317. std::string sni_hostname; // For server: received from client via SNI callback
  16318. WolfSSLSession() = default;
  16319. ~WolfSSLSession() {
  16320. if (ssl) { wolfSSL_free(ssl); }
  16321. }
  16322. WolfSSLSession(const WolfSSLSession &) = delete;
  16323. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16324. };
  16325. // Thread-local error code accessor for wolfSSL
  16326. inline uint64_t &wolfssl_last_error() {
  16327. static thread_local uint64_t err = 0;
  16328. return err;
  16329. }
  16330. // Helper to map wolfSSL error to ErrorCode.
  16331. // ssl_error is the value from wolfSSL_get_error().
  16332. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16333. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16334. int &out_errno) {
  16335. switch (ssl_error) {
  16336. case SSL_ERROR_NONE: return ErrorCode::Success;
  16337. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16338. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16339. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16340. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16341. default:
  16342. if (ssl) {
  16343. // wolfSSL stores the low-level error code as a negative value.
  16344. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16345. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16346. if (low_err == DOMAIN_NAME_MISMATCH) {
  16347. return ErrorCode::HostnameMismatch;
  16348. }
  16349. // Check verify result to distinguish cert verification from generic SSL
  16350. // errors.
  16351. long vr = wolfSSL_get_verify_result(ssl);
  16352. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16353. }
  16354. return ErrorCode::Fatal;
  16355. }
  16356. }
  16357. // WolfSSLContext constructor/destructor implementations
  16358. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16359. inline WolfSSLContext::~WolfSSLContext() {
  16360. if (ctx) { wolfSSL_CTX_free(ctx); }
  16361. }
  16362. // Thread-local storage for SNI captured during handshake
  16363. inline std::string &wolfssl_pending_sni() {
  16364. static thread_local std::string sni;
  16365. return sni;
  16366. }
  16367. // SNI callback for wolfSSL server to capture client's SNI hostname
  16368. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16369. (void)ret;
  16370. (void)exArg;
  16371. void *name_data = nullptr;
  16372. unsigned short name_len =
  16373. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16374. if (name_data && name_len > 0) {
  16375. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16376. name_len);
  16377. } else {
  16378. wolfssl_pending_sni().clear();
  16379. }
  16380. return 0; // Continue regardless
  16381. }
  16382. // wolfSSL verify callback wrapper
  16383. inline int wolfssl_verify_callback(int preverify_ok,
  16384. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16385. auto &callback = get_verify_callback();
  16386. if (!callback) { return preverify_ok; }
  16387. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16388. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16389. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16390. // Get the WOLFSSL object from the X509_STORE_CTX
  16391. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16392. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16393. VerifyContext verify_ctx;
  16394. verify_ctx.session = static_cast<session_t>(ssl);
  16395. verify_ctx.cert = static_cast<cert_t>(cert);
  16396. verify_ctx.depth = depth;
  16397. verify_ctx.preverify_ok = (preverify_ok != 0);
  16398. verify_ctx.error_code = static_cast<long>(err);
  16399. if (err != 0) {
  16400. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16401. } else {
  16402. verify_ctx.error_string = nullptr;
  16403. }
  16404. bool accepted = callback(verify_ctx);
  16405. return accepted ? 1 : 0;
  16406. }
  16407. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16408. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16409. wolfSSL_CTX_set_default_passwd_cb(
  16410. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16411. auto *pwd = static_cast<const char *>(userdata);
  16412. if (!pwd) return 0;
  16413. auto len = static_cast<int>(strlen(pwd));
  16414. if (len > size) len = size;
  16415. memcpy(buf, pwd, static_cast<size_t>(len));
  16416. return len;
  16417. });
  16418. }
  16419. } // namespace impl
  16420. inline ctx_t create_client_context() {
  16421. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16422. if (!ctx) { return nullptr; }
  16423. ctx->is_server = false;
  16424. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16425. if (!method) {
  16426. delete ctx;
  16427. return nullptr;
  16428. }
  16429. ctx->ctx = wolfSSL_CTX_new(method);
  16430. if (!ctx->ctx) {
  16431. delete ctx;
  16432. return nullptr;
  16433. }
  16434. // Default: verify peer certificate
  16435. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16436. return static_cast<ctx_t>(ctx);
  16437. }
  16438. inline ctx_t create_server_context() {
  16439. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16440. if (!ctx) { return nullptr; }
  16441. ctx->is_server = true;
  16442. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16443. if (!method) {
  16444. delete ctx;
  16445. return nullptr;
  16446. }
  16447. ctx->ctx = wolfSSL_CTX_new(method);
  16448. if (!ctx->ctx) {
  16449. delete ctx;
  16450. return nullptr;
  16451. }
  16452. // Default: don't verify client
  16453. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16454. // Enable SNI on server
  16455. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16456. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16457. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16458. return static_cast<ctx_t>(ctx);
  16459. }
  16460. inline void free_context(ctx_t ctx) {
  16461. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16462. }
  16463. inline bool set_min_version(ctx_t ctx, Version version) {
  16464. if (!ctx) { return false; }
  16465. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16466. int min_ver = WOLFSSL_TLSV1_2;
  16467. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16468. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16469. }
  16470. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16471. if (!ctx || !pem) { return false; }
  16472. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16473. int ret = wolfSSL_CTX_load_verify_buffer(
  16474. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16475. static_cast<long>(len), SSL_FILETYPE_PEM);
  16476. if (ret != SSL_SUCCESS) {
  16477. impl::wolfssl_last_error() =
  16478. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16479. return false;
  16480. }
  16481. wctx->ca_pem_data_.append(pem, len);
  16482. return true;
  16483. }
  16484. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16485. if (!ctx || !file_path) { return false; }
  16486. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16487. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16488. if (ret != SSL_SUCCESS) {
  16489. impl::wolfssl_last_error() =
  16490. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16491. return false;
  16492. }
  16493. return true;
  16494. }
  16495. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16496. if (!ctx || !dir_path) { return false; }
  16497. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16498. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16499. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16500. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16501. // immediately. Return true even on failure since the CA file may have
  16502. // already been loaded, matching OpenSSL's lenient behavior.
  16503. (void)ret;
  16504. return true;
  16505. }
  16506. inline bool load_system_certs(ctx_t ctx) {
  16507. if (!ctx) { return false; }
  16508. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16509. bool loaded = false;
  16510. #ifdef _WIN32
  16511. loaded = impl::enumerate_windows_system_certs(
  16512. [&](const unsigned char *data, size_t len) {
  16513. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16514. static_cast<long>(len),
  16515. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16516. });
  16517. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16518. loaded = impl::enumerate_macos_keychain_certs(
  16519. [&](const unsigned char *data, size_t len) {
  16520. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16521. static_cast<long>(len),
  16522. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16523. });
  16524. #else
  16525. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16526. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16527. SSL_SUCCESS) {
  16528. loaded = true;
  16529. break;
  16530. }
  16531. }
  16532. if (!loaded) {
  16533. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16534. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16535. SSL_SUCCESS) {
  16536. loaded = true;
  16537. break;
  16538. }
  16539. }
  16540. }
  16541. #endif
  16542. return loaded;
  16543. }
  16544. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16545. const char *password) {
  16546. if (!ctx || !cert || !key) { return false; }
  16547. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16548. // Load certificate
  16549. int ret = wolfSSL_CTX_use_certificate_buffer(
  16550. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16551. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16552. if (ret != SSL_SUCCESS) {
  16553. impl::wolfssl_last_error() =
  16554. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16555. return false;
  16556. }
  16557. // Set password callback if password is provided
  16558. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16559. // Load private key
  16560. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16561. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16562. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16563. if (ret != SSL_SUCCESS) {
  16564. impl::wolfssl_last_error() =
  16565. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16566. return false;
  16567. }
  16568. // Verify that the certificate and private key match
  16569. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16570. }
  16571. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16572. const char *key_path, const char *password) {
  16573. if (!ctx || !cert_path || !key_path) { return false; }
  16574. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16575. // Load certificate file
  16576. int ret =
  16577. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16578. if (ret != SSL_SUCCESS) {
  16579. impl::wolfssl_last_error() =
  16580. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16581. return false;
  16582. }
  16583. // Set password callback if password is provided
  16584. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16585. // Load private key file
  16586. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16587. if (ret != SSL_SUCCESS) {
  16588. impl::wolfssl_last_error() =
  16589. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16590. return false;
  16591. }
  16592. // Verify that the certificate and private key match
  16593. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16594. }
  16595. inline void set_verify_client(ctx_t ctx, bool require) {
  16596. if (!ctx) { return; }
  16597. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16598. wctx->verify_client = require;
  16599. if (require) {
  16600. wolfSSL_CTX_set_verify(
  16601. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16602. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16603. } else {
  16604. if (wctx->has_verify_callback) {
  16605. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16606. impl::wolfssl_verify_callback);
  16607. } else {
  16608. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16609. }
  16610. }
  16611. }
  16612. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16613. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16614. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16615. auto session = new (std::nothrow) impl::WolfSSLSession();
  16616. if (!session) { return nullptr; }
  16617. session->sock = sock;
  16618. session->ssl = wolfSSL_new(wctx->ctx);
  16619. if (!session->ssl) {
  16620. impl::wolfssl_last_error() =
  16621. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16622. delete session;
  16623. return nullptr;
  16624. }
  16625. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16626. return static_cast<session_t>(session);
  16627. }
  16628. inline void free_session(session_t session) {
  16629. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16630. }
  16631. inline bool set_sni(session_t session, const char *hostname) {
  16632. if (!session || !hostname) { return false; }
  16633. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16634. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16635. static_cast<word16>(strlen(hostname)));
  16636. if (ret != WOLFSSL_SUCCESS) {
  16637. impl::wolfssl_last_error() =
  16638. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16639. return false;
  16640. }
  16641. // Also set hostname for verification
  16642. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16643. wsession->hostname = hostname;
  16644. return true;
  16645. }
  16646. inline bool set_hostname(session_t session, const char *hostname) {
  16647. // In wolfSSL, set_hostname also sets up hostname verification
  16648. return set_sni(session, hostname);
  16649. }
  16650. inline TlsError connect(session_t session) {
  16651. TlsError err;
  16652. if (!session) {
  16653. err.code = ErrorCode::Fatal;
  16654. return err;
  16655. }
  16656. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16657. int ret = wolfSSL_connect(wsession->ssl);
  16658. if (ret == SSL_SUCCESS) {
  16659. err.code = ErrorCode::Success;
  16660. } else {
  16661. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16662. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16663. err.backend_code = static_cast<uint64_t>(ssl_error);
  16664. impl::wolfssl_last_error() = err.backend_code;
  16665. }
  16666. return err;
  16667. }
  16668. inline TlsError accept(session_t session) {
  16669. TlsError err;
  16670. if (!session) {
  16671. err.code = ErrorCode::Fatal;
  16672. return err;
  16673. }
  16674. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16675. int ret = wolfSSL_accept(wsession->ssl);
  16676. if (ret == SSL_SUCCESS) {
  16677. err.code = ErrorCode::Success;
  16678. // Capture SNI from thread-local storage after successful handshake
  16679. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16680. impl::wolfssl_pending_sni().clear();
  16681. } else {
  16682. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16683. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16684. err.backend_code = static_cast<uint64_t>(ssl_error);
  16685. impl::wolfssl_last_error() = err.backend_code;
  16686. }
  16687. return err;
  16688. }
  16689. inline bool connect_nonblocking(session_t session, socket_t sock,
  16690. time_t timeout_sec, time_t timeout_usec,
  16691. TlsError *err) {
  16692. if (!session) {
  16693. if (err) { err->code = ErrorCode::Fatal; }
  16694. return false;
  16695. }
  16696. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16697. // Set socket to non-blocking mode
  16698. detail::set_nonblocking(sock, true);
  16699. auto cleanup =
  16700. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16701. int ret;
  16702. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16703. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16704. if (ssl_error == SSL_ERROR_WANT_READ) {
  16705. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16706. continue;
  16707. }
  16708. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16709. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16710. continue;
  16711. }
  16712. }
  16713. // Error or timeout
  16714. if (err) {
  16715. err->code =
  16716. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16717. err->backend_code = static_cast<uint64_t>(ssl_error);
  16718. }
  16719. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16720. return false;
  16721. }
  16722. if (err) { err->code = ErrorCode::Success; }
  16723. return true;
  16724. }
  16725. inline bool accept_nonblocking(session_t session, socket_t sock,
  16726. time_t timeout_sec, time_t timeout_usec,
  16727. TlsError *err) {
  16728. if (!session) {
  16729. if (err) { err->code = ErrorCode::Fatal; }
  16730. return false;
  16731. }
  16732. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16733. // Set socket to non-blocking mode
  16734. detail::set_nonblocking(sock, true);
  16735. auto cleanup =
  16736. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16737. int ret;
  16738. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16739. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16740. if (ssl_error == SSL_ERROR_WANT_READ) {
  16741. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16742. continue;
  16743. }
  16744. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16745. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16746. continue;
  16747. }
  16748. }
  16749. // Error or timeout
  16750. if (err) {
  16751. err->code =
  16752. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16753. err->backend_code = static_cast<uint64_t>(ssl_error);
  16754. }
  16755. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16756. return false;
  16757. }
  16758. if (err) { err->code = ErrorCode::Success; }
  16759. // Capture SNI from thread-local storage after successful handshake
  16760. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16761. impl::wolfssl_pending_sni().clear();
  16762. return true;
  16763. }
  16764. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16765. if (!session || !buf) {
  16766. err.code = ErrorCode::Fatal;
  16767. return -1;
  16768. }
  16769. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16770. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16771. if (ret > 0) {
  16772. err.code = ErrorCode::Success;
  16773. return static_cast<ssize_t>(ret);
  16774. }
  16775. if (ret == 0) {
  16776. err.code = ErrorCode::PeerClosed;
  16777. return 0;
  16778. }
  16779. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16780. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16781. err.backend_code = static_cast<uint64_t>(ssl_error);
  16782. impl::wolfssl_last_error() = err.backend_code;
  16783. return -1;
  16784. }
  16785. inline ssize_t write(session_t session, const void *buf, size_t len,
  16786. TlsError &err) {
  16787. if (!session || !buf) {
  16788. err.code = ErrorCode::Fatal;
  16789. return -1;
  16790. }
  16791. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16792. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16793. if (ret > 0) {
  16794. err.code = ErrorCode::Success;
  16795. return static_cast<ssize_t>(ret);
  16796. }
  16797. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16798. // Treat this as an error (return -1) so callers don't spin in a
  16799. // write loop adding zero to the offset.
  16800. if (ret == 0) {
  16801. err.code = ErrorCode::PeerClosed;
  16802. return -1;
  16803. }
  16804. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16805. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16806. err.backend_code = static_cast<uint64_t>(ssl_error);
  16807. impl::wolfssl_last_error() = err.backend_code;
  16808. return -1;
  16809. }
  16810. inline int pending(const_session_t session) {
  16811. if (!session) { return 0; }
  16812. auto wsession =
  16813. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16814. return wolfSSL_pending(wsession->ssl);
  16815. }
  16816. inline void shutdown(session_t session, bool graceful) {
  16817. if (!session) { return; }
  16818. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16819. if (graceful) {
  16820. int ret;
  16821. int attempts = 0;
  16822. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16823. attempts < 3) {
  16824. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16825. if (ssl_error != SSL_ERROR_WANT_READ &&
  16826. ssl_error != SSL_ERROR_WANT_WRITE) {
  16827. break;
  16828. }
  16829. attempts++;
  16830. }
  16831. } else {
  16832. wolfSSL_shutdown(wsession->ssl);
  16833. }
  16834. }
  16835. inline bool is_peer_closed(session_t session, socket_t sock) {
  16836. if (!session || sock == INVALID_SOCKET) { return true; }
  16837. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16838. // Check if there's already decrypted data available
  16839. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16840. // Set socket to non-blocking to avoid blocking on read
  16841. detail::set_nonblocking(sock, true);
  16842. auto cleanup =
  16843. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16844. // Peek 1 byte to check connection status without consuming data
  16845. unsigned char buf;
  16846. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16847. // If we got data or WANT_READ (would block), connection is alive
  16848. if (ret > 0) { return false; }
  16849. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16850. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16851. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16852. ret == 0;
  16853. }
  16854. inline cert_t get_peer_cert(const_session_t session) {
  16855. if (!session) { return nullptr; }
  16856. auto wsession =
  16857. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16858. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16859. return static_cast<cert_t>(cert);
  16860. }
  16861. inline void free_cert(cert_t cert) {
  16862. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16863. }
  16864. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16865. if (!cert || !hostname) { return false; }
  16866. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16867. std::string host_str(hostname);
  16868. // Check if hostname is an IP address (IPv4 or IPv6)
  16869. unsigned char ip_bytes[16];
  16870. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16871. auto is_ip = ip_len > 0;
  16872. // Check Subject Alternative Names
  16873. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16874. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16875. if (san_names) {
  16876. int san_count = wolfSSL_sk_num(san_names);
  16877. for (int i = 0; i < san_count; i++) {
  16878. auto *names =
  16879. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16880. if (!names) continue;
  16881. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16882. // DNS name
  16883. unsigned char *dns_name = nullptr;
  16884. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16885. if (dns_name && dns_len > 0) {
  16886. std::string san_name(reinterpret_cast<char *>(dns_name),
  16887. static_cast<size_t>(dns_len));
  16888. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16889. if (detail::match_hostname(san_name, host_str)) {
  16890. wolfSSL_sk_free(san_names);
  16891. return true;
  16892. }
  16893. }
  16894. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16895. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16896. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16897. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16898. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16899. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16900. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16901. wolfSSL_sk_free(san_names);
  16902. return true;
  16903. }
  16904. }
  16905. }
  16906. wolfSSL_sk_free(san_names);
  16907. }
  16908. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16909. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16910. // the OpenSSL backend's X509_check_ip behaves the same way).
  16911. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16912. if (subject) {
  16913. char cn[256] = {};
  16914. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16915. sizeof(cn));
  16916. if (cn_len > 0) {
  16917. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16918. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16919. }
  16920. }
  16921. return false;
  16922. }
  16923. inline uint64_t hostname_mismatch_code() {
  16924. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16925. }
  16926. inline long get_verify_result(const_session_t session) {
  16927. if (!session) { return -1; }
  16928. auto wsession =
  16929. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16930. long result = wolfSSL_get_verify_result(wsession->ssl);
  16931. return result;
  16932. }
  16933. inline std::string get_cert_subject_cn(cert_t cert) {
  16934. if (!cert) return "";
  16935. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16936. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16937. if (!subject) return "";
  16938. char cn[256] = {};
  16939. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16940. sizeof(cn));
  16941. if (cn_len <= 0) return "";
  16942. return std::string(cn, static_cast<size_t>(cn_len));
  16943. }
  16944. inline std::string get_cert_issuer_name(cert_t cert) {
  16945. if (!cert) return "";
  16946. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16947. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16948. if (!issuer) return "";
  16949. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16950. if (!name_str) return "";
  16951. std::string result(name_str);
  16952. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16953. return result;
  16954. }
  16955. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16956. sans.clear();
  16957. if (!cert) return false;
  16958. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16959. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16960. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16961. if (!san_names) return true; // No SANs is not an error
  16962. int count = wolfSSL_sk_num(san_names);
  16963. for (int i = 0; i < count; i++) {
  16964. auto *name =
  16965. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16966. if (!name) continue;
  16967. SanEntry entry;
  16968. switch (name->type) {
  16969. case WOLFSSL_GEN_DNS: {
  16970. entry.type = SanType::DNS;
  16971. unsigned char *dns_name = nullptr;
  16972. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16973. if (dns_name && dns_len > 0) {
  16974. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16975. static_cast<size_t>(dns_len));
  16976. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16977. }
  16978. break;
  16979. }
  16980. case WOLFSSL_GEN_IPADD: {
  16981. entry.type = SanType::IP;
  16982. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16983. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16984. if (ip_data && ip_len == 4) {
  16985. char buf[16];
  16986. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16987. ip_data[2], ip_data[3]);
  16988. entry.value = buf;
  16989. } else if (ip_data && ip_len == 16) {
  16990. char buf[64];
  16991. snprintf(buf, sizeof(buf),
  16992. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16993. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16994. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16995. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16996. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16997. ip_data[14], ip_data[15]);
  16998. entry.value = buf;
  16999. }
  17000. break;
  17001. }
  17002. case WOLFSSL_GEN_EMAIL:
  17003. entry.type = SanType::EMAIL;
  17004. {
  17005. unsigned char *email = nullptr;
  17006. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  17007. if (email && email_len > 0) {
  17008. entry.value = std::string(reinterpret_cast<char *>(email),
  17009. static_cast<size_t>(email_len));
  17010. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  17011. }
  17012. }
  17013. break;
  17014. case WOLFSSL_GEN_URI:
  17015. entry.type = SanType::URI;
  17016. {
  17017. unsigned char *uri = nullptr;
  17018. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  17019. &uri, name->d.uniformResourceIdentifier);
  17020. if (uri && uri_len > 0) {
  17021. entry.value = std::string(reinterpret_cast<char *>(uri),
  17022. static_cast<size_t>(uri_len));
  17023. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  17024. }
  17025. }
  17026. break;
  17027. default: entry.type = SanType::OTHER; break;
  17028. }
  17029. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17030. }
  17031. wolfSSL_sk_free(san_names);
  17032. return true;
  17033. }
  17034. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17035. time_t &not_after) {
  17036. if (!cert) return false;
  17037. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17038. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  17039. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  17040. if (!nb || !na) return false;
  17041. // wolfSSL_ASN1_TIME_to_tm is available
  17042. struct tm tm_nb = {}, tm_na = {};
  17043. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  17044. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  17045. #ifdef _WIN32
  17046. not_before = _mkgmtime(&tm_nb);
  17047. not_after = _mkgmtime(&tm_na);
  17048. #else
  17049. not_before = timegm(&tm_nb);
  17050. not_after = timegm(&tm_na);
  17051. #endif
  17052. return true;
  17053. }
  17054. inline std::string get_cert_serial(cert_t cert) {
  17055. if (!cert) return "";
  17056. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17057. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  17058. if (!serial_asn1) return "";
  17059. // Get the serial number data
  17060. int len = serial_asn1->length;
  17061. unsigned char *data = serial_asn1->data;
  17062. if (!data || len <= 0) return "";
  17063. std::string result;
  17064. result.reserve(static_cast<size_t>(len) * 2);
  17065. for (int i = 0; i < len; i++) {
  17066. char hex[3];
  17067. snprintf(hex, sizeof(hex), "%02X", data[i]);
  17068. result += hex;
  17069. }
  17070. return result;
  17071. }
  17072. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17073. if (!cert) return false;
  17074. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17075. int der_len = 0;
  17076. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  17077. if (!der_data || der_len <= 0) return false;
  17078. der.assign(der_data, der_data + der_len);
  17079. return true;
  17080. }
  17081. inline const char *get_sni(const_session_t session) {
  17082. if (!session) return nullptr;
  17083. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17084. // For server: return SNI received from client during handshake
  17085. if (!wsession->sni_hostname.empty()) {
  17086. return wsession->sni_hostname.c_str();
  17087. }
  17088. // For client: return the hostname set via set_sni
  17089. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17090. return nullptr;
  17091. }
  17092. inline uint64_t peek_error() {
  17093. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17094. }
  17095. inline uint64_t get_error() {
  17096. uint64_t err = impl::wolfssl_last_error();
  17097. impl::wolfssl_last_error() = 0;
  17098. return err;
  17099. }
  17100. inline std::string error_string(uint64_t code) {
  17101. char buf[256];
  17102. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17103. return std::string(buf);
  17104. }
  17105. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17106. if (!pem || len == 0) { return nullptr; }
  17107. // Validate by attempting to load into a temporary ctx
  17108. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17109. if (!tmp_ctx) { return nullptr; }
  17110. int ret = wolfSSL_CTX_load_verify_buffer(
  17111. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17112. static_cast<long>(len), SSL_FILETYPE_PEM);
  17113. wolfSSL_CTX_free(tmp_ctx);
  17114. if (ret != SSL_SUCCESS) { return nullptr; }
  17115. return static_cast<ca_store_t>(
  17116. new impl::WolfSSLCAStore{std::string(pem, len)});
  17117. }
  17118. inline void free_ca_store(ca_store_t store) {
  17119. delete static_cast<impl::WolfSSLCAStore *>(store);
  17120. }
  17121. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17122. if (!ctx || !store) { return false; }
  17123. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17124. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17125. int ret = wolfSSL_CTX_load_verify_buffer(
  17126. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17127. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17128. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17129. // This function takes ownership of the store; the PEM data was copied into
  17130. // the context, so release the source
  17131. free_ca_store(store);
  17132. return ret == SSL_SUCCESS;
  17133. }
  17134. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17135. certs.clear();
  17136. if (!ctx) { return 0; }
  17137. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17138. if (wctx->ca_pem_data_.empty()) { return 0; }
  17139. const std::string &pem = wctx->ca_pem_data_;
  17140. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17141. const std::string end_marker = "-----END CERTIFICATE-----";
  17142. size_t pos = 0;
  17143. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17144. size_t end_pos = pem.find(end_marker, pos);
  17145. if (end_pos == std::string::npos) { break; }
  17146. end_pos += end_marker.size();
  17147. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17148. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17149. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17150. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17151. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17152. pos = end_pos;
  17153. }
  17154. return certs.size();
  17155. }
  17156. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17157. std::vector<std::string> names;
  17158. if (!ctx) { return names; }
  17159. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17160. if (wctx->ca_pem_data_.empty()) { return names; }
  17161. const std::string &pem = wctx->ca_pem_data_;
  17162. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17163. const std::string end_marker = "-----END CERTIFICATE-----";
  17164. size_t pos = 0;
  17165. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17166. size_t end_pos = pem.find(end_marker, pos);
  17167. if (end_pos == std::string::npos) { break; }
  17168. end_pos += end_marker.size();
  17169. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17170. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17171. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17172. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17173. if (x509) {
  17174. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17175. if (subject) {
  17176. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17177. if (name_str) {
  17178. names.push_back(name_str);
  17179. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17180. }
  17181. }
  17182. wolfSSL_X509_free(x509);
  17183. }
  17184. pos = end_pos;
  17185. }
  17186. return names;
  17187. }
  17188. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17189. const char *key_pem, const char *password) {
  17190. if (!ctx || !cert_pem || !key_pem) { return false; }
  17191. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17192. // Load new certificate
  17193. int ret = wolfSSL_CTX_use_certificate_buffer(
  17194. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17195. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17196. if (ret != SSL_SUCCESS) {
  17197. impl::wolfssl_last_error() =
  17198. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17199. return false;
  17200. }
  17201. // Set password if provided
  17202. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17203. // Load new private key
  17204. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17205. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17206. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17207. if (ret != SSL_SUCCESS) {
  17208. impl::wolfssl_last_error() =
  17209. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17210. return false;
  17211. }
  17212. return true;
  17213. }
  17214. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17215. if (!ctx || !ca_pem) { return false; }
  17216. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17217. int ret = wolfSSL_CTX_load_verify_buffer(
  17218. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17219. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17220. if (ret != SSL_SUCCESS) {
  17221. impl::wolfssl_last_error() =
  17222. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17223. return false;
  17224. }
  17225. return true;
  17226. }
  17227. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17228. if (!ctx) { return false; }
  17229. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17230. impl::get_verify_callback() = std::move(callback);
  17231. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17232. if (wctx->has_verify_callback) {
  17233. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17234. impl::wolfssl_verify_callback);
  17235. } else {
  17236. wolfSSL_CTX_set_verify(
  17237. wctx->ctx,
  17238. wctx->verify_client
  17239. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17240. : SSL_VERIFY_NONE,
  17241. nullptr);
  17242. }
  17243. return true;
  17244. }
  17245. inline long get_verify_error(const_session_t session) {
  17246. if (!session) { return -1; }
  17247. auto *wsession =
  17248. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17249. return wolfSSL_get_verify_result(wsession->ssl);
  17250. }
  17251. inline std::string verify_error_string(long error_code) {
  17252. if (error_code == 0) { return ""; }
  17253. const char *str =
  17254. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17255. return str ? std::string(str) : std::string();
  17256. }
  17257. } // namespace tls
  17258. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17259. // WebSocket implementation
  17260. namespace ws {
  17261. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17262. bool fin) {
  17263. std::lock_guard<std::mutex> lock(write_mutex_);
  17264. if (closed_) { return false; }
  17265. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17266. }
  17267. inline ReadResult WebSocket::read(std::string &msg) {
  17268. while (!closed_) {
  17269. Opcode opcode;
  17270. std::string payload;
  17271. bool fin;
  17272. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17273. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17274. closed_ = true;
  17275. return Fail;
  17276. }
  17277. switch (opcode) {
  17278. case Opcode::Ping: {
  17279. std::lock_guard<std::mutex> lock(write_mutex_);
  17280. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17281. payload.size(), true, !is_server_);
  17282. continue;
  17283. }
  17284. case Opcode::Pong: {
  17285. std::lock_guard<std::mutex> lock(ping_mutex_);
  17286. unacked_pings_ = 0;
  17287. continue;
  17288. }
  17289. case Opcode::Close: {
  17290. if (!closed_.exchange(true)) {
  17291. // Echo close frame back
  17292. std::lock_guard<std::mutex> lock(write_mutex_);
  17293. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17294. payload.size(), true, !is_server_);
  17295. }
  17296. return Fail;
  17297. }
  17298. case Opcode::Text:
  17299. case Opcode::Binary: {
  17300. auto result = opcode == Opcode::Text ? Text : Binary;
  17301. msg = std::move(payload);
  17302. // Handle fragmentation
  17303. if (!fin) {
  17304. while (true) {
  17305. Opcode cont_opcode;
  17306. std::string cont_payload;
  17307. bool cont_fin;
  17308. if (!impl::read_websocket_frame(
  17309. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17310. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17311. closed_ = true;
  17312. return Fail;
  17313. }
  17314. if (cont_opcode == Opcode::Ping) {
  17315. std::lock_guard<std::mutex> lock(write_mutex_);
  17316. detail::write_websocket_frame(
  17317. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17318. true, !is_server_);
  17319. continue;
  17320. }
  17321. if (cont_opcode == Opcode::Pong) {
  17322. std::lock_guard<std::mutex> lock(ping_mutex_);
  17323. unacked_pings_ = 0;
  17324. continue;
  17325. }
  17326. if (cont_opcode == Opcode::Close) {
  17327. if (!closed_.exchange(true)) {
  17328. std::lock_guard<std::mutex> lock(write_mutex_);
  17329. detail::write_websocket_frame(
  17330. strm_, Opcode::Close, cont_payload.data(),
  17331. cont_payload.size(), true, !is_server_);
  17332. }
  17333. return Fail;
  17334. }
  17335. // RFC 6455: continuation frames must use opcode 0x0
  17336. if (cont_opcode != Opcode::Continuation) {
  17337. closed_ = true;
  17338. return Fail;
  17339. }
  17340. msg += cont_payload;
  17341. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17342. closed_ = true;
  17343. return Fail;
  17344. }
  17345. if (cont_fin) { break; }
  17346. }
  17347. }
  17348. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17349. if (result == Text && !impl::is_valid_utf8(msg)) {
  17350. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17351. return Fail;
  17352. }
  17353. return result;
  17354. }
  17355. default: closed_ = true; return Fail;
  17356. }
  17357. }
  17358. return Fail;
  17359. }
  17360. inline bool WebSocket::send(const std::string &data) {
  17361. return send_frame(Opcode::Text, data.data(), data.size());
  17362. }
  17363. inline bool WebSocket::send(const char *data, size_t len) {
  17364. return send_frame(Opcode::Binary, data, len);
  17365. }
  17366. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17367. if (closed_.exchange(true)) { return; }
  17368. ping_cv_.notify_all();
  17369. std::string payload;
  17370. auto code = static_cast<uint16_t>(status);
  17371. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17372. payload.push_back(static_cast<char>(code & 0xFF));
  17373. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17374. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17375. payload += reason.substr(0, 123);
  17376. {
  17377. std::lock_guard<std::mutex> lock(write_mutex_);
  17378. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17379. payload.size(), true, !is_server_);
  17380. }
  17381. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17382. // Close response before closing the TCP connection. Use a short timeout to
  17383. // avoid hanging if the peer doesn't respond.
  17384. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17385. Opcode op;
  17386. std::string resp;
  17387. bool fin;
  17388. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17389. if (op == Opcode::Close) { break; }
  17390. }
  17391. }
  17392. inline WebSocket::~WebSocket() {
  17393. {
  17394. std::lock_guard<std::mutex> lock(ping_mutex_);
  17395. closed_ = true;
  17396. }
  17397. ping_cv_.notify_all();
  17398. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17399. }
  17400. inline void WebSocket::start_heartbeat() {
  17401. if (ping_interval_sec_ == 0) { return; }
  17402. ping_thread_ = std::thread([this]() {
  17403. std::unique_lock<std::mutex> lock(ping_mutex_);
  17404. while (!closed_) {
  17405. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17406. if (closed_) { break; }
  17407. // If the peer has failed to respond to the previous pings, give up.
  17408. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17409. // opt-in liveness check controlled by max_missed_pongs_.
  17410. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17411. lock.unlock();
  17412. close(CloseStatus::GoingAway, "pong timeout");
  17413. return;
  17414. }
  17415. lock.unlock();
  17416. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17417. lock.lock();
  17418. closed_ = true;
  17419. break;
  17420. }
  17421. lock.lock();
  17422. unacked_pings_++;
  17423. }
  17424. });
  17425. }
  17426. inline const Request &WebSocket::request() const { return req_; }
  17427. inline bool WebSocket::is_open() const { return !closed_; }
  17428. // WebSocketClient implementation
  17429. inline WebSocketClient::WebSocketClient(
  17430. const std::string &scheme_host_port_path, const Headers &headers)
  17431. : headers_(headers) {
  17432. detail::UrlComponents uc;
  17433. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17434. !uc.host.empty() && !uc.path.empty()) {
  17435. auto &scheme = uc.scheme;
  17436. #ifdef CPPHTTPLIB_SSL_ENABLED
  17437. if (scheme != "ws" && scheme != "wss") {
  17438. #else
  17439. if (scheme != "ws") {
  17440. #endif
  17441. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17442. std::string msg = "'" + scheme + "' scheme is not supported.";
  17443. throw std::invalid_argument(msg);
  17444. #endif
  17445. return;
  17446. }
  17447. auto is_ssl = scheme == "wss";
  17448. host_ = std::move(uc.host);
  17449. port_ = is_ssl ? 443 : 80;
  17450. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17451. path_ = std::move(uc.path);
  17452. if (!uc.query.empty()) { path_ += uc.query; }
  17453. #ifdef CPPHTTPLIB_SSL_ENABLED
  17454. is_ssl_ = is_ssl;
  17455. if (is_ssl_) {
  17456. // The context lives as long as the client so that CA configuration
  17457. // survives reconnects; sessions are created per connection.
  17458. tls_ctx_ = tls::create_client_context();
  17459. if (!tls_ctx_) { return; }
  17460. }
  17461. #else
  17462. if (is_ssl) { return; }
  17463. #endif
  17464. is_valid_ = true;
  17465. }
  17466. }
  17467. inline WebSocketClient::~WebSocketClient() {
  17468. shutdown_and_close();
  17469. #ifdef CPPHTTPLIB_SSL_ENABLED
  17470. if (tls_ctx_) {
  17471. tls::free_context(tls_ctx_);
  17472. tls_ctx_ = nullptr;
  17473. }
  17474. #endif
  17475. }
  17476. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17477. inline void WebSocketClient::shutdown_and_close() {
  17478. // Send the close frame while the TLS session is still alive: ws_ holds an
  17479. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  17480. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  17481. if (ws_ && ws_->is_open()) { ws_->close(); }
  17482. ws_.reset();
  17483. #ifdef CPPHTTPLIB_SSL_ENABLED
  17484. if (is_ssl_) {
  17485. if (tls_session_) {
  17486. tls::shutdown(tls_session_, true);
  17487. tls::free_session(tls_session_);
  17488. tls_session_ = nullptr;
  17489. }
  17490. }
  17491. #endif
  17492. if (sock_ != INVALID_SOCKET) {
  17493. detail::shutdown_socket(sock_);
  17494. detail::close_socket(sock_);
  17495. sock_ = INVALID_SOCKET;
  17496. }
  17497. }
  17498. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17499. #ifdef CPPHTTPLIB_SSL_ENABLED
  17500. if (is_ssl_) {
  17501. if (server_certificate_verification_ && !certs_loaded_) {
  17502. uint64_t backend_error = 0;
  17503. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17504. custom_ca_loaded_, system_ca_mode_,
  17505. backend_error);
  17506. certs_loaded_ = true;
  17507. }
  17508. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17509. server_certificate_verification_,
  17510. read_timeout_sec_,
  17511. read_timeout_usec_)) {
  17512. return false;
  17513. }
  17514. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17515. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17516. write_timeout_sec_, write_timeout_usec_));
  17517. return true;
  17518. }
  17519. #endif
  17520. strm = std::unique_ptr<Stream>(
  17521. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17522. write_timeout_sec_, write_timeout_usec_));
  17523. return true;
  17524. }
  17525. inline bool WebSocketClient::connect() {
  17526. if (!is_valid_) { return false; }
  17527. shutdown_and_close();
  17528. // Check is custom IP specified for host_
  17529. std::string ip;
  17530. auto it = addr_map_.find(host_);
  17531. if (it != addr_map_.end()) { ip = it->second; }
  17532. Error error;
  17533. sock_ = detail::create_client_socket(
  17534. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17535. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17536. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17537. write_timeout_usec_, interface_, error);
  17538. if (sock_ == INVALID_SOCKET) { return false; }
  17539. std::unique_ptr<Stream> strm;
  17540. if (!create_stream(strm)) {
  17541. shutdown_and_close();
  17542. return false;
  17543. }
  17544. #ifdef CPPHTTPLIB_SSL_ENABLED
  17545. auto is_ssl = is_ssl_;
  17546. #else
  17547. auto is_ssl = false;
  17548. #endif
  17549. std::string selected_subprotocol;
  17550. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17551. headers_, selected_subprotocol)) {
  17552. shutdown_and_close();
  17553. return false;
  17554. }
  17555. subprotocol_ = std::move(selected_subprotocol);
  17556. Request req;
  17557. req.method = "GET";
  17558. req.path = path_;
  17559. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17560. websocket_ping_interval_sec_,
  17561. websocket_max_missed_pongs_));
  17562. return true;
  17563. }
  17564. inline ReadResult WebSocketClient::read(std::string &msg) {
  17565. if (!ws_) { return Fail; }
  17566. return ws_->read(msg);
  17567. }
  17568. inline bool WebSocketClient::send(const std::string &data) {
  17569. if (!ws_) { return false; }
  17570. return ws_->send(data);
  17571. }
  17572. inline bool WebSocketClient::send(const char *data, size_t len) {
  17573. if (!ws_) { return false; }
  17574. return ws_->send(data, len);
  17575. }
  17576. inline void WebSocketClient::close(CloseStatus status,
  17577. const std::string &reason) {
  17578. if (ws_) { ws_->close(status, reason); }
  17579. }
  17580. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17581. inline const std::string &WebSocketClient::subprotocol() const {
  17582. return subprotocol_;
  17583. }
  17584. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17585. read_timeout_sec_ = sec;
  17586. read_timeout_usec_ = usec;
  17587. }
  17588. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17589. write_timeout_sec_ = sec;
  17590. write_timeout_usec_ = usec;
  17591. }
  17592. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17593. websocket_ping_interval_sec_ = sec;
  17594. }
  17595. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17596. websocket_max_missed_pongs_ = count;
  17597. }
  17598. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17599. inline void WebSocketClient::set_address_family(int family) {
  17600. address_family_ = family;
  17601. }
  17602. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17603. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17604. socket_options_ = std::move(socket_options);
  17605. }
  17606. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17607. connection_timeout_sec_ = sec;
  17608. connection_timeout_usec_ = usec;
  17609. }
  17610. inline void WebSocketClient::set_interface(const std::string &intf) {
  17611. interface_ = intf;
  17612. }
  17613. inline void WebSocketClient::set_hostname_addr_map(
  17614. std::map<std::string, std::string> addr_map) {
  17615. addr_map_ = std::move(addr_map);
  17616. }
  17617. #ifdef CPPHTTPLIB_SSL_ENABLED
  17618. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17619. ca_cert_file_path_ = path;
  17620. }
  17621. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17622. if (store && tls_ctx_) {
  17623. // set_ca_store takes ownership of store
  17624. tls::set_ca_store(tls_ctx_, store);
  17625. custom_ca_loaded_ = true;
  17626. } else if (store) {
  17627. tls::free_ca_store(store);
  17628. }
  17629. }
  17630. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17631. std::size_t size) {
  17632. if (tls_ctx_ && ca_cert && size > 0) {
  17633. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17634. custom_ca_loaded_ = true;
  17635. }
  17636. }
  17637. inline void
  17638. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17639. server_certificate_verification_ = enabled;
  17640. }
  17641. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17642. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17643. }
  17644. #endif // CPPHTTPLIB_SSL_ENABLED
  17645. } // namespace ws
  17646. // ----------------------------------------------------------------------------
  17647. } // namespace httplib
  17648. #endif // CPPHTTPLIB_HTTPLIB_H