httplib.h 778 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885
  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.56.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003800"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH
  106. // 1400 rather than a round number: a body that already fits in one 1500-byte
  107. // MTU gains nothing from being made smaller.
  108. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH 1400
  109. #endif
  110. #ifndef CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH
  111. #define CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH (4 * 1024 * 1024) // 4MB
  112. #endif
  113. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  114. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  115. #endif
  116. // std::regex_match's backtracking implementation (most acutely on libstdc++)
  117. // recurses roughly once per matched character for quantified patterns such
  118. // as "(.*)", so a long enough path can exhaust the calling thread's stack; on
  119. // a default ~8MB thread stack that has been observed to take on the order of
  120. // a couple thousand characters for a simple pattern. 256 leaves a wide safety
  121. // margin below that (well under the 8192-byte request URI limit) while still
  122. // fitting any realistic route segment; raise it if a route legitimately needs
  123. // longer paths. Regex routes are never applied to paths longer than this.
  124. #ifndef CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH
  125. #define CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH 256
  126. #endif
  127. #ifndef CPPHTTPLIB_TCP_NODELAY
  128. #define CPPHTTPLIB_TCP_NODELAY false
  129. #endif
  130. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  131. #define CPPHTTPLIB_IPV6_V6ONLY false
  132. #endif
  133. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  134. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  135. #endif
  136. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  137. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  138. #endif
  139. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  140. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  141. #endif
  142. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  143. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  144. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  145. ? std::thread::hardware_concurrency() - 1 \
  146. : 0))
  147. #endif
  148. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  149. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  150. #endif
  151. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  152. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  153. #endif
  154. #ifndef CPPHTTPLIB_RECV_FLAGS
  155. #define CPPHTTPLIB_RECV_FLAGS 0
  156. #endif
  157. #ifndef CPPHTTPLIB_SEND_FLAGS
  158. #define CPPHTTPLIB_SEND_FLAGS 0
  159. #endif
  160. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  161. #define CPPHTTPLIB_LISTEN_BACKLOG 128
  162. #endif
  163. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  164. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  165. #endif
  166. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  167. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  168. #endif
  169. // One macro used to set the read timeout for both sides. They want different
  170. // defaults: a client's read timeout is the caller's own tool (it waits forever
  171. // until asked not to), while a server keeps a ceiling that reclaims a worker
  172. // from a peer that has gone quiet. The old name still works and sets both.
  173. #ifdef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  174. #pragma message( \
  175. "CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND is deprecated; define " \
  176. "CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND and/or " \
  177. "CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND instead")
  178. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  179. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND \
  180. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  181. #endif
  182. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  183. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND \
  184. CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  185. #endif
  186. #endif
  187. // 0 waits forever. A read timeout is how a caller gets control back to send on
  188. // the same connection; it is not a liveness check (that is ping/pong). Only a
  189. // timeout set at runtime through set_read_timeout() is reported as
  190. // ws::Timeout; when one of these compile-time defaults elapses, read() returns
  191. // ws::Fail and closes the connection.
  192. #ifndef CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND
  193. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND 0
  194. #endif
  195. #ifndef CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND
  196. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND 300
  197. #endif
  198. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  199. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  200. #endif
  201. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  202. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  203. #endif
  204. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  205. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  206. #endif
  207. /*
  208. * Headers
  209. */
  210. #ifdef _WIN32
  211. #ifndef _CRT_SECURE_NO_WARNINGS
  212. #define _CRT_SECURE_NO_WARNINGS
  213. #endif //_CRT_SECURE_NO_WARNINGS
  214. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  215. #define _CRT_NONSTDC_NO_DEPRECATE
  216. #endif //_CRT_NONSTDC_NO_DEPRECATE
  217. #if defined(_MSC_VER)
  218. #if _MSC_VER < 1900
  219. #error Sorry, Visual Studio versions prior to 2015 are not supported
  220. #endif
  221. #pragma comment(lib, "ws2_32.lib")
  222. #ifndef _SSIZE_T_DEFINED
  223. using ssize_t = __int64;
  224. #define _SSIZE_T_DEFINED
  225. #endif
  226. #endif // _MSC_VER
  227. #ifndef S_ISREG
  228. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  229. #endif // S_ISREG
  230. #ifndef S_ISDIR
  231. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  232. #endif // S_ISDIR
  233. #ifndef NOMINMAX
  234. #define NOMINMAX
  235. #endif // NOMINMAX
  236. #include <io.h>
  237. #include <winsock2.h>
  238. #include <ws2tcpip.h>
  239. #if defined(__has_include)
  240. #if __has_include(<afunix.h>)
  241. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  242. #include <afunix.h>
  243. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  244. #endif
  245. #endif
  246. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  247. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  248. #endif
  249. using nfds_t = unsigned long;
  250. using socket_t = SOCKET;
  251. using socklen_t = int;
  252. #else // not _WIN32
  253. #include <arpa/inet.h>
  254. #if !defined(_AIX) && !defined(__MVS__)
  255. #include <ifaddrs.h>
  256. #endif
  257. #ifdef __MVS__
  258. #include <strings.h>
  259. #ifndef NI_MAXHOST
  260. #define NI_MAXHOST 1025
  261. #endif
  262. #endif
  263. #include <net/if.h>
  264. #include <netdb.h>
  265. #include <netinet/in.h>
  266. #ifdef __linux__
  267. #include <resolv.h>
  268. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  269. #endif
  270. #include <csignal>
  271. #include <netinet/tcp.h>
  272. #include <poll.h>
  273. #include <pthread.h>
  274. #include <sys/mman.h>
  275. #include <sys/socket.h>
  276. #include <sys/un.h>
  277. #include <unistd.h>
  278. using socket_t = int;
  279. #ifndef INVALID_SOCKET
  280. #define INVALID_SOCKET (-1)
  281. #endif
  282. #endif //_WIN32
  283. #if defined(__APPLE__)
  284. #include <TargetConditionals.h>
  285. #endif
  286. #include <algorithm>
  287. #include <array>
  288. #include <atomic>
  289. #include <cassert>
  290. #include <chrono>
  291. #include <climits>
  292. #include <condition_variable>
  293. #include <cstdlib>
  294. #include <cstring>
  295. #include <errno.h>
  296. #include <exception>
  297. #include <fcntl.h>
  298. #include <fstream>
  299. #include <functional>
  300. #include <iomanip>
  301. #include <iostream>
  302. #include <iterator>
  303. #include <list>
  304. #include <map>
  305. #include <memory>
  306. #include <mutex>
  307. #include <random>
  308. #include <regex>
  309. #include <set>
  310. #include <sstream>
  311. #include <string>
  312. #include <sys/stat.h>
  313. #include <system_error>
  314. #include <thread>
  315. #include <type_traits>
  316. #include <unordered_map>
  317. #include <unordered_set>
  318. #include <utility>
  319. #include <vector>
  320. // On macOS with a TLS backend, enable Keychain root certificates by default
  321. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  322. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  323. // only; on those platforms the user must provide a CA bundle explicitly.
  324. #if defined(__APPLE__) && defined(__clang__) && \
  325. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  326. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  327. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  328. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  329. #if TARGET_OS_OSX
  330. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  331. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  332. #endif
  333. #endif
  334. #endif
  335. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  336. defined(__APPLE__) && !TARGET_OS_OSX
  337. #error \
  338. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  339. #endif
  340. // On Windows, enable Schannel certificate verification by default
  341. // unless the user explicitly opts out.
  342. #if defined(_WIN32) && \
  343. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  344. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  345. #endif
  346. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  347. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  348. #if TARGET_OS_MAC && defined(__clang__)
  349. #include <CFNetwork/CFHost.h>
  350. #include <CoreFoundation/CoreFoundation.h>
  351. #endif
  352. #endif
  353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  354. #ifdef _WIN32
  355. #include <wincrypt.h>
  356. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  357. // used
  358. #undef X509_NAME
  359. #undef X509_CERT_PAIR
  360. #undef X509_EXTENSIONS
  361. #undef PKCS7_SIGNER_INFO
  362. #ifdef _MSC_VER
  363. #pragma comment(lib, "crypt32.lib")
  364. #endif
  365. #endif // _WIN32
  366. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  367. #if TARGET_OS_OSX
  368. #include <Security/Security.h>
  369. #endif
  370. #endif
  371. #include <openssl/err.h>
  372. #include <openssl/evp.h>
  373. #include <openssl/ssl.h>
  374. #include <openssl/x509v3.h>
  375. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  376. #include <openssl/applink.c>
  377. #endif
  378. #include <iostream>
  379. #include <sstream>
  380. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  381. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  382. #error Please use OpenSSL or a current version of BoringSSL
  383. #endif
  384. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  385. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  386. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  387. #endif
  388. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  389. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  390. // version.h defines MBEDTLS_VERSION_MAJOR (on 2.x/3.x/4.x alike); it is pulled
  391. // in with this first include group so the version gating below can use it.
  392. #include <mbedtls/error.h>
  393. #include <mbedtls/net_sockets.h>
  394. #include <mbedtls/oid.h>
  395. #include <mbedtls/pk.h>
  396. #include <mbedtls/ssl.h>
  397. #include <mbedtls/version.h>
  398. #include <mbedtls/x509_crt.h>
  399. #if MBEDTLS_VERSION_MAJOR >= 4
  400. // Mbed TLS 4.x moved hashing/RNG to PSA Crypto and removed these headers.
  401. #include <psa/crypto.h>
  402. #else
  403. #include <mbedtls/ctr_drbg.h>
  404. #include <mbedtls/entropy.h>
  405. #include <mbedtls/md5.h>
  406. #include <mbedtls/sha1.h>
  407. #include <mbedtls/sha256.h>
  408. #include <mbedtls/sha512.h>
  409. #endif
  410. #ifdef _WIN32
  411. #include <wincrypt.h>
  412. #ifdef _MSC_VER
  413. #pragma comment(lib, "crypt32.lib")
  414. #endif
  415. #endif // _WIN32
  416. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  417. #if TARGET_OS_OSX
  418. #include <Security/Security.h>
  419. #endif
  420. #endif
  421. // Mbed TLS version API compatibility. Note: V4 implies V3 (both defined on
  422. // 4.x), so version-specific 3.x-only code must check V3 && !V4.
  423. #if MBEDTLS_VERSION_MAJOR >= 4
  424. #define CPPHTTPLIB_MBEDTLS_V4
  425. #endif
  426. #if MBEDTLS_VERSION_MAJOR >= 3
  427. #define CPPHTTPLIB_MBEDTLS_V3
  428. #endif
  429. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  430. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  431. #include <wolfssl/options.h>
  432. #include <wolfssl/openssl/x509v3.h>
  433. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  434. #ifndef WOLFSSL_GEN_EMAIL
  435. #define WOLFSSL_GEN_EMAIL 1
  436. #endif
  437. #ifndef WOLFSSL_GEN_DNS
  438. #define WOLFSSL_GEN_DNS 2
  439. #endif
  440. #ifndef WOLFSSL_GEN_URI
  441. #define WOLFSSL_GEN_URI 6
  442. #endif
  443. #ifndef WOLFSSL_GEN_IPADD
  444. #define WOLFSSL_GEN_IPADD 7
  445. #endif
  446. #include <wolfssl/ssl.h>
  447. #include <wolfssl/wolfcrypt/hash.h>
  448. #include <wolfssl/wolfcrypt/md5.h>
  449. #include <wolfssl/wolfcrypt/sha256.h>
  450. #include <wolfssl/wolfcrypt/sha512.h>
  451. #ifdef _WIN32
  452. #include <wincrypt.h>
  453. #ifdef _MSC_VER
  454. #pragma comment(lib, "crypt32.lib")
  455. #endif
  456. #endif // _WIN32
  457. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  458. #if TARGET_OS_OSX
  459. #include <Security/Security.h>
  460. #endif
  461. #endif
  462. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  463. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  464. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  465. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  466. #define CPPHTTPLIB_SSL_ENABLED
  467. #endif
  468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  469. #include <zlib.h>
  470. #endif
  471. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  472. #include <brotli/decode.h>
  473. #include <brotli/encode.h>
  474. #endif
  475. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  476. #include <zstd.h>
  477. #endif
  478. /*
  479. * Declaration
  480. */
  481. namespace httplib {
  482. namespace ws {
  483. class WebSocket;
  484. } // namespace ws
  485. namespace detail {
  486. /*
  487. * Backport std::make_unique from C++14.
  488. *
  489. * NOTE: This code came up with the following stackoverflow post:
  490. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  491. *
  492. */
  493. template <class T, class... Args>
  494. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  495. make_unique(Args &&...args) {
  496. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  497. }
  498. template <class T>
  499. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  500. make_unique(std::size_t n) {
  501. typedef typename std::remove_extent<T>::type RT;
  502. return std::unique_ptr<T>(new RT[n]);
  503. }
  504. // Locale-independent ASCII character classification. The <cctype>
  505. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  506. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  507. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  508. // classified without regard to the locale.
  509. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  510. inline bool is_ascii_alpha(char c) {
  511. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  512. }
  513. inline bool is_ascii_alnum(char c) {
  514. return is_ascii_digit(c) || is_ascii_alpha(c);
  515. }
  516. namespace case_ignore {
  517. inline unsigned char to_lower(int c) {
  518. const static unsigned char table[256] = {
  519. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  520. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  521. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  522. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  523. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  524. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  525. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  526. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  527. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  528. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  529. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  530. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  531. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  532. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  533. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  534. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  535. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  536. 255,
  537. };
  538. return table[(unsigned char)(char)c];
  539. }
  540. inline std::string to_lower(const std::string &s) {
  541. std::string result = s;
  542. std::transform(
  543. result.begin(), result.end(), result.begin(),
  544. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  545. return result;
  546. }
  547. inline bool equal(const std::string &a, const std::string &b) {
  548. return a.size() == b.size() &&
  549. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  550. return to_lower(ca) == to_lower(cb);
  551. });
  552. }
  553. struct equal_to {
  554. bool operator()(const std::string &a, const std::string &b) const {
  555. return equal(a, b);
  556. }
  557. };
  558. struct hash {
  559. size_t operator()(const std::string &key) const {
  560. return hash_core(key.data(), key.size(), 0);
  561. }
  562. size_t hash_core(const char *s, size_t l, size_t h) const {
  563. return (l == 0) ? h
  564. : hash_core(s + 1, l - 1,
  565. // Unsets the 6 high bits of h, therefore no
  566. // overflow happens
  567. (((std::numeric_limits<size_t>::max)() >> 6) &
  568. h * 33) ^
  569. static_cast<unsigned char>(to_lower(*s)));
  570. }
  571. };
  572. template <typename T>
  573. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  574. detail::case_ignore::equal_to>;
  575. } // namespace case_ignore
  576. // This is based on
  577. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  578. struct scope_exit {
  579. explicit scope_exit(std::function<void(void)> &&f)
  580. : exit_function(std::move(f)), execute_on_destruction{true} {}
  581. scope_exit(scope_exit &&rhs) noexcept
  582. : exit_function(std::move(rhs.exit_function)),
  583. execute_on_destruction{rhs.execute_on_destruction} {
  584. rhs.release();
  585. }
  586. ~scope_exit() {
  587. if (execute_on_destruction) { this->exit_function(); }
  588. }
  589. void release() { this->execute_on_destruction = false; }
  590. private:
  591. scope_exit(const scope_exit &) = delete;
  592. void operator=(const scope_exit &) = delete;
  593. scope_exit &operator=(scope_exit &&) = delete;
  594. std::function<void(void)> exit_function;
  595. bool execute_on_destruction;
  596. };
  597. // Simple from_chars implementation for integer and double types (C++17
  598. // substitute)
  599. template <typename T> struct from_chars_result {
  600. const char *ptr;
  601. std::errc ec;
  602. };
  603. template <typename T>
  604. inline from_chars_result<T> from_chars(const char *first, const char *last,
  605. T &value, int base = 10) {
  606. value = 0;
  607. const char *p = first;
  608. bool negative = false;
  609. if (p != last && *p == '-') {
  610. negative = true;
  611. ++p;
  612. }
  613. if (p == last) { return {first, std::errc::invalid_argument}; }
  614. T result = 0;
  615. for (; p != last; ++p) {
  616. char c = *p;
  617. int digit = -1;
  618. if (is_ascii_digit(c)) {
  619. digit = c - '0';
  620. } else if ('a' <= c && c <= 'z') {
  621. digit = c - 'a' + 10;
  622. } else if ('A' <= c && c <= 'Z') {
  623. digit = c - 'A' + 10;
  624. } else {
  625. break;
  626. }
  627. if (digit < 0 || digit >= base) { break; }
  628. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  629. return {p, std::errc::result_out_of_range};
  630. }
  631. result = result * base + digit;
  632. }
  633. if (p == first || (negative && p == first + 1)) {
  634. return {first, std::errc::invalid_argument};
  635. }
  636. value = negative ? T(0) - result : result;
  637. return {p, std::errc{}};
  638. }
  639. // from_chars for double (hand-written, locale-independent)
  640. //
  641. // The only double consumed by this library is the HTTP quality value, whose
  642. // grammar is (RFC 9110 12.4.2):
  643. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  644. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  645. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  646. // '.' always the decimal separator (std::strtod would instead read it from the
  647. // global C locale, mis-parsing q-values once an embedder calls
  648. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  649. // the result to [0, 1], so inputs outside that range need not be distinguished
  650. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  651. // cases that exponent and wide-range handling would introduce.
  652. inline from_chars_result<double> from_chars(const char *first, const char *last,
  653. double &value) {
  654. value = 0.0;
  655. const char *p = first;
  656. // Each 1eN is exactly representable, so a single final division by the
  657. // matching entry yields a correctly-rounded result.
  658. static const double powers_of_ten[] = {
  659. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  660. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  661. const int max_frac_digits =
  662. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  663. // Accumulate digits into a 64-bit integer and remember how many were
  664. // fractional. Two independent caps keep this bounded and safe:
  665. // * accumulation saturates before mantissa could overflow uint64_t, and
  666. // * frac_digits is capped at max_frac_digits so it is always a valid index
  667. // into powers_of_ten (without this an input like "0.000...0" would never
  668. // grow mantissa, so the saturation cap alone would not bound it).
  669. // Both caps only drop digits far beyond the precision a q-value needs; any
  670. // value they would change is well outside [0, 1] and rejected by the caller.
  671. uint64_t mantissa = 0;
  672. int frac_digits = 0;
  673. bool seen_digit = false;
  674. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  675. auto accumulate = [&](char c) {
  676. if (mantissa <= limit) {
  677. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  678. return true;
  679. }
  680. return false;
  681. };
  682. for (; p != last && is_ascii_digit(*p); ++p) {
  683. seen_digit = true;
  684. accumulate(*p);
  685. }
  686. if (p != last && *p == '.') {
  687. ++p;
  688. for (; p != last && is_ascii_digit(*p); ++p) {
  689. seen_digit = true;
  690. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  691. }
  692. }
  693. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  694. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  695. return {p, std::errc{}};
  696. }
  697. inline bool parse_port(const char *s, size_t len, int &port) {
  698. int val = 0;
  699. auto r = from_chars(s, s + len, val);
  700. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  701. port = val;
  702. return true;
  703. }
  704. inline bool parse_port(const std::string &s, int &port) {
  705. return parse_port(s.data(), s.size(), port);
  706. }
  707. struct UrlComponents {
  708. std::string scheme;
  709. std::string host;
  710. std::string port;
  711. std::string path;
  712. std::string query;
  713. };
  714. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  715. uc = {};
  716. size_t pos = 0;
  717. auto sep = url.find("://");
  718. if (sep != std::string::npos) {
  719. uc.scheme = url.substr(0, sep);
  720. // Scheme must be [a-z]+ only
  721. if (uc.scheme.empty()) { return false; }
  722. for (auto c : uc.scheme) {
  723. if (c < 'a' || c > 'z') { return false; }
  724. }
  725. pos = sep + 3;
  726. } else if (url.compare(0, 2, "//") == 0) {
  727. pos = 2;
  728. }
  729. auto has_authority_prefix = pos > 0;
  730. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  731. url[0] != '?' && url[0] != '#');
  732. if (has_authority) {
  733. if (pos < url.size() && url[pos] == '[') {
  734. auto close = url.find(']', pos);
  735. if (close == std::string::npos) { return false; }
  736. uc.host = url.substr(pos + 1, close - pos - 1);
  737. // IPv6 host must be [a-fA-F0-9:]+ only
  738. if (uc.host.empty()) { return false; }
  739. for (auto c : uc.host) {
  740. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  741. (c >= 'A' && c <= 'F') || c == ':')) {
  742. return false;
  743. }
  744. }
  745. pos = close + 1;
  746. // The IPv6 literal is the whole host, so ']' must be followed by a port,
  747. // path, query or fragment delimiter (or the end of input). Otherwise the
  748. // trailing bytes would be folded into the path while the connection
  749. // still targets the bracketed address.
  750. if (pos < url.size()) {
  751. auto c = url[pos];
  752. if (c != ':' && c != '/' && c != '?' && c != '#') { return false; }
  753. }
  754. } else {
  755. auto end = url.find_first_of(":/?#", pos);
  756. if (end == std::string::npos) { end = url.size(); }
  757. uc.host = url.substr(pos, end - pos);
  758. pos = end;
  759. }
  760. if (pos < url.size() && url[pos] == ':') {
  761. ++pos;
  762. auto end = url.find_first_of("/?#", pos);
  763. if (end == std::string::npos) { end = url.size(); }
  764. uc.port = url.substr(pos, end - pos);
  765. pos = end;
  766. }
  767. // Without :// or //, the entire input must be consumed as host[:port].
  768. // If there is leftover (path, query, etc.), this is not a valid
  769. // host[:port] string — clear and reparse as a plain path.
  770. if (!has_authority_prefix && pos < url.size()) {
  771. uc.host.clear();
  772. uc.port.clear();
  773. pos = 0;
  774. }
  775. }
  776. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  777. auto end = url.find_first_of("?#", pos);
  778. if (end == std::string::npos) { end = url.size(); }
  779. uc.path = url.substr(pos, end - pos);
  780. pos = end;
  781. }
  782. if (pos < url.size() && url[pos] == '?') {
  783. auto end = url.find('#', pos);
  784. if (end == std::string::npos) { end = url.size(); }
  785. uc.query = url.substr(pos, end - pos);
  786. }
  787. return true;
  788. }
  789. } // namespace detail
  790. enum class SSLVerifierResponse {
  791. // no decision has been made, use the built-in certificate verifier
  792. NoDecisionMade,
  793. // connection certificate is verified and accepted
  794. CertificateAccepted,
  795. // connection certificate was processed but is rejected
  796. CertificateRejected
  797. };
  798. // System CA loading policy for SSL clients. Auto (the default) loads system
  799. // CA certs only when no custom CA is configured; enable_system_ca() switches
  800. // to an explicit policy.
  801. enum class SystemCAMode { Auto, Enabled, Disabled };
  802. enum StatusCode {
  803. // Information responses
  804. Continue_100 = 100,
  805. SwitchingProtocol_101 = 101,
  806. Processing_102 = 102,
  807. EarlyHints_103 = 103,
  808. // Successful responses
  809. OK_200 = 200,
  810. Created_201 = 201,
  811. Accepted_202 = 202,
  812. NonAuthoritativeInformation_203 = 203,
  813. NoContent_204 = 204,
  814. ResetContent_205 = 205,
  815. PartialContent_206 = 206,
  816. MultiStatus_207 = 207,
  817. AlreadyReported_208 = 208,
  818. IMUsed_226 = 226,
  819. // Redirection messages
  820. MultipleChoices_300 = 300,
  821. MovedPermanently_301 = 301,
  822. Found_302 = 302,
  823. SeeOther_303 = 303,
  824. NotModified_304 = 304,
  825. UseProxy_305 = 305,
  826. unused_306 = 306,
  827. TemporaryRedirect_307 = 307,
  828. PermanentRedirect_308 = 308,
  829. // Client error responses
  830. BadRequest_400 = 400,
  831. Unauthorized_401 = 401,
  832. PaymentRequired_402 = 402,
  833. Forbidden_403 = 403,
  834. NotFound_404 = 404,
  835. MethodNotAllowed_405 = 405,
  836. NotAcceptable_406 = 406,
  837. ProxyAuthenticationRequired_407 = 407,
  838. RequestTimeout_408 = 408,
  839. Conflict_409 = 409,
  840. Gone_410 = 410,
  841. LengthRequired_411 = 411,
  842. PreconditionFailed_412 = 412,
  843. PayloadTooLarge_413 = 413,
  844. UriTooLong_414 = 414,
  845. UnsupportedMediaType_415 = 415,
  846. RangeNotSatisfiable_416 = 416,
  847. ExpectationFailed_417 = 417,
  848. ImATeapot_418 = 418,
  849. MisdirectedRequest_421 = 421,
  850. UnprocessableContent_422 = 422,
  851. Locked_423 = 423,
  852. FailedDependency_424 = 424,
  853. TooEarly_425 = 425,
  854. UpgradeRequired_426 = 426,
  855. PreconditionRequired_428 = 428,
  856. TooManyRequests_429 = 429,
  857. RequestHeaderFieldsTooLarge_431 = 431,
  858. UnavailableForLegalReasons_451 = 451,
  859. // Server error responses
  860. InternalServerError_500 = 500,
  861. NotImplemented_501 = 501,
  862. BadGateway_502 = 502,
  863. ServiceUnavailable_503 = 503,
  864. GatewayTimeout_504 = 504,
  865. HttpVersionNotSupported_505 = 505,
  866. VariantAlsoNegotiates_506 = 506,
  867. InsufficientStorage_507 = 507,
  868. LoopDetected_508 = 508,
  869. NotExtended_510 = 510,
  870. NetworkAuthenticationRequired_511 = 511,
  871. };
  872. namespace detail {
  873. // A multimap that keeps its entries in the order they were inserted.
  874. //
  875. // HTTP needs that order in two places. RFC 9110 5.3 makes the order of header
  876. // fields sharing a field name significant and forbids a proxy from reordering
  877. // them, and a query string's parameters are meaningful in the order the caller
  878. // wrote them. Neither standard container expresses it: std::unordered_multimap
  879. // gives no ordering guarantee at all for equivalent keys (libstdc++ yields
  880. // reverse insertion order, libc++ insertion order), and std::multimap sorts by
  881. // key, which would drop control data such as Host behind whatever else the
  882. // message carries and alphabetise a query string.
  883. //
  884. // Entries are therefore kept in a flat vector, in order. Lookup is a linear
  885. // scan, which beats hashing for the handful of entries a message carries
  886. // (headers are capped at CPPHTTPLIB_HEADER_MAX_COUNT).
  887. //
  888. // KeyEqual compares keys; it is what makes Headers case-insensitive and
  889. // Params, whose parameter names are case-sensitive, not.
  890. template <typename Mapped, typename KeyEqual> class insertion_ordered_multimap {
  891. public:
  892. using key_type = std::string;
  893. using mapped_type = Mapped;
  894. using value_type = std::pair<std::string, Mapped>;
  895. using size_type = std::size_t;
  896. using difference_type = std::ptrdiff_t;
  897. using reference = value_type &;
  898. using const_reference = const value_type &;
  899. private:
  900. static size_type npos() { return static_cast<size_type>(-1); }
  901. static bool keys_equal(const std::string &a, const std::string &b) {
  902. return KeyEqual()(a, b);
  903. }
  904. // Iterating yields every entry in insertion order, but equal_range() and
  905. // find() have to walk only the entries sharing one key, which are not
  906. // adjacent. Both are the same iterator type: key_idx_ selects between the
  907. // two traversals, and since equality compares only the position, an iterator
  908. // restricted to one key still compares equal to end().
  909. template <typename V> class iterator_t {
  910. public:
  911. using iterator_category = std::bidirectional_iterator_tag;
  912. using value_type = insertion_ordered_multimap::value_type;
  913. using difference_type = insertion_ordered_multimap::difference_type;
  914. using pointer = V *;
  915. using reference = V &;
  916. iterator_t() : data_(nullptr), idx_(0), size_(0), key_idx_(npos()) {}
  917. template <typename U,
  918. typename std::enable_if<std::is_convertible<U *, V *>::value,
  919. int>::type = 0>
  920. iterator_t(const iterator_t<U> &rhs)
  921. : data_(rhs.data_), idx_(rhs.idx_), size_(rhs.size_),
  922. key_idx_(rhs.key_idx_) {}
  923. reference operator*() const { return data_[idx_]; }
  924. pointer operator->() const { return data_ + idx_; }
  925. iterator_t &operator++() {
  926. // Saturating, so that advancing past the last entry of a key (which
  927. // get_multimap_value() does when asked for an out-of-range id) stays at
  928. // end() instead of running off the container.
  929. if (idx_ >= size_) { return *this; }
  930. ++idx_;
  931. if (key_idx_ != npos()) {
  932. while (idx_ < size_ && !matches(idx_)) {
  933. ++idx_;
  934. }
  935. }
  936. return *this;
  937. }
  938. iterator_t operator++(int) {
  939. auto tmp = *this;
  940. ++*this;
  941. return tmp;
  942. }
  943. iterator_t &operator--() {
  944. if (idx_ == 0) { return *this; }
  945. --idx_;
  946. if (key_idx_ != npos()) {
  947. while (idx_ > 0 && !matches(idx_)) {
  948. --idx_;
  949. }
  950. }
  951. return *this;
  952. }
  953. iterator_t operator--(int) {
  954. auto tmp = *this;
  955. --*this;
  956. return tmp;
  957. }
  958. template <typename U> bool operator==(const iterator_t<U> &rhs) const {
  959. return idx_ == rhs.idx_;
  960. }
  961. template <typename U> bool operator!=(const iterator_t<U> &rhs) const {
  962. return idx_ != rhs.idx_;
  963. }
  964. private:
  965. friend class insertion_ordered_multimap;
  966. template <typename> friend class iterator_t;
  967. iterator_t(V *data, size_type idx, size_type size, size_type key_idx)
  968. : data_(data), idx_(idx), size_(size), key_idx_(key_idx) {}
  969. bool matches(size_type i) const {
  970. return keys_equal(data_[i].first, data_[key_idx_].first);
  971. }
  972. V *data_;
  973. size_type idx_;
  974. size_type size_;
  975. size_type key_idx_;
  976. };
  977. public:
  978. using iterator = iterator_t<value_type>;
  979. using const_iterator = iterator_t<const value_type>;
  980. insertion_ordered_multimap() = default;
  981. insertion_ordered_multimap(std::initializer_list<value_type> il)
  982. : entries_(il) {}
  983. template <typename InputIt>
  984. insertion_ordered_multimap(InputIt first, InputIt last)
  985. : entries_(first, last) {}
  986. iterator begin() { return make_iter(0, npos()); }
  987. iterator end() { return make_iter(entries_.size(), npos()); }
  988. const_iterator begin() const { return make_citer(0, npos()); }
  989. const_iterator end() const { return make_citer(entries_.size(), npos()); }
  990. const_iterator cbegin() const { return begin(); }
  991. const_iterator cend() const { return end(); }
  992. bool empty() const { return entries_.empty(); }
  993. size_type size() const { return entries_.size(); }
  994. void clear() { entries_.clear(); }
  995. void swap(insertion_ordered_multimap &rhs) { entries_.swap(rhs.entries_); }
  996. iterator insert(const value_type &val) {
  997. entries_.push_back(val);
  998. return make_iter(entries_.size() - 1, npos());
  999. }
  1000. iterator insert(value_type &&val) {
  1001. entries_.push_back(std::move(val));
  1002. return make_iter(entries_.size() - 1, npos());
  1003. }
  1004. template <typename... Args> iterator emplace(Args &&...args) {
  1005. entries_.emplace_back(std::forward<Args>(args)...);
  1006. return make_iter(entries_.size() - 1, npos());
  1007. }
  1008. // For entries that have to lead the message, such as the Host header field
  1009. // (RFC 9110 5.3 recommends sending control data first).
  1010. template <typename... Args> iterator emplace_front(Args &&...args) {
  1011. entries_.emplace(entries_.begin(), std::forward<Args>(args)...);
  1012. return make_iter(0, npos());
  1013. }
  1014. iterator find(const std::string &key) {
  1015. auto i = index_of(key);
  1016. return i == npos() ? end() : make_iter(i, i);
  1017. }
  1018. const_iterator find(const std::string &key) const {
  1019. auto i = index_of(key);
  1020. return i == npos() ? end() : make_citer(i, i);
  1021. }
  1022. size_type count(const std::string &key) const {
  1023. size_type n = 0;
  1024. for (const auto &entry : entries_) {
  1025. if (keys_equal(entry.first, key)) { n++; }
  1026. }
  1027. return n;
  1028. }
  1029. std::pair<iterator, iterator> equal_range(const std::string &key) {
  1030. auto i = index_of(key);
  1031. return i == npos() ? std::make_pair(end(), end())
  1032. : std::make_pair(make_iter(i, i), end());
  1033. }
  1034. std::pair<const_iterator, const_iterator>
  1035. equal_range(const std::string &key) const {
  1036. auto i = index_of(key);
  1037. return i == npos() ? std::make_pair(end(), end())
  1038. : std::make_pair(make_citer(i, i), end());
  1039. }
  1040. size_type erase(const std::string &key) {
  1041. auto before = entries_.size();
  1042. entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
  1043. [&](const value_type &entry) {
  1044. return keys_equal(entry.first, key);
  1045. }),
  1046. entries_.end());
  1047. return before - entries_.size();
  1048. }
  1049. iterator erase(const_iterator pos) {
  1050. entries_.erase(entries_.begin() + static_cast<difference_type>(pos.idx_));
  1051. return make_iter(pos.idx_, npos());
  1052. }
  1053. // Erases what iterating [first, last) would actually visit, so erasing an
  1054. // equal_range() removes only the entries with that key, not everything
  1055. // positioned between them.
  1056. iterator erase(const_iterator first, const_iterator last) {
  1057. auto from = first.idx_;
  1058. auto to = last.idx_;
  1059. if (from >= to) { return make_iter(from, npos()); }
  1060. auto begin_it = entries_.begin();
  1061. auto from_it = begin_it + static_cast<difference_type>(from);
  1062. auto to_it = begin_it + static_cast<difference_type>(to);
  1063. if (first.key_idx_ == npos()) {
  1064. entries_.erase(from_it, to_it);
  1065. } else {
  1066. auto key = entries_[first.key_idx_].first;
  1067. auto keep = from_it;
  1068. for (auto it = from_it; it != to_it; ++it) {
  1069. if (!keys_equal(it->first, key)) {
  1070. if (keep != it) { *keep = std::move(*it); }
  1071. ++keep;
  1072. }
  1073. }
  1074. if (keep != to_it) {
  1075. keep = std::move(to_it, entries_.end(), keep);
  1076. } else {
  1077. keep = entries_.end();
  1078. }
  1079. entries_.erase(keep, entries_.end());
  1080. }
  1081. return make_iter(from, npos());
  1082. }
  1083. friend bool operator==(const insertion_ordered_multimap &lhs,
  1084. const insertion_ordered_multimap &rhs) {
  1085. return lhs.entries_ == rhs.entries_;
  1086. }
  1087. friend bool operator!=(const insertion_ordered_multimap &lhs,
  1088. const insertion_ordered_multimap &rhs) {
  1089. return !(lhs == rhs);
  1090. }
  1091. private:
  1092. size_type index_of(const std::string &key) const {
  1093. for (size_type i = 0; i < entries_.size(); i++) {
  1094. if (keys_equal(entries_[i].first, key)) { return i; }
  1095. }
  1096. return npos();
  1097. }
  1098. iterator make_iter(size_type idx, size_type key_idx) {
  1099. return iterator(entries_.data(), idx, entries_.size(), key_idx);
  1100. }
  1101. const_iterator make_citer(size_type idx, size_type key_idx) const {
  1102. return const_iterator(entries_.data(), idx, entries_.size(), key_idx);
  1103. }
  1104. std::vector<value_type> entries_;
  1105. };
  1106. } // namespace detail
  1107. using Headers =
  1108. detail::insertion_ordered_multimap<std::string,
  1109. detail::case_ignore::equal_to>;
  1110. // Query parameter names are case-sensitive, unlike header field names.
  1111. using Params =
  1112. detail::insertion_ordered_multimap<std::string, std::equal_to<std::string>>;
  1113. using Match = std::smatch;
  1114. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  1115. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  1116. /*
  1117. * detail: type-erased storage used by UserData.
  1118. * ABI-stable regardless of C++ standard — always uses this custom
  1119. * implementation instead of std::any.
  1120. */
  1121. namespace detail {
  1122. using any_type_id = const void *;
  1123. template <typename T> any_type_id any_typeid() noexcept {
  1124. static const char id = 0;
  1125. return &id;
  1126. }
  1127. struct any_storage {
  1128. virtual ~any_storage() = default;
  1129. virtual std::unique_ptr<any_storage> clone() const = 0;
  1130. virtual any_type_id type_id() const noexcept = 0;
  1131. };
  1132. template <typename T> struct any_value final : any_storage {
  1133. T value;
  1134. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  1135. std::unique_ptr<any_storage> clone() const override {
  1136. return std::unique_ptr<any_storage>(new any_value<T>(value));
  1137. }
  1138. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  1139. };
  1140. } // namespace detail
  1141. class UserData {
  1142. public:
  1143. UserData() = default;
  1144. UserData(UserData &&) noexcept = default;
  1145. UserData &operator=(UserData &&) noexcept = default;
  1146. UserData(const UserData &o) {
  1147. for (const auto &e : o.entries_) {
  1148. if (e.second) { entries_[e.first] = e.second->clone(); }
  1149. }
  1150. }
  1151. UserData &operator=(const UserData &o) {
  1152. if (this != &o) {
  1153. entries_.clear();
  1154. for (const auto &e : o.entries_) {
  1155. if (e.second) { entries_[e.first] = e.second->clone(); }
  1156. }
  1157. }
  1158. return *this;
  1159. }
  1160. template <typename T> void set(const std::string &key, T &&value) {
  1161. using D = typename std::decay<T>::type;
  1162. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  1163. }
  1164. template <typename T> T *get(const std::string &key) noexcept {
  1165. auto it = entries_.find(key);
  1166. if (it == entries_.end() || !it->second) { return nullptr; }
  1167. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1168. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  1169. }
  1170. template <typename T> const T *get(const std::string &key) const noexcept {
  1171. auto it = entries_.find(key);
  1172. if (it == entries_.end() || !it->second) { return nullptr; }
  1173. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1174. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  1175. }
  1176. bool has(const std::string &key) const noexcept {
  1177. return entries_.find(key) != entries_.end();
  1178. }
  1179. void erase(const std::string &key) { entries_.erase(key); }
  1180. void clear() noexcept { entries_.clear(); }
  1181. private:
  1182. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  1183. entries_;
  1184. };
  1185. struct Response;
  1186. using ResponseHandler = std::function<bool(const Response &response)>;
  1187. struct FormData {
  1188. std::string name;
  1189. std::string content;
  1190. std::string filename;
  1191. std::string content_type;
  1192. Headers headers;
  1193. };
  1194. struct FormField {
  1195. std::string name;
  1196. std::string content;
  1197. Headers headers;
  1198. };
  1199. // RFC 7578 5.2: a form processor "SHOULD send back results in order" and
  1200. // "Intermediaries MUST NOT reorder the results", so a handler walking these
  1201. // should see the parts as they were sent. A std::multimap sorts by field name
  1202. // and loses that. Field names are case-sensitive, hence std::equal_to rather
  1203. // than the case-insensitive predicate Headers uses.
  1204. using FormFields =
  1205. detail::insertion_ordered_multimap<FormField, std::equal_to<std::string>>;
  1206. using FormFiles =
  1207. detail::insertion_ordered_multimap<FormData, std::equal_to<std::string>>;
  1208. struct MultipartFormData {
  1209. FormFields fields; // Text fields from multipart
  1210. FormFiles files; // Files from multipart
  1211. // Text field access
  1212. std::string get_field(const std::string &key, size_t id = 0) const;
  1213. std::vector<std::string> get_fields(const std::string &key) const;
  1214. bool has_field(const std::string &key) const;
  1215. size_t get_field_count(const std::string &key) const;
  1216. // File access
  1217. FormData get_file(const std::string &key, size_t id = 0) const;
  1218. std::vector<FormData> get_files(const std::string &key) const;
  1219. bool has_file(const std::string &key) const;
  1220. size_t get_file_count(const std::string &key) const;
  1221. };
  1222. struct UploadFormData {
  1223. std::string name;
  1224. std::string content;
  1225. std::string filename;
  1226. std::string content_type;
  1227. };
  1228. using UploadFormDataItems = std::vector<UploadFormData>;
  1229. class DataSink {
  1230. public:
  1231. DataSink() : os(&sb_), sb_(*this) {}
  1232. DataSink(const DataSink &) = delete;
  1233. DataSink &operator=(const DataSink &) = delete;
  1234. DataSink(DataSink &&) = delete;
  1235. DataSink &operator=(DataSink &&) = delete;
  1236. std::function<bool(const char *data, size_t data_len)> write;
  1237. // Only `write` is mandatory. The rest are defaulted so that a provider
  1238. // calling one on a writer that does not set it gets sensible behaviour
  1239. // rather than std::bad_function_call thrown from a worker thread. Capturing
  1240. // `this` is safe: DataSink is neither copyable nor movable.
  1241. std::function<bool()> is_writable = []() { return true; };
  1242. std::function<void()> done = []() {};
  1243. std::function<void(const Headers &trailer)> done_with_trailer =
  1244. [this](const Headers & /*trailer*/) { done(); };
  1245. std::ostream os;
  1246. private:
  1247. class data_sink_streambuf final : public std::streambuf {
  1248. public:
  1249. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  1250. protected:
  1251. std::streamsize xsputn(const char *s, std::streamsize n) override {
  1252. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  1253. return 0;
  1254. }
  1255. private:
  1256. DataSink &sink_;
  1257. };
  1258. data_sink_streambuf sb_;
  1259. };
  1260. using ContentProvider =
  1261. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  1262. using ContentProviderWithoutLength =
  1263. std::function<bool(size_t offset, DataSink &sink)>;
  1264. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  1265. struct FormDataProvider {
  1266. std::string name;
  1267. ContentProviderWithoutLength provider;
  1268. std::string filename;
  1269. std::string content_type;
  1270. };
  1271. using FormDataProviderItems = std::vector<FormDataProvider>;
  1272. inline FormDataProvider
  1273. make_file_provider(const std::string &name, const std::string &filepath,
  1274. const std::string &filename = std::string(),
  1275. const std::string &content_type = std::string()) {
  1276. FormDataProvider fdp;
  1277. fdp.name = name;
  1278. fdp.filename = filename.empty() ? filepath : filename;
  1279. fdp.content_type = content_type;
  1280. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  1281. std::ifstream f(filepath, std::ios::binary);
  1282. if (!f) { return false; }
  1283. if (offset > 0) {
  1284. f.seekg(static_cast<std::streamoff>(offset));
  1285. if (!f.good()) {
  1286. sink.done();
  1287. return true;
  1288. }
  1289. }
  1290. char buf[8192];
  1291. f.read(buf, sizeof(buf));
  1292. auto n = static_cast<size_t>(f.gcount());
  1293. if (n > 0) { return sink.write(buf, n); }
  1294. sink.done(); // EOF
  1295. return true;
  1296. };
  1297. return fdp;
  1298. }
  1299. inline std::pair<size_t, ContentProvider>
  1300. make_file_body(const std::string &filepath) {
  1301. size_t size = 0;
  1302. {
  1303. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  1304. if (!f) { return {0, ContentProvider{}}; }
  1305. size = static_cast<size_t>(f.tellg());
  1306. }
  1307. ContentProvider provider = [filepath](size_t offset, size_t length,
  1308. DataSink &sink) -> bool {
  1309. std::ifstream f(filepath, std::ios::binary);
  1310. if (!f) { return false; }
  1311. f.seekg(static_cast<std::streamoff>(offset));
  1312. if (!f.good()) { return false; }
  1313. char buf[8192];
  1314. while (length > 0) {
  1315. auto to_read = (std::min)(sizeof(buf), length);
  1316. f.read(buf, static_cast<std::streamsize>(to_read));
  1317. auto n = static_cast<size_t>(f.gcount());
  1318. // The file is shorter than the size make_file_body() measured, which the
  1319. // caller has already committed to as Content-Length. The body cannot be
  1320. // completed, so fail as every other error here does.
  1321. if (n == 0) { return false; }
  1322. if (!sink.write(buf, n)) { return false; }
  1323. length -= n;
  1324. }
  1325. return true;
  1326. };
  1327. return {size, std::move(provider)};
  1328. }
  1329. using ContentReceiverWithProgress = std::function<bool(
  1330. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1331. using ContentReceiver =
  1332. std::function<bool(const char *data, size_t data_length)>;
  1333. using FormDataHeader = std::function<bool(const FormData &file)>;
  1334. class ContentReader {
  1335. public:
  1336. using Reader = std::function<bool(ContentReceiver receiver)>;
  1337. using FormDataReader =
  1338. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1339. ContentReader(Reader reader, FormDataReader multipart_reader)
  1340. : reader_(std::move(reader)),
  1341. formdata_reader_(std::move(multipart_reader)) {}
  1342. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1343. return formdata_reader_(std::move(header), std::move(receiver));
  1344. }
  1345. bool operator()(ContentReceiver receiver) const {
  1346. return reader_(std::move(receiver));
  1347. }
  1348. Reader reader_;
  1349. FormDataReader formdata_reader_;
  1350. };
  1351. using Range = std::pair<ssize_t, ssize_t>;
  1352. using Ranges = std::vector<Range>;
  1353. #ifdef CPPHTTPLIB_SSL_ENABLED
  1354. // TLS abstraction layer - public type definitions and API
  1355. namespace tls {
  1356. // Opaque handles (defined as void* for abstraction)
  1357. using ctx_t = void *;
  1358. using session_t = void *;
  1359. using const_session_t = const void *; // For read-only session access
  1360. using cert_t = void *;
  1361. using ca_store_t = void *;
  1362. // TLS versions
  1363. enum class Version {
  1364. TLS1_2 = 0x0303,
  1365. TLS1_3 = 0x0304,
  1366. };
  1367. // Subject Alternative Names (SAN) entry types
  1368. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1369. // SAN entry structure
  1370. struct SanEntry {
  1371. SanType type;
  1372. std::string value;
  1373. };
  1374. // Verification context for certificate verification callback
  1375. struct VerifyContext {
  1376. session_t session; // TLS session handle
  1377. cert_t cert; // Current certificate being verified
  1378. int depth; // Certificate chain depth (0 = leaf)
  1379. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1380. long error_code; // Backend-specific error code (0 = no error)
  1381. const char *error_string; // Human-readable error description
  1382. // Certificate introspection methods
  1383. std::string subject_cn() const;
  1384. std::string issuer_name() const;
  1385. bool check_hostname(const char *hostname) const;
  1386. std::vector<SanEntry> sans() const;
  1387. bool validity(time_t &not_before, time_t &not_after) const;
  1388. std::string serial() const;
  1389. };
  1390. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1391. // TlsError codes for TLS operations (backend-independent)
  1392. enum class ErrorCode : int {
  1393. Success = 0,
  1394. WantRead, // Non-blocking: need to wait for read
  1395. WantWrite, // Non-blocking: need to wait for write
  1396. PeerClosed, // Peer closed the connection
  1397. Fatal, // Unrecoverable error
  1398. SyscallError, // System call error (check sys_errno)
  1399. CertVerifyFailed, // Certificate verification failed
  1400. HostnameMismatch, // Hostname verification failed
  1401. };
  1402. // TLS error information
  1403. struct TlsError {
  1404. ErrorCode code = ErrorCode::Fatal;
  1405. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1406. int sys_errno = 0; // errno when SyscallError
  1407. // Convert verification error code to human-readable string
  1408. static std::string verify_error_to_string(long error_code);
  1409. };
  1410. // RAII wrapper for peer certificate
  1411. class PeerCert {
  1412. public:
  1413. PeerCert();
  1414. PeerCert(PeerCert &&other) noexcept;
  1415. PeerCert &operator=(PeerCert &&other) noexcept;
  1416. ~PeerCert();
  1417. PeerCert(const PeerCert &) = delete;
  1418. PeerCert &operator=(const PeerCert &) = delete;
  1419. explicit operator bool() const;
  1420. std::string subject_cn() const;
  1421. std::string issuer_name() const;
  1422. bool check_hostname(const char *hostname) const;
  1423. std::vector<SanEntry> sans() const;
  1424. bool validity(time_t &not_before, time_t &not_after) const;
  1425. std::string serial() const;
  1426. private:
  1427. explicit PeerCert(cert_t cert);
  1428. cert_t cert_ = nullptr;
  1429. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1430. };
  1431. // Callback for TLS context setup (used by SSLServer constructor)
  1432. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1433. } // namespace tls
  1434. #endif
  1435. struct Request {
  1436. std::string method;
  1437. std::string path;
  1438. std::string matched_route;
  1439. Params params;
  1440. Headers headers;
  1441. Headers trailers;
  1442. std::string body;
  1443. std::string remote_addr;
  1444. int remote_port = -1;
  1445. std::string local_addr;
  1446. int local_port = -1;
  1447. // for server
  1448. std::string version;
  1449. std::string target;
  1450. MultipartFormData form;
  1451. Ranges ranges;
  1452. Match matches;
  1453. std::unordered_map<std::string, std::string> path_params;
  1454. std::function<bool()> is_connection_closed = []() { return true; };
  1455. // for client
  1456. std::vector<std::string> accept_content_types;
  1457. ResponseHandler response_handler;
  1458. ContentReceiverWithProgress content_receiver;
  1459. DownloadProgress download_progress;
  1460. UploadProgress upload_progress;
  1461. bool has_header(const std::string &key) const;
  1462. std::string get_header_value(const std::string &key, const char *def = "",
  1463. size_t id = 0) const;
  1464. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1465. size_t id = 0) const;
  1466. size_t get_header_value_count(const std::string &key) const;
  1467. void set_header(const std::string &key, const std::string &val);
  1468. bool has_trailer(const std::string &key) const;
  1469. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1470. size_t get_trailer_value_count(const std::string &key) const;
  1471. bool has_param(const std::string &key) const;
  1472. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1473. std::vector<std::string> get_param_values(const std::string &key) const;
  1474. size_t get_param_value_count(const std::string &key) const;
  1475. bool is_multipart_form_data() const;
  1476. // private members...
  1477. bool body_consumed_ = false;
  1478. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1479. size_t content_length_ = 0;
  1480. ContentProvider content_provider_;
  1481. bool is_chunked_content_provider_ = false;
  1482. size_t authorization_count_ = 0;
  1483. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1484. (std::chrono::steady_clock::time_point::min)();
  1485. #ifdef CPPHTTPLIB_SSL_ENABLED
  1486. tls::const_session_t ssl = nullptr;
  1487. tls::PeerCert peer_cert() const;
  1488. std::string sni() const;
  1489. #endif
  1490. };
  1491. namespace detail {
  1492. // Declared up here, away from the rest of the compression helpers, because
  1493. // `Response` stores one.
  1494. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1495. } // namespace detail
  1496. struct Response {
  1497. std::string version;
  1498. int status = -1;
  1499. std::string reason;
  1500. Headers headers;
  1501. Headers trailers;
  1502. std::string body;
  1503. std::string location; // Redirect location
  1504. // User-defined context — set by pre-routing/pre-request handlers and read
  1505. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1506. UserData user_data;
  1507. bool has_header(const std::string &key) const;
  1508. std::string get_header_value(const std::string &key, const char *def = "",
  1509. size_t id = 0) const;
  1510. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1511. size_t id = 0) const;
  1512. size_t get_header_value_count(const std::string &key) const;
  1513. void set_header(const std::string &key, const std::string &val);
  1514. bool has_trailer(const std::string &key) const;
  1515. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1516. size_t get_trailer_value_count(const std::string &key) const;
  1517. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1518. void set_content(const char *s, size_t n, const std::string &content_type);
  1519. void set_content(const std::string &s, const std::string &content_type);
  1520. void set_content(std::string &&s, const std::string &content_type);
  1521. void set_content_provider(
  1522. size_t length, const std::string &content_type, ContentProvider provider,
  1523. ContentProviderResourceReleaser resource_releaser = nullptr);
  1524. void set_content_provider(
  1525. const std::string &content_type, ContentProviderWithoutLength provider,
  1526. ContentProviderResourceReleaser resource_releaser = nullptr);
  1527. void set_chunked_content_provider(
  1528. const std::string &content_type, ContentProviderWithoutLength provider,
  1529. ContentProviderResourceReleaser resource_releaser = nullptr);
  1530. void set_file_content(const std::string &path,
  1531. const std::string &content_type);
  1532. void set_file_content(const std::string &path);
  1533. Response() = default;
  1534. Response(const Response &) = default;
  1535. Response &operator=(const Response &) = default;
  1536. Response(Response &&) = default;
  1537. Response &operator=(Response &&) = default;
  1538. ~Response() {
  1539. if (content_provider_resource_releaser_) {
  1540. content_provider_resource_releaser_(content_provider_success_);
  1541. }
  1542. }
  1543. // private members...
  1544. size_t content_length_ = 0;
  1545. ContentProvider content_provider_;
  1546. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1547. bool is_chunked_content_provider_ = false;
  1548. bool content_provider_success_ = false;
  1549. std::string file_content_path_;
  1550. std::string file_content_content_type_;
  1551. // Content coding chosen for the response body, decided once so that the
  1552. // headers and the body cannot disagree: where the file is opened for a
  1553. // file-backed content provider (keeping the ETag honest), and in
  1554. // `apply_ranges()` for a chunked content provider. `EncodingType::None`
  1555. // for every other kind of response.
  1556. detail::EncodingType content_coding_ = detail::EncodingType::None;
  1557. };
  1558. enum class Error {
  1559. Success = 0,
  1560. Unknown,
  1561. Connection,
  1562. BindIPAddress,
  1563. Read,
  1564. Write,
  1565. ExceedRedirectCount,
  1566. Canceled,
  1567. SSLConnection,
  1568. SSLLoadingCerts,
  1569. SSLServerVerification,
  1570. SSLServerHostnameVerification,
  1571. UnsupportedMultipartBoundaryChars,
  1572. Compression,
  1573. ConnectionTimeout,
  1574. ProxyConnection,
  1575. ConnectionClosed,
  1576. Timeout,
  1577. ResourceExhaustion,
  1578. TooManyFormDataFiles,
  1579. ExceedMaxPayloadSize,
  1580. ExceedUriMaxLength,
  1581. ExceedMaxSocketDescriptorCount,
  1582. InvalidRequestLine,
  1583. InvalidHTTPMethod,
  1584. InvalidHTTPVersion,
  1585. InvalidHeaders,
  1586. MultipartParsing,
  1587. OpenFile,
  1588. Listen,
  1589. GetSockName,
  1590. UnsupportedAddressFamily,
  1591. HTTPParsing,
  1592. InvalidRangeHeader,
  1593. UnsupportedContentEncoding,
  1594. WebSocketHandshake,
  1595. UserCallbackException,
  1596. // For internal use only
  1597. SSLPeerCouldBeClosed_,
  1598. };
  1599. std::string to_string(Error error);
  1600. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1601. class Stream {
  1602. public:
  1603. virtual ~Stream() = default;
  1604. virtual bool is_readable() const = 0;
  1605. virtual bool wait_readable() const = 0;
  1606. virtual bool wait_writable() const = 0;
  1607. virtual bool is_peer_alive() const { return wait_writable(); }
  1608. virtual ssize_t read(char *ptr, size_t size) = 0;
  1609. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1610. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1611. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1612. virtual socket_t socket() const = 0;
  1613. virtual time_t duration() const = 0;
  1614. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1615. (void)sec;
  1616. (void)usec;
  1617. }
  1618. // Bytes already pulled off the socket and sitting in this stream's own
  1619. // buffer. Exposing them lets a line reader scan for a terminator in one
  1620. // pass instead of asking for a byte at a time. A stream that does no
  1621. // buffering of its own reports none, and readers fall back to read().
  1622. virtual const char *buffered_data(size_t &size) const {
  1623. size = 0;
  1624. return nullptr;
  1625. }
  1626. // Discards `size` bytes previously returned by buffered_data().
  1627. virtual void consume_buffered(size_t size) { (void)size; }
  1628. ssize_t write(const char *ptr);
  1629. ssize_t write(const std::string &s);
  1630. Error get_error() const { return error_; }
  1631. protected:
  1632. Error error_ = Error::Success;
  1633. };
  1634. class TaskQueue {
  1635. public:
  1636. TaskQueue() = default;
  1637. virtual ~TaskQueue() = default;
  1638. virtual bool enqueue(std::function<void()> fn) = 0;
  1639. virtual void shutdown() = 0;
  1640. virtual void on_idle() {}
  1641. };
  1642. class ThreadPool final : public TaskQueue {
  1643. public:
  1644. explicit ThreadPool(
  1645. size_t n, size_t max_n = 0, size_t mqr = 0,
  1646. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1647. ThreadPool(const ThreadPool &) = delete;
  1648. ~ThreadPool() override = default;
  1649. bool enqueue(std::function<void()> fn) override;
  1650. void shutdown() override;
  1651. private:
  1652. void worker(bool is_dynamic);
  1653. void move_to_finished(std::thread::id id);
  1654. void cleanup_finished_threads();
  1655. size_t base_thread_count_;
  1656. size_t max_thread_count_;
  1657. size_t max_queued_requests_;
  1658. time_t idle_timeout_sec_;
  1659. size_t idle_thread_count_;
  1660. bool shutdown_;
  1661. std::list<std::function<void()>> jobs_;
  1662. std::vector<std::thread> threads_; // base threads
  1663. std::list<std::thread> dynamic_threads_; // dynamic threads
  1664. std::vector<std::thread>
  1665. finished_threads_; // exited dynamic threads awaiting join
  1666. std::condition_variable cond_;
  1667. std::mutex mutex_;
  1668. };
  1669. using Logger = std::function<void(const Request &, const Response &)>;
  1670. // Forward declaration for Error type
  1671. enum class Error;
  1672. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1673. using SocketOptions = std::function<void(socket_t sock)>;
  1674. void default_socket_options(socket_t sock);
  1675. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1676. const char *status_message(int status);
  1677. std::string to_string(Error error);
  1678. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1679. std::string get_bearer_token_auth(const Request &req);
  1680. namespace detail {
  1681. class MatcherBase {
  1682. public:
  1683. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1684. virtual ~MatcherBase() = default;
  1685. const std::string &pattern() const { return pattern_; }
  1686. // Match request path and populate its matches and
  1687. virtual bool match(Request &request) const = 0;
  1688. private:
  1689. std::string pattern_;
  1690. };
  1691. /**
  1692. * Captures parameters in request path and stores them in Request::path_params
  1693. *
  1694. * Capture name is a substring of a pattern from : to /.
  1695. * The rest of the pattern is matched against the request path directly
  1696. * Parameters are captured starting from the next character after
  1697. * the end of the last matched static pattern fragment until the next /.
  1698. *
  1699. * Example pattern:
  1700. * "/path/fragments/:capture/more/fragments/:second_capture"
  1701. * Static fragments:
  1702. * "/path/fragments/", "more/fragments/"
  1703. *
  1704. * Given the following request path:
  1705. * "/path/fragments/:1/more/fragments/:2"
  1706. * the resulting capture will be
  1707. * {{"capture", "1"}, {"second_capture", "2"}}
  1708. */
  1709. class PathParamsMatcher final : public MatcherBase {
  1710. public:
  1711. PathParamsMatcher(const std::string &pattern);
  1712. bool match(Request &request) const override;
  1713. private:
  1714. // Treat segment separators as the end of path parameter capture
  1715. // Does not need to handle query parameters as they are parsed before path
  1716. // matching
  1717. static constexpr char separator = '/';
  1718. // Contains static path fragments to match against, excluding the '/' after
  1719. // path params
  1720. // Fragments are separated by path params
  1721. std::vector<std::string> static_fragments_;
  1722. // Stores the names of the path parameters to be used as keys in the
  1723. // Request::path_params map
  1724. std::vector<std::string> param_names_;
  1725. };
  1726. /**
  1727. * Performs std::regex_match on request path
  1728. * and stores the result in Request::matches
  1729. *
  1730. * Note that regex match is performed directly on the whole request.
  1731. * This means that wildcard patterns may match multiple path segments with /:
  1732. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1733. */
  1734. class RegexMatcher final : public MatcherBase {
  1735. public:
  1736. RegexMatcher(const std::string &pattern)
  1737. : MatcherBase(pattern), regex_(pattern) {}
  1738. bool match(Request &request) const override;
  1739. private:
  1740. std::regex regex_;
  1741. };
  1742. int close_socket(socket_t sock) noexcept;
  1743. bool is_accept_resource_error();
  1744. bool is_accept_transient_error();
  1745. ssize_t write_headers(Stream &strm, const Headers &headers);
  1746. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1747. time_t usec);
  1748. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1749. const std::string &boundary);
  1750. ContentProvider
  1751. make_multipart_content_provider(const UploadFormDataItems &items,
  1752. const std::string &boundary);
  1753. } // namespace detail
  1754. bool is_valid_multipart_boundary(const std::string &boundary);
  1755. // Serializer for multipart/form-data request bodies. The boundary is owned
  1756. // by the writer so that per-part framing and the final terminator always
  1757. // agree. Field names and filenames are escaped following the WHATWG HTML
  1758. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1759. // in content types.
  1760. class MultipartFormDataWriter {
  1761. public:
  1762. MultipartFormDataWriter();
  1763. // precondition: is_valid_multipart_boundary(boundary)
  1764. explicit MultipartFormDataWriter(std::string boundary);
  1765. const std::string &boundary() const;
  1766. std::string content_type() const;
  1767. // In-memory items -> whole body (known length)
  1768. std::string serialize(const UploadFormDataItems &items) const;
  1769. size_t content_length(const UploadFormDataItems &items) const;
  1770. // Per-part framing for streaming via a content provider
  1771. std::string item_begin(const UploadFormData &item) const;
  1772. static std::string item_end();
  1773. std::string finish() const;
  1774. private:
  1775. std::string boundary_;
  1776. };
  1777. class Server {
  1778. public:
  1779. using Handler = std::function<void(const Request &, Response &)>;
  1780. using ExceptionHandler =
  1781. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1782. enum class HandlerResponse {
  1783. Handled,
  1784. Unhandled,
  1785. };
  1786. using HandlerWithResponse =
  1787. std::function<HandlerResponse(const Request &, Response &)>;
  1788. using HandlerWithContentReader = std::function<void(
  1789. const Request &, Response &, const ContentReader &content_reader)>;
  1790. using Expect100ContinueHandler =
  1791. std::function<int(const Request &, Response &)>;
  1792. using StartHandler = std::function<void()>;
  1793. using WebSocketHandler =
  1794. std::function<void(const Request &, ws::WebSocket &)>;
  1795. using SubProtocolSelector =
  1796. std::function<std::string(const std::vector<std::string> &protocols)>;
  1797. Server();
  1798. virtual ~Server();
  1799. virtual bool is_valid() const;
  1800. Server &Get(const std::string &pattern, Handler handler);
  1801. Server &Post(const std::string &pattern, Handler handler);
  1802. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1803. Server &Put(const std::string &pattern, Handler handler);
  1804. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1805. Server &Patch(const std::string &pattern, Handler handler);
  1806. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1807. Server &Delete(const std::string &pattern, Handler handler);
  1808. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1809. Server &Options(const std::string &pattern, Handler handler);
  1810. // Register a handler for an HTTP method outside the built-in set (e.g. the
  1811. // WebDAV methods from RFC 4918). Registering a method here is what makes the
  1812. // server accept it; an unregistered method is still rejected with 400.
  1813. // `method` must be a valid HTTP method token and must not be one of the
  1814. // built-in methods, which have their own registration functions above. A
  1815. // rejected registration makes is_valid() return false, so listen() fails.
  1816. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1817. Handler handler);
  1818. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1819. HandlerWithContentReader handler);
  1820. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1821. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1822. SubProtocolSelector sub_protocol_selector);
  1823. bool set_base_dir(const std::string &dir,
  1824. const std::string &mount_point = std::string());
  1825. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1826. Headers headers = Headers());
  1827. bool remove_mount_point(const std::string &mount_point);
  1828. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1829. const std::string &mime);
  1830. Server &set_default_file_mimetype(const std::string &mime);
  1831. Server &set_file_request_handler(Handler handler);
  1832. template <class ErrorHandlerFunc>
  1833. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1834. return set_error_handler_core(
  1835. std::forward<ErrorHandlerFunc>(handler),
  1836. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1837. }
  1838. Server &set_exception_handler(ExceptionHandler handler);
  1839. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1840. Server &set_post_routing_handler(Handler handler);
  1841. Server &set_pre_request_handler(HandlerWithResponse handler);
  1842. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1843. Server &set_start_handler(StartHandler handler);
  1844. Server &set_logger(Logger logger);
  1845. Server &set_pre_compression_logger(Logger logger);
  1846. Server &set_error_logger(ErrorLogger error_logger);
  1847. Server &set_address_family(int family);
  1848. Server &set_tcp_nodelay(bool on);
  1849. Server &set_ipv6_v6only(bool on);
  1850. Server &set_socket_options(SocketOptions socket_options);
  1851. Server &set_default_headers(Headers headers);
  1852. Server &
  1853. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1854. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1855. Server &set_keep_alive_max_count(size_t count);
  1856. Server &set_keep_alive_timeout(time_t sec);
  1857. template <class Rep, class Period>
  1858. Server &
  1859. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1860. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1861. template <class Rep, class Period>
  1862. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1863. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1864. template <class Rep, class Period>
  1865. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1866. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1867. template <class Rep, class Period>
  1868. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1869. Server &set_payload_max_length(size_t length);
  1870. Server &set_static_file_compression(bool on);
  1871. Server &set_static_file_compression_min_length(size_t length);
  1872. Server &set_static_file_compression_max_length(size_t length);
  1873. Server &set_websocket_ping_interval(time_t sec);
  1874. template <class Rep, class Period>
  1875. Server &set_websocket_ping_interval(
  1876. const std::chrono::duration<Rep, Period> &duration);
  1877. Server &set_websocket_max_missed_pongs(int count);
  1878. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1879. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1880. bool listen_after_bind();
  1881. bool listen(const std::string &host, int port, int socket_flags = 0);
  1882. bool is_running() const;
  1883. void wait_until_ready() const;
  1884. void stop() noexcept;
  1885. void decommission();
  1886. std::function<TaskQueue *(void)> new_task_queue;
  1887. protected:
  1888. bool process_request(Stream &strm, const std::string &remote_addr,
  1889. int remote_port, const std::string &local_addr,
  1890. int local_port, bool close_connection,
  1891. bool &connection_closed,
  1892. const std::function<void(Request &)> &setup_request,
  1893. bool *websocket_upgraded = nullptr);
  1894. // Runs the per-connection serving loop and stops an exception thrown by a
  1895. // user callback from escaping the worker thread.
  1896. //
  1897. // process_request() wraps only routing() in a try/catch. Content providers,
  1898. // the post-routing, error, logging and expect-100 handlers and WebSocket
  1899. // handlers all run outside it, and the task queue calls the job without a
  1900. // catch, so an exception from any of those would terminate the process.
  1901. //
  1902. // No 500 is possible here: by the time a content provider runs, the status
  1903. // line and headers are already on the wire. Report it through the error
  1904. // logger and drop the connection, which is what the peer observes either
  1905. // way. Other connections are unaffected.
  1906. template <typename Serve> bool serve_guarded(Serve &&serve) const {
  1907. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  1908. return serve();
  1909. #else
  1910. try {
  1911. return serve();
  1912. } catch (...) {
  1913. // The error logger is a user callback too, so it must not be able to
  1914. // throw the guard back open.
  1915. try {
  1916. output_error_log(Error::UserCallbackException, nullptr);
  1917. } catch (...) {}
  1918. return false;
  1919. }
  1920. #endif
  1921. }
  1922. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1923. std::vector<std::string> trusted_proxies_;
  1924. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1925. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1926. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1927. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1928. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1929. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1930. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1931. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1932. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1933. bool static_file_compression_ = false;
  1934. size_t static_file_compression_min_length_ =
  1935. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH;
  1936. size_t static_file_compression_max_length_ =
  1937. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH;
  1938. time_t websocket_ping_interval_sec_ =
  1939. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1940. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1941. private:
  1942. using Handlers =
  1943. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1944. using HandlersForContentReader =
  1945. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1946. HandlerWithContentReader>>;
  1947. // Both handler tables for one custom method live in a single entry, so that
  1948. // routing() needs only one map lookup per request to reach either of them.
  1949. struct CustomHandlerEntry {
  1950. Handlers handlers;
  1951. HandlersForContentReader handlers_for_content_reader;
  1952. };
  1953. using CustomHandlers = std::map<std::string, CustomHandlerEntry>;
  1954. static std::unique_ptr<detail::MatcherBase>
  1955. make_matcher(const std::string &pattern);
  1956. static const std::set<std::string> &builtin_methods();
  1957. CustomHandlerEntry *custom_entry_for_registration(const std::string &method);
  1958. const CustomHandlerEntry *find_custom_entry(const std::string &method) const;
  1959. template <typename H>
  1960. Server &add_handler(
  1961. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1962. const std::string &pattern, H handler) {
  1963. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1964. return *this;
  1965. }
  1966. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1967. Server &set_error_handler_core(Handler handler, std::false_type);
  1968. socket_t create_server_socket(const std::string &host, int port,
  1969. int socket_flags,
  1970. SocketOptions socket_options) const;
  1971. int bind_internal(const std::string &host, int port, int socket_flags);
  1972. bool listen_internal();
  1973. bool routing(Request &req, Response &res, Stream &strm);
  1974. bool handle_file_request(Request &req, Response &res);
  1975. bool check_if_not_modified(const Request &req, Response &res,
  1976. const std::string &etag, time_t mtime) const;
  1977. bool check_if_range(Request &req, const std::string &etag,
  1978. time_t mtime) const;
  1979. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1980. Stream &strm);
  1981. bool dispatch_request_for_content_reader(
  1982. Request &req, Response &res, ContentReader content_reader,
  1983. const HandlersForContentReader &handlers) const;
  1984. bool parse_request_line(const char *s, Request &req) const;
  1985. detail::EncodingType static_file_encoding(const Request &req,
  1986. const Response &res,
  1987. const std::string &content_type,
  1988. size_t length) const;
  1989. bool apply_static_file_compression(const Request &req, Response &res) const;
  1990. void apply_ranges(const Request &req, Response &res,
  1991. std::string &content_type, std::string &boundary) const;
  1992. bool write_response(Stream &strm, bool close_connection, Request &req,
  1993. Response &res);
  1994. bool write_response_with_content(Stream &strm, bool close_connection,
  1995. const Request &req, Response &res);
  1996. bool write_response_core(Stream &strm, bool close_connection,
  1997. const Request &req, Response &res,
  1998. bool need_apply_ranges);
  1999. bool write_content_with_provider(Stream &strm, const Request &req,
  2000. Response &res, const std::string &boundary,
  2001. const std::string &content_type);
  2002. bool read_content(Stream &strm, Request &req, Response &res);
  2003. bool read_content_with_content_receiver(Stream &strm, Request &req,
  2004. Response &res,
  2005. ContentReceiver receiver,
  2006. FormDataHeader multipart_header,
  2007. ContentReceiver multipart_receiver);
  2008. bool read_content_core(Stream &strm, Request &req, Response &res,
  2009. ContentReceiver receiver,
  2010. FormDataHeader multipart_header,
  2011. ContentReceiver multipart_receiver) const;
  2012. virtual bool process_and_close_socket(socket_t sock);
  2013. void output_log(const Request &req, const Response &res) const;
  2014. void output_pre_compression_log(const Request &req,
  2015. const Response &res) const;
  2016. void output_error_log(const Error &err, const Request *req) const;
  2017. std::atomic<bool> is_running_{false};
  2018. std::atomic<bool> is_decommissioned{false};
  2019. // Set when CustomRoute() refuses a registration. Written before listen(),
  2020. // read by is_valid() on the same thread, so it needs no synchronization.
  2021. bool has_invalid_registration_ = false;
  2022. struct MountPointEntry {
  2023. std::string mount_point;
  2024. std::string base_dir;
  2025. std::string resolved_base_dir;
  2026. Headers headers;
  2027. };
  2028. std::vector<MountPointEntry> base_dirs_;
  2029. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  2030. std::string default_file_mimetype_ = "application/octet-stream";
  2031. Handler file_request_handler_;
  2032. Handlers get_handlers_;
  2033. Handlers post_handlers_;
  2034. HandlersForContentReader post_handlers_for_content_reader_;
  2035. Handlers put_handlers_;
  2036. HandlersForContentReader put_handlers_for_content_reader_;
  2037. Handlers patch_handlers_;
  2038. HandlersForContentReader patch_handlers_for_content_reader_;
  2039. Handlers delete_handlers_;
  2040. HandlersForContentReader delete_handlers_for_content_reader_;
  2041. Handlers options_handlers_;
  2042. CustomHandlers custom_handlers_;
  2043. struct WebSocketHandlerEntry {
  2044. std::unique_ptr<detail::MatcherBase> matcher;
  2045. WebSocketHandler handler;
  2046. SubProtocolSelector sub_protocol_selector;
  2047. };
  2048. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  2049. WebSocketHandlers websocket_handlers_;
  2050. HandlerWithResponse error_handler_;
  2051. ExceptionHandler exception_handler_;
  2052. HandlerWithResponse pre_routing_handler_;
  2053. Handler post_routing_handler_;
  2054. HandlerWithResponse pre_request_handler_;
  2055. Expect100ContinueHandler expect_100_continue_handler_;
  2056. StartHandler start_handler_;
  2057. mutable std::mutex logger_mutex_;
  2058. Logger logger_;
  2059. Logger pre_compression_logger_;
  2060. ErrorLogger error_logger_;
  2061. int address_family_ = AF_UNSPEC;
  2062. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2063. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2064. SocketOptions socket_options_ = default_socket_options;
  2065. Headers default_headers_;
  2066. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2067. detail::write_headers;
  2068. };
  2069. class Result {
  2070. public:
  2071. Result() = default;
  2072. Result(std::unique_ptr<Response> &&res, Error err,
  2073. Headers &&request_headers = Headers{})
  2074. : res_(std::move(res)), err_(err),
  2075. request_headers_(std::move(request_headers)) {}
  2076. // Response
  2077. operator bool() const { return res_ != nullptr; }
  2078. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  2079. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  2080. const Response &value() const { return *res_; }
  2081. Response &value() { return *res_; }
  2082. const Response &operator*() const { return *res_; }
  2083. Response &operator*() { return *res_; }
  2084. const Response *operator->() const { return res_.get(); }
  2085. Response *operator->() { return res_.get(); }
  2086. // Error
  2087. Error error() const { return err_; }
  2088. // Request Headers
  2089. bool has_request_header(const std::string &key) const;
  2090. std::string get_request_header_value(const std::string &key,
  2091. const char *def = "",
  2092. size_t id = 0) const;
  2093. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  2094. size_t id = 0) const;
  2095. size_t get_request_header_value_count(const std::string &key) const;
  2096. private:
  2097. std::unique_ptr<Response> res_;
  2098. Error err_ = Error::Unknown;
  2099. Headers request_headers_;
  2100. #ifdef CPPHTTPLIB_SSL_ENABLED
  2101. public:
  2102. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2103. int ssl_error)
  2104. : res_(std::move(res)), err_(err),
  2105. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  2106. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2107. int ssl_error, uint64_t ssl_backend_error)
  2108. : res_(std::move(res)), err_(err),
  2109. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  2110. ssl_backend_error_(ssl_backend_error) {}
  2111. int ssl_error() const { return ssl_error_; }
  2112. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  2113. private:
  2114. int ssl_error_ = 0;
  2115. uint64_t ssl_backend_error_ = 0;
  2116. #endif
  2117. };
  2118. struct ClientConnection {
  2119. socket_t sock = INVALID_SOCKET;
  2120. bool is_open() const { return sock != INVALID_SOCKET; }
  2121. ClientConnection() = default;
  2122. ~ClientConnection();
  2123. ClientConnection(const ClientConnection &) = delete;
  2124. ClientConnection &operator=(const ClientConnection &) = delete;
  2125. ClientConnection(ClientConnection &&other) noexcept
  2126. : sock(other.sock)
  2127. #ifdef CPPHTTPLIB_SSL_ENABLED
  2128. ,
  2129. session(other.session)
  2130. #endif
  2131. {
  2132. other.sock = INVALID_SOCKET;
  2133. #ifdef CPPHTTPLIB_SSL_ENABLED
  2134. other.session = nullptr;
  2135. #endif
  2136. }
  2137. ClientConnection &operator=(ClientConnection &&other) noexcept {
  2138. if (this != &other) {
  2139. sock = other.sock;
  2140. other.sock = INVALID_SOCKET;
  2141. #ifdef CPPHTTPLIB_SSL_ENABLED
  2142. session = other.session;
  2143. other.session = nullptr;
  2144. #endif
  2145. }
  2146. return *this;
  2147. }
  2148. #ifdef CPPHTTPLIB_SSL_ENABLED
  2149. tls::session_t session = nullptr;
  2150. #endif
  2151. };
  2152. namespace detail {
  2153. struct ChunkedDecoder;
  2154. struct BodyReader {
  2155. Stream *stream = nullptr;
  2156. bool has_content_length = false;
  2157. size_t content_length = 0;
  2158. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2159. size_t bytes_read = 0;
  2160. bool chunked = false;
  2161. bool eof = false;
  2162. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  2163. Error last_error = Error::Success;
  2164. ssize_t read(char *buf, size_t len);
  2165. bool has_error() const { return last_error != Error::Success; }
  2166. };
  2167. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  2168. size_t len) {
  2169. (void)stream;
  2170. return br.read(buf, len);
  2171. }
  2172. class decompressor;
  2173. enum class NoProxyKind {
  2174. Wildcard, // "*"
  2175. HostnameSuffix, // "example.com" or ".example.com"
  2176. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  2177. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  2178. };
  2179. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  2180. // Lets one CIDR matcher cover both families.
  2181. using IPBytes = std::array<uint8_t, 16>;
  2182. struct NoProxyEntry {
  2183. NoProxyKind kind = NoProxyKind::Wildcard;
  2184. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  2185. IPBytes net{};
  2186. int prefix_bits = 0;
  2187. };
  2188. struct NormalizedTarget {
  2189. std::string hostname; // lowercase; brackets and trailing dot removed
  2190. bool is_ipv4 = false;
  2191. bool is_ipv6 = false;
  2192. IPBytes ip{};
  2193. };
  2194. } // namespace detail
  2195. class ClientImpl {
  2196. public:
  2197. explicit ClientImpl(const std::string &host);
  2198. explicit ClientImpl(const std::string &host, int port);
  2199. explicit ClientImpl(const std::string &host, int port,
  2200. const std::string &client_cert_path,
  2201. const std::string &client_key_path);
  2202. virtual ~ClientImpl();
  2203. virtual bool is_valid() const;
  2204. struct StreamHandle {
  2205. std::unique_ptr<Response> response;
  2206. Error error = Error::Success;
  2207. StreamHandle() = default;
  2208. StreamHandle(const StreamHandle &) = delete;
  2209. StreamHandle &operator=(const StreamHandle &) = delete;
  2210. StreamHandle(StreamHandle &&) = default;
  2211. StreamHandle &operator=(StreamHandle &&) = default;
  2212. ~StreamHandle() = default;
  2213. bool is_valid() const {
  2214. return response != nullptr && error == Error::Success;
  2215. }
  2216. ssize_t read(char *buf, size_t len);
  2217. void parse_trailers_if_needed();
  2218. Error get_read_error() const { return body_reader_.last_error; }
  2219. bool has_read_error() const { return body_reader_.has_error(); }
  2220. bool trailers_parsed_ = false;
  2221. private:
  2222. friend class ClientImpl;
  2223. ssize_t read_with_decompression(char *buf, size_t len);
  2224. std::unique_ptr<ClientConnection> connection_;
  2225. std::unique_ptr<Stream> socket_stream_;
  2226. Stream *stream_ = nullptr;
  2227. detail::BodyReader body_reader_;
  2228. std::unique_ptr<detail::decompressor> decompressor_;
  2229. std::string decompress_buffer_;
  2230. size_t decompress_offset_ = 0;
  2231. size_t decompressed_bytes_read_ = 0;
  2232. };
  2233. // clang-format off
  2234. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2235. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2236. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2237. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2238. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2239. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2240. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2241. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2242. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2243. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2244. Result Head(const std::string &path);
  2245. Result Head(const std::string &path, const Headers &headers);
  2246. Result Post(const std::string &path);
  2247. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2248. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2249. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2250. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2251. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2252. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2253. Result Post(const std::string &path, const Params &params);
  2254. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2255. Result Post(const std::string &path, const Headers &headers);
  2256. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2257. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2258. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2259. 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);
  2260. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2261. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2262. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2263. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2264. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2265. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2266. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2267. Result Put(const std::string &path);
  2268. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2269. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2270. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2271. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2272. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2273. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2274. Result Put(const std::string &path, const Params &params);
  2275. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2276. Result Put(const std::string &path, const Headers &headers);
  2277. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2278. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2279. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2280. 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);
  2281. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2282. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2283. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2284. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2285. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2286. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2287. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2288. Result Patch(const std::string &path);
  2289. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2290. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2291. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2292. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2293. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2294. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2295. Result Patch(const std::string &path, const Params &params);
  2296. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2297. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  2298. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2299. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2300. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2301. 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);
  2302. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2303. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2304. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2305. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2306. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2307. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2308. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2309. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2310. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2311. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2312. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2313. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2314. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2315. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2316. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2317. Result Options(const std::string &path);
  2318. Result Options(const std::string &path, const Headers &headers);
  2319. // clang-format on
  2320. // Streaming API: Open a stream for reading response body incrementally
  2321. // Socket ownership is transferred to StreamHandle for true streaming
  2322. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2323. StreamHandle open_stream(const std::string &method, const std::string &path,
  2324. const Params &params = {},
  2325. const Headers &headers = {},
  2326. const std::string &body = {},
  2327. const std::string &content_type = {});
  2328. bool send(Request &req, Response &res, Error &error);
  2329. Result send(const Request &req);
  2330. void stop();
  2331. std::string host() const;
  2332. int port() const;
  2333. size_t is_socket_open() const;
  2334. socket_t socket() const;
  2335. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2336. void set_default_headers(Headers headers);
  2337. void
  2338. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2339. void set_address_family(int family);
  2340. void set_tcp_nodelay(bool on);
  2341. void set_ipv6_v6only(bool on);
  2342. void set_socket_options(SocketOptions socket_options);
  2343. void set_connection_timeout(time_t sec, time_t usec = 0);
  2344. template <class Rep, class Period>
  2345. void
  2346. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2347. void set_read_timeout(time_t sec, time_t usec = 0);
  2348. template <class Rep, class Period>
  2349. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2350. void set_write_timeout(time_t sec, time_t usec = 0);
  2351. template <class Rep, class Period>
  2352. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2353. void set_max_timeout(time_t msec);
  2354. template <class Rep, class Period>
  2355. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2356. void set_basic_auth(const std::string &username, const std::string &password);
  2357. void set_bearer_token_auth(const std::string &token);
  2358. void set_keep_alive(bool on);
  2359. void set_follow_location(bool on);
  2360. void set_path_encode(bool on);
  2361. void set_compress(bool on);
  2362. void set_decompress(bool on);
  2363. void set_payload_max_length(size_t length);
  2364. void set_interface(const std::string &intf);
  2365. void set_proxy(const std::string &host, int port);
  2366. void set_proxy_basic_auth(const std::string &username,
  2367. const std::string &password);
  2368. void set_proxy_bearer_token_auth(const std::string &token);
  2369. void set_no_proxy(const std::vector<std::string> &patterns);
  2370. void set_logger(Logger logger);
  2371. void set_error_logger(ErrorLogger error_logger);
  2372. protected:
  2373. struct Socket {
  2374. socket_t sock = INVALID_SOCKET;
  2375. // For Mbed TLS compatibility: start_time for request timeout tracking
  2376. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2377. bool is_open() const { return sock != INVALID_SOCKET; }
  2378. #ifdef CPPHTTPLIB_SSL_ENABLED
  2379. tls::session_t ssl = nullptr;
  2380. #endif
  2381. };
  2382. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  2383. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  2384. virtual bool setup_proxy_connection(
  2385. Socket &socket,
  2386. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2387. Response &res, bool &success, Error &error);
  2388. bool is_proxy_enabled_for_host(const std::string &host) const;
  2389. // All of:
  2390. // shutdown_ssl
  2391. // shutdown_socket
  2392. // close_socket
  2393. // disconnect
  2394. // should ONLY be called when socket_mutex_ is locked, and only when
  2395. // no other thread is using the socket.
  2396. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  2397. void shutdown_socket(Socket &socket) const;
  2398. void close_socket(Socket &socket);
  2399. void disconnect(bool gracefully);
  2400. bool process_request(Stream &strm, Request &req, Response &res,
  2401. bool close_connection, Error &error);
  2402. bool write_content_with_provider(Stream &strm, const Request &req,
  2403. Error &error) const;
  2404. void copy_settings(const ClientImpl &rhs);
  2405. void output_log(const Request &req, const Response &res) const;
  2406. void output_error_log(const Error &err, const Request *req) const;
  2407. // Socket endpoint information
  2408. const std::string host_;
  2409. const int port_;
  2410. // Current open socket
  2411. Socket socket_;
  2412. mutable std::mutex socket_mutex_;
  2413. std::recursive_mutex request_mutex_;
  2414. // These are all protected under socket_mutex
  2415. size_t socket_requests_in_flight_ = 0;
  2416. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2417. bool socket_should_be_closed_when_request_is_done_ = false;
  2418. // Hostname to connection target map. The value is an IP literal or another
  2419. // hostname; only the connection target changes, never the identity.
  2420. std::map<std::string, std::string> addr_map_;
  2421. // Default headers
  2422. Headers default_headers_;
  2423. // Header writer
  2424. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2425. detail::write_headers;
  2426. // Settings
  2427. std::string client_cert_path_;
  2428. std::string client_key_path_;
  2429. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2430. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2431. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2432. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2433. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2434. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2435. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2436. std::string basic_auth_username_;
  2437. std::string basic_auth_password_;
  2438. std::string bearer_token_auth_token_;
  2439. bool keep_alive_ = false;
  2440. bool follow_location_ = false;
  2441. bool path_encode_ = true;
  2442. int address_family_ = AF_UNSPEC;
  2443. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2444. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2445. SocketOptions socket_options_ = nullptr;
  2446. bool compress_ = false;
  2447. bool decompress_ = true;
  2448. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2449. bool has_payload_max_length_ = false;
  2450. std::string interface_;
  2451. std::string proxy_host_;
  2452. int proxy_port_ = -1;
  2453. std::string proxy_basic_auth_username_;
  2454. std::string proxy_basic_auth_password_;
  2455. std::string proxy_bearer_token_auth_token_;
  2456. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2457. mutable detail::NormalizedTarget host_normalized_;
  2458. mutable bool host_normalized_valid_ = false;
  2459. mutable std::mutex logger_mutex_;
  2460. Logger logger_;
  2461. ErrorLogger error_logger_;
  2462. private:
  2463. bool send_(Request &req, Response &res, Error &error);
  2464. Result send_(Request &&req);
  2465. socket_t create_client_socket(Error &error) const;
  2466. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2467. bool skip_100_continue = true) const;
  2468. bool write_request(Stream &strm, Request &req, bool close_connection,
  2469. Error &error, bool skip_body = false);
  2470. bool write_request_body(Stream &strm, Request &req, Error &error);
  2471. void prepare_default_headers(Request &r, bool for_stream,
  2472. const std::string &ct);
  2473. bool redirect(Request &req, Response &res, Error &error);
  2474. bool create_redirect_client(const std::string &scheme,
  2475. const std::string &host, int port, Request &req,
  2476. Response &res, const std::string &path,
  2477. const std::string &location, Error &error);
  2478. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2479. bool handle_request(Stream &strm, Request &req, Response &res,
  2480. bool close_connection, Error &error);
  2481. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2482. Request &req, const char *body, size_t content_length,
  2483. ContentProvider content_provider,
  2484. ContentProviderWithoutLength content_provider_without_length,
  2485. const std::string &content_type, ContentReceiver content_receiver,
  2486. Error &error);
  2487. Result send_with_content_provider_and_receiver(
  2488. const std::string &method, const std::string &path,
  2489. const Headers &headers, const char *body, size_t content_length,
  2490. ContentProvider content_provider,
  2491. ContentProviderWithoutLength content_provider_without_length,
  2492. const std::string &content_type, ContentReceiver content_receiver,
  2493. UploadProgress progress);
  2494. ContentProviderWithoutLength get_multipart_content_provider(
  2495. const std::string &boundary, const UploadFormDataItems &items,
  2496. const FormDataProviderItems &provider_items) const;
  2497. virtual bool
  2498. process_socket(const Socket &socket,
  2499. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2500. std::function<bool(Stream &strm)> callback);
  2501. virtual bool is_ssl() const;
  2502. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. public:
  2505. void set_digest_auth(const std::string &username,
  2506. const std::string &password);
  2507. void set_proxy_digest_auth(const std::string &username,
  2508. const std::string &password);
  2509. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2510. const std::string &ca_cert_dir_path = std::string());
  2511. void enable_server_certificate_verification(bool enabled);
  2512. void enable_server_hostname_verification(bool enabled);
  2513. void enable_system_ca(bool enabled);
  2514. protected:
  2515. std::string digest_auth_username_;
  2516. std::string digest_auth_password_;
  2517. std::string proxy_digest_auth_username_;
  2518. std::string proxy_digest_auth_password_;
  2519. std::string ca_cert_file_path_;
  2520. std::string ca_cert_dir_path_;
  2521. bool server_certificate_verification_ = true;
  2522. bool server_hostname_verification_ = true;
  2523. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2524. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2525. int last_ssl_error_ = 0;
  2526. uint64_t last_backend_error_ = 0;
  2527. #endif
  2528. };
  2529. class Client {
  2530. public:
  2531. // Universal interface
  2532. explicit Client(const std::string &scheme_host_port);
  2533. explicit Client(const std::string &scheme_host_port,
  2534. const std::string &client_cert_path,
  2535. const std::string &client_key_path);
  2536. // HTTP only interface
  2537. explicit Client(const std::string &host, int port);
  2538. explicit Client(const std::string &host, int port,
  2539. const std::string &client_cert_path,
  2540. const std::string &client_key_path);
  2541. Client(Client &&) = default;
  2542. Client &operator=(Client &&) = default;
  2543. ~Client();
  2544. bool is_valid() const;
  2545. // clang-format off
  2546. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2547. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2548. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2549. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2550. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2551. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2552. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2553. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2554. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2555. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2556. Result Head(const std::string &path);
  2557. Result Head(const std::string &path, const Headers &headers);
  2558. Result Post(const std::string &path);
  2559. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2560. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2561. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2562. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2563. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2564. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2565. Result Post(const std::string &path, const Params &params);
  2566. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2567. Result Post(const std::string &path, const Headers &headers);
  2568. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2569. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2570. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2571. 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);
  2572. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2573. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2574. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2575. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2576. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2577. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2578. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2579. Result Put(const std::string &path);
  2580. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2581. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2582. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2583. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2584. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2585. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2586. Result Put(const std::string &path, const Params &params);
  2587. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2588. Result Put(const std::string &path, const Headers &headers);
  2589. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2590. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2591. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2592. 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);
  2593. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2594. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2595. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2596. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2597. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2598. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2599. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2600. Result Patch(const std::string &path);
  2601. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2602. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2603. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2604. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2605. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2606. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2607. Result Patch(const std::string &path, const Params &params);
  2608. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2609. Result Patch(const std::string &path, const Headers &headers);
  2610. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2611. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2612. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2613. 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);
  2614. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2615. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2616. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2617. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2618. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2619. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2620. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2621. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2622. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2623. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2624. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2625. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2626. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2627. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2628. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2629. Result Options(const std::string &path);
  2630. Result Options(const std::string &path, const Headers &headers);
  2631. // clang-format on
  2632. // Streaming API: Open a stream for reading response body incrementally
  2633. // Socket ownership is transferred to StreamHandle for true streaming
  2634. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2635. ClientImpl::StreamHandle open_stream(const std::string &method,
  2636. const std::string &path,
  2637. const Params &params = {},
  2638. const Headers &headers = {},
  2639. const std::string &body = {},
  2640. const std::string &content_type = {});
  2641. bool send(Request &req, Response &res, Error &error);
  2642. Result send(const Request &req);
  2643. void stop();
  2644. std::string host() const;
  2645. int port() const;
  2646. size_t is_socket_open() const;
  2647. socket_t socket() const;
  2648. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2649. void set_default_headers(Headers headers);
  2650. void
  2651. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2652. void set_address_family(int family);
  2653. void set_tcp_nodelay(bool on);
  2654. void set_socket_options(SocketOptions socket_options);
  2655. void set_connection_timeout(time_t sec, time_t usec = 0);
  2656. template <class Rep, class Period>
  2657. void
  2658. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2659. void set_read_timeout(time_t sec, time_t usec = 0);
  2660. template <class Rep, class Period>
  2661. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2662. void set_write_timeout(time_t sec, time_t usec = 0);
  2663. template <class Rep, class Period>
  2664. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2665. void set_max_timeout(time_t msec);
  2666. template <class Rep, class Period>
  2667. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2668. void set_basic_auth(const std::string &username, const std::string &password);
  2669. void set_bearer_token_auth(const std::string &token);
  2670. void set_keep_alive(bool on);
  2671. void set_follow_location(bool on);
  2672. void set_path_encode(bool on);
  2673. void set_compress(bool on);
  2674. void set_decompress(bool on);
  2675. void set_payload_max_length(size_t length);
  2676. void set_interface(const std::string &intf);
  2677. void set_proxy(const std::string &host, int port);
  2678. void set_proxy_basic_auth(const std::string &username,
  2679. const std::string &password);
  2680. void set_proxy_bearer_token_auth(const std::string &token);
  2681. void set_no_proxy(const std::vector<std::string> &patterns);
  2682. void set_logger(Logger logger);
  2683. void set_error_logger(ErrorLogger error_logger);
  2684. private:
  2685. std::unique_ptr<ClientImpl> cli_;
  2686. #ifdef CPPHTTPLIB_SSL_ENABLED
  2687. public:
  2688. void set_digest_auth(const std::string &username,
  2689. const std::string &password);
  2690. void set_proxy_digest_auth(const std::string &username,
  2691. const std::string &password);
  2692. void enable_server_certificate_verification(bool enabled);
  2693. void enable_server_hostname_verification(bool enabled);
  2694. void enable_system_ca(bool enabled);
  2695. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2696. const std::string &ca_cert_dir_path = std::string());
  2697. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2698. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2699. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2700. void set_session_verifier(
  2701. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2702. tls::ctx_t tls_context() const;
  2703. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2704. void enable_windows_certificate_verification(bool enabled);
  2705. #endif
  2706. private:
  2707. bool is_ssl_ = false;
  2708. #endif
  2709. };
  2710. #ifdef CPPHTTPLIB_SSL_ENABLED
  2711. class SSLServer : public Server {
  2712. public:
  2713. SSLServer(const char *cert_path, const char *private_key_path,
  2714. const char *client_ca_cert_file_path = nullptr,
  2715. const char *client_ca_cert_dir_path = nullptr,
  2716. const char *private_key_password = nullptr);
  2717. struct PemMemory {
  2718. const char *cert_pem;
  2719. size_t cert_pem_len;
  2720. const char *key_pem;
  2721. size_t key_pem_len;
  2722. const char *client_ca_pem;
  2723. size_t client_ca_pem_len;
  2724. const char *private_key_password;
  2725. };
  2726. explicit SSLServer(const PemMemory &pem);
  2727. // The callback receives the ctx_t handle which can be cast to the
  2728. // appropriate backend type (SSL_CTX* for OpenSSL,
  2729. // tls::impl::MbedTlsContext* for Mbed TLS)
  2730. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2731. ~SSLServer() override;
  2732. bool is_valid() const override;
  2733. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2734. const char *client_ca_pem = nullptr,
  2735. const char *password = nullptr);
  2736. tls::ctx_t tls_context() const { return ctx_; }
  2737. int ssl_last_error() const { return last_ssl_error_; }
  2738. private:
  2739. bool process_and_close_socket(socket_t sock) override;
  2740. tls::ctx_t ctx_ = nullptr;
  2741. std::mutex ctx_mutex_;
  2742. int last_ssl_error_ = 0;
  2743. };
  2744. class SSLClient final : public ClientImpl {
  2745. public:
  2746. explicit SSLClient(const std::string &host);
  2747. explicit SSLClient(const std::string &host, int port);
  2748. explicit SSLClient(const std::string &host, int port,
  2749. const std::string &client_cert_path,
  2750. const std::string &client_key_path,
  2751. const std::string &private_key_password = std::string());
  2752. struct PemMemory {
  2753. const char *cert_pem;
  2754. size_t cert_pem_len;
  2755. const char *key_pem;
  2756. size_t key_pem_len;
  2757. const char *private_key_password;
  2758. };
  2759. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2760. ~SSLClient() override;
  2761. bool is_valid() const override;
  2762. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2763. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2764. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2765. // Post-handshake session verifier (backend-independent)
  2766. void set_session_verifier(
  2767. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2768. tls::ctx_t tls_context() const { return ctx_; }
  2769. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2770. void enable_windows_certificate_verification(bool enabled);
  2771. #endif
  2772. private:
  2773. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2774. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2775. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2776. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2777. bool
  2778. process_socket(const Socket &socket,
  2779. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2780. std::function<bool(Stream &strm)> callback) override;
  2781. bool is_ssl() const override;
  2782. bool setup_proxy_connection(
  2783. Socket &socket,
  2784. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2785. Response &res, bool &success, Error &error) override;
  2786. bool connect_with_proxy(
  2787. Socket &sock,
  2788. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2789. Response &res, bool &success, Error &error);
  2790. bool initialize_ssl(Socket &socket, Error &error);
  2791. void init_ctx();
  2792. void reset_ctx_on_error();
  2793. bool load_certs();
  2794. tls::ctx_t ctx_ = nullptr;
  2795. std::mutex ctx_mutex_;
  2796. std::once_flag initialize_cert_;
  2797. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2798. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2799. // Used to keep custom CA configuration exclusive with system CA loading.
  2800. bool ca_cert_store_set_ = false;
  2801. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2802. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2803. bool enable_windows_cert_verification_ = true;
  2804. #endif
  2805. friend class ClientImpl;
  2806. };
  2807. #endif // CPPHTTPLIB_SSL_ENABLED
  2808. namespace detail {
  2809. template <typename T, typename U>
  2810. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2811. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2812. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2813. duration - std::chrono::seconds(sec))
  2814. .count();
  2815. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2816. }
  2817. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2818. return N - 1;
  2819. }
  2820. inline bool is_numeric(const std::string &str) {
  2821. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2822. }
  2823. inline size_t get_header_value_u64(const Headers &headers,
  2824. const std::string &key, size_t def,
  2825. size_t id, bool &is_invalid_value) {
  2826. is_invalid_value = false;
  2827. auto rng = headers.equal_range(key);
  2828. auto it = rng.first;
  2829. std::advance(it, static_cast<ssize_t>(id));
  2830. if (it != rng.second) {
  2831. if (is_numeric(it->second)) {
  2832. // Parse at size_t width so an out-of-range Content-Length is reported
  2833. // rather than silently saturated/truncated (a value above 2^32 would
  2834. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  2835. // and return SIZE_MAX so the existing oversized-value guards reject it.
  2836. size_t val = 0;
  2837. const auto &s = it->second;
  2838. auto r = from_chars(s.data(), s.data() + s.size(), val);
  2839. if (r.ec == std::errc::result_out_of_range) {
  2840. is_invalid_value = true;
  2841. return (std::numeric_limits<size_t>::max)();
  2842. }
  2843. return val;
  2844. } else {
  2845. is_invalid_value = true;
  2846. }
  2847. }
  2848. return def;
  2849. }
  2850. inline size_t get_header_value_u64(const Headers &headers,
  2851. const std::string &key, size_t def,
  2852. size_t id) {
  2853. auto dummy = false;
  2854. return get_header_value_u64(headers, key, def, id, dummy);
  2855. }
  2856. } // namespace detail
  2857. template <class Rep, class Period>
  2858. inline Server &
  2859. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2860. detail::duration_to_sec_and_usec(
  2861. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2862. return *this;
  2863. }
  2864. template <class Rep, class Period>
  2865. inline Server &
  2866. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2867. detail::duration_to_sec_and_usec(
  2868. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2869. return *this;
  2870. }
  2871. template <class Rep, class Period>
  2872. inline Server &
  2873. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2874. detail::duration_to_sec_and_usec(
  2875. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2876. return *this;
  2877. }
  2878. template <class Rep, class Period>
  2879. inline void ClientImpl::set_connection_timeout(
  2880. const std::chrono::duration<Rep, Period> &duration) {
  2881. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2882. set_connection_timeout(sec, usec);
  2883. });
  2884. }
  2885. template <class Rep, class Period>
  2886. inline void ClientImpl::set_read_timeout(
  2887. const std::chrono::duration<Rep, Period> &duration) {
  2888. detail::duration_to_sec_and_usec(
  2889. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2890. }
  2891. template <class Rep, class Period>
  2892. inline void ClientImpl::set_write_timeout(
  2893. const std::chrono::duration<Rep, Period> &duration) {
  2894. detail::duration_to_sec_and_usec(
  2895. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2896. }
  2897. template <class Rep, class Period>
  2898. inline void ClientImpl::set_max_timeout(
  2899. const std::chrono::duration<Rep, Period> &duration) {
  2900. auto msec =
  2901. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2902. set_max_timeout(msec);
  2903. }
  2904. template <class Rep, class Period>
  2905. inline void Client::set_connection_timeout(
  2906. const std::chrono::duration<Rep, Period> &duration) {
  2907. cli_->set_connection_timeout(duration);
  2908. }
  2909. template <class Rep, class Period>
  2910. inline void
  2911. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2912. cli_->set_read_timeout(duration);
  2913. }
  2914. template <class Rep, class Period>
  2915. inline void
  2916. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2917. cli_->set_write_timeout(duration);
  2918. }
  2919. inline void Client::set_max_timeout(time_t msec) {
  2920. cli_->set_max_timeout(msec);
  2921. }
  2922. template <class Rep, class Period>
  2923. inline void
  2924. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2925. cli_->set_max_timeout(duration);
  2926. }
  2927. /*
  2928. * Forward declarations and types that will be part of the .h file if split into
  2929. * .h + .cc.
  2930. */
  2931. std::string hosted_at(const std::string &hostname);
  2932. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2933. // JavaScript-style URL encoding/decoding functions
  2934. std::string encode_uri_component(const std::string &value);
  2935. std::string encode_uri(const std::string &value);
  2936. std::string decode_uri_component(const std::string &value);
  2937. std::string decode_uri(const std::string &value);
  2938. // RFC 3986 compliant URL component encoding/decoding functions
  2939. std::string encode_path_component(const std::string &component);
  2940. std::string decode_path_component(const std::string &component);
  2941. std::string encode_query_component(const std::string &component,
  2942. bool space_as_plus = true);
  2943. std::string decode_query_component(const std::string &component,
  2944. bool plus_as_space = true);
  2945. std::string sanitize_filename(const std::string &filename);
  2946. std::string append_query_params(const std::string &path, const Params &params);
  2947. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2948. std::pair<std::string, std::string>
  2949. make_basic_authentication_header(const std::string &username,
  2950. const std::string &password,
  2951. bool is_proxy = false);
  2952. namespace detail {
  2953. #if defined(_WIN32)
  2954. inline std::wstring u8string_to_wstring(const char *s) {
  2955. if (!s) { return std::wstring(); }
  2956. auto len = static_cast<int>(strlen(s));
  2957. if (!len) { return std::wstring(); }
  2958. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2959. if (!wlen) { return std::wstring(); }
  2960. std::wstring ws;
  2961. ws.resize(wlen);
  2962. wlen = ::MultiByteToWideChar(
  2963. CP_UTF8, 0, s, len,
  2964. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2965. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2966. return ws;
  2967. }
  2968. #endif
  2969. struct FileStat {
  2970. FileStat(const std::string &path);
  2971. bool is_file() const;
  2972. bool is_dir() const;
  2973. time_t mtime() const;
  2974. size_t size() const;
  2975. private:
  2976. #if defined(_WIN32)
  2977. struct _stat st_;
  2978. #else
  2979. struct stat st_;
  2980. #endif
  2981. int ret_ = -1;
  2982. };
  2983. std::string make_host_and_port_string(const std::string &host, int port,
  2984. bool is_ssl);
  2985. template <typename T>
  2986. bool check_and_write_headers(Stream &strm, Headers &headers, T header_writer,
  2987. Error &error);
  2988. std::string trim_copy(const std::string &s);
  2989. void divide(
  2990. const char *data, std::size_t size, char d,
  2991. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2992. fn);
  2993. void divide(
  2994. const std::string &str, char d,
  2995. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2996. fn);
  2997. void split(const char *b, const char *e, char d,
  2998. std::function<void(const char *, const char *)> fn);
  2999. void split(const char *b, const char *e, char d, size_t m,
  3000. std::function<void(const char *, const char *)> fn);
  3001. bool split_find(const char *b, const char *e, char d,
  3002. std::function<bool(const char *, const char *)> fn);
  3003. bool has_header_token(const Headers &headers, const std::string &key,
  3004. const std::string &token);
  3005. std::string websocket_accept_key(const std::string &client_key);
  3006. bool is_websocket_upgrade(const Request &req);
  3007. bool process_client_socket(
  3008. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3009. time_t write_timeout_sec, time_t write_timeout_usec,
  3010. time_t max_timeout_msec,
  3011. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3012. std::function<bool(Stream &)> callback);
  3013. socket_t create_client_socket(const std::string &host, const std::string &ip,
  3014. int port, int address_family, bool tcp_nodelay,
  3015. bool ipv6_v6only, SocketOptions socket_options,
  3016. time_t connection_timeout_sec,
  3017. time_t connection_timeout_usec,
  3018. time_t read_timeout_sec, time_t read_timeout_usec,
  3019. time_t write_timeout_sec,
  3020. time_t write_timeout_usec,
  3021. const std::string &intf, Error &error);
  3022. const char *get_header_value(const Headers &headers, const std::string &key,
  3023. const char *def, size_t id);
  3024. std::string get_combined_header_value(const Headers &headers,
  3025. const std::string &key);
  3026. std::string params_to_query_str(const Params &params);
  3027. void parse_query_text(const char *data, std::size_t size, Params &params);
  3028. void parse_query_text(const std::string &s, Params &params);
  3029. bool parse_multipart_boundary(const std::string &content_type,
  3030. std::string &boundary);
  3031. bool parse_range_header(const std::string &s, Ranges &ranges);
  3032. bool parse_accept_header(const std::string &s,
  3033. std::vector<std::string> &content_types);
  3034. void parse_disposition_params(const std::string &s, Params &params);
  3035. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  3036. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  3037. EncodingType encoding_type(const Request &req, const std::string &content_type);
  3038. EncodingType encoding_type(const Request &req, const Response &res,
  3039. const std::string &content_type);
  3040. EncodingType encoding_type(const Request &req, const Response &res);
  3041. class BufferStream final : public Stream {
  3042. public:
  3043. BufferStream() = default;
  3044. ~BufferStream() override = default;
  3045. bool is_readable() const override;
  3046. bool wait_readable() const override;
  3047. bool wait_writable() const override;
  3048. ssize_t read(char *ptr, size_t size) override;
  3049. ssize_t write(const char *ptr, size_t size) override;
  3050. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3051. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3052. socket_t socket() const override;
  3053. time_t duration() const override;
  3054. const std::string &get_buffer() const;
  3055. private:
  3056. std::string buffer;
  3057. size_t position = 0;
  3058. };
  3059. class compressor {
  3060. public:
  3061. virtual ~compressor() = default;
  3062. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3063. virtual bool compress(const char *data, size_t data_length, bool last,
  3064. Callback callback) = 0;
  3065. };
  3066. class decompressor {
  3067. public:
  3068. virtual ~decompressor() = default;
  3069. virtual bool is_valid() const = 0;
  3070. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3071. virtual bool decompress(const char *data, size_t data_length,
  3072. Callback callback) = 0;
  3073. };
  3074. class nocompressor final : public compressor {
  3075. public:
  3076. ~nocompressor() override = default;
  3077. bool compress(const char *data, size_t data_length, bool /*last*/,
  3078. Callback callback) override;
  3079. };
  3080. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3081. class gzip_compressor final : public compressor {
  3082. public:
  3083. gzip_compressor();
  3084. ~gzip_compressor() override;
  3085. bool compress(const char *data, size_t data_length, bool last,
  3086. Callback callback) override;
  3087. private:
  3088. bool is_valid_ = false;
  3089. z_stream strm_;
  3090. };
  3091. class gzip_decompressor final : public decompressor {
  3092. public:
  3093. gzip_decompressor();
  3094. ~gzip_decompressor() override;
  3095. bool is_valid() const override;
  3096. bool decompress(const char *data, size_t data_length,
  3097. Callback callback) override;
  3098. private:
  3099. bool is_valid_ = false;
  3100. z_stream strm_;
  3101. };
  3102. #endif
  3103. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3104. class brotli_compressor final : public compressor {
  3105. public:
  3106. brotli_compressor();
  3107. ~brotli_compressor();
  3108. bool compress(const char *data, size_t data_length, bool last,
  3109. Callback callback) override;
  3110. private:
  3111. BrotliEncoderState *state_ = nullptr;
  3112. };
  3113. class brotli_decompressor final : public decompressor {
  3114. public:
  3115. brotli_decompressor();
  3116. ~brotli_decompressor();
  3117. bool is_valid() const override;
  3118. bool decompress(const char *data, size_t data_length,
  3119. Callback callback) override;
  3120. private:
  3121. BrotliDecoderResult decoder_r;
  3122. BrotliDecoderState *decoder_s = nullptr;
  3123. };
  3124. #endif
  3125. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3126. class zstd_compressor : public compressor {
  3127. public:
  3128. zstd_compressor();
  3129. ~zstd_compressor();
  3130. bool compress(const char *data, size_t data_length, bool last,
  3131. Callback callback) override;
  3132. private:
  3133. ZSTD_CCtx *ctx_ = nullptr;
  3134. };
  3135. class zstd_decompressor : public decompressor {
  3136. public:
  3137. zstd_decompressor();
  3138. ~zstd_decompressor();
  3139. bool is_valid() const override;
  3140. bool decompress(const char *data, size_t data_length,
  3141. Callback callback) override;
  3142. private:
  3143. ZSTD_DCtx *ctx_ = nullptr;
  3144. };
  3145. #endif
  3146. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  3147. // to store data. The call can set memory on stack for performance.
  3148. class stream_line_reader {
  3149. public:
  3150. stream_line_reader(Stream &strm, char *fixed_buffer,
  3151. size_t fixed_buffer_size);
  3152. const char *ptr() const;
  3153. size_t size() const;
  3154. bool end_with_crlf() const;
  3155. bool getline();
  3156. private:
  3157. void append(char c);
  3158. void append(const char *data, size_t size);
  3159. Stream &strm_;
  3160. char *fixed_buffer_;
  3161. const size_t fixed_buffer_size_;
  3162. size_t fixed_buffer_used_size_ = 0;
  3163. std::string growable_buffer_;
  3164. };
  3165. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3166. const Headers &src_headers);
  3167. struct ChunkedDecoder {
  3168. Stream &strm;
  3169. size_t chunk_remaining = 0;
  3170. bool finished = false;
  3171. char line_buf[64];
  3172. size_t last_chunk_total = 0;
  3173. size_t last_chunk_offset = 0;
  3174. explicit ChunkedDecoder(Stream &s);
  3175. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  3176. size_t &out_chunk_total);
  3177. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  3178. };
  3179. class mmap {
  3180. public:
  3181. mmap(const char *path);
  3182. ~mmap();
  3183. bool open(const char *path);
  3184. void close();
  3185. bool is_open() const;
  3186. size_t size() const;
  3187. const char *data() const;
  3188. private:
  3189. #if defined(_WIN32)
  3190. HANDLE hFile_ = NULL;
  3191. HANDLE hMapping_ = NULL;
  3192. #else
  3193. int fd_ = -1;
  3194. #endif
  3195. size_t size_ = 0;
  3196. void *addr_ = nullptr;
  3197. bool is_open_empty_file = false;
  3198. };
  3199. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  3200. namespace fields {
  3201. bool is_token_char(char c);
  3202. bool is_token(const std::string &s);
  3203. bool is_field_name(const std::string &s);
  3204. bool is_vchar(char c);
  3205. bool is_obs_text(char c);
  3206. bool is_field_vchar(char c);
  3207. bool is_field_content(const std::string &s);
  3208. bool is_field_value(const std::string &s);
  3209. bool is_field_valid(const std::string &name, const std::string &value);
  3210. } // namespace fields
  3211. } // namespace detail
  3212. /*
  3213. * TLS Abstraction Layer Declarations
  3214. */
  3215. #ifdef CPPHTTPLIB_SSL_ENABLED
  3216. // TLS abstraction layer - backend-specific type declarations
  3217. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  3218. namespace tls {
  3219. namespace impl {
  3220. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  3221. // cert/key). This struct is accessible via tls::impl for use in SSL context
  3222. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  3223. struct MbedTlsContext {
  3224. mbedtls_ssl_config conf;
  3225. #ifndef CPPHTTPLIB_MBEDTLS_V4
  3226. // Mbed TLS 4.x uses PSA Crypto's internal RNG; no explicit entropy/DRBG.
  3227. mbedtls_entropy_context entropy;
  3228. mbedtls_ctr_drbg_context ctr_drbg;
  3229. #endif
  3230. mbedtls_x509_crt ca_chain;
  3231. mbedtls_x509_crt own_cert;
  3232. mbedtls_pk_context own_key;
  3233. bool is_server = false;
  3234. bool verify_client = false;
  3235. bool has_verify_callback = false;
  3236. MbedTlsContext();
  3237. ~MbedTlsContext();
  3238. MbedTlsContext(const MbedTlsContext &) = delete;
  3239. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  3240. };
  3241. } // namespace impl
  3242. } // namespace tls
  3243. #endif
  3244. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  3245. namespace tls {
  3246. namespace impl {
  3247. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  3248. // This struct is accessible via tls::impl for use in SSL context
  3249. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  3250. struct WolfSSLContext {
  3251. WOLFSSL_CTX *ctx = nullptr;
  3252. bool is_server = false;
  3253. bool verify_client = false;
  3254. bool has_verify_callback = false;
  3255. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  3256. WolfSSLContext();
  3257. ~WolfSSLContext();
  3258. WolfSSLContext(const WolfSSLContext &) = delete;
  3259. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  3260. };
  3261. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  3262. struct WolfSSLCAStore {
  3263. std::string pem_data;
  3264. };
  3265. } // namespace impl
  3266. } // namespace tls
  3267. #endif
  3268. #endif // CPPHTTPLIB_SSL_ENABLED
  3269. namespace stream {
  3270. class Result {
  3271. public:
  3272. Result();
  3273. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  3274. Result(Result &&other) noexcept;
  3275. Result &operator=(Result &&other) noexcept;
  3276. Result(const Result &) = delete;
  3277. Result &operator=(const Result &) = delete;
  3278. // Response info
  3279. bool is_valid() const;
  3280. explicit operator bool() const;
  3281. int status() const;
  3282. const Headers &headers() const;
  3283. std::string get_header_value(const std::string &key,
  3284. const char *def = "") const;
  3285. bool has_header(const std::string &key) const;
  3286. Error error() const;
  3287. Error read_error() const;
  3288. bool has_read_error() const;
  3289. // Stream reading
  3290. bool next();
  3291. const char *data() const;
  3292. size_t size() const;
  3293. std::string read_all();
  3294. private:
  3295. ClientImpl::StreamHandle handle_;
  3296. std::string buffer_;
  3297. size_t current_size_ = 0;
  3298. size_t chunk_size_;
  3299. bool finished_ = false;
  3300. };
  3301. // GET
  3302. template <typename ClientType>
  3303. inline Result Get(ClientType &cli, const std::string &path,
  3304. size_t chunk_size = 8192) {
  3305. return Result{cli.open_stream("GET", path), chunk_size};
  3306. }
  3307. template <typename ClientType>
  3308. inline Result Get(ClientType &cli, const std::string &path,
  3309. const Headers &headers, size_t chunk_size = 8192) {
  3310. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  3311. }
  3312. template <typename ClientType>
  3313. inline Result Get(ClientType &cli, const std::string &path,
  3314. const Params &params, size_t chunk_size = 8192) {
  3315. return Result{cli.open_stream("GET", path, params), chunk_size};
  3316. }
  3317. template <typename ClientType>
  3318. inline Result Get(ClientType &cli, const std::string &path,
  3319. const Params &params, const Headers &headers,
  3320. size_t chunk_size = 8192) {
  3321. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  3322. }
  3323. // POST
  3324. template <typename ClientType>
  3325. inline Result Post(ClientType &cli, const std::string &path,
  3326. const std::string &body, const std::string &content_type,
  3327. size_t chunk_size = 8192) {
  3328. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  3329. chunk_size};
  3330. }
  3331. template <typename ClientType>
  3332. inline Result Post(ClientType &cli, const std::string &path,
  3333. const Headers &headers, const std::string &body,
  3334. const std::string &content_type, size_t chunk_size = 8192) {
  3335. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  3336. chunk_size};
  3337. }
  3338. template <typename ClientType>
  3339. inline Result Post(ClientType &cli, const std::string &path,
  3340. const Params &params, const std::string &body,
  3341. const std::string &content_type, size_t chunk_size = 8192) {
  3342. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  3343. chunk_size};
  3344. }
  3345. template <typename ClientType>
  3346. inline Result Post(ClientType &cli, const std::string &path,
  3347. const Params &params, const Headers &headers,
  3348. const std::string &body, const std::string &content_type,
  3349. size_t chunk_size = 8192) {
  3350. return Result{
  3351. cli.open_stream("POST", path, params, headers, body, content_type),
  3352. chunk_size};
  3353. }
  3354. // PUT
  3355. template <typename ClientType>
  3356. inline Result Put(ClientType &cli, const std::string &path,
  3357. const std::string &body, const std::string &content_type,
  3358. size_t chunk_size = 8192) {
  3359. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  3360. chunk_size};
  3361. }
  3362. template <typename ClientType>
  3363. inline Result Put(ClientType &cli, const std::string &path,
  3364. const Headers &headers, const std::string &body,
  3365. const std::string &content_type, size_t chunk_size = 8192) {
  3366. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  3367. chunk_size};
  3368. }
  3369. template <typename ClientType>
  3370. inline Result Put(ClientType &cli, const std::string &path,
  3371. const Params &params, const std::string &body,
  3372. const std::string &content_type, size_t chunk_size = 8192) {
  3373. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  3374. chunk_size};
  3375. }
  3376. template <typename ClientType>
  3377. inline Result Put(ClientType &cli, const std::string &path,
  3378. const Params &params, const Headers &headers,
  3379. const std::string &body, const std::string &content_type,
  3380. size_t chunk_size = 8192) {
  3381. return Result{
  3382. cli.open_stream("PUT", path, params, headers, body, content_type),
  3383. chunk_size};
  3384. }
  3385. // PATCH
  3386. template <typename ClientType>
  3387. inline Result Patch(ClientType &cli, const std::string &path,
  3388. const std::string &body, const std::string &content_type,
  3389. size_t chunk_size = 8192) {
  3390. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  3391. chunk_size};
  3392. }
  3393. template <typename ClientType>
  3394. inline Result Patch(ClientType &cli, const std::string &path,
  3395. const Headers &headers, const std::string &body,
  3396. const std::string &content_type, size_t chunk_size = 8192) {
  3397. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  3398. chunk_size};
  3399. }
  3400. template <typename ClientType>
  3401. inline Result Patch(ClientType &cli, const std::string &path,
  3402. const Params &params, const std::string &body,
  3403. const std::string &content_type, size_t chunk_size = 8192) {
  3404. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  3405. chunk_size};
  3406. }
  3407. template <typename ClientType>
  3408. inline Result Patch(ClientType &cli, const std::string &path,
  3409. const Params &params, const Headers &headers,
  3410. const std::string &body, const std::string &content_type,
  3411. size_t chunk_size = 8192) {
  3412. return Result{
  3413. cli.open_stream("PATCH", path, params, headers, body, content_type),
  3414. chunk_size};
  3415. }
  3416. // DELETE
  3417. template <typename ClientType>
  3418. inline Result Delete(ClientType &cli, const std::string &path,
  3419. size_t chunk_size = 8192) {
  3420. return Result{cli.open_stream("DELETE", path), chunk_size};
  3421. }
  3422. template <typename ClientType>
  3423. inline Result Delete(ClientType &cli, const std::string &path,
  3424. const Headers &headers, size_t chunk_size = 8192) {
  3425. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  3426. }
  3427. template <typename ClientType>
  3428. inline Result Delete(ClientType &cli, const std::string &path,
  3429. const std::string &body, const std::string &content_type,
  3430. size_t chunk_size = 8192) {
  3431. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3432. chunk_size};
  3433. }
  3434. template <typename ClientType>
  3435. inline Result Delete(ClientType &cli, const std::string &path,
  3436. const Headers &headers, const std::string &body,
  3437. const std::string &content_type,
  3438. size_t chunk_size = 8192) {
  3439. return Result{
  3440. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3441. chunk_size};
  3442. }
  3443. template <typename ClientType>
  3444. inline Result Delete(ClientType &cli, const std::string &path,
  3445. const Params &params, size_t chunk_size = 8192) {
  3446. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3447. }
  3448. template <typename ClientType>
  3449. inline Result Delete(ClientType &cli, const std::string &path,
  3450. const Params &params, const Headers &headers,
  3451. size_t chunk_size = 8192) {
  3452. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3453. }
  3454. template <typename ClientType>
  3455. inline Result Delete(ClientType &cli, const std::string &path,
  3456. const Params &params, const std::string &body,
  3457. const std::string &content_type,
  3458. size_t chunk_size = 8192) {
  3459. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3460. chunk_size};
  3461. }
  3462. template <typename ClientType>
  3463. inline Result Delete(ClientType &cli, const std::string &path,
  3464. const Params &params, const Headers &headers,
  3465. const std::string &body, const std::string &content_type,
  3466. size_t chunk_size = 8192) {
  3467. return Result{
  3468. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3469. chunk_size};
  3470. }
  3471. // HEAD
  3472. template <typename ClientType>
  3473. inline Result Head(ClientType &cli, const std::string &path,
  3474. size_t chunk_size = 8192) {
  3475. return Result{cli.open_stream("HEAD", path), chunk_size};
  3476. }
  3477. template <typename ClientType>
  3478. inline Result Head(ClientType &cli, const std::string &path,
  3479. const Headers &headers, size_t chunk_size = 8192) {
  3480. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3481. }
  3482. template <typename ClientType>
  3483. inline Result Head(ClientType &cli, const std::string &path,
  3484. const Params &params, size_t chunk_size = 8192) {
  3485. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3486. }
  3487. template <typename ClientType>
  3488. inline Result Head(ClientType &cli, const std::string &path,
  3489. const Params &params, const Headers &headers,
  3490. size_t chunk_size = 8192) {
  3491. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3492. }
  3493. // OPTIONS
  3494. template <typename ClientType>
  3495. inline Result Options(ClientType &cli, const std::string &path,
  3496. size_t chunk_size = 8192) {
  3497. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3498. }
  3499. template <typename ClientType>
  3500. inline Result Options(ClientType &cli, const std::string &path,
  3501. const Headers &headers, size_t chunk_size = 8192) {
  3502. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3503. }
  3504. template <typename ClientType>
  3505. inline Result Options(ClientType &cli, const std::string &path,
  3506. const Params &params, size_t chunk_size = 8192) {
  3507. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3508. }
  3509. template <typename ClientType>
  3510. inline Result Options(ClientType &cli, const std::string &path,
  3511. const Params &params, const Headers &headers,
  3512. size_t chunk_size = 8192) {
  3513. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3514. }
  3515. } // namespace stream
  3516. namespace sse {
  3517. struct SSEMessage {
  3518. std::string event; // Event type (default: "message")
  3519. std::string data; // Event payload
  3520. std::string id; // Event ID for Last-Event-ID header
  3521. SSEMessage();
  3522. void clear();
  3523. };
  3524. class SSEClient {
  3525. public:
  3526. using MessageHandler = std::function<void(const SSEMessage &)>;
  3527. using ErrorHandler = std::function<void(Error)>;
  3528. using OpenHandler = std::function<void()>;
  3529. SSEClient(Client &client, const std::string &path);
  3530. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3531. ~SSEClient();
  3532. SSEClient(const SSEClient &) = delete;
  3533. SSEClient &operator=(const SSEClient &) = delete;
  3534. // Event handlers
  3535. SSEClient &on_message(MessageHandler handler);
  3536. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3537. SSEClient &on_open(OpenHandler handler);
  3538. SSEClient &on_error(ErrorHandler handler);
  3539. SSEClient &set_reconnect_interval(int ms);
  3540. SSEClient &set_max_reconnect_attempts(int n);
  3541. // Update headers (thread-safe)
  3542. SSEClient &set_headers(const Headers &headers);
  3543. // State accessors
  3544. bool is_connected() const;
  3545. const std::string &last_event_id() const;
  3546. // Blocking start - runs event loop with auto-reconnect
  3547. void start();
  3548. // Non-blocking start - runs in background thread
  3549. void start_async();
  3550. // Stop the client (thread-safe)
  3551. void stop();
  3552. private:
  3553. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3554. void run_event_loop();
  3555. void dispatch_event(const SSEMessage &msg);
  3556. bool should_reconnect(int count) const;
  3557. void wait_for_reconnect();
  3558. // Client and path
  3559. Client &client_;
  3560. std::string path_;
  3561. Headers headers_;
  3562. mutable std::mutex headers_mutex_;
  3563. // Callbacks
  3564. MessageHandler on_message_;
  3565. std::map<std::string, MessageHandler> event_handlers_;
  3566. OpenHandler on_open_;
  3567. ErrorHandler on_error_;
  3568. // Configuration
  3569. int reconnect_interval_ms_ = 3000;
  3570. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3571. // State
  3572. std::atomic<bool> running_{false};
  3573. std::atomic<bool> connected_{false};
  3574. std::string last_event_id_;
  3575. // Async support
  3576. std::thread async_thread_;
  3577. };
  3578. } // namespace sse
  3579. namespace ws {
  3580. enum class Opcode : uint8_t {
  3581. Continuation = 0x0,
  3582. Text = 0x1,
  3583. Binary = 0x2,
  3584. Close = 0x8,
  3585. Ping = 0x9,
  3586. Pong = 0xA,
  3587. };
  3588. enum class CloseStatus : uint16_t {
  3589. Normal = 1000,
  3590. GoingAway = 1001,
  3591. ProtocolError = 1002,
  3592. UnsupportedData = 1003,
  3593. NoStatus = 1005,
  3594. Abnormal = 1006,
  3595. InvalidPayload = 1007,
  3596. PolicyViolation = 1008,
  3597. MessageTooBig = 1009,
  3598. MandatoryExtension = 1010,
  3599. InternalError = 1011,
  3600. };
  3601. // Timeout is returned only when a read timeout was set and it elapsed before
  3602. // any byte of a frame arrived: nothing was consumed and the connection is
  3603. // still open, so the caller can send on it and read again. `msg` is left
  3604. // untouched, so a `while (ws.read(msg))` loop must not treat it as a message.
  3605. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2, Timeout = 3 };
  3606. // Result of WebSocketClient::connect(). Truthy only when the WebSocket
  3607. // upgrade handshake fully succeeded. On failure error() identifies the
  3608. // failing layer; status()/headers() expose the server's upgrade response
  3609. // when one was received (status() is -1 otherwise).
  3610. class Result {
  3611. public:
  3612. Result() = default;
  3613. Result(Error err, int status, Headers &&headers)
  3614. : err_(err), status_(status), headers_(std::move(headers)) {}
  3615. explicit operator bool() const { return err_ == Error::Success; }
  3616. Error error() const { return err_; }
  3617. // Upgrade response info
  3618. int status() const { return status_; }
  3619. const Headers &headers() const { return headers_; }
  3620. std::string get_header_value(const std::string &key,
  3621. const char *def = "") const {
  3622. return detail::get_header_value(headers_, key, def, 0);
  3623. }
  3624. bool has_header(const std::string &key) const {
  3625. return headers_.find(key) != headers_.end();
  3626. }
  3627. #ifdef CPPHTTPLIB_SSL_ENABLED
  3628. Result(Error err, int status, Headers &&headers, int ssl_error,
  3629. uint64_t ssl_backend_error)
  3630. : err_(err), status_(status), headers_(std::move(headers)),
  3631. ssl_error_(ssl_error), ssl_backend_error_(ssl_backend_error) {}
  3632. int ssl_error() const { return ssl_error_; }
  3633. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  3634. #endif
  3635. private:
  3636. Error err_ = Error::Unknown; // a default-constructed Result is falsy
  3637. int status_ = -1;
  3638. Headers headers_;
  3639. #ifdef CPPHTTPLIB_SSL_ENABLED
  3640. int ssl_error_ = 0;
  3641. uint64_t ssl_backend_error_ = 0;
  3642. #endif
  3643. };
  3644. class WebSocket {
  3645. public:
  3646. WebSocket(const WebSocket &) = delete;
  3647. WebSocket &operator=(const WebSocket &) = delete;
  3648. ~WebSocket();
  3649. ReadResult read(std::string &msg);
  3650. bool send(const std::string &data);
  3651. bool send(const char *data, size_t len);
  3652. void close(CloseStatus status = CloseStatus::Normal,
  3653. const std::string &reason = "");
  3654. const Request &request() const;
  3655. bool is_open() const;
  3656. // Bound how long read() waits before returning Timeout. 0 waits forever.
  3657. // A server handler owns its connection's timeout this way; a client sets it
  3658. // through WebSocketClient. Safe to call while another thread is in read().
  3659. //
  3660. // Only a timeout set here is reported as Timeout. The compile-time default
  3661. // (CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND) is a backstop rather
  3662. // than a request for control, so when it elapses read() returns Fail and
  3663. // closes the connection, and `while (ws.read(msg))` ends as it always has.
  3664. void set_read_timeout(time_t sec, time_t usec = 0);
  3665. template <class Rep, class Period>
  3666. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  3667. private:
  3668. friend class httplib::Server;
  3669. friend class WebSocketClient;
  3670. WebSocket(
  3671. Stream &strm, const Request &req, bool is_server,
  3672. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3673. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3674. : strm_(strm), req_(req), is_server_(is_server),
  3675. ping_interval_sec_(ping_interval_sec),
  3676. max_missed_pongs_(max_missed_pongs) {
  3677. start_heartbeat();
  3678. }
  3679. WebSocket(
  3680. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3681. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3682. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3683. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3684. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3685. max_missed_pongs_(max_missed_pongs) {
  3686. start_heartbeat();
  3687. }
  3688. void start_heartbeat();
  3689. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3690. Stream &strm_;
  3691. std::unique_ptr<Stream> owned_strm_;
  3692. Request req_;
  3693. bool is_server_;
  3694. time_t ping_interval_sec_;
  3695. int max_missed_pongs_;
  3696. int unacked_pings_ = 0;
  3697. std::atomic<bool> closed_{false};
  3698. // Set once the caller has bounded read() through set_read_timeout(). Until
  3699. // then the timeout in effect is the compile-time default, and elapsing it
  3700. // is a failure that closes the connection, not a Timeout.
  3701. std::atomic<bool> read_timeout_set_{false};
  3702. std::mutex write_mutex_;
  3703. // Owned by whichever thread is parsing frames off strm_. Only one thread
  3704. // may do so: read_websocket_frame() reads a payload until it has the whole
  3705. // declared length, so a second parser stealing bytes silently corrupts the
  3706. // message the first one is assembling.
  3707. std::mutex read_mutex_;
  3708. std::thread ping_thread_;
  3709. std::mutex ping_mutex_;
  3710. std::condition_variable ping_cv_;
  3711. };
  3712. class WebSocketClient {
  3713. public:
  3714. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3715. const Headers &headers = {});
  3716. ~WebSocketClient();
  3717. WebSocketClient(const WebSocketClient &) = delete;
  3718. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3719. bool is_valid() const;
  3720. Result connect();
  3721. ReadResult read(std::string &msg);
  3722. bool send(const std::string &data);
  3723. bool send(const char *data, size_t len);
  3724. void close(CloseStatus status = CloseStatus::Normal,
  3725. const std::string &reason = "");
  3726. bool is_open() const;
  3727. const std::string &subprotocol() const;
  3728. void set_read_timeout(time_t sec, time_t usec = 0);
  3729. template <class Rep, class Period>
  3730. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  3731. void set_write_timeout(time_t sec, time_t usec = 0);
  3732. template <class Rep, class Period>
  3733. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  3734. void set_websocket_ping_interval(time_t sec);
  3735. void set_websocket_max_missed_pongs(int count);
  3736. void set_tcp_nodelay(bool on);
  3737. void set_address_family(int family);
  3738. void set_ipv6_v6only(bool on);
  3739. void set_socket_options(SocketOptions socket_options);
  3740. void set_connection_timeout(time_t sec, time_t usec = 0);
  3741. template <class Rep, class Period>
  3742. void
  3743. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  3744. void set_interface(const std::string &intf);
  3745. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3746. #ifdef CPPHTTPLIB_SSL_ENABLED
  3747. struct PemMemory {
  3748. const char *cert_pem;
  3749. size_t cert_pem_len;
  3750. const char *key_pem;
  3751. size_t key_pem_len;
  3752. const char *private_key_password;
  3753. };
  3754. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3755. const PemMemory &pem, const Headers &headers = {});
  3756. void set_ca_cert_path(const std::string &ca_cert_file_path,
  3757. const std::string &ca_cert_dir_path = std::string());
  3758. void set_ca_cert_store(tls::ca_store_t store);
  3759. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3760. void enable_server_certificate_verification(bool enabled);
  3761. void enable_server_hostname_verification(bool enabled);
  3762. void enable_system_ca(bool enabled);
  3763. #endif
  3764. private:
  3765. void shutdown_and_close();
  3766. bool create_stream(std::unique_ptr<Stream> &strm, Error &error,
  3767. int &ssl_error, uint64_t &ssl_backend_error);
  3768. void prepare_default_headers(Request &req);
  3769. std::string host_;
  3770. int port_;
  3771. std::string path_;
  3772. Headers headers_;
  3773. std::string subprotocol_;
  3774. bool is_valid_ = false;
  3775. socket_t sock_ = INVALID_SOCKET;
  3776. std::unique_ptr<WebSocket> ws_;
  3777. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND;
  3778. time_t read_timeout_usec_ = 0;
  3779. bool read_timeout_set_ = false; // see WebSocket::read_timeout_set_
  3780. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3781. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3782. time_t websocket_ping_interval_sec_ =
  3783. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3784. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3785. int address_family_ = AF_UNSPEC;
  3786. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3787. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3788. SocketOptions socket_options_ = nullptr;
  3789. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3790. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3791. std::string interface_;
  3792. // Hostname to connection target map. The value is an IP literal or another
  3793. // hostname; only the connection target changes, never the identity.
  3794. std::map<std::string, std::string> addr_map_;
  3795. #ifdef CPPHTTPLIB_SSL_ENABLED
  3796. bool is_ssl_ = false;
  3797. tls::ctx_t tls_ctx_ = nullptr;
  3798. tls::session_t tls_session_ = nullptr;
  3799. std::string ca_cert_file_path_;
  3800. std::string ca_cert_dir_path_;
  3801. bool custom_ca_loaded_ = false;
  3802. bool certs_loaded_ = false;
  3803. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3804. bool server_certificate_verification_ = true;
  3805. bool server_hostname_verification_ = true;
  3806. #endif
  3807. };
  3808. template <class Rep, class Period>
  3809. inline void WebSocket::set_read_timeout(
  3810. const std::chrono::duration<Rep, Period> &duration) {
  3811. detail::duration_to_sec_and_usec(
  3812. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3813. }
  3814. template <class Rep, class Period>
  3815. inline void WebSocketClient::set_read_timeout(
  3816. const std::chrono::duration<Rep, Period> &duration) {
  3817. detail::duration_to_sec_and_usec(
  3818. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3819. }
  3820. template <class Rep, class Period>
  3821. inline void WebSocketClient::set_write_timeout(
  3822. const std::chrono::duration<Rep, Period> &duration) {
  3823. detail::duration_to_sec_and_usec(
  3824. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3825. }
  3826. template <class Rep, class Period>
  3827. inline void WebSocketClient::set_connection_timeout(
  3828. const std::chrono::duration<Rep, Period> &duration) {
  3829. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  3830. set_connection_timeout(sec, usec);
  3831. });
  3832. }
  3833. namespace impl {
  3834. bool is_valid_utf8(const std::string &s);
  3835. // Three states, because a failure that consumed bytes and one that consumed
  3836. // none are not the same thing: the first has left the stream in the middle of
  3837. // a frame and the connection cannot be reused, the second can just be retried.
  3838. enum class FrameRead { Ok, Fail, Timeout };
  3839. FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  3840. std::string &payload, bool &fin,
  3841. bool expect_masked, size_t max_len);
  3842. } // namespace impl
  3843. } // namespace ws
  3844. // ----------------------------------------------------------------------------
  3845. /*
  3846. * Implementation that will be part of the .cc file if split into .h + .cc.
  3847. */
  3848. namespace stream {
  3849. // stream::Result implementations
  3850. inline Result::Result() : chunk_size_(8192) {}
  3851. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3852. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3853. inline Result::Result(Result &&other) noexcept
  3854. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3855. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3856. finished_(other.finished_) {
  3857. other.current_size_ = 0;
  3858. other.finished_ = true;
  3859. }
  3860. inline Result &Result::operator=(Result &&other) noexcept {
  3861. if (this != &other) {
  3862. handle_ = std::move(other.handle_);
  3863. buffer_ = std::move(other.buffer_);
  3864. current_size_ = other.current_size_;
  3865. chunk_size_ = other.chunk_size_;
  3866. finished_ = other.finished_;
  3867. other.current_size_ = 0;
  3868. other.finished_ = true;
  3869. }
  3870. return *this;
  3871. }
  3872. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3873. inline Result::operator bool() const { return is_valid(); }
  3874. inline int Result::status() const {
  3875. return handle_.response ? handle_.response->status : -1;
  3876. }
  3877. inline const Headers &Result::headers() const {
  3878. static const Headers empty_headers;
  3879. return handle_.response ? handle_.response->headers : empty_headers;
  3880. }
  3881. inline std::string Result::get_header_value(const std::string &key,
  3882. const char *def) const {
  3883. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3884. }
  3885. inline bool Result::has_header(const std::string &key) const {
  3886. return handle_.response ? handle_.response->has_header(key) : false;
  3887. }
  3888. inline Error Result::error() const { return handle_.error; }
  3889. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3890. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3891. inline bool Result::next() {
  3892. if (!handle_.is_valid() || finished_) { return false; }
  3893. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3894. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3895. if (n > 0) {
  3896. current_size_ = static_cast<size_t>(n);
  3897. return true;
  3898. }
  3899. current_size_ = 0;
  3900. finished_ = true;
  3901. return false;
  3902. }
  3903. inline const char *Result::data() const { return buffer_.data(); }
  3904. inline size_t Result::size() const { return current_size_; }
  3905. inline std::string Result::read_all() {
  3906. std::string result;
  3907. while (next()) {
  3908. result.append(data(), size());
  3909. }
  3910. return result;
  3911. }
  3912. } // namespace stream
  3913. namespace sse {
  3914. // SSEMessage implementations
  3915. inline SSEMessage::SSEMessage() : event("message") {}
  3916. inline void SSEMessage::clear() {
  3917. event = "message";
  3918. data.clear();
  3919. id.clear();
  3920. }
  3921. // SSEClient implementations
  3922. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3923. : client_(client), path_(path) {}
  3924. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3925. const Headers &headers)
  3926. : client_(client), path_(path), headers_(headers) {}
  3927. inline SSEClient::~SSEClient() { stop(); }
  3928. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3929. on_message_ = std::move(handler);
  3930. return *this;
  3931. }
  3932. inline SSEClient &SSEClient::on_event(const std::string &type,
  3933. MessageHandler handler) {
  3934. event_handlers_[type] = std::move(handler);
  3935. return *this;
  3936. }
  3937. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3938. on_open_ = std::move(handler);
  3939. return *this;
  3940. }
  3941. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3942. on_error_ = std::move(handler);
  3943. return *this;
  3944. }
  3945. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3946. reconnect_interval_ms_ = ms;
  3947. return *this;
  3948. }
  3949. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3950. max_reconnect_attempts_ = n;
  3951. return *this;
  3952. }
  3953. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3954. std::lock_guard<std::mutex> lock(headers_mutex_);
  3955. headers_ = headers;
  3956. return *this;
  3957. }
  3958. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3959. inline const std::string &SSEClient::last_event_id() const {
  3960. return last_event_id_;
  3961. }
  3962. inline void SSEClient::start() {
  3963. running_.store(true);
  3964. run_event_loop();
  3965. }
  3966. inline void SSEClient::start_async() {
  3967. running_.store(true);
  3968. async_thread_ = std::thread([this]() { run_event_loop(); });
  3969. }
  3970. inline void SSEClient::stop() {
  3971. running_.store(false);
  3972. client_.stop(); // Cancel any pending operations
  3973. if (async_thread_.joinable()) { async_thread_.join(); }
  3974. }
  3975. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3976. int &retry_ms) {
  3977. // Blank line signals end of event
  3978. if (line.empty() || line == "\r") { return true; }
  3979. // Lines starting with ':' are comments (ignored)
  3980. if (!line.empty() && line[0] == ':') { return false; }
  3981. // Find the colon separator
  3982. auto colon_pos = line.find(':');
  3983. if (colon_pos == std::string::npos) {
  3984. // Line with no colon is treated as field name with empty value
  3985. return false;
  3986. }
  3987. auto field = line.substr(0, colon_pos);
  3988. std::string value;
  3989. // Value starts after colon, skip optional single space
  3990. if (colon_pos + 1 < line.size()) {
  3991. auto value_start = colon_pos + 1;
  3992. if (line[value_start] == ' ') { value_start++; }
  3993. value = line.substr(value_start);
  3994. // Remove trailing \r if present
  3995. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3996. }
  3997. // Handle known fields
  3998. if (field == "event") {
  3999. msg.event = value;
  4000. } else if (field == "data") {
  4001. // Multiple data lines are concatenated with newlines
  4002. if (!msg.data.empty()) { msg.data += "\n"; }
  4003. msg.data += value;
  4004. } else if (field == "id") {
  4005. // Empty id is valid (clears the last event ID)
  4006. msg.id = value;
  4007. } else if (field == "retry") {
  4008. // Parse retry interval in milliseconds
  4009. {
  4010. int v = 0;
  4011. auto res =
  4012. detail::from_chars(value.data(), value.data() + value.size(), v);
  4013. if (res.ec == std::errc{}) { retry_ms = v; }
  4014. }
  4015. }
  4016. // Unknown fields are ignored per SSE spec
  4017. return false;
  4018. }
  4019. inline void SSEClient::run_event_loop() {
  4020. auto reconnect_count = 0;
  4021. while (running_.load()) {
  4022. // Build headers, including Last-Event-ID if we have one
  4023. Headers request_headers;
  4024. {
  4025. std::lock_guard<std::mutex> lock(headers_mutex_);
  4026. request_headers = headers_;
  4027. }
  4028. if (!last_event_id_.empty()) {
  4029. request_headers.emplace("Last-Event-ID", last_event_id_);
  4030. }
  4031. // Open streaming connection
  4032. auto result = stream::Get(client_, path_, request_headers);
  4033. // Connection error handling
  4034. if (!result) {
  4035. connected_.store(false);
  4036. if (on_error_) { on_error_(result.error()); }
  4037. if (!should_reconnect(reconnect_count)) { break; }
  4038. wait_for_reconnect();
  4039. reconnect_count++;
  4040. continue;
  4041. }
  4042. if (result.status() != StatusCode::OK_200) {
  4043. connected_.store(false);
  4044. if (on_error_) { on_error_(Error::Connection); }
  4045. // For certain errors, don't reconnect.
  4046. // Note: 401 is intentionally absent so that handlers can refresh
  4047. // credentials via set_headers() and let the client reconnect.
  4048. if (result.status() == StatusCode::NoContent_204 ||
  4049. result.status() == StatusCode::NotFound_404 ||
  4050. result.status() == StatusCode::Forbidden_403) {
  4051. break;
  4052. }
  4053. if (!should_reconnect(reconnect_count)) { break; }
  4054. wait_for_reconnect();
  4055. reconnect_count++;
  4056. continue;
  4057. }
  4058. // Connection successful
  4059. connected_.store(true);
  4060. reconnect_count = 0;
  4061. if (on_open_) { on_open_(); }
  4062. // Event receiving loop
  4063. std::string buffer;
  4064. SSEMessage current_msg;
  4065. while (running_.load() && result.next()) {
  4066. buffer.append(result.data(), result.size());
  4067. // Process complete lines in the buffer
  4068. size_t line_start = 0;
  4069. size_t newline_pos;
  4070. while ((newline_pos = buffer.find('\n', line_start)) !=
  4071. std::string::npos) {
  4072. auto line = buffer.substr(line_start, newline_pos - line_start);
  4073. line_start = newline_pos + 1;
  4074. // Parse the line and check if event is complete
  4075. auto event_complete =
  4076. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  4077. if (event_complete && !current_msg.data.empty()) {
  4078. // Update last_event_id for reconnection
  4079. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  4080. // Dispatch event to appropriate handler
  4081. dispatch_event(current_msg);
  4082. current_msg.clear();
  4083. }
  4084. }
  4085. // Keep unprocessed data in buffer
  4086. buffer.erase(0, line_start);
  4087. }
  4088. // Connection ended
  4089. connected_.store(false);
  4090. if (!running_.load()) { break; }
  4091. // Check for read errors
  4092. if (result.has_read_error()) {
  4093. if (on_error_) { on_error_(result.read_error()); }
  4094. }
  4095. if (!should_reconnect(reconnect_count)) { break; }
  4096. wait_for_reconnect();
  4097. reconnect_count++;
  4098. }
  4099. connected_.store(false);
  4100. }
  4101. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  4102. // Check for specific event type handler first
  4103. auto it = event_handlers_.find(msg.event);
  4104. if (it != event_handlers_.end()) {
  4105. it->second(msg);
  4106. return;
  4107. }
  4108. // Fall back to generic message handler
  4109. if (on_message_) { on_message_(msg); }
  4110. }
  4111. inline bool SSEClient::should_reconnect(int count) const {
  4112. if (!running_.load()) { return false; }
  4113. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  4114. return count < max_reconnect_attempts_;
  4115. }
  4116. inline void SSEClient::wait_for_reconnect() {
  4117. // Use small increments to check running_ flag frequently
  4118. auto waited = 0;
  4119. while (running_.load() && waited < reconnect_interval_ms_) {
  4120. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4121. waited += 100;
  4122. }
  4123. }
  4124. } // namespace sse
  4125. #ifdef CPPHTTPLIB_SSL_ENABLED
  4126. /*
  4127. * TLS abstraction layer - internal function declarations
  4128. * These are implementation details and not part of the public API.
  4129. */
  4130. namespace tls {
  4131. // Client context
  4132. ctx_t create_client_context();
  4133. void free_context(ctx_t ctx);
  4134. bool set_min_version(ctx_t ctx, Version version);
  4135. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  4136. bool load_ca_file(ctx_t ctx, const char *file_path);
  4137. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  4138. bool load_system_certs(ctx_t ctx);
  4139. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4140. const char *password);
  4141. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  4142. const char *key_path, const char *password);
  4143. // Server context
  4144. ctx_t create_server_context();
  4145. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4146. const char *password);
  4147. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  4148. const char *key_path, const char *password);
  4149. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  4150. void set_verify_client(ctx_t ctx, bool require);
  4151. // Session management
  4152. session_t create_session(ctx_t ctx, socket_t sock);
  4153. void free_session(session_t session);
  4154. bool set_sni(session_t session, const char *hostname, bool verify_hostname);
  4155. // Handshake (non-blocking capable)
  4156. TlsError connect(session_t session);
  4157. TlsError accept(session_t session);
  4158. // Handshake with timeout (blocking until timeout)
  4159. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4160. time_t timeout_usec, TlsError *err);
  4161. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4162. time_t timeout_usec, TlsError *err);
  4163. // I/O (non-blocking capable)
  4164. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  4165. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  4166. int pending(const_session_t session);
  4167. void shutdown(session_t session, bool graceful);
  4168. // Connection state
  4169. bool is_peer_closed(session_t session, socket_t sock);
  4170. // Certificate verification
  4171. cert_t get_peer_cert(const_session_t session);
  4172. void free_cert(cert_t cert);
  4173. bool verify_hostname(cert_t cert, const char *hostname);
  4174. uint64_t hostname_mismatch_code();
  4175. long get_verify_result(const_session_t session);
  4176. // Certificate introspection
  4177. std::string get_cert_subject_cn(cert_t cert);
  4178. std::string get_cert_issuer_name(cert_t cert);
  4179. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  4180. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  4181. std::string get_cert_serial(cert_t cert);
  4182. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  4183. const char *get_sni(const_session_t session);
  4184. // CA store management
  4185. ca_store_t create_ca_store(const char *pem, size_t len);
  4186. void free_ca_store(ca_store_t store);
  4187. bool set_ca_store(ctx_t ctx, ca_store_t store);
  4188. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  4189. std::vector<std::string> get_ca_names(ctx_t ctx);
  4190. // Dynamic certificate update (for servers)
  4191. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  4192. const char *password);
  4193. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  4194. // Certificate verification callback
  4195. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  4196. long get_verify_error(const_session_t session);
  4197. std::string verify_error_string(long error_code);
  4198. // TlsError information
  4199. uint64_t peek_error();
  4200. uint64_t get_error();
  4201. std::string error_string(uint64_t code);
  4202. } // namespace tls
  4203. #endif // CPPHTTPLIB_SSL_ENABLED
  4204. /*
  4205. * Group 1: detail namespace - Non-SSL utilities
  4206. */
  4207. namespace detail {
  4208. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  4209. const void *optval, socklen_t optlen) {
  4210. return setsockopt(sock, level, optname,
  4211. #ifdef _WIN32
  4212. reinterpret_cast<const char *>(optval),
  4213. #else
  4214. optval,
  4215. #endif
  4216. optlen) == 0;
  4217. }
  4218. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  4219. time_t sec, time_t usec) {
  4220. #ifdef _WIN32
  4221. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  4222. #else
  4223. timeval timeout;
  4224. timeout.tv_sec = static_cast<long>(sec);
  4225. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  4226. #endif
  4227. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  4228. }
  4229. inline bool is_hex(char c, int &v) {
  4230. if (is_ascii_digit(c)) {
  4231. v = c - '0';
  4232. return true;
  4233. } else if ('A' <= c && c <= 'F') {
  4234. v = c - 'A' + 10;
  4235. return true;
  4236. } else if ('a' <= c && c <= 'f') {
  4237. v = c - 'a' + 10;
  4238. return true;
  4239. }
  4240. return false;
  4241. }
  4242. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  4243. int &val) {
  4244. if (i >= s.size()) { return false; }
  4245. val = 0;
  4246. for (; cnt; i++, cnt--) {
  4247. if (!s[i]) { return false; }
  4248. auto v = 0;
  4249. if (is_hex(s[i], v)) {
  4250. val = val * 16 + v;
  4251. } else {
  4252. return false;
  4253. }
  4254. }
  4255. return true;
  4256. }
  4257. inline std::string from_i_to_hex(size_t n) {
  4258. static const auto charset = "0123456789abcdef";
  4259. std::string ret;
  4260. do {
  4261. ret = charset[n & 15] + ret;
  4262. n >>= 4;
  4263. } while (n > 0);
  4264. return ret;
  4265. }
  4266. inline std::string compute_etag(const FileStat &fs,
  4267. const std::string &suffix = std::string()) {
  4268. if (!fs.is_file()) { return std::string(); }
  4269. // If mtime cannot be determined (negative value indicates an error
  4270. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  4271. // value like 0 could collide with a real file that legitimately has
  4272. // mtime == 0 (epoch) and lead to misleading validators.
  4273. auto mtime_raw = fs.mtime();
  4274. if (mtime_raw < 0) { return std::string(); }
  4275. auto mtime = static_cast<size_t>(mtime_raw);
  4276. auto size = fs.size();
  4277. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  4278. from_i_to_hex(size) + suffix + "\"";
  4279. }
  4280. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  4281. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  4282. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  4283. inline std::string file_mtime_to_http_date(time_t mtime) {
  4284. if (mtime < 0) { return std::string(); }
  4285. struct tm tm_buf;
  4286. #ifdef _WIN32
  4287. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  4288. #else
  4289. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  4290. #endif
  4291. char buf[64];
  4292. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  4293. return std::string();
  4294. }
  4295. return std::string(buf);
  4296. }
  4297. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  4298. inline time_t parse_http_date(const std::string &date_str) {
  4299. struct tm tm_buf;
  4300. // Create a classic locale object once for all parsing attempts
  4301. const std::locale classic_locale = std::locale::classic();
  4302. // Try to parse using std::get_time (C++11, cross-platform)
  4303. auto try_parse = [&](const char *fmt) -> bool {
  4304. std::istringstream ss(date_str);
  4305. ss.imbue(classic_locale);
  4306. memset(&tm_buf, 0, sizeof(tm_buf));
  4307. ss >> std::get_time(&tm_buf, fmt);
  4308. return !ss.fail();
  4309. };
  4310. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  4311. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  4312. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  4313. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  4314. // asctime format: "Sun Nov 6 08:49:37 1994"
  4315. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  4316. return static_cast<time_t>(-1);
  4317. }
  4318. }
  4319. }
  4320. #ifdef _WIN32
  4321. return _mkgmtime(&tm_buf);
  4322. #elif defined _AIX
  4323. return mktime(&tm_buf);
  4324. #else
  4325. return timegm(&tm_buf);
  4326. #endif
  4327. }
  4328. inline bool is_weak_etag(const std::string &s) {
  4329. // Check if the string is a weak ETag (starts with 'W/"')
  4330. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  4331. }
  4332. inline bool is_strong_etag(const std::string &s) {
  4333. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  4334. // chars)
  4335. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  4336. }
  4337. inline size_t to_utf8(int code, char *buff) {
  4338. if (code < 0x0080) {
  4339. buff[0] = static_cast<char>(code & 0x7F);
  4340. return 1;
  4341. } else if (code < 0x0800) {
  4342. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  4343. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  4344. return 2;
  4345. } else if (code < 0xD800) {
  4346. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4347. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4348. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4349. return 3;
  4350. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  4351. return 0;
  4352. } else if (code < 0x10000) {
  4353. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4354. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4355. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4356. return 3;
  4357. } else if (code < 0x110000) {
  4358. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  4359. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  4360. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4361. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  4362. return 4;
  4363. }
  4364. // NOTREACHED
  4365. return 0;
  4366. }
  4367. } // namespace detail
  4368. namespace ws {
  4369. namespace impl {
  4370. inline bool is_valid_utf8(const std::string &s) {
  4371. size_t i = 0;
  4372. auto n = s.size();
  4373. while (i < n) {
  4374. auto c = static_cast<unsigned char>(s[i]);
  4375. size_t len;
  4376. uint32_t cp;
  4377. if (c < 0x80) {
  4378. i++;
  4379. continue;
  4380. } else if ((c & 0xE0) == 0xC0) {
  4381. len = 2;
  4382. cp = c & 0x1F;
  4383. } else if ((c & 0xF0) == 0xE0) {
  4384. len = 3;
  4385. cp = c & 0x0F;
  4386. } else if ((c & 0xF8) == 0xF0) {
  4387. len = 4;
  4388. cp = c & 0x07;
  4389. } else {
  4390. return false;
  4391. }
  4392. if (i + len > n) { return false; }
  4393. for (size_t j = 1; j < len; j++) {
  4394. auto b = static_cast<unsigned char>(s[i + j]);
  4395. if ((b & 0xC0) != 0x80) { return false; }
  4396. cp = (cp << 6) | (b & 0x3F);
  4397. }
  4398. // Overlong encoding check
  4399. if (len == 2 && cp < 0x80) { return false; }
  4400. if (len == 3 && cp < 0x800) { return false; }
  4401. if (len == 4 && cp < 0x10000) { return false; }
  4402. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  4403. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  4404. if (cp > 0x10FFFF) { return false; }
  4405. i += len;
  4406. }
  4407. return true;
  4408. }
  4409. } // namespace impl
  4410. } // namespace ws
  4411. namespace detail {
  4412. // NOTE: This code came up with the following stackoverflow post:
  4413. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  4414. inline std::string base64_encode(const std::string &in) {
  4415. static const auto lookup =
  4416. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4417. std::string out;
  4418. out.reserve(in.size());
  4419. // Unsigned: the accumulator is never masked, so with a signed int the
  4420. // `val << 8` below overflows once enough bytes are folded in (undefined
  4421. // behaviour before C++20). Only the low bits are ever emitted, so the
  4422. // wrap-around of an unsigned accumulator does not affect the output.
  4423. uint32_t val = 0;
  4424. auto valb = -6;
  4425. for (auto c : in) {
  4426. val = (val << 8) + static_cast<uint8_t>(c);
  4427. valb += 8;
  4428. while (valb >= 0) {
  4429. out.push_back(lookup[(val >> valb) & 0x3F]);
  4430. valb -= 6;
  4431. }
  4432. }
  4433. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  4434. while (out.size() % 4) {
  4435. out.push_back('=');
  4436. }
  4437. return out;
  4438. }
  4439. inline std::string sha1(const std::string &input) {
  4440. // RFC 3174 SHA-1 implementation
  4441. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  4442. return (x << n) | (x >> (32 - n));
  4443. };
  4444. uint32_t h0 = 0x67452301;
  4445. uint32_t h1 = 0xEFCDAB89;
  4446. uint32_t h2 = 0x98BADCFE;
  4447. uint32_t h3 = 0x10325476;
  4448. uint32_t h4 = 0xC3D2E1F0;
  4449. // Pre-processing: adding padding bits
  4450. std::string msg = input;
  4451. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  4452. msg.push_back(static_cast<char>(0x80u));
  4453. while (msg.size() % 64 != 56) {
  4454. msg.push_back(0);
  4455. }
  4456. // Append original length in bits as 64-bit big-endian
  4457. for (int i = 56; i >= 0; i -= 8) {
  4458. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  4459. }
  4460. // Process each 512-bit chunk
  4461. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  4462. uint32_t w[80];
  4463. for (size_t i = 0; i < 16; i++) {
  4464. w[i] =
  4465. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  4466. << 24) |
  4467. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  4468. << 16) |
  4469. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  4470. << 8) |
  4471. (static_cast<uint32_t>(
  4472. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  4473. }
  4474. for (int i = 16; i < 80; i++) {
  4475. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  4476. }
  4477. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  4478. for (int i = 0; i < 80; i++) {
  4479. uint32_t f, k;
  4480. if (i < 20) {
  4481. f = (b & c) | ((~b) & d);
  4482. k = 0x5A827999;
  4483. } else if (i < 40) {
  4484. f = b ^ c ^ d;
  4485. k = 0x6ED9EBA1;
  4486. } else if (i < 60) {
  4487. f = (b & c) | (b & d) | (c & d);
  4488. k = 0x8F1BBCDC;
  4489. } else {
  4490. f = b ^ c ^ d;
  4491. k = 0xCA62C1D6;
  4492. }
  4493. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  4494. e = d;
  4495. d = c;
  4496. c = left_rotate(b, 30);
  4497. b = a;
  4498. a = temp;
  4499. }
  4500. h0 += a;
  4501. h1 += b;
  4502. h2 += c;
  4503. h3 += d;
  4504. h4 += e;
  4505. }
  4506. // Produce the final hash as a 20-byte binary string
  4507. std::string hash(20, '\0');
  4508. for (size_t i = 0; i < 4; i++) {
  4509. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  4510. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  4511. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  4512. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  4513. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  4514. }
  4515. return hash;
  4516. }
  4517. inline std::string websocket_accept_key(const std::string &client_key) {
  4518. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  4519. return base64_encode(sha1(client_key + magic));
  4520. }
  4521. inline bool is_websocket_upgrade(const Request &req) {
  4522. if (req.method != "GET") { return false; }
  4523. // Check Upgrade: websocket. RFC 9110 7.8 defines Upgrade as a comma-separated
  4524. // list of protocols and asks recipients to match each name
  4525. // case-insensitively, so look for the token rather than compare the whole
  4526. // field value.
  4527. if (!has_header_token(req.headers, "Upgrade", "websocket")) { return false; }
  4528. // Check Connection: Upgrade
  4529. if (!has_header_token(req.headers, "Connection", "upgrade")) { return false; }
  4530. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  4531. // RFC 6455 Section 4.2.1
  4532. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  4533. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  4534. return false;
  4535. }
  4536. static const std::string b64chars =
  4537. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4538. for (size_t i = 0; i < 22; i++) {
  4539. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  4540. }
  4541. // Check Sec-WebSocket-Version: 13
  4542. auto version = req.get_header_value("Sec-WebSocket-Version");
  4543. if (version != "13") { return false; }
  4544. return true;
  4545. }
  4546. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  4547. const char *data, size_t len, bool fin,
  4548. bool mask) {
  4549. // First byte: FIN + opcode
  4550. uint8_t header[2];
  4551. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  4552. (static_cast<uint8_t>(opcode) & 0x0F));
  4553. // Second byte: MASK + payload length
  4554. if (len < 126) {
  4555. header[1] = static_cast<uint8_t>(len);
  4556. if (mask) { header[1] |= 0x80; }
  4557. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4558. } else if (len <= 0xFFFF) {
  4559. header[1] = 126;
  4560. if (mask) { header[1] |= 0x80; }
  4561. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4562. uint8_t ext[2];
  4563. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4564. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4565. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4566. } else {
  4567. header[1] = 127;
  4568. if (mask) { header[1] |= 0x80; }
  4569. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4570. uint8_t ext[8];
  4571. for (int i = 7; i >= 0; i--) {
  4572. ext[7 - i] =
  4573. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4574. }
  4575. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4576. }
  4577. if (mask) {
  4578. // Generate random mask key
  4579. thread_local std::mt19937 rng(std::random_device{}());
  4580. uint8_t mask_key[4];
  4581. auto r = rng();
  4582. std::memcpy(mask_key, &r, 4);
  4583. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4584. // Write masked payload in chunks
  4585. const size_t chunk_size = 4096;
  4586. std::vector<char> buf((std::min)(len, chunk_size));
  4587. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4588. size_t n = (std::min)(chunk_size, len - offset);
  4589. for (size_t i = 0; i < n; i++) {
  4590. buf[i] =
  4591. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4592. }
  4593. if (strm.write(buf.data(), n) < 0) { return false; }
  4594. }
  4595. } else {
  4596. if (len > 0) {
  4597. if (strm.write(data, len) < 0) { return false; }
  4598. }
  4599. }
  4600. return true;
  4601. }
  4602. } // namespace detail
  4603. namespace ws {
  4604. namespace impl {
  4605. // Read exactly `size` bytes. Stream::read may return less than asked for -- it
  4606. // hands back whatever its buffer already holds -- so every multi-byte field has
  4607. // to loop. Reading a 2-byte header with a single read() fails whenever the
  4608. // header straddles the read buffer's boundary.
  4609. //
  4610. // Timeout is reported only when nothing at all was consumed. Once a byte has
  4611. // been taken the stream sits mid-field and cannot be resumed, so a timeout
  4612. // there is a failure like any other. (When read() fails it always records why,
  4613. // so the error belongs to this call and not to an earlier one.)
  4614. inline FrameRead read_exact(Stream &strm, void *buf, size_t size) {
  4615. auto p = static_cast<char *>(buf);
  4616. size_t total = 0;
  4617. while (total < size) {
  4618. auto n = strm.read(p + total, size - total);
  4619. if (n <= 0) {
  4620. auto timed_out = total == 0 && strm.get_error() == Error::Timeout;
  4621. return timed_out ? FrameRead::Timeout : FrameRead::Fail;
  4622. }
  4623. total += static_cast<size_t>(n);
  4624. }
  4625. return FrameRead::Ok;
  4626. }
  4627. inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  4628. std::string &payload, bool &fin,
  4629. bool expect_masked, size_t max_len) {
  4630. // Read first 2 bytes. This is the only read that may report a timeout: it
  4631. // sits on a frame boundary, where nothing has been consumed yet.
  4632. uint8_t header[2];
  4633. FrameRead first = read_exact(strm, header, 2);
  4634. if (first != FrameRead::Ok) { return first; }
  4635. fin = (header[0] & 0x80) != 0;
  4636. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4637. if (header[0] & 0x70) { return FrameRead::Fail; }
  4638. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4639. bool masked = (header[1] & 0x80) != 0;
  4640. uint64_t payload_len = header[1] & 0x7F;
  4641. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4642. // MUST have a payload length of 125 bytes or less
  4643. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4644. if (is_control) {
  4645. if (!fin) { return FrameRead::Fail; }
  4646. if (payload_len > 125) { return FrameRead::Fail; }
  4647. }
  4648. if (masked != expect_masked) { return FrameRead::Fail; }
  4649. // Extended payload length
  4650. if (payload_len == 126) {
  4651. uint8_t ext[2];
  4652. if (read_exact(strm, ext, 2) != FrameRead::Ok) { return FrameRead::Fail; }
  4653. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4654. } else if (payload_len == 127) {
  4655. uint8_t ext[8];
  4656. if (read_exact(strm, ext, 8) != FrameRead::Ok) { return FrameRead::Fail; }
  4657. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4658. if (ext[0] & 0x80) { return FrameRead::Fail; }
  4659. payload_len = 0;
  4660. for (int i = 0; i < 8; i++) {
  4661. payload_len = (payload_len << 8) | ext[i];
  4662. }
  4663. }
  4664. if (payload_len > max_len) { return FrameRead::Fail; }
  4665. // Read mask key if present
  4666. uint8_t mask_key[4] = {0};
  4667. if (masked) {
  4668. if (read_exact(strm, mask_key, 4) != FrameRead::Ok) {
  4669. return FrameRead::Fail;
  4670. }
  4671. }
  4672. // Read payload
  4673. payload.resize(static_cast<size_t>(payload_len));
  4674. if (payload_len > 0 &&
  4675. read_exact(strm, &payload[0], static_cast<size_t>(payload_len)) !=
  4676. FrameRead::Ok) {
  4677. return FrameRead::Fail;
  4678. }
  4679. // Unmask if needed
  4680. if (masked) {
  4681. for (size_t i = 0; i < payload.size(); i++) {
  4682. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4683. }
  4684. }
  4685. return FrameRead::Ok;
  4686. }
  4687. } // namespace impl
  4688. } // namespace ws
  4689. namespace detail {
  4690. inline bool is_valid_path(const std::string &path) {
  4691. size_t level = 0;
  4692. size_t i = 0;
  4693. // Skip slash
  4694. while (i < path.size() && path[i] == '/') {
  4695. i++;
  4696. }
  4697. while (i < path.size()) {
  4698. // Read component
  4699. auto beg = i;
  4700. while (i < path.size() && path[i] != '/') {
  4701. if (path[i] == '\0') {
  4702. return false;
  4703. } else if (path[i] == '\\') {
  4704. return false;
  4705. }
  4706. i++;
  4707. }
  4708. auto len = i - beg;
  4709. assert(len > 0);
  4710. if (!path.compare(beg, len, ".")) {
  4711. ;
  4712. } else if (!path.compare(beg, len, "..")) {
  4713. if (level == 0) { return false; }
  4714. level--;
  4715. } else {
  4716. level++;
  4717. }
  4718. // Skip slash
  4719. while (i < path.size() && path[i] == '/') {
  4720. i++;
  4721. }
  4722. }
  4723. return true;
  4724. }
  4725. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4726. #if defined(_WIN32)
  4727. char buf[_MAX_PATH];
  4728. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4729. resolved = buf;
  4730. #elif defined(PATH_MAX)
  4731. char buf[PATH_MAX];
  4732. if (realpath(path, buf) == nullptr) { return false; }
  4733. resolved = buf;
  4734. #else
  4735. auto buf = realpath(path, nullptr);
  4736. auto guard = scope_exit([&]() { std::free(buf); });
  4737. if (buf == nullptr) { return false; }
  4738. resolved = buf;
  4739. #endif
  4740. return true;
  4741. }
  4742. inline bool is_path_within_base(const std::string &resolved_path,
  4743. const std::string &resolved_base) {
  4744. #if defined(_WIN32)
  4745. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4746. resolved_base.size()) == 0;
  4747. #else
  4748. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4749. resolved_base.size()) == 0;
  4750. #endif
  4751. }
  4752. inline FileStat::FileStat(const std::string &path) {
  4753. #if defined(_WIN32)
  4754. auto wpath = u8string_to_wstring(path.c_str());
  4755. ret_ = _wstat(wpath.c_str(), &st_);
  4756. #else
  4757. ret_ = stat(path.c_str(), &st_);
  4758. #endif
  4759. }
  4760. inline bool FileStat::is_file() const {
  4761. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4762. }
  4763. inline bool FileStat::is_dir() const {
  4764. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4765. }
  4766. inline time_t FileStat::mtime() const {
  4767. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4768. : static_cast<time_t>(-1);
  4769. }
  4770. inline size_t FileStat::size() const {
  4771. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4772. }
  4773. inline std::string encode_path(const std::string &s) {
  4774. std::string result;
  4775. result.reserve(s.size());
  4776. for (size_t i = 0; s[i]; i++) {
  4777. switch (s[i]) {
  4778. case ' ': result += "%20"; break;
  4779. case '+': result += "%2B"; break;
  4780. case '\r': result += "%0D"; break;
  4781. case '\n': result += "%0A"; break;
  4782. case '\'': result += "%27"; break;
  4783. case ',': result += "%2C"; break;
  4784. // case ':': result += "%3A"; break; // ok? probably...
  4785. case ';': result += "%3B"; break;
  4786. default:
  4787. auto c = static_cast<uint8_t>(s[i]);
  4788. if (c >= 0x80) {
  4789. result += '%';
  4790. char hex[4];
  4791. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4792. assert(len == 2);
  4793. result.append(hex, static_cast<size_t>(len));
  4794. } else {
  4795. result += s[i];
  4796. }
  4797. break;
  4798. }
  4799. }
  4800. return result;
  4801. }
  4802. inline std::string file_extension(const std::string &path) {
  4803. std::smatch m;
  4804. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4805. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4806. return std::string();
  4807. }
  4808. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4809. template <typename T>
  4810. inline bool parse_header(const char *beg, const char *end, T fn);
  4811. template <typename T>
  4812. inline bool parse_header(const char *beg, const char *end, T fn) {
  4813. // Skip trailing spaces and tabs.
  4814. while (beg < end && is_space_or_tab(end[-1])) {
  4815. end--;
  4816. }
  4817. auto p = beg;
  4818. while (p < end && *p != ':') {
  4819. p++;
  4820. }
  4821. auto name = std::string(beg, p);
  4822. if (!detail::fields::is_field_name(name)) { return false; }
  4823. if (p == end) { return false; }
  4824. auto key_end = p;
  4825. if (*p++ != ':') { return false; }
  4826. while (p < end && is_space_or_tab(*p)) {
  4827. p++;
  4828. }
  4829. if (p <= end) {
  4830. auto key_len = key_end - beg;
  4831. if (!key_len) { return false; }
  4832. auto key = std::string(beg, key_end);
  4833. auto val = std::string(p, end);
  4834. if (!detail::fields::is_field_value(val)) { return false; }
  4835. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4836. // percent-decoded by the recipient. Applications that need to interpret a
  4837. // value as a URI component should call httplib::decode_uri_component()
  4838. // (or decode_path_component()) explicitly.
  4839. fn(key, val);
  4840. return true;
  4841. }
  4842. return false;
  4843. }
  4844. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4845. const Headers &src_headers) {
  4846. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4847. // transfer coding is complete when a chunk with a chunk-size of zero is
  4848. // received, possibly followed by a trailer section, and finally terminated by
  4849. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4850. //
  4851. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4852. // doesn't care for the existence of the final CRLF. In other words, it seems
  4853. // to be ok whether the final CRLF exists or not in the chunked data.
  4854. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4855. //
  4856. // According to the reference code in RFC 9112, cpp-httplib now allows
  4857. // chunked transfer coding data without the final CRLF.
  4858. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4859. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4860. "transfer-encoding",
  4861. "content-length",
  4862. "host",
  4863. "authorization",
  4864. "www-authenticate",
  4865. "proxy-authenticate",
  4866. "proxy-authorization",
  4867. "cookie",
  4868. "set-cookie",
  4869. "cache-control",
  4870. "expect",
  4871. "max-forwards",
  4872. "pragma",
  4873. "range",
  4874. "te",
  4875. "age",
  4876. "expires",
  4877. "date",
  4878. "location",
  4879. "retry-after",
  4880. "vary",
  4881. "warning",
  4882. "content-encoding",
  4883. "content-type",
  4884. "content-range",
  4885. "trailer"};
  4886. case_ignore::unordered_set<std::string> declared_trailers;
  4887. auto trailer_header = get_combined_header_value(src_headers, "Trailer");
  4888. if (!trailer_header.empty()) {
  4889. // split() trims each token and skips empty ones, so the name arrives ready
  4890. // to look up.
  4891. split(trailer_header.data(), trailer_header.data() + trailer_header.size(),
  4892. ',', [&](const char *b, const char *e) {
  4893. // A legitimate message declares only a handful of trailers. Cap the
  4894. // set so a peer cannot grow it without bound: an oversized set only
  4895. // arises from an attempt to force many colliding names into
  4896. // quadratic lookups (case_ignore::hash is unkeyed).
  4897. if (declared_trailers.size() >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  4898. return;
  4899. }
  4900. std::string key(b, e);
  4901. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4902. declared_trailers.insert(key);
  4903. }
  4904. });
  4905. }
  4906. size_t trailer_header_count = 0;
  4907. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4908. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4909. // Count every received trailer field, not only the declared ones stored in
  4910. // dest, so undeclared fields cannot keep this loop running past the limit.
  4911. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4912. constexpr auto line_terminator_len = 2;
  4913. auto line_beg = line_reader.ptr();
  4914. auto line_end =
  4915. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4916. if (!parse_header(line_beg, line_end,
  4917. [&](const std::string &key, const std::string &val) {
  4918. if (declared_trailers.find(key) !=
  4919. declared_trailers.end()) {
  4920. dest.emplace(key, val);
  4921. }
  4922. })) {
  4923. return false;
  4924. }
  4925. trailer_header_count++;
  4926. if (!line_reader.getline()) { return false; }
  4927. }
  4928. return true;
  4929. }
  4930. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4931. size_t right) {
  4932. while (b + left < e && is_space_or_tab(b[left])) {
  4933. left++;
  4934. }
  4935. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4936. right--;
  4937. }
  4938. return std::make_pair(left, right);
  4939. }
  4940. inline std::string trim_copy(const std::string &s) {
  4941. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4942. return s.substr(r.first, r.second - r.first);
  4943. }
  4944. inline std::string trim_double_quotes_copy(const std::string &s) {
  4945. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4946. return s.substr(1, s.size() - 2);
  4947. }
  4948. return s;
  4949. }
  4950. inline void
  4951. divide(const char *data, std::size_t size, char d,
  4952. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4953. fn) {
  4954. const auto it = std::find(data, data + size, d);
  4955. const auto found = static_cast<std::size_t>(it != data + size);
  4956. const auto lhs_data = data;
  4957. const auto lhs_size = static_cast<std::size_t>(it - data);
  4958. const auto rhs_data = it + found;
  4959. const auto rhs_size = size - lhs_size - found;
  4960. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4961. }
  4962. inline void
  4963. divide(const std::string &str, char d,
  4964. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4965. fn) {
  4966. divide(str.data(), str.size(), d, std::move(fn));
  4967. }
  4968. inline void split(const char *b, const char *e, char d,
  4969. std::function<void(const char *, const char *)> fn) {
  4970. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4971. }
  4972. inline void split(const char *b, const char *e, char d, size_t m,
  4973. std::function<void(const char *, const char *)> fn) {
  4974. size_t i = 0;
  4975. size_t beg = 0;
  4976. size_t count = 1;
  4977. while (e ? (b + i < e) : (b[i] != '\0')) {
  4978. if (b[i] == d && count < m) {
  4979. auto r = trim(b, e, beg, i);
  4980. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4981. beg = i + 1;
  4982. count++;
  4983. }
  4984. i++;
  4985. }
  4986. if (i) {
  4987. auto r = trim(b, e, beg, i);
  4988. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4989. }
  4990. }
  4991. // Same contract as split(), except that a delimiter inside a quoted-string is
  4992. // not a delimiter. RFC 9110 Section 5.6.6 lets a parameter value be a
  4993. // quoted-string, and ';' and '=' are legal characters inside one.
  4994. inline void split_unquoted(const char *b, const char *e, char d, size_t m,
  4995. std::function<void(const char *, const char *)> fn) {
  4996. size_t i = 0;
  4997. size_t beg = 0;
  4998. size_t count = 1;
  4999. auto in_quotes = false;
  5000. while (e ? (b + i < e) : (b[i] != '\0')) {
  5001. if (b[i] == '"') {
  5002. in_quotes = !in_quotes;
  5003. } else if (b[i] == d && !in_quotes && count < m) {
  5004. auto r = trim(b, e, beg, i);
  5005. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5006. beg = i + 1;
  5007. count++;
  5008. }
  5009. i++;
  5010. }
  5011. if (i) {
  5012. auto r = trim(b, e, beg, i);
  5013. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5014. }
  5015. }
  5016. inline void split_unquoted(const char *b, const char *e, char d,
  5017. std::function<void(const char *, const char *)> fn) {
  5018. return split_unquoted(b, e, d, (std::numeric_limits<size_t>::max)(),
  5019. std::move(fn));
  5020. }
  5021. // Divide a header parameter at its first '='. RFC 9110 Section 5.6.6 makes the
  5022. // key a token, so the first '=' is the separator even when the value is a
  5023. // quoted-string carrying more of them.
  5024. inline void divide_param_pair(const char *b, const char *e, std::string &key,
  5025. std::string &val) {
  5026. divide(
  5027. b, static_cast<std::size_t>(e - b), '=',
  5028. [&](const char *kb, std::size_t klen, const char *vb, std::size_t vlen) {
  5029. const auto kr = trim(kb, kb + klen, 0, klen);
  5030. key.assign(kb + kr.first, kb + kr.second);
  5031. const auto vr = trim(vb, vb + vlen, 0, vlen);
  5032. val.assign(vb + vr.first, vb + vr.second);
  5033. });
  5034. }
  5035. inline bool split_find(const char *b, const char *e, char d, size_t m,
  5036. std::function<bool(const char *, const char *)> fn) {
  5037. size_t i = 0;
  5038. size_t beg = 0;
  5039. size_t count = 1;
  5040. while (e ? (b + i < e) : (b[i] != '\0')) {
  5041. if (b[i] == d && count < m) {
  5042. auto r = trim(b, e, beg, i);
  5043. if (r.first < r.second) {
  5044. auto found = fn(&b[r.first], &b[r.second]);
  5045. if (found) { return true; }
  5046. }
  5047. beg = i + 1;
  5048. count++;
  5049. }
  5050. i++;
  5051. }
  5052. if (i) {
  5053. auto r = trim(b, e, beg, i);
  5054. if (r.first < r.second) {
  5055. auto found = fn(&b[r.first], &b[r.second]);
  5056. if (found) { return true; }
  5057. }
  5058. }
  5059. return false;
  5060. }
  5061. inline bool split_find(const char *b, const char *e, char d,
  5062. std::function<bool(const char *, const char *)> fn) {
  5063. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  5064. std::move(fn));
  5065. }
  5066. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  5067. size_t fixed_buffer_size)
  5068. : strm_(strm), fixed_buffer_(fixed_buffer),
  5069. fixed_buffer_size_(fixed_buffer_size) {}
  5070. inline const char *stream_line_reader::ptr() const {
  5071. if (growable_buffer_.empty()) {
  5072. return fixed_buffer_;
  5073. } else {
  5074. return growable_buffer_.data();
  5075. }
  5076. }
  5077. inline size_t stream_line_reader::size() const {
  5078. if (growable_buffer_.empty()) {
  5079. return fixed_buffer_used_size_;
  5080. } else {
  5081. return growable_buffer_.size();
  5082. }
  5083. }
  5084. inline bool stream_line_reader::end_with_crlf() const {
  5085. auto end = ptr() + size();
  5086. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  5087. }
  5088. inline bool stream_line_reader::getline() {
  5089. fixed_buffer_used_size_ = 0;
  5090. growable_buffer_.clear();
  5091. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5092. char prev_byte = 0;
  5093. #endif
  5094. for (size_t i = 0;; i++) {
  5095. // Fast path: whatever the stream has already buffered can be scanned for
  5096. // the terminator in one pass. Asking for a byte at a time costs a virtual
  5097. // call, a bounds check and a one-byte copy per character of the request.
  5098. size_t buffered_size = 0;
  5099. if (auto buffered = strm_.buffered_data(buffered_size)) {
  5100. auto take = buffered_size;
  5101. auto terminated = false;
  5102. for (size_t at = 0; at < buffered_size;) {
  5103. auto nl = static_cast<const char *>(
  5104. memchr(buffered + at, '\n', buffered_size - at));
  5105. if (!nl) { break; }
  5106. auto pos = static_cast<size_t>(nl - buffered);
  5107. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5108. take = pos + 1;
  5109. terminated = true;
  5110. break;
  5111. #else
  5112. // A bare LF does not end the line; keep looking for CRLF. The CR may
  5113. // be the last byte of an earlier chunk, hence prev_byte.
  5114. if ((pos > 0 ? buffered[pos - 1] : prev_byte) == '\r') {
  5115. take = pos + 1;
  5116. terminated = true;
  5117. break;
  5118. }
  5119. at = pos + 1;
  5120. #endif
  5121. }
  5122. if (size() + take > CPPHTTPLIB_MAX_LINE_LENGTH) { return false; }
  5123. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5124. prev_byte = buffered[take - 1];
  5125. #endif
  5126. append(buffered, take);
  5127. strm_.consume_buffered(take);
  5128. i += take;
  5129. if (terminated) { return true; }
  5130. continue;
  5131. }
  5132. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  5133. // Treat exceptionally long lines as an error to
  5134. // prevent infinite loops/memory exhaustion
  5135. return false;
  5136. }
  5137. char byte;
  5138. auto n = strm_.read(&byte, 1);
  5139. if (n < 0) {
  5140. return false;
  5141. } else if (n == 0) {
  5142. if (i == 0) {
  5143. return false;
  5144. } else {
  5145. break;
  5146. }
  5147. }
  5148. append(byte);
  5149. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5150. if (byte == '\n') { break; }
  5151. #else
  5152. if (prev_byte == '\r' && byte == '\n') { break; }
  5153. prev_byte = byte;
  5154. #endif
  5155. }
  5156. return true;
  5157. }
  5158. inline void stream_line_reader::append(char c) { append(&c, 1); }
  5159. inline void stream_line_reader::append(const char *data, size_t size) {
  5160. // Once the line has outgrown the fixed buffer everything must keep going to
  5161. // the growable one, even if a later chunk would have fit. Without the
  5162. // emptiness check a short append after a long one would land in the fixed
  5163. // buffer, which ptr() and size() no longer look at, and be lost.
  5164. if (growable_buffer_.empty() &&
  5165. fixed_buffer_used_size_ + size < fixed_buffer_size_) {
  5166. memcpy(fixed_buffer_ + fixed_buffer_used_size_, data, size);
  5167. fixed_buffer_used_size_ += size;
  5168. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  5169. } else {
  5170. // Unlike the per-character overload, this can be the very first append of
  5171. // the line, so the fixed buffer may hold nothing and carry no terminator
  5172. // yet. assign() takes an explicit length and does not need one.
  5173. if (growable_buffer_.empty()) {
  5174. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  5175. }
  5176. growable_buffer_.append(data, size);
  5177. }
  5178. }
  5179. inline mmap::mmap(const char *path) { open(path); }
  5180. inline mmap::~mmap() { close(); }
  5181. inline bool mmap::open(const char *path) {
  5182. close();
  5183. #if defined(_WIN32)
  5184. auto wpath = u8string_to_wstring(path);
  5185. if (wpath.empty()) { return false; }
  5186. hFile_ =
  5187. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  5188. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  5189. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  5190. LARGE_INTEGER size{};
  5191. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  5192. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  5193. // See:
  5194. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  5195. if (static_cast<ULONGLONG>(size.QuadPart) >
  5196. (std::numeric_limits<decltype(size_)>::max)()) {
  5197. // `size_t` might be 32-bits, on 32-bits Windows.
  5198. return false;
  5199. }
  5200. size_ = static_cast<size_t>(size.QuadPart);
  5201. hMapping_ =
  5202. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  5203. // Special treatment for an empty file...
  5204. if (hMapping_ == NULL && size_ == 0) {
  5205. close();
  5206. is_open_empty_file = true;
  5207. return true;
  5208. }
  5209. if (hMapping_ == NULL) {
  5210. close();
  5211. return false;
  5212. }
  5213. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  5214. if (addr_ == nullptr) {
  5215. close();
  5216. return false;
  5217. }
  5218. #else
  5219. fd_ = ::open(path, O_RDONLY);
  5220. if (fd_ == -1) { return false; }
  5221. struct stat sb;
  5222. if (fstat(fd_, &sb) == -1) {
  5223. close();
  5224. return false;
  5225. }
  5226. size_ = static_cast<size_t>(sb.st_size);
  5227. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  5228. // Special treatment for an empty file...
  5229. if (addr_ == MAP_FAILED && size_ == 0) {
  5230. close();
  5231. is_open_empty_file = true;
  5232. return false;
  5233. }
  5234. if (addr_ == MAP_FAILED) {
  5235. // Clear the sentinel before `close()`, since `is_open()` only checks
  5236. // `addr_` against nullptr and `munmap()` must not be called with it.
  5237. addr_ = nullptr;
  5238. close();
  5239. return false;
  5240. }
  5241. #endif
  5242. return true;
  5243. }
  5244. inline bool mmap::is_open() const {
  5245. return is_open_empty_file ? true : addr_ != nullptr;
  5246. }
  5247. inline size_t mmap::size() const { return size_; }
  5248. inline const char *mmap::data() const {
  5249. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  5250. }
  5251. inline void mmap::close() {
  5252. #if defined(_WIN32)
  5253. if (addr_) {
  5254. ::UnmapViewOfFile(addr_);
  5255. addr_ = nullptr;
  5256. }
  5257. if (hMapping_) {
  5258. ::CloseHandle(hMapping_);
  5259. hMapping_ = NULL;
  5260. }
  5261. if (hFile_ != INVALID_HANDLE_VALUE) {
  5262. ::CloseHandle(hFile_);
  5263. hFile_ = INVALID_HANDLE_VALUE;
  5264. }
  5265. is_open_empty_file = false;
  5266. #else
  5267. if (addr_ != nullptr) {
  5268. munmap(addr_, size_);
  5269. addr_ = nullptr;
  5270. }
  5271. if (fd_ != -1) {
  5272. ::close(fd_);
  5273. fd_ = -1;
  5274. }
  5275. #endif
  5276. size_ = 0;
  5277. }
  5278. inline int close_socket(socket_t sock) noexcept {
  5279. #ifdef _WIN32
  5280. return closesocket(sock);
  5281. #else
  5282. return close(sock);
  5283. #endif
  5284. }
  5285. template <typename T> inline ssize_t handle_EINTR(T fn) {
  5286. ssize_t res = 0;
  5287. while (true) {
  5288. res = fn();
  5289. if (res < 0 && errno == EINTR) {
  5290. std::this_thread::sleep_for(std::chrono::microseconds{1});
  5291. continue;
  5292. }
  5293. break;
  5294. }
  5295. return res;
  5296. }
  5297. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  5298. return handle_EINTR([&]() {
  5299. return recv(sock,
  5300. #ifdef _WIN32
  5301. static_cast<char *>(ptr), static_cast<int>(size),
  5302. #else
  5303. ptr, size,
  5304. #endif
  5305. flags);
  5306. });
  5307. }
  5308. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  5309. int flags) {
  5310. return handle_EINTR([&]() {
  5311. return send(sock,
  5312. #ifdef _WIN32
  5313. static_cast<const char *>(ptr), static_cast<int>(size),
  5314. #else
  5315. ptr, size,
  5316. #endif
  5317. flags);
  5318. });
  5319. }
  5320. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  5321. #ifdef _WIN32
  5322. return ::WSAPoll(fds, nfds, timeout);
  5323. #else
  5324. return ::poll(fds, nfds, timeout);
  5325. #endif
  5326. }
  5327. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  5328. time_t usec) {
  5329. struct pollfd pfd;
  5330. pfd.fd = sock;
  5331. pfd.events = events;
  5332. pfd.revents = 0;
  5333. // A negative timeout waits forever, poll's own convention. 0 keeps meaning
  5334. // "return immediately", which callers here rely on to probe a socket.
  5335. auto timeout = sec < 0 ? -1 : static_cast<int>(sec * 1000 + usec / 1000);
  5336. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  5337. }
  5338. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  5339. return select_impl(sock, POLLIN, sec, usec);
  5340. }
  5341. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  5342. return select_impl(sock, POLLOUT, sec, usec);
  5343. }
  5344. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  5345. time_t usec) {
  5346. struct pollfd pfd_read;
  5347. pfd_read.fd = sock;
  5348. pfd_read.events = POLLIN | POLLOUT;
  5349. pfd_read.revents = 0;
  5350. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  5351. auto poll_res =
  5352. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  5353. if (poll_res == 0) { return Error::ConnectionTimeout; }
  5354. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  5355. auto error = 0;
  5356. socklen_t len = sizeof(error);
  5357. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  5358. reinterpret_cast<char *>(&error), &len);
  5359. auto successful = res >= 0 && !error;
  5360. return successful ? Error::Success : Error::Connection;
  5361. }
  5362. return Error::Connection;
  5363. }
  5364. inline bool is_socket_alive(socket_t sock) {
  5365. const auto val = detail::select_read(sock, 0, 0);
  5366. if (val == 0) {
  5367. return true;
  5368. } else if (val < 0 && errno == EBADF) {
  5369. return false;
  5370. }
  5371. char buf[1];
  5372. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  5373. }
  5374. class SocketStream final : public Stream {
  5375. public:
  5376. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5377. time_t write_timeout_sec, time_t write_timeout_usec,
  5378. time_t max_timeout_msec = 0,
  5379. std::chrono::time_point<std::chrono::steady_clock> start_time =
  5380. (std::chrono::steady_clock::time_point::min)());
  5381. ~SocketStream() override;
  5382. bool is_readable() const override;
  5383. bool wait_readable() const override;
  5384. bool wait_writable() const override;
  5385. bool is_peer_alive() const override;
  5386. ssize_t read(char *ptr, size_t size) override;
  5387. ssize_t write(const char *ptr, size_t size) override;
  5388. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  5389. void get_local_ip_and_port(std::string &ip, int &port) const override;
  5390. socket_t socket() const override;
  5391. time_t duration() const override;
  5392. void set_read_timeout(time_t sec, time_t usec = 0) override;
  5393. const char *buffered_data(size_t &size) const override;
  5394. void consume_buffered(size_t size) override;
  5395. // The caller has just seen this socket become readable. Lets the next read
  5396. // skip its own readiness wait, which would otherwise ask the kernel a
  5397. // question that was answered a moment ago. Consumed by that read.
  5398. void set_readable_hint() { readable_hint_ = true; }
  5399. private:
  5400. bool ensure_readable();
  5401. socket_t sock_;
  5402. // Atomic because ws::WebSocket::set_read_timeout() reaches this from another
  5403. // thread while a read is in flight -- that is the point of it, for a caller
  5404. // holding one connection and wanting control back to send on it.
  5405. std::atomic<time_t> read_timeout_sec_;
  5406. std::atomic<time_t> read_timeout_usec_;
  5407. time_t write_timeout_sec_;
  5408. time_t write_timeout_usec_;
  5409. time_t max_timeout_msec_;
  5410. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  5411. std::vector<char> read_buff_;
  5412. size_t read_buff_off_ = 0;
  5413. size_t read_buff_content_size_ = 0;
  5414. bool readable_hint_ = false;
  5415. static const size_t read_buff_size_ = 1024l * 4;
  5416. };
  5417. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5418. time_t keep_alive_timeout_sec) {
  5419. using namespace std::chrono;
  5420. const auto interval_usec =
  5421. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  5422. // Avoid expensive `steady_clock::now()` call for the first time
  5423. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  5424. const auto start = steady_clock::now() - microseconds{interval_usec};
  5425. const auto timeout = seconds{keep_alive_timeout_sec};
  5426. while (true) {
  5427. if (svr_sock == INVALID_SOCKET) {
  5428. break; // Server socket is closed
  5429. }
  5430. auto val = select_read(sock, 0, interval_usec);
  5431. if (val < 0) {
  5432. break; // Ssocket error
  5433. } else if (val == 0) {
  5434. if (steady_clock::now() - start > timeout) {
  5435. break; // Timeout
  5436. }
  5437. } else {
  5438. return true; // Ready for read
  5439. }
  5440. }
  5441. return false;
  5442. }
  5443. template <typename T>
  5444. inline bool
  5445. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5446. size_t keep_alive_max_count,
  5447. time_t keep_alive_timeout_sec, T callback) {
  5448. assert(keep_alive_max_count > 0);
  5449. auto ret = false;
  5450. auto count = keep_alive_max_count;
  5451. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  5452. auto close_connection = count == 1;
  5453. auto connection_closed = false;
  5454. ret = callback(close_connection, connection_closed);
  5455. if (!ret || connection_closed) { break; }
  5456. count--;
  5457. }
  5458. return ret;
  5459. }
  5460. template <typename T>
  5461. inline bool
  5462. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5463. size_t keep_alive_max_count,
  5464. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  5465. time_t read_timeout_usec, time_t write_timeout_sec,
  5466. time_t write_timeout_usec, T callback) {
  5467. return process_server_socket_core(
  5468. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  5469. [&](bool close_connection, bool &connection_closed) {
  5470. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5471. write_timeout_sec, write_timeout_usec);
  5472. // process_server_socket_core() only gets here once keep_alive() has
  5473. // seen the socket go readable.
  5474. strm.set_readable_hint();
  5475. return callback(strm, close_connection, connection_closed);
  5476. });
  5477. }
  5478. inline bool process_client_socket(
  5479. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5480. time_t write_timeout_sec, time_t write_timeout_usec,
  5481. time_t max_timeout_msec,
  5482. std::chrono::time_point<std::chrono::steady_clock> start_time,
  5483. std::function<bool(Stream &)> callback) {
  5484. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5485. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  5486. start_time);
  5487. return callback(strm);
  5488. }
  5489. inline int shutdown_socket(socket_t sock) noexcept {
  5490. #ifdef _WIN32
  5491. return shutdown(sock, SD_BOTH);
  5492. #else
  5493. return shutdown(sock, SHUT_RDWR);
  5494. #endif
  5495. }
  5496. // Half-closes the write side and drains any in-flight/queued bytes before
  5497. // the final shutdown+close. Closing with unread data in the receive queue
  5498. // (or bytes arriving after the receive side is closed) makes the stack send
  5499. // an abortive RST instead of a graceful FIN, which can make the peer see the
  5500. // response as a failed read even though it was fully written.
  5501. inline void drain_and_close_socket(socket_t sock) noexcept {
  5502. #ifdef _WIN32
  5503. shutdown(sock, SD_SEND);
  5504. #else
  5505. shutdown(sock, SHUT_WR);
  5506. #endif
  5507. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5508. size_t total = 0;
  5509. const auto deadline = std::chrono::steady_clock::now() +
  5510. std::chrono::milliseconds(100); // bound #1
  5511. while (total < size_t(1024u * 1024u)) { // bound #2
  5512. const auto remaining =
  5513. std::chrono::duration_cast<std::chrono::microseconds>(
  5514. deadline - std::chrono::steady_clock::now())
  5515. .count();
  5516. if (remaining <= 0) { break; }
  5517. if (select_read(sock, 0, static_cast<time_t>(remaining)) <= 0) { break; }
  5518. const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  5519. if (n <= 0) { break; }
  5520. total += static_cast<size_t>(n);
  5521. }
  5522. shutdown_socket(sock);
  5523. close_socket(sock);
  5524. }
  5525. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  5526. if (s.size() > 1 && s[0] == '\0') {
  5527. auto ret = s;
  5528. ret[0] = '@';
  5529. return ret;
  5530. }
  5531. return s;
  5532. }
  5533. inline std::string
  5534. unescape_abstract_namespace_unix_domain(const std::string &s) {
  5535. if (s.size() > 1 && s[0] == '@') {
  5536. auto ret = s;
  5537. ret[0] = '\0';
  5538. return ret;
  5539. }
  5540. return s;
  5541. }
  5542. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  5543. const struct addrinfo *hints,
  5544. struct addrinfo **res, time_t timeout_sec) {
  5545. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  5546. if (timeout_sec <= 0) {
  5547. // No timeout specified, use standard getaddrinfo
  5548. return getaddrinfo(node, service, hints, res);
  5549. }
  5550. #ifdef _WIN32
  5551. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  5552. OVERLAPPED overlapped = {};
  5553. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  5554. if (!event) { return EAI_FAIL; }
  5555. overlapped.hEvent = event;
  5556. PADDRINFOEXW result_addrinfo = nullptr;
  5557. HANDLE cancel_handle = nullptr;
  5558. ADDRINFOEXW hints_ex = {};
  5559. if (hints) {
  5560. hints_ex.ai_flags = hints->ai_flags;
  5561. hints_ex.ai_family = hints->ai_family;
  5562. hints_ex.ai_socktype = hints->ai_socktype;
  5563. hints_ex.ai_protocol = hints->ai_protocol;
  5564. }
  5565. auto wnode = u8string_to_wstring(node);
  5566. auto wservice = u8string_to_wstring(service);
  5567. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  5568. hints ? &hints_ex : nullptr, &result_addrinfo,
  5569. nullptr, &overlapped, nullptr, &cancel_handle);
  5570. if (ret == WSA_IO_PENDING) {
  5571. auto wait_result =
  5572. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  5573. if (wait_result == WAIT_TIMEOUT) {
  5574. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  5575. ::CloseHandle(event);
  5576. return EAI_AGAIN;
  5577. }
  5578. DWORD bytes_returned;
  5579. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  5580. &bytes_returned, FALSE)) {
  5581. ::CloseHandle(event);
  5582. return ::WSAGetLastError();
  5583. }
  5584. }
  5585. ::CloseHandle(event);
  5586. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  5587. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  5588. return 0;
  5589. }
  5590. return ret;
  5591. #elif TARGET_OS_MAC && defined(__clang__)
  5592. if (!node) { return EAI_NONAME; }
  5593. // macOS implementation using CFHost API for asynchronous DNS resolution
  5594. CFStringRef hostname_ref = CFStringCreateWithCString(
  5595. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  5596. if (!hostname_ref) { return EAI_MEMORY; }
  5597. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  5598. CFRelease(hostname_ref);
  5599. if (!host_ref) { return EAI_MEMORY; }
  5600. // Set up context for callback
  5601. struct CFHostContext {
  5602. bool completed = false;
  5603. bool success = false;
  5604. CFArrayRef addresses = nullptr;
  5605. std::mutex mutex;
  5606. std::condition_variable cv;
  5607. } context;
  5608. CFHostClientContext client_context;
  5609. memset(&client_context, 0, sizeof(client_context));
  5610. client_context.info = &context;
  5611. // Set callback
  5612. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  5613. const CFStreamError *error, void *info) {
  5614. auto ctx = static_cast<CFHostContext *>(info);
  5615. std::lock_guard<std::mutex> lock(ctx->mutex);
  5616. if (error && error->error != 0) {
  5617. ctx->success = false;
  5618. } else {
  5619. Boolean hasBeenResolved;
  5620. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  5621. if (ctx->addresses && hasBeenResolved) {
  5622. CFRetain(ctx->addresses);
  5623. ctx->success = true;
  5624. } else {
  5625. ctx->success = false;
  5626. }
  5627. }
  5628. ctx->completed = true;
  5629. ctx->cv.notify_one();
  5630. };
  5631. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  5632. CFRelease(host_ref);
  5633. return EAI_SYSTEM;
  5634. }
  5635. // Schedule on run loop
  5636. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  5637. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5638. // Start resolution
  5639. CFStreamError stream_error;
  5640. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  5641. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5642. CFRelease(host_ref);
  5643. return EAI_FAIL;
  5644. }
  5645. // Wait for completion with timeout
  5646. auto timeout_time =
  5647. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  5648. bool timed_out = false;
  5649. {
  5650. std::unique_lock<std::mutex> lock(context.mutex);
  5651. while (!context.completed) {
  5652. auto now = std::chrono::steady_clock::now();
  5653. if (now >= timeout_time) {
  5654. timed_out = true;
  5655. break;
  5656. }
  5657. // Run the runloop for a short time
  5658. lock.unlock();
  5659. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  5660. lock.lock();
  5661. }
  5662. }
  5663. // Clean up
  5664. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5665. CFHostSetClient(host_ref, nullptr, nullptr);
  5666. if (timed_out || !context.completed) {
  5667. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  5668. CFRelease(host_ref);
  5669. return EAI_AGAIN;
  5670. }
  5671. if (!context.success || !context.addresses) {
  5672. CFRelease(host_ref);
  5673. return EAI_NODATA;
  5674. }
  5675. // Convert CFArray to addrinfo
  5676. CFIndex count = CFArrayGetCount(context.addresses);
  5677. if (count == 0) {
  5678. CFRelease(context.addresses);
  5679. CFRelease(host_ref);
  5680. return EAI_NODATA;
  5681. }
  5682. struct addrinfo *result_addrinfo = nullptr;
  5683. struct addrinfo **current = &result_addrinfo;
  5684. for (CFIndex i = 0; i < count; i++) {
  5685. CFDataRef addr_data =
  5686. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  5687. if (!addr_data) continue;
  5688. const struct sockaddr *sockaddr_ptr =
  5689. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  5690. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  5691. // Allocate addrinfo structure
  5692. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  5693. if (!*current) {
  5694. freeaddrinfo(result_addrinfo);
  5695. CFRelease(context.addresses);
  5696. CFRelease(host_ref);
  5697. return EAI_MEMORY;
  5698. }
  5699. memset(*current, 0, sizeof(struct addrinfo));
  5700. // Set up addrinfo fields
  5701. (*current)->ai_family = sockaddr_ptr->sa_family;
  5702. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  5703. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  5704. (*current)->ai_addrlen = sockaddr_len;
  5705. // Copy sockaddr
  5706. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  5707. if (!(*current)->ai_addr) {
  5708. freeaddrinfo(result_addrinfo);
  5709. CFRelease(context.addresses);
  5710. CFRelease(host_ref);
  5711. return EAI_MEMORY;
  5712. }
  5713. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  5714. // Set port if service is specified
  5715. if (service && *service) {
  5716. int port = 0;
  5717. if (parse_port(service, strlen(service), port)) {
  5718. if (sockaddr_ptr->sa_family == AF_INET) {
  5719. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5720. ->sin_port = htons(static_cast<uint16_t>(port));
  5721. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5722. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5723. ->sin6_port = htons(static_cast<uint16_t>(port));
  5724. }
  5725. }
  5726. }
  5727. current = &((*current)->ai_next);
  5728. }
  5729. CFRelease(context.addresses);
  5730. CFRelease(host_ref);
  5731. *res = result_addrinfo;
  5732. return 0;
  5733. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5734. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5735. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5736. // the resolver worker still references the stack-local gaicb. The cancel
  5737. // path therefore waits (gai_suspend with no timeout) for the worker to
  5738. // actually finish before letting the stack frame go. The trade-off is that
  5739. // a wedged DNS server can hold this thread for the system resolver timeout
  5740. // (~30s by default) past the caller's connection timeout.
  5741. struct gaicb request{};
  5742. struct gaicb *requests[1] = {&request};
  5743. struct sigevent sevp{};
  5744. struct timespec timeout{timeout_sec, 0};
  5745. request.ar_name = node;
  5746. request.ar_service = service;
  5747. request.ar_request = hints;
  5748. sevp.sigev_notify = SIGEV_NONE;
  5749. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5750. if (rc != 0) { return rc; }
  5751. auto cleanup = scope_exit([&] {
  5752. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5753. });
  5754. int wait_result = gai_suspend(requests, 1, &timeout);
  5755. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5756. int gai_result = gai_error(&request);
  5757. if (gai_result == 0) {
  5758. *res = request.ar_result;
  5759. request.ar_result = nullptr;
  5760. return 0;
  5761. }
  5762. return gai_result;
  5763. }
  5764. gai_cancel(&request);
  5765. while (gai_error(&request) == EAI_INPROGRESS) {
  5766. gai_suspend(requests, 1, nullptr);
  5767. }
  5768. return wait_result;
  5769. #else
  5770. // Fallback implementation using thread-based timeout for other Unix systems.
  5771. struct GetAddrInfoState {
  5772. ~GetAddrInfoState() {
  5773. if (info) { freeaddrinfo(info); }
  5774. }
  5775. std::mutex mutex;
  5776. std::condition_variable result_cv;
  5777. bool completed = false;
  5778. int result = EAI_SYSTEM;
  5779. std::string node;
  5780. std::string service;
  5781. struct addrinfo hints;
  5782. struct addrinfo *info = nullptr;
  5783. };
  5784. // Allocate on the heap, so the resolver thread can keep using the data.
  5785. auto state = std::make_shared<GetAddrInfoState>();
  5786. if (node) { state->node = node; }
  5787. state->service = service;
  5788. state->hints = *hints;
  5789. std::thread resolve_thread([state]() {
  5790. auto thread_result =
  5791. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5792. &state->info);
  5793. std::lock_guard<std::mutex> lock(state->mutex);
  5794. state->result = thread_result;
  5795. state->completed = true;
  5796. state->result_cv.notify_one();
  5797. });
  5798. // Wait for completion or timeout
  5799. std::unique_lock<std::mutex> lock(state->mutex);
  5800. auto finished =
  5801. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5802. [&] { return state->completed; });
  5803. if (finished) {
  5804. // Operation completed within timeout
  5805. resolve_thread.join();
  5806. *res = state->info;
  5807. state->info = nullptr; // Pass ownership to caller
  5808. return state->result;
  5809. } else {
  5810. // Timeout occurred
  5811. resolve_thread.detach(); // Let the thread finish in background
  5812. return EAI_AGAIN; // Return timeout error
  5813. }
  5814. #endif
  5815. #else
  5816. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5817. return getaddrinfo(node, service, hints, res);
  5818. #endif
  5819. }
  5820. template <typename BindOrConnect>
  5821. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5822. int address_family, int socket_flags, bool tcp_nodelay,
  5823. bool ipv6_v6only, SocketOptions socket_options,
  5824. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5825. // Get address info
  5826. const char *node = nullptr;
  5827. struct addrinfo hints;
  5828. struct addrinfo *result;
  5829. memset(&hints, 0, sizeof(struct addrinfo));
  5830. hints.ai_socktype = SOCK_STREAM;
  5831. hints.ai_protocol = IPPROTO_IP;
  5832. if (!ip.empty()) {
  5833. node = ip.c_str();
  5834. // Ask getaddrinfo to convert IP in c-string to address
  5835. hints.ai_family = AF_UNSPEC;
  5836. hints.ai_flags = AI_NUMERICHOST;
  5837. } else {
  5838. if (!host.empty()) { node = host.c_str(); }
  5839. hints.ai_family = address_family;
  5840. hints.ai_flags = socket_flags;
  5841. }
  5842. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5843. if (hints.ai_family == AF_UNIX) {
  5844. const auto addrlen = host.length();
  5845. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5846. #ifdef SOCK_CLOEXEC
  5847. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5848. hints.ai_protocol);
  5849. #else
  5850. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5851. #endif
  5852. if (sock != INVALID_SOCKET) {
  5853. sockaddr_un addr{};
  5854. addr.sun_family = AF_UNIX;
  5855. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5856. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5857. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5858. hints.ai_addrlen = static_cast<socklen_t>(
  5859. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5860. #ifndef SOCK_CLOEXEC
  5861. #ifndef _WIN32
  5862. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5863. #endif
  5864. #endif
  5865. if (socket_options) { socket_options(sock); }
  5866. #ifdef _WIN32
  5867. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5868. // remove the option.
  5869. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5870. #endif
  5871. bool dummy;
  5872. if (!bind_or_connect(sock, hints, dummy)) {
  5873. close_socket(sock);
  5874. sock = INVALID_SOCKET;
  5875. }
  5876. }
  5877. return sock;
  5878. }
  5879. #endif
  5880. auto service = std::to_string(port);
  5881. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5882. timeout_sec)) {
  5883. #if defined __linux__ && !defined __ANDROID__
  5884. res_init();
  5885. #endif
  5886. return INVALID_SOCKET;
  5887. }
  5888. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5889. for (auto rp = result; rp; rp = rp->ai_next) {
  5890. // Create a socket
  5891. #ifdef _WIN32
  5892. auto sock =
  5893. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5894. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5895. /**
  5896. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5897. * and above the socket creation fails on older Windows Systems.
  5898. *
  5899. * Let's try to create a socket the old way in this case.
  5900. *
  5901. * Reference:
  5902. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5903. *
  5904. * WSA_FLAG_NO_HANDLE_INHERIT:
  5905. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5906. * SP1, and later
  5907. *
  5908. */
  5909. if (sock == INVALID_SOCKET) {
  5910. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5911. }
  5912. #else
  5913. #ifdef SOCK_CLOEXEC
  5914. auto sock =
  5915. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5916. #else
  5917. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5918. #endif
  5919. #endif
  5920. if (sock == INVALID_SOCKET) { continue; }
  5921. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5922. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5923. close_socket(sock);
  5924. continue;
  5925. }
  5926. #endif
  5927. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5928. if (rp->ai_family == AF_INET6) {
  5929. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5930. }
  5931. if (socket_options) { socket_options(sock); }
  5932. // bind or connect
  5933. auto quit = false;
  5934. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5935. close_socket(sock);
  5936. if (quit) { break; }
  5937. }
  5938. return INVALID_SOCKET;
  5939. }
  5940. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5941. #ifdef _WIN32
  5942. auto flags = nonblocking ? 1UL : 0UL;
  5943. ioctlsocket(sock, FIONBIO, &flags);
  5944. #else
  5945. auto flags = fcntl(sock, F_GETFL, 0);
  5946. fcntl(sock, F_SETFL,
  5947. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5948. #endif
  5949. }
  5950. inline bool is_connection_error() {
  5951. #ifdef _WIN32
  5952. return WSAGetLastError() != WSAEWOULDBLOCK;
  5953. #else
  5954. return errno != EINPROGRESS;
  5955. #endif
  5956. }
  5957. // accept() failed because the process or the network stack is temporarily out
  5958. // of resources. The listening socket is still usable, so back off briefly and
  5959. // try again.
  5960. inline bool is_accept_resource_error() {
  5961. #ifdef _WIN32
  5962. auto err = WSAGetLastError();
  5963. return err == WSAEMFILE || err == WSAENOBUFS;
  5964. #else
  5965. auto err = errno;
  5966. return err == EMFILE || err == ENFILE || err == ENOBUFS || err == ENOMEM;
  5967. #endif
  5968. }
  5969. // accept() failed for a reason that says nothing about the listening socket:
  5970. // the pending connection went away before it could be accepted, or the call
  5971. // was interrupted. Retry immediately. WSAAccept()'s own documentation omits
  5972. // WSAECONNRESET, but the accept() it wraps reports an aborted pending
  5973. // connection that way.
  5974. inline bool is_accept_transient_error() {
  5975. #ifdef _WIN32
  5976. auto err = WSAGetLastError();
  5977. return err == WSAEINTR || err == WSAEWOULDBLOCK || err == WSAECONNRESET ||
  5978. err == WSAECONNABORTED;
  5979. #else
  5980. auto err = errno;
  5981. return err == EINTR || err == EAGAIN || err == EWOULDBLOCK ||
  5982. err == ECONNABORTED;
  5983. #endif
  5984. }
  5985. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5986. struct addrinfo hints;
  5987. struct addrinfo *result;
  5988. memset(&hints, 0, sizeof(struct addrinfo));
  5989. hints.ai_family = AF_UNSPEC;
  5990. hints.ai_socktype = SOCK_STREAM;
  5991. hints.ai_protocol = 0;
  5992. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5993. return false;
  5994. }
  5995. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5996. auto ret = false;
  5997. for (auto rp = result; rp; rp = rp->ai_next) {
  5998. const auto &ai = *rp;
  5999. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6000. ret = true;
  6001. break;
  6002. }
  6003. }
  6004. return ret;
  6005. }
  6006. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  6007. #define USE_IF2IP
  6008. #endif
  6009. #ifdef USE_IF2IP
  6010. inline std::string if2ip(int address_family, const std::string &ifn) {
  6011. struct ifaddrs *ifap;
  6012. getifaddrs(&ifap);
  6013. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  6014. std::string addr_candidate;
  6015. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  6016. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  6017. (AF_UNSPEC == address_family ||
  6018. ifa->ifa_addr->sa_family == address_family)) {
  6019. if (ifa->ifa_addr->sa_family == AF_INET) {
  6020. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  6021. char buf[INET_ADDRSTRLEN];
  6022. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  6023. return std::string(buf, INET_ADDRSTRLEN);
  6024. }
  6025. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  6026. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  6027. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  6028. char buf[INET6_ADDRSTRLEN] = {};
  6029. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  6030. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  6031. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  6032. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  6033. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  6034. } else {
  6035. return std::string(buf, INET6_ADDRSTRLEN);
  6036. }
  6037. }
  6038. }
  6039. }
  6040. }
  6041. }
  6042. return addr_candidate;
  6043. }
  6044. #endif
  6045. inline socket_t create_client_socket(
  6046. const std::string &host, const std::string &ip, int port,
  6047. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  6048. SocketOptions socket_options, time_t connection_timeout_sec,
  6049. time_t connection_timeout_usec, time_t read_timeout_sec,
  6050. time_t read_timeout_usec, time_t write_timeout_sec,
  6051. time_t write_timeout_usec, const std::string &intf, Error &error) {
  6052. auto sock = create_socket(
  6053. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  6054. std::move(socket_options),
  6055. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  6056. if (!intf.empty()) {
  6057. #ifdef USE_IF2IP
  6058. auto ip_from_if = if2ip(address_family, intf);
  6059. if (ip_from_if.empty()) { ip_from_if = intf; }
  6060. if (!bind_ip_address(sock2, ip_from_if)) {
  6061. error = Error::BindIPAddress;
  6062. return false;
  6063. }
  6064. #endif
  6065. }
  6066. set_nonblocking(sock2, true);
  6067. auto ret =
  6068. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  6069. if (ret < 0) {
  6070. if (is_connection_error()) {
  6071. error = Error::Connection;
  6072. return false;
  6073. }
  6074. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  6075. connection_timeout_usec);
  6076. if (error != Error::Success) {
  6077. if (error == Error::ConnectionTimeout) { quit = true; }
  6078. return false;
  6079. }
  6080. }
  6081. set_nonblocking(sock2, false);
  6082. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  6083. read_timeout_usec);
  6084. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  6085. write_timeout_usec);
  6086. error = Error::Success;
  6087. return true;
  6088. },
  6089. connection_timeout_sec); // Pass DNS timeout
  6090. if (sock != INVALID_SOCKET) {
  6091. error = Error::Success;
  6092. } else {
  6093. if (error == Error::Success) { error = Error::Connection; }
  6094. }
  6095. return sock;
  6096. }
  6097. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  6098. socklen_t addr_len, std::string &ip, int &port) {
  6099. if (addr.ss_family == AF_INET) {
  6100. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  6101. } else if (addr.ss_family == AF_INET6) {
  6102. port =
  6103. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  6104. } else {
  6105. return false;
  6106. }
  6107. std::array<char, NI_MAXHOST> ipstr{};
  6108. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  6109. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  6110. 0, NI_NUMERICHOST)) {
  6111. return false;
  6112. }
  6113. ip = ipstr.data();
  6114. return true;
  6115. }
  6116. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  6117. struct sockaddr_storage addr;
  6118. socklen_t addr_len = sizeof(addr);
  6119. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  6120. &addr_len)) {
  6121. get_ip_and_port(addr, addr_len, ip, port);
  6122. }
  6123. }
  6124. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  6125. struct sockaddr_storage addr;
  6126. socklen_t addr_len = sizeof(addr);
  6127. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  6128. &addr_len)) {
  6129. #ifndef _WIN32
  6130. if (addr.ss_family == AF_UNIX) {
  6131. #if defined(__linux__)
  6132. struct ucred ucred;
  6133. socklen_t len = sizeof(ucred);
  6134. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  6135. port = ucred.pid;
  6136. }
  6137. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  6138. pid_t pid;
  6139. socklen_t len = sizeof(pid);
  6140. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  6141. port = pid;
  6142. }
  6143. #endif
  6144. return;
  6145. }
  6146. #endif
  6147. get_ip_and_port(addr, addr_len, ip, port);
  6148. }
  6149. }
  6150. // Recursive form retained so operator""_t below can compute hashes for
  6151. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  6152. // call from runtime paths with arbitrary-length inputs — use str2tag()
  6153. // instead, which is iterative and stack-safe.
  6154. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  6155. unsigned int h) {
  6156. return (l == 0)
  6157. ? h
  6158. : str2tag_core(
  6159. s + 1, l - 1,
  6160. // Unsets the 6 high bits of h, therefore no overflow happens
  6161. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  6162. h * 33) ^
  6163. static_cast<unsigned char>(*s));
  6164. }
  6165. inline unsigned int str2tag(const std::string &s) {
  6166. // Iterative form of str2tag_core: the recursive constexpr version is kept
  6167. // for compile-time UDL evaluation of short string literals, but at runtime
  6168. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  6169. // would blow the stack with one frame per character.
  6170. unsigned int h = 0;
  6171. for (auto c : s) {
  6172. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  6173. static_cast<unsigned char>(c);
  6174. }
  6175. return h;
  6176. }
  6177. namespace udl {
  6178. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  6179. return str2tag_core(s, l, 0);
  6180. }
  6181. } // namespace udl
  6182. inline std::string
  6183. find_content_type(const std::string &path,
  6184. const std::map<std::string, std::string> &user_data,
  6185. const std::string &default_content_type) {
  6186. auto ext = file_extension(path);
  6187. auto it = user_data.find(ext);
  6188. if (it != user_data.end()) { return it->second; }
  6189. using udl::operator""_t;
  6190. switch (str2tag(ext)) {
  6191. default: return default_content_type;
  6192. case "css"_t: return "text/css";
  6193. case "csv"_t: return "text/csv";
  6194. case "htm"_t:
  6195. case "html"_t: return "text/html";
  6196. case "js"_t:
  6197. case "mjs"_t: return "text/javascript";
  6198. case "txt"_t: return "text/plain";
  6199. case "vtt"_t: return "text/vtt";
  6200. case "apng"_t: return "image/apng";
  6201. case "avif"_t: return "image/avif";
  6202. case "bmp"_t: return "image/bmp";
  6203. case "gif"_t: return "image/gif";
  6204. case "png"_t: return "image/png";
  6205. case "svg"_t: return "image/svg+xml";
  6206. case "webp"_t: return "image/webp";
  6207. case "ico"_t: return "image/x-icon";
  6208. case "tif"_t: return "image/tiff";
  6209. case "tiff"_t: return "image/tiff";
  6210. case "jpg"_t:
  6211. case "jpeg"_t: return "image/jpeg";
  6212. case "mp4"_t: return "video/mp4";
  6213. case "mpeg"_t: return "video/mpeg";
  6214. case "webm"_t: return "video/webm";
  6215. case "mp3"_t: return "audio/mp3";
  6216. case "mpga"_t: return "audio/mpeg";
  6217. case "weba"_t: return "audio/webm";
  6218. case "wav"_t: return "audio/wave";
  6219. case "otf"_t: return "font/otf";
  6220. case "ttf"_t: return "font/ttf";
  6221. case "woff"_t: return "font/woff";
  6222. case "woff2"_t: return "font/woff2";
  6223. case "7z"_t: return "application/x-7z-compressed";
  6224. case "atom"_t: return "application/atom+xml";
  6225. case "pdf"_t: return "application/pdf";
  6226. case "json"_t: return "application/json";
  6227. case "rss"_t: return "application/rss+xml";
  6228. case "tar"_t: return "application/x-tar";
  6229. case "xht"_t:
  6230. case "xhtml"_t: return "application/xhtml+xml";
  6231. case "xslt"_t: return "application/xslt+xml";
  6232. case "xml"_t: return "application/xml";
  6233. case "gz"_t: return "application/gzip";
  6234. case "zip"_t: return "application/zip";
  6235. case "wasm"_t: return "application/wasm";
  6236. }
  6237. }
  6238. inline std::string
  6239. extract_media_type(const std::string &content_type,
  6240. std::map<std::string, std::string> *params = nullptr) {
  6241. // Extract type/subtype from Content-Type value (RFC 2045)
  6242. // e.g. "application/json; charset=utf-8" -> "application/json"
  6243. auto media_type = content_type;
  6244. auto semicolon_pos = media_type.find(';');
  6245. if (semicolon_pos != std::string::npos) {
  6246. auto param_str = media_type.substr(semicolon_pos + 1);
  6247. media_type = media_type.substr(0, semicolon_pos);
  6248. if (params) {
  6249. // Parse parameters: key=value pairs separated by ';'
  6250. split_unquoted(param_str.data(), param_str.data() + param_str.size(), ';',
  6251. [&](const char *b, const char *e) {
  6252. std::string key;
  6253. std::string val;
  6254. divide_param_pair(b, e, key, val);
  6255. if (!key.empty()) {
  6256. params->emplace(trim_copy(key),
  6257. trim_double_quotes_copy(val));
  6258. }
  6259. });
  6260. }
  6261. }
  6262. // Trim whitespace from media type
  6263. return trim_copy(media_type);
  6264. }
  6265. inline bool can_compress_content_type(const std::string &content_type) {
  6266. using udl::operator""_t;
  6267. auto mime_type = extract_media_type(content_type);
  6268. auto tag = str2tag(mime_type);
  6269. switch (tag) {
  6270. case "image/svg+xml"_t:
  6271. case "application/javascript"_t:
  6272. case "application/x-javascript"_t:
  6273. case "application/json"_t:
  6274. case "application/ld+json"_t:
  6275. case "application/xml"_t:
  6276. case "application/xhtml+xml"_t:
  6277. case "application/rss+xml"_t:
  6278. case "application/atom+xml"_t:
  6279. case "application/xslt+xml"_t:
  6280. case "application/protobuf"_t: return true;
  6281. case "text/event-stream"_t: return false;
  6282. default: return !mime_type.rfind("text/", 0);
  6283. }
  6284. }
  6285. inline bool parse_quality(const char *b, const char *e, std::string &token,
  6286. double &quality) {
  6287. quality = 1.0;
  6288. token.clear();
  6289. // Split on first ';': left = token name, right = parameters
  6290. const char *params_b = nullptr;
  6291. std::size_t params_len = 0;
  6292. divide(
  6293. b, static_cast<std::size_t>(e - b), ';',
  6294. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  6295. auto r = trim(lb, lb + llen, 0, llen);
  6296. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  6297. params_b = rb;
  6298. params_len = rlen;
  6299. });
  6300. if (token.empty()) { return false; }
  6301. if (params_len == 0) { return true; }
  6302. // Scan parameters for q= (stops on first match)
  6303. bool invalid = false;
  6304. split_find(params_b, params_b + params_len, ';',
  6305. (std::numeric_limits<size_t>::max)(),
  6306. [&](const char *pb, const char *pe) -> bool {
  6307. // Match exactly "q=" or "Q=" (not "query=" etc.)
  6308. auto len = static_cast<size_t>(pe - pb);
  6309. if (len < 2) { return false; }
  6310. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  6311. return false;
  6312. }
  6313. // Trim the value portion
  6314. auto r = trim(pb, pe, 2, len);
  6315. if (r.first >= r.second) {
  6316. invalid = true;
  6317. return true;
  6318. }
  6319. double v = 0.0;
  6320. auto res = from_chars(pb + r.first, pb + r.second, v);
  6321. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  6322. invalid = true;
  6323. return true;
  6324. }
  6325. quality = v;
  6326. return true;
  6327. });
  6328. return !invalid;
  6329. }
  6330. inline EncodingType encoding_type(const Request &req,
  6331. const std::string &content_type) {
  6332. if (!can_compress_content_type(content_type)) { return EncodingType::None; }
  6333. auto s = get_combined_header_value(req.headers, "Accept-Encoding");
  6334. if (s.empty()) { return EncodingType::None; }
  6335. // Single-pass: iterate tokens and track the best supported encoding.
  6336. // Server preference breaks ties (br > gzip > zstd).
  6337. EncodingType best = EncodingType::None;
  6338. double best_q = 0.0; // q=0 means "not acceptable"
  6339. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  6340. auto priority = [](EncodingType t) -> int {
  6341. switch (t) {
  6342. case EncodingType::Brotli: return 0;
  6343. case EncodingType::Gzip: return 1;
  6344. case EncodingType::Zstd: return 2;
  6345. default: return 3;
  6346. }
  6347. };
  6348. std::string name;
  6349. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6350. double quality = 1.0;
  6351. if (!parse_quality(b, e, name, quality)) { return; }
  6352. if (quality <= 0.0) { return; }
  6353. EncodingType type = EncodingType::None;
  6354. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6355. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  6356. #endif
  6357. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6358. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  6359. type = EncodingType::Gzip;
  6360. }
  6361. #endif
  6362. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6363. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  6364. type = EncodingType::Zstd;
  6365. }
  6366. #endif
  6367. if (type == EncodingType::None) { return; }
  6368. // Higher q-value wins; for equal q, server preference breaks ties
  6369. if (quality > best_q ||
  6370. (quality == best_q && priority(type) < priority(best))) {
  6371. best_q = quality;
  6372. best = type;
  6373. }
  6374. });
  6375. return best;
  6376. }
  6377. // `content_type` is taken separately because a file-backed response has not
  6378. // been given one yet when its coding has to be decided.
  6379. inline EncodingType encoding_type(const Request &req, const Response &res,
  6380. const std::string &content_type) {
  6381. // The response already names a content coding of its own: a handler serving
  6382. // a body it encoded itself (pre-compressed static assets, say), or a mount
  6383. // point whose headers name the coding its files are stored in. Applying one
  6384. // on top of that would double-encode the body and append a second
  6385. // `Content-Encoding` field line.
  6386. if (res.has_header("Content-Encoding")) { return EncodingType::None; }
  6387. return encoding_type(req, content_type);
  6388. }
  6389. inline EncodingType encoding_type(const Request &req, const Response &res) {
  6390. return encoding_type(req, res, res.get_header_value("Content-Type"));
  6391. }
  6392. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  6393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6394. if (type == EncodingType::Gzip) {
  6395. return detail::make_unique<gzip_compressor>();
  6396. }
  6397. #endif
  6398. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6399. if (type == EncodingType::Brotli) {
  6400. return detail::make_unique<brotli_compressor>();
  6401. }
  6402. #endif
  6403. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6404. if (type == EncodingType::Zstd) {
  6405. return detail::make_unique<zstd_compressor>();
  6406. }
  6407. #endif
  6408. (void)type;
  6409. return nullptr;
  6410. }
  6411. inline const char *encoding_name(EncodingType type) {
  6412. switch (type) {
  6413. case EncodingType::Gzip: return "gzip";
  6414. case EncodingType::Brotli: return "br";
  6415. case EncodingType::Zstd: return "zstd";
  6416. default: return "";
  6417. }
  6418. }
  6419. inline bool nocompressor::compress(const char *data, size_t data_length,
  6420. bool /*last*/, Callback callback) {
  6421. if (!data_length) { return true; }
  6422. return callback(data, data_length);
  6423. }
  6424. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6425. inline gzip_compressor::gzip_compressor() {
  6426. std::memset(&strm_, 0, sizeof(strm_));
  6427. strm_.zalloc = Z_NULL;
  6428. strm_.zfree = Z_NULL;
  6429. strm_.opaque = Z_NULL;
  6430. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  6431. Z_DEFAULT_STRATEGY) == Z_OK;
  6432. }
  6433. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  6434. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  6435. bool last, Callback callback) {
  6436. assert(is_valid_);
  6437. do {
  6438. constexpr size_t max_avail_in =
  6439. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6440. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6441. (std::min)(data_length, max_avail_in));
  6442. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6443. data_length -= strm_.avail_in;
  6444. data += strm_.avail_in;
  6445. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  6446. auto ret = Z_OK;
  6447. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6448. do {
  6449. strm_.avail_out = static_cast<uInt>(buff.size());
  6450. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6451. ret = deflate(&strm_, flush);
  6452. if (ret == Z_STREAM_ERROR) { return false; }
  6453. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6454. return false;
  6455. }
  6456. } while (strm_.avail_out == 0);
  6457. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  6458. (flush == Z_NO_FLUSH && ret == Z_OK));
  6459. assert(strm_.avail_in == 0);
  6460. } while (data_length > 0);
  6461. return true;
  6462. }
  6463. inline gzip_decompressor::gzip_decompressor() {
  6464. std::memset(&strm_, 0, sizeof(strm_));
  6465. strm_.zalloc = Z_NULL;
  6466. strm_.zfree = Z_NULL;
  6467. strm_.opaque = Z_NULL;
  6468. // 15 is the value of wbits, which should be at the maximum possible value
  6469. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  6470. // that the stream type should be automatically detected either gzip or
  6471. // deflate.
  6472. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  6473. }
  6474. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  6475. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  6476. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  6477. Callback callback) {
  6478. assert(is_valid_);
  6479. auto ret = Z_OK;
  6480. do {
  6481. constexpr size_t max_avail_in =
  6482. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6483. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6484. (std::min)(data_length, max_avail_in));
  6485. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6486. data_length -= strm_.avail_in;
  6487. data += strm_.avail_in;
  6488. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6489. while (strm_.avail_in > 0 && ret == Z_OK) {
  6490. strm_.avail_out = static_cast<uInt>(buff.size());
  6491. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6492. ret = inflate(&strm_, Z_NO_FLUSH);
  6493. assert(ret != Z_STREAM_ERROR);
  6494. switch (ret) {
  6495. case Z_NEED_DICT:
  6496. case Z_DATA_ERROR:
  6497. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  6498. }
  6499. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6500. return false;
  6501. }
  6502. }
  6503. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  6504. } while (data_length > 0);
  6505. return true;
  6506. }
  6507. #endif
  6508. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6509. inline brotli_compressor::brotli_compressor() {
  6510. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  6511. }
  6512. inline brotli_compressor::~brotli_compressor() {
  6513. BrotliEncoderDestroyInstance(state_);
  6514. }
  6515. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  6516. bool last, Callback callback) {
  6517. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6518. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  6519. auto available_in = data_length;
  6520. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6521. for (;;) {
  6522. if (last) {
  6523. if (BrotliEncoderIsFinished(state_)) { break; }
  6524. } else {
  6525. if (!available_in) { break; }
  6526. }
  6527. auto available_out = buff.size();
  6528. auto next_out = buff.data();
  6529. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  6530. &available_out, &next_out, nullptr)) {
  6531. return false;
  6532. }
  6533. auto output_bytes = buff.size() - available_out;
  6534. if (output_bytes) {
  6535. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  6536. }
  6537. }
  6538. return true;
  6539. }
  6540. inline brotli_decompressor::brotli_decompressor() {
  6541. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  6542. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  6543. : BROTLI_DECODER_RESULT_ERROR;
  6544. }
  6545. inline brotli_decompressor::~brotli_decompressor() {
  6546. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  6547. }
  6548. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  6549. inline bool brotli_decompressor::decompress(const char *data,
  6550. size_t data_length,
  6551. Callback callback) {
  6552. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6553. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  6554. return 0;
  6555. }
  6556. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6557. size_t avail_in = data_length;
  6558. size_t total_out;
  6559. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  6560. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6561. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  6562. char *next_out = buff.data();
  6563. size_t avail_out = buff.size();
  6564. decoder_r = BrotliDecoderDecompressStream(
  6565. decoder_s, &avail_in, &next_in, &avail_out,
  6566. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  6567. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  6568. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  6569. }
  6570. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6571. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  6572. }
  6573. #endif
  6574. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6575. inline zstd_compressor::zstd_compressor() {
  6576. ctx_ = ZSTD_createCCtx();
  6577. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  6578. }
  6579. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  6580. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  6581. bool last, Callback callback) {
  6582. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6583. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  6584. ZSTD_inBuffer input = {data, data_length, 0};
  6585. bool finished;
  6586. do {
  6587. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6588. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  6589. if (ZSTD_isError(remaining)) { return false; }
  6590. if (!callback(buff.data(), output.pos)) { return false; }
  6591. finished = last ? (remaining == 0) : (input.pos == input.size);
  6592. } while (!finished);
  6593. return true;
  6594. }
  6595. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  6596. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  6597. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  6598. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  6599. Callback callback) {
  6600. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6601. ZSTD_inBuffer input = {data, data_length, 0};
  6602. while (input.pos < input.size) {
  6603. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6604. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  6605. if (ZSTD_isError(remaining)) { return false; }
  6606. if (!callback(buff.data(), output.pos)) { return false; }
  6607. }
  6608. return true;
  6609. }
  6610. #endif
  6611. // Content codings are case-insensitive (RFC 9110 8.4.1). Matching them
  6612. // case-sensitively would make a response labeled e.g. "GZIP" look like an
  6613. // unknown coding, and its payload would be handed back still compressed.
  6614. inline bool is_zlib_encoding(const std::string &encoding) {
  6615. return case_ignore::equal(encoding, "gzip") ||
  6616. case_ignore::equal(encoding, "deflate");
  6617. }
  6618. inline bool is_brotli_encoding(const std::string &encoding) {
  6619. return case_ignore::equal(encoding, "br");
  6620. }
  6621. inline bool is_zstd_encoding(const std::string &encoding) {
  6622. return case_ignore::equal(encoding, "zstd");
  6623. }
  6624. // Returns true if the content coding is one cpp-httplib is able to decompress
  6625. // when the corresponding support is compiled in.
  6626. inline bool is_known_content_encoding(const std::string &encoding) {
  6627. return is_zlib_encoding(encoding) || is_brotli_encoding(encoding) ||
  6628. is_zstd_encoding(encoding);
  6629. }
  6630. inline std::unique_ptr<decompressor>
  6631. create_decompressor(const std::string &encoding) {
  6632. std::unique_ptr<decompressor> decompressor;
  6633. if (is_zlib_encoding(encoding)) {
  6634. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6635. decompressor = detail::make_unique<gzip_decompressor>();
  6636. #endif
  6637. } else if (is_brotli_encoding(encoding)) {
  6638. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6639. decompressor = detail::make_unique<brotli_decompressor>();
  6640. #endif
  6641. } else if (is_zstd_encoding(encoding)) {
  6642. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6643. decompressor = detail::make_unique<zstd_decompressor>();
  6644. #endif
  6645. }
  6646. return decompressor;
  6647. }
  6648. // Returns the best available compressor and its Content-Encoding name.
  6649. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  6650. inline std::pair<std::unique_ptr<compressor>, const char *>
  6651. create_compressor() {
  6652. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6653. return {detail::make_unique<brotli_compressor>(), "br"};
  6654. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6655. return {detail::make_unique<gzip_compressor>(), "gzip"};
  6656. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6657. return {detail::make_unique<zstd_compressor>(), "zstd"};
  6658. #else
  6659. return {nullptr, nullptr};
  6660. #endif
  6661. }
  6662. inline bool is_prohibited_header_name(const std::string &name) {
  6663. using udl::operator""_t;
  6664. switch (str2tag(name)) {
  6665. case "REMOTE_ADDR"_t:
  6666. case "REMOTE_PORT"_t:
  6667. case "LOCAL_ADDR"_t:
  6668. case "LOCAL_PORT"_t: return true;
  6669. default: return false;
  6670. }
  6671. }
  6672. inline bool has_header(const Headers &headers, const std::string &key) {
  6673. if (is_prohibited_header_name(key)) { return false; }
  6674. return headers.find(key) != headers.end();
  6675. }
  6676. inline const char *get_header_value(const Headers &headers,
  6677. const std::string &key, const char *def,
  6678. size_t id) {
  6679. if (is_prohibited_header_name(key)) {
  6680. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6681. std::string msg = "Prohibited header name '" + key + "' is specified.";
  6682. throw std::invalid_argument(msg);
  6683. #else
  6684. return "";
  6685. #endif
  6686. }
  6687. auto rng = headers.equal_range(key);
  6688. auto it = rng.first;
  6689. std::advance(it, static_cast<ssize_t>(id));
  6690. if (it != rng.second) { return it->second.c_str(); }
  6691. return def;
  6692. }
  6693. inline size_t get_header_value_count(const Headers &headers,
  6694. const std::string &key) {
  6695. return headers.count(key);
  6696. }
  6697. // RFC 9110 Section 5.2 and 5.3: a field that is defined as a comma-separated
  6698. // list may be sent as several field lines, and the combined field value is
  6699. // those values joined by commas in the order they were received. Callers that
  6700. // parse such a list must work on the combined value; reading only the first
  6701. // occurrence silently drops whatever the later field lines carry.
  6702. inline std::string get_combined_header_value(const Headers &headers,
  6703. const std::string &key) {
  6704. std::string combined;
  6705. auto rng = headers.equal_range(key);
  6706. for (auto it = rng.first; it != rng.second; ++it) {
  6707. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  6708. // elements, so an empty field line must not contribute a bare comma to the
  6709. // combined value.
  6710. if (it->second.empty()) { continue; }
  6711. if (!combined.empty()) { combined += ", "; }
  6712. combined += it->second;
  6713. }
  6714. return combined;
  6715. }
  6716. inline bool has_header_token(const Headers &headers, const std::string &key,
  6717. const std::string &token) {
  6718. // RFC 9110 7.6.1: a comma-separated token list field such as Connection may
  6719. // carry several tokens, and RFC 9110 5.3 lets that list be split across
  6720. // several lines. Match complete tokens rather than searching the raw value,
  6721. // so that a value such as "notupgrade" is not read as the token "upgrade".
  6722. auto rng = headers.equal_range(key);
  6723. for (auto it = rng.first; it != rng.second; ++it) {
  6724. const auto &value = it->second;
  6725. if (split_find(value.data(), value.data() + value.size(), ',',
  6726. [&](const char *b, const char *e) {
  6727. return case_ignore::equal(std::string(b, e), token);
  6728. })) {
  6729. return true;
  6730. }
  6731. }
  6732. return false;
  6733. }
  6734. template <typename Map>
  6735. inline typename Map::mapped_type
  6736. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  6737. auto rng = m.equal_range(key);
  6738. auto it = rng.first;
  6739. std::advance(it, static_cast<ssize_t>(id));
  6740. if (it != rng.second) { return it->second; }
  6741. return typename Map::mapped_type();
  6742. }
  6743. inline void set_header(Headers &headers, const std::string &key,
  6744. const std::string &val) {
  6745. if (fields::is_field_valid(key, val)) { headers.emplace(key, val); }
  6746. }
  6747. inline bool read_headers(Stream &strm, Headers &headers) {
  6748. const auto bufsiz = 2048;
  6749. char buf[bufsiz];
  6750. stream_line_reader line_reader(strm, buf, bufsiz);
  6751. size_t header_count = 0;
  6752. for (;;) {
  6753. if (!line_reader.getline()) { return false; }
  6754. // Check if the line ends with CRLF.
  6755. auto line_terminator_len = 2;
  6756. if (line_reader.end_with_crlf()) {
  6757. // Blank line indicates end of headers.
  6758. if (line_reader.size() == 2) { break; }
  6759. } else {
  6760. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6761. // Blank line indicates end of headers.
  6762. if (line_reader.size() == 1) { break; }
  6763. line_terminator_len = 1;
  6764. #else
  6765. continue; // Skip invalid line.
  6766. #endif
  6767. }
  6768. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6769. // Check header count limit
  6770. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  6771. // Exclude line terminator
  6772. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  6773. if (!parse_header(line_reader.ptr(), end,
  6774. [&](const std::string &key, const std::string &val) {
  6775. headers.emplace(key, val);
  6776. })) {
  6777. return false;
  6778. }
  6779. header_count++;
  6780. }
  6781. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  6782. // headers that have different values to prevent request smuggling.
  6783. auto cl_range = headers.equal_range("Content-Length");
  6784. if (cl_range.first != cl_range.second) {
  6785. const auto &first_val = cl_range.first->second;
  6786. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  6787. if (it->second != first_val) { return false; }
  6788. }
  6789. }
  6790. return true;
  6791. }
  6792. inline bool parse_status_line(const char *line, std::string &version,
  6793. int &status, std::string &reason) {
  6794. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6795. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  6796. #else
  6797. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  6798. #endif
  6799. std::cmatch m;
  6800. if (!std::regex_match(line, m, re)) { return false; }
  6801. version = std::string(m[1]);
  6802. status = std::stoi(std::string(m[2]));
  6803. reason = std::string(m[3]);
  6804. return true;
  6805. }
  6806. // Everything WebSocketClient::connect() reports about the upgrade exchange.
  6807. // status stays -1 until a status line is parsed, mirroring stream::Result.
  6808. struct WebSocketUpgradeResponse {
  6809. Error error = Error::Success;
  6810. int status = -1;
  6811. Headers headers;
  6812. std::string selected_subprotocol;
  6813. };
  6814. inline bool read_websocket_upgrade_response(Stream &strm,
  6815. const std::string &expected_accept,
  6816. WebSocketUpgradeResponse &upgrade) {
  6817. // Read status line
  6818. const auto bufsiz = 2048;
  6819. char buf[bufsiz];
  6820. stream_line_reader line_reader(strm, buf, bufsiz);
  6821. if (!line_reader.getline()) {
  6822. upgrade.error = Error::Read;
  6823. return false;
  6824. }
  6825. std::string version;
  6826. std::string reason;
  6827. if (!parse_status_line(line_reader.ptr(), version, upgrade.status, reason)) {
  6828. upgrade.error = Error::WebSocketHandshake;
  6829. return false;
  6830. }
  6831. // Read the headers even for a rejection so the caller can see why the
  6832. // server refused the upgrade. A non-101 response may carry a body; it is
  6833. // deliberately left unread since the caller closes the socket right away.
  6834. if (!read_headers(strm, upgrade.headers)) {
  6835. upgrade.error = Error::Read;
  6836. return false;
  6837. }
  6838. const auto &headers = upgrade.headers;
  6839. if (upgrade.status != StatusCode::SwitchingProtocol_101) {
  6840. upgrade.error = Error::WebSocketHandshake;
  6841. return false;
  6842. }
  6843. // Verify Upgrade: websocket (a comma-separated list, matched per token)
  6844. if (!has_header_token(headers, "Upgrade", "websocket")) {
  6845. upgrade.error = Error::WebSocketHandshake;
  6846. return false;
  6847. }
  6848. // Verify Connection: Upgrade
  6849. if (!has_header_token(headers, "Connection", "upgrade")) {
  6850. upgrade.error = Error::WebSocketHandshake;
  6851. return false;
  6852. }
  6853. // Verify Sec-WebSocket-Accept header value
  6854. auto it = headers.find("Sec-WebSocket-Accept");
  6855. if (it == headers.end() || it->second != expected_accept) {
  6856. upgrade.error = Error::WebSocketHandshake;
  6857. return false;
  6858. }
  6859. // Extract negotiated subprotocol
  6860. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6861. if (proto_it != headers.end()) {
  6862. upgrade.selected_subprotocol = proto_it->second;
  6863. }
  6864. return true;
  6865. }
  6866. enum class ReadContentResult {
  6867. Success, // Successfully read the content
  6868. PayloadTooLarge, // The content exceeds the specified payload limit
  6869. Error // An error occurred while reading the content
  6870. };
  6871. inline ReadContentResult read_content_with_length(
  6872. Stream &strm, size_t len, DownloadProgress progress,
  6873. ContentReceiverWithProgress out,
  6874. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6875. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6876. detail::BodyReader br;
  6877. br.stream = &strm;
  6878. br.has_content_length = true;
  6879. br.content_length = len;
  6880. br.payload_max_length = payload_max_length;
  6881. br.chunked = false;
  6882. br.bytes_read = 0;
  6883. br.last_error = Error::Success;
  6884. size_t r = 0;
  6885. while (r < len) {
  6886. auto read_len = static_cast<size_t>(len - r);
  6887. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6888. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6889. if (n <= 0) {
  6890. // Check if it was a payload size error
  6891. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6892. return ReadContentResult::PayloadTooLarge;
  6893. }
  6894. return ReadContentResult::Error;
  6895. }
  6896. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6897. return ReadContentResult::Error;
  6898. }
  6899. r += static_cast<size_t>(n);
  6900. if (progress) {
  6901. if (!progress(r, len)) { return ReadContentResult::Error; }
  6902. }
  6903. }
  6904. return ReadContentResult::Success;
  6905. }
  6906. inline ReadContentResult
  6907. read_content_without_length(Stream &strm, size_t payload_max_length,
  6908. ContentReceiverWithProgress out) {
  6909. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6910. size_t r = 0;
  6911. for (;;) {
  6912. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6913. if (n == 0) { return ReadContentResult::Success; }
  6914. if (n < 0) { return ReadContentResult::Error; }
  6915. // Check if adding this data would exceed the payload limit
  6916. if (r > payload_max_length ||
  6917. payload_max_length - r < static_cast<size_t>(n)) {
  6918. return ReadContentResult::PayloadTooLarge;
  6919. }
  6920. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6921. return ReadContentResult::Error;
  6922. }
  6923. r += static_cast<size_t>(n);
  6924. }
  6925. return ReadContentResult::Success;
  6926. }
  6927. template <typename T>
  6928. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6929. size_t payload_max_length,
  6930. ContentReceiverWithProgress out) {
  6931. detail::ChunkedDecoder dec(strm);
  6932. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6933. size_t total_len = 0;
  6934. for (;;) {
  6935. size_t chunk_offset = 0;
  6936. size_t chunk_total = 0;
  6937. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6938. if (n < 0) { return ReadContentResult::Error; }
  6939. if (n == 0) {
  6940. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6941. return ReadContentResult::Error;
  6942. }
  6943. return ReadContentResult::Success;
  6944. }
  6945. if (total_len > payload_max_length ||
  6946. payload_max_length - total_len < static_cast<size_t>(n)) {
  6947. return ReadContentResult::PayloadTooLarge;
  6948. }
  6949. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6950. return ReadContentResult::Error;
  6951. }
  6952. total_len += static_cast<size_t>(n);
  6953. }
  6954. }
  6955. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6956. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  6957. // is the final transfer coding. A single field value may list several
  6958. // codings ("gzip, chunked"), and RFC 9110 5.3 lets that list be split across
  6959. // several Transfer-Encoding lines, which combine into one comma-separated
  6960. // list in the order the lines were received. Headers preserves that order,
  6961. // so the final coding is the last token of the last line. Match it
  6962. // case-insensitively rather than comparing the whole value against
  6963. // "chunked".
  6964. //
  6965. // Security: reading a chunked message as unframed leaves its body in the
  6966. // socket, where a keep-alive connection parses it as a smuggled request.
  6967. // Server::process_request() answers 400 and closes when the final coding is
  6968. // not chunked, so a request whose framing cannot be determined never
  6969. // reaches the "no body" path.
  6970. auto rng = headers.equal_range("Transfer-Encoding");
  6971. if (rng.first == rng.second) { return false; }
  6972. // Cleared per line, so a trailing line carrying no coding at all leaves the
  6973. // combined list ending in nothing rather than inheriting the line before it.
  6974. std::string last_coding;
  6975. for (auto it = rng.first; it != rng.second; ++it) {
  6976. const auto &value = it->second;
  6977. last_coding.clear();
  6978. split(value.data(), value.data() + value.size(), ',',
  6979. [&](const char *b, const char *e) { last_coding.assign(b, e); });
  6980. }
  6981. return case_ignore::equal(last_coding, "chunked");
  6982. }
  6983. inline bool has_conflicting_content_length(const Headers &headers) {
  6984. // RFC 9112 §6.3: a message carrying both Transfer-Encoding and a non-zero
  6985. // Content-Length is framed ambiguously. The body readers here delimit it by
  6986. // the transfer coding and drop Content-Length, while an intermediary may do
  6987. // the reverse, so the two disagree on where the body ends and a reused
  6988. // connection is desynchronised (request/response smuggling). Content-Length:
  6989. // 0 is tolerated for compatibility with existing peers.
  6990. return has_header(headers, "Transfer-Encoding") &&
  6991. get_header_value_u64(headers, "Content-Length", 0, 0) > 0;
  6992. }
  6993. template <typename T, typename U>
  6994. bool prepare_content_receiver(T &x, int &status,
  6995. ContentReceiverWithProgress receiver,
  6996. bool decompress, size_t payload_max_length,
  6997. bool &exceed_payload_max_length, U callback) {
  6998. if (decompress) {
  6999. auto encoding = get_combined_header_value(x.headers, "Content-Encoding");
  7000. std::unique_ptr<decompressor> decompressor;
  7001. if (!encoding.empty()) {
  7002. // A coding we know about but were not built with is an error. An
  7003. // unrecognized coding (including "identity") is left alone and the
  7004. // payload is passed through as-is, since some servers misuse the header,
  7005. // e.g. by sending a character set such as "Content-Encoding: UTF-8".
  7006. decompressor = detail::create_decompressor(encoding);
  7007. if (!decompressor && detail::is_known_content_encoding(encoding)) {
  7008. status = StatusCode::UnsupportedMediaType_415;
  7009. return false;
  7010. }
  7011. }
  7012. if (decompressor) {
  7013. if (decompressor->is_valid()) {
  7014. size_t decompressed_size = 0;
  7015. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  7016. size_t off, size_t len) {
  7017. return decompressor->decompress(
  7018. buf, n, [&](const char *buf2, size_t n2) {
  7019. // Guard against zip-bomb: check
  7020. // decompressed size against limit.
  7021. if (payload_max_length > 0 &&
  7022. (decompressed_size >= payload_max_length ||
  7023. n2 > payload_max_length - decompressed_size)) {
  7024. exceed_payload_max_length = true;
  7025. return false;
  7026. }
  7027. decompressed_size += n2;
  7028. return receiver(buf2, n2, off, len);
  7029. });
  7030. };
  7031. return callback(std::move(out));
  7032. } else {
  7033. status = StatusCode::InternalServerError_500;
  7034. return false;
  7035. }
  7036. }
  7037. }
  7038. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  7039. size_t len) {
  7040. return receiver(buf, n, off, len);
  7041. };
  7042. return callback(std::move(out));
  7043. }
  7044. template <typename T>
  7045. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  7046. DownloadProgress progress,
  7047. ContentReceiverWithProgress receiver, bool decompress) {
  7048. bool exceed_payload_max_length = false;
  7049. return prepare_content_receiver(
  7050. x, status, std::move(receiver), decompress, payload_max_length,
  7051. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  7052. auto ret = true;
  7053. // Note: exceed_payload_max_length may also be set by the decompressor
  7054. // wrapper in prepare_content_receiver when the decompressed payload
  7055. // size exceeds the limit.
  7056. if (is_chunked_transfer_encoding(x.headers)) {
  7057. auto result = read_content_chunked(strm, x, payload_max_length, out);
  7058. if (result == ReadContentResult::Success) {
  7059. ret = true;
  7060. } else if (result == ReadContentResult::PayloadTooLarge) {
  7061. exceed_payload_max_length = true;
  7062. ret = false;
  7063. } else {
  7064. ret = false;
  7065. }
  7066. } else if (!has_header(x.headers, "Content-Length")) {
  7067. auto result =
  7068. read_content_without_length(strm, payload_max_length, out);
  7069. if (result == ReadContentResult::Success) {
  7070. ret = true;
  7071. } else if (result == ReadContentResult::PayloadTooLarge) {
  7072. exceed_payload_max_length = true;
  7073. ret = false;
  7074. } else {
  7075. ret = false;
  7076. }
  7077. } else {
  7078. auto is_invalid_value = false;
  7079. auto len = get_header_value_u64(x.headers, "Content-Length",
  7080. (std::numeric_limits<size_t>::max)(),
  7081. 0, is_invalid_value);
  7082. if (is_invalid_value) {
  7083. ret = false;
  7084. } else if (len > 0) {
  7085. auto result = read_content_with_length(
  7086. strm, len, std::move(progress), out, payload_max_length);
  7087. ret = (result == ReadContentResult::Success);
  7088. if (result == ReadContentResult::PayloadTooLarge) {
  7089. exceed_payload_max_length = true;
  7090. }
  7091. }
  7092. }
  7093. if (!ret) {
  7094. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  7095. : StatusCode::BadRequest_400;
  7096. }
  7097. return ret;
  7098. });
  7099. }
  7100. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  7101. const std::string &path) {
  7102. // A request target must not carry CR/LF (or other control octets); otherwise
  7103. // a value smuggled into it splits the request line and injects headers or a
  7104. // whole request. The same field-value check already guards header values in
  7105. // check_and_write_headers and the request target in
  7106. // perform_websocket_handshake; apply it here too.
  7107. if (!fields::is_field_value(path)) { return -1; }
  7108. std::string s = method;
  7109. s += ' ';
  7110. s += path;
  7111. s += " HTTP/1.1\r\n";
  7112. return strm.write(s.data(), s.size());
  7113. }
  7114. inline ssize_t write_response_line(Stream &strm, int status) {
  7115. std::string s = "HTTP/1.1 ";
  7116. s += std::to_string(status);
  7117. s += ' ';
  7118. s += httplib::status_message(status);
  7119. s += "\r\n";
  7120. return strm.write(s.data(), s.size());
  7121. }
  7122. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  7123. ssize_t write_len = 0;
  7124. for (const auto &x : headers) {
  7125. // Skip fields with invalid names or values to prevent response splitting
  7126. // via CR/LF injection, matching set_header(). The client validates request
  7127. // headers up front in check_and_write_headers, but the server passes
  7128. // res.headers straight to this writer, and res.headers is a public field
  7129. // an application can populate directly with request-derived values.
  7130. if (!fields::is_field_valid(x.first, x.second)) { continue; }
  7131. std::string s;
  7132. s = x.first;
  7133. s += ": ";
  7134. s += x.second;
  7135. s += "\r\n";
  7136. auto len = strm.write(s.data(), s.size());
  7137. if (len < 0) { return len; }
  7138. write_len += len;
  7139. }
  7140. auto len = strm.write("\r\n");
  7141. if (len < 0) { return len; }
  7142. write_len += len;
  7143. return write_len;
  7144. }
  7145. inline bool write_data(Stream &strm, const char *d, size_t l) {
  7146. size_t offset = 0;
  7147. while (offset < l) {
  7148. auto length = strm.write(d + offset, l - offset);
  7149. if (length < 0) { return false; }
  7150. offset += static_cast<size_t>(length);
  7151. }
  7152. return true;
  7153. }
  7154. template <typename T>
  7155. inline bool write_content_with_progress(Stream &strm,
  7156. const ContentProvider &content_provider,
  7157. size_t offset, size_t length,
  7158. T is_shutting_down,
  7159. const UploadProgress &upload_progress,
  7160. Error &error) {
  7161. size_t end_offset = offset + length;
  7162. size_t start_offset = offset;
  7163. auto ok = true;
  7164. auto finished = false;
  7165. DataSink data_sink;
  7166. data_sink.write = [&](const char *d, size_t l) -> bool {
  7167. if (ok) {
  7168. if (write_data(strm, d, l)) {
  7169. offset += l;
  7170. if (upload_progress && length > 0) {
  7171. size_t current_written = offset - start_offset;
  7172. if (!upload_progress(current_written, length)) {
  7173. ok = false;
  7174. return false;
  7175. }
  7176. }
  7177. } else {
  7178. ok = false;
  7179. }
  7180. }
  7181. return ok;
  7182. };
  7183. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7184. // The body is framed by `length`, so a provider that reports itself done
  7185. // early has truncated it. Record that and let the short-body check below
  7186. // fail the write, rather than calling the provider again forever.
  7187. data_sink.done = [&]() { finished = true; };
  7188. while (offset < end_offset && !finished && !is_shutting_down()) {
  7189. auto last_offset = offset;
  7190. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7191. error = Error::Write;
  7192. return false;
  7193. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  7194. error = Error::Canceled;
  7195. return false;
  7196. } else if (!ok) {
  7197. error = Error::Write;
  7198. return false;
  7199. }
  7200. // A provider that reports success without writing anything and without
  7201. // reporting itself done gets handed the same offset and length again on
  7202. // the next pass, so it would spin here for as long as the peer stays
  7203. // connected. Treat making no progress as a short body, like done() early.
  7204. if (!finished && offset == last_offset) {
  7205. error = Error::Write;
  7206. return false;
  7207. }
  7208. }
  7209. if (offset < end_offset) { // done() called early, or is_shutting_down()
  7210. error = Error::Write;
  7211. return false;
  7212. }
  7213. error = Error::Success;
  7214. return true;
  7215. }
  7216. template <typename T>
  7217. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  7218. size_t offset, size_t length, T is_shutting_down,
  7219. Error &error) {
  7220. return write_content_with_progress<T>(strm, content_provider, offset, length,
  7221. is_shutting_down, nullptr, error);
  7222. }
  7223. template <typename T>
  7224. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  7225. size_t offset, size_t length,
  7226. const T &is_shutting_down) {
  7227. auto error = Error::Success;
  7228. return write_content(strm, content_provider, offset, length, is_shutting_down,
  7229. error);
  7230. }
  7231. template <typename T>
  7232. inline bool
  7233. write_content_without_length(Stream &strm,
  7234. const ContentProvider &content_provider,
  7235. const T &is_shutting_down) {
  7236. size_t offset = 0;
  7237. auto data_available = true;
  7238. auto ok = true;
  7239. DataSink data_sink;
  7240. data_sink.write = [&](const char *d, size_t l) -> bool {
  7241. if (ok) {
  7242. offset += l;
  7243. if (!write_data(strm, d, l)) { ok = false; }
  7244. }
  7245. return ok;
  7246. };
  7247. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7248. data_sink.done = [&](void) { data_available = false; };
  7249. while (data_available && !is_shutting_down()) {
  7250. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7251. return false;
  7252. } else if (!content_provider(offset, 0, data_sink)) {
  7253. return false;
  7254. } else if (!ok) {
  7255. return false;
  7256. }
  7257. }
  7258. return !data_available; // true only if done() was called, false if shutting
  7259. // down
  7260. }
  7261. // Runs a known-length content provider to completion and compresses what it
  7262. // writes into `out`. Nothing is buffered in identity form: a provider backed
  7263. // by an mmap hands the compressor a pointer straight into the mapping.
  7264. inline bool compress_content_provider(const ContentProvider &content_provider,
  7265. size_t length, compressor &cmp,
  7266. std::string &out) {
  7267. size_t offset = 0;
  7268. auto ok = true;
  7269. auto finished = false;
  7270. DataSink data_sink;
  7271. auto append = [&](const char *data, size_t data_len) {
  7272. out.append(data, data_len);
  7273. return true;
  7274. };
  7275. data_sink.write = [&](const char *d, size_t l) -> bool {
  7276. if (!ok) { return false; }
  7277. offset += l;
  7278. if (l > 0 && !cmp.compress(d, l, false, append)) { ok = false; }
  7279. return ok;
  7280. };
  7281. // The body is framed by `length`, so a provider that reports itself done
  7282. // early has truncated it; the short-body check below turns that into a
  7283. // failure rather than calling the provider again forever.
  7284. data_sink.done = [&]() { finished = true; };
  7285. while (offset < length && !finished) {
  7286. auto prev_offset = offset;
  7287. if (!content_provider(offset, length - offset, data_sink) || !ok) {
  7288. return false;
  7289. }
  7290. // No Stream to block on here, so a provider that keeps returning true
  7291. // without writing would spin. Treat a pass that made no progress as a
  7292. // failure.
  7293. if (offset == prev_offset) { return false; }
  7294. }
  7295. if (offset != length) { return false; }
  7296. return cmp.compress(nullptr, 0, true, append);
  7297. }
  7298. // Serves `m` as the response body. `set_content_provider()` clears the coding,
  7299. // so recording it has to come after; keeping both here means a third
  7300. // file-serving path cannot get that order wrong.
  7301. inline void set_file_content_provider(Response &res,
  7302. const std::shared_ptr<mmap> &m,
  7303. const std::string &content_type,
  7304. EncodingType encoding) {
  7305. res.set_content_provider(
  7306. m->size(), content_type,
  7307. [m](size_t offset, size_t length, DataSink &sink) -> bool {
  7308. sink.write(m->data() + offset, length);
  7309. return true;
  7310. });
  7311. res.content_coding_ = encoding;
  7312. }
  7313. template <typename T, typename U>
  7314. inline bool
  7315. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  7316. const T &is_shutting_down, U &compressor, Error &error) {
  7317. size_t offset = 0;
  7318. auto data_available = true;
  7319. auto ok = true;
  7320. DataSink data_sink;
  7321. data_sink.write = [&](const char *d, size_t l) -> bool {
  7322. // Only done()/done_with_trailer() end a chunked body. A pass with nothing
  7323. // to hand over is ordinary (an empty buffer popped off a queue), and a
  7324. // zero-length chunk is the terminator, so it must not be emitted here.
  7325. if (ok && l > 0) {
  7326. offset += l;
  7327. std::string payload;
  7328. if (compressor.compress(d, l, false,
  7329. [&](const char *data, size_t data_len) {
  7330. payload.append(data, data_len);
  7331. return true;
  7332. })) {
  7333. if (!payload.empty()) {
  7334. // Emit chunked response header and footer for each chunk
  7335. auto chunk =
  7336. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7337. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  7338. }
  7339. } else {
  7340. ok = false;
  7341. }
  7342. }
  7343. return ok;
  7344. };
  7345. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7346. auto done_with_trailer = [&](const Headers *trailer) {
  7347. if (!ok) { return; }
  7348. data_available = false;
  7349. std::string payload;
  7350. if (!compressor.compress(nullptr, 0, true,
  7351. [&](const char *data, size_t data_len) {
  7352. payload.append(data, data_len);
  7353. return true;
  7354. })) {
  7355. ok = false;
  7356. return;
  7357. }
  7358. if (!payload.empty()) {
  7359. // Emit chunked response header and footer for each chunk
  7360. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7361. if (!write_data(strm, chunk.data(), chunk.size())) {
  7362. ok = false;
  7363. return;
  7364. }
  7365. }
  7366. constexpr const char done_marker[] = "0\r\n";
  7367. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  7368. // Trailer
  7369. if (trailer) {
  7370. for (const auto &kv : *trailer) {
  7371. // Skip fields with invalid names or values to prevent response
  7372. // splitting via CR/LF injection, matching set_header().
  7373. if (!fields::is_field_valid(kv.first, kv.second)) { continue; }
  7374. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  7375. if (!write_data(strm, field_line.data(), field_line.size())) {
  7376. ok = false;
  7377. }
  7378. }
  7379. }
  7380. constexpr const char crlf[] = "\r\n";
  7381. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  7382. };
  7383. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  7384. data_sink.done_with_trailer = [&](const Headers &trailer) {
  7385. done_with_trailer(&trailer);
  7386. };
  7387. while (data_available && !is_shutting_down()) {
  7388. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7389. error = Error::Write;
  7390. return false;
  7391. } else if (!content_provider(offset, 0, data_sink)) {
  7392. error = Error::Canceled;
  7393. return false;
  7394. } else if (!ok) {
  7395. error = Error::Write;
  7396. return false;
  7397. }
  7398. }
  7399. if (data_available) { // exited due to is_shutting_down(), not done()
  7400. error = Error::Write;
  7401. return false;
  7402. }
  7403. error = Error::Success;
  7404. return true;
  7405. }
  7406. template <typename T, typename U>
  7407. inline bool write_content_chunked(Stream &strm,
  7408. const ContentProvider &content_provider,
  7409. const T &is_shutting_down, U &compressor) {
  7410. auto error = Error::Success;
  7411. return write_content_chunked(strm, content_provider, is_shutting_down,
  7412. compressor, error);
  7413. }
  7414. template <typename T>
  7415. inline bool redirect(T &cli, Request &req, Response &res,
  7416. const std::string &path, const std::string &location,
  7417. Error &error) {
  7418. Request new_req = req;
  7419. new_req.path = path;
  7420. new_req.redirect_count_ -= 1;
  7421. if (res.status == StatusCode::SeeOther_303 &&
  7422. (req.method != "GET" && req.method != "HEAD")) {
  7423. new_req.method = "GET";
  7424. new_req.body.clear();
  7425. new_req.headers.clear();
  7426. }
  7427. Response new_res;
  7428. auto ret = cli.send(new_req, new_res, error);
  7429. if (ret) {
  7430. req = std::move(new_req);
  7431. res = std::move(new_res);
  7432. if (res.location.empty()) { res.location = location; }
  7433. }
  7434. return ret;
  7435. }
  7436. inline std::string params_to_query_str(const Params &params) {
  7437. std::string query;
  7438. for (auto it = params.begin(); it != params.end(); ++it) {
  7439. if (it != params.begin()) { query += '&'; }
  7440. query += encode_query_component(it->first);
  7441. query += '=';
  7442. query += encode_query_component(it->second);
  7443. }
  7444. return query;
  7445. }
  7446. // Splits one "key=value" span of a query string at its first '='. A span with
  7447. // no '=' at all lands entirely in key, leaving val empty, which is how a bare
  7448. // "?flag" keeps its name.
  7449. inline void divide_query_pair(const char *b, const char *e, std::string &key,
  7450. std::string &val) {
  7451. divide(b, static_cast<std::size_t>(e - b), '=',
  7452. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  7453. std::size_t rhs_size) {
  7454. key.assign(lhs_data, lhs_size);
  7455. val.assign(rhs_data, rhs_size);
  7456. });
  7457. }
  7458. inline void parse_query_text(const char *data, std::size_t size,
  7459. Params &params) {
  7460. std::set<std::string> cache;
  7461. split(data, data + size, '&', [&](const char *b, const char *e) {
  7462. std::string kv(b, e);
  7463. if (cache.find(kv) != cache.end()) { return; }
  7464. cache.insert(std::move(kv));
  7465. std::string key;
  7466. std::string val;
  7467. divide_query_pair(b, e, key, val);
  7468. if (!key.empty()) {
  7469. params.emplace(decode_query_component(key), decode_query_component(val));
  7470. }
  7471. });
  7472. }
  7473. inline void parse_query_text(const std::string &s, Params &params) {
  7474. parse_query_text(s.data(), s.size(), params);
  7475. }
  7476. // Normalize a query string by decoding and re-encoding each key/value pair
  7477. // while preserving the original parameter order. This avoids double-encoding
  7478. // and ensures consistent encoding. It works on the raw string rather than
  7479. // parsing into Params and re-serializing, because that round trip cannot
  7480. // reproduce the input: params_to_query_str() always emits '=', so a bare
  7481. // "flag" would come back as "flag=", and parse_query_text() drops exactly
  7482. // duplicated pairs.
  7483. inline std::string normalize_query_string(const std::string &query) {
  7484. std::string result;
  7485. split(query.data(), query.data() + query.size(), '&',
  7486. [&](const char *b, const char *e) {
  7487. std::string key;
  7488. std::string val;
  7489. divide_query_pair(b, e, key, val);
  7490. if (!key.empty()) {
  7491. auto dec_key = decode_query_component(key);
  7492. auto dec_val = decode_query_component(val);
  7493. if (!result.empty()) { result += '&'; }
  7494. result += encode_query_component(dec_key);
  7495. if (!val.empty() || std::find(b, e, '=') != e) {
  7496. result += '=';
  7497. result += encode_query_component(dec_val);
  7498. }
  7499. }
  7500. });
  7501. return result;
  7502. }
  7503. // Build the request target that goes on the wire from a caller-supplied path.
  7504. // Shared by the buffered send path and the streaming API so that both put the
  7505. // same bytes in the request line for the same input.
  7506. inline std::string encode_request_target(const std::string &target,
  7507. bool path_encode) {
  7508. // `substr(0, npos)` yields the whole string, which is what the no-query
  7509. // case needs.
  7510. auto query_pos = target.find('?');
  7511. auto path_part = target.substr(0, query_pos);
  7512. std::string query_part;
  7513. if (query_pos != std::string::npos) {
  7514. query_part = target.substr(query_pos + 1);
  7515. }
  7516. auto result = path_encode ? encode_path(path_part) : std::move(path_part);
  7517. if (!query_part.empty()) {
  7518. // When path encoding is disabled the caller has supplied an already-encoded
  7519. // target and expects the exact bytes to be sent on the wire, so skip
  7520. // normalization for the query too. Normalizing would decode-then-re-encode
  7521. // it and corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  7522. // which a strict RFC 3986 server decodes back as `+`, not a space).
  7523. if (path_encode) {
  7524. auto normalized = normalize_query_string(query_part);
  7525. if (!normalized.empty()) {
  7526. result += '?';
  7527. result += normalized;
  7528. }
  7529. } else {
  7530. result += '?';
  7531. result += query_part;
  7532. }
  7533. }
  7534. return result;
  7535. }
  7536. inline bool parse_multipart_boundary(const std::string &content_type,
  7537. std::string &boundary) {
  7538. std::map<std::string, std::string> params;
  7539. extract_media_type(content_type, &params);
  7540. auto it = params.find("boundary");
  7541. if (it == params.end()) { return false; }
  7542. boundary = it->second;
  7543. // RFC 2046 5.1.1 caps a boundary at 70 characters. The parser scans the body
  7544. // for "--" + boundary, so a body crafted to repeat that delimiter's leading
  7545. // bytes costs a nearly full comparison at nearly every position: the
  7546. // boundary's length multiplies the worst-case cost of scanning a body.
  7547. return !boundary.empty() && boundary.size() <= 70;
  7548. }
  7549. inline void parse_disposition_params(const std::string &s, Params &params) {
  7550. std::set<std::string> cache;
  7551. split_unquoted(s.data(), s.data() + s.size(), ';',
  7552. [&](const char *b, const char *e) {
  7553. std::string kv(b, e);
  7554. if (cache.find(kv) != cache.end()) { return; }
  7555. cache.insert(kv);
  7556. std::string key;
  7557. std::string val;
  7558. divide_param_pair(b, e, key, val);
  7559. if (!key.empty()) {
  7560. params.emplace(trim_double_quotes_copy(key),
  7561. trim_double_quotes_copy(val));
  7562. }
  7563. });
  7564. }
  7565. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7566. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  7567. #else
  7568. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  7569. #endif
  7570. auto is_valid = [](const std::string &str) {
  7571. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  7572. };
  7573. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  7574. const auto pos = static_cast<size_t>(6);
  7575. const auto len = static_cast<size_t>(s.size() - 6);
  7576. auto all_valid_ranges = true;
  7577. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  7578. if (!all_valid_ranges) { return; }
  7579. const auto it = std::find(b, e, '-');
  7580. if (it == e) {
  7581. all_valid_ranges = false;
  7582. return;
  7583. }
  7584. const auto lhs = std::string(b, it);
  7585. const auto rhs = std::string(it + 1, e);
  7586. if (!is_valid(lhs) || !is_valid(rhs)) {
  7587. all_valid_ranges = false;
  7588. return;
  7589. }
  7590. ssize_t first = -1;
  7591. if (!lhs.empty()) {
  7592. // Reject an overflowing first-byte-pos; treating it as absent (-1)
  7593. // would turn the range into a suffix range.
  7594. auto res =
  7595. detail::from_chars(lhs.data(), lhs.data() + lhs.size(), first);
  7596. if (res.ec != std::errc{}) {
  7597. all_valid_ranges = false;
  7598. return;
  7599. }
  7600. }
  7601. ssize_t last = -1;
  7602. if (!rhs.empty()) {
  7603. // An overflowing last-byte-pos is past any content length, so keeping
  7604. // -1 ("remainder", RFC 9110 14.1.2) is correct here.
  7605. ssize_t v;
  7606. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  7607. if (res.ec == std::errc{}) { last = v; }
  7608. }
  7609. if ((first == -1 && last == -1) ||
  7610. (first != -1 && last != -1 && first > last)) {
  7611. all_valid_ranges = false;
  7612. return;
  7613. }
  7614. ranges.emplace_back(first, last);
  7615. });
  7616. return all_valid_ranges && !ranges.empty();
  7617. }
  7618. return false;
  7619. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7620. }
  7621. #else
  7622. } catch (...) { return false; }
  7623. #endif
  7624. inline bool parse_accept_header(const std::string &s,
  7625. std::vector<std::string> &content_types) {
  7626. content_types.clear();
  7627. // Empty string is considered valid (no preference)
  7628. if (s.empty()) { return true; }
  7629. struct AcceptEntry {
  7630. std::string media_type;
  7631. double quality;
  7632. int order;
  7633. };
  7634. std::vector<AcceptEntry> entries;
  7635. int order = 0;
  7636. bool has_invalid_entry = false;
  7637. // Split by comma and parse each entry. RFC 9110 Section 5.6.1.2: a recipient
  7638. // has to parse and ignore empty list elements, so a leading, trailing or
  7639. // doubled comma must not turn a legal Accept value into 400 Bad Request.
  7640. // split() skips them, and the header length limit bounds how many a sender
  7641. // can send, so ignoring all of them cannot be used as a denial-of-service
  7642. // vector.
  7643. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  7644. std::string entry(b, e);
  7645. entry = trim_copy(entry);
  7646. AcceptEntry accept_entry;
  7647. accept_entry.order = order++;
  7648. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  7649. accept_entry.media_type, accept_entry.quality)) {
  7650. has_invalid_entry = true;
  7651. return;
  7652. }
  7653. // Remove additional parameters from media type
  7654. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  7655. // Basic validation of media type format
  7656. if (accept_entry.media_type.empty()) {
  7657. has_invalid_entry = true;
  7658. return;
  7659. }
  7660. // Check for basic media type format (should contain '/' or be '*')
  7661. if (accept_entry.media_type != "*" &&
  7662. accept_entry.media_type.find('/') == std::string::npos) {
  7663. has_invalid_entry = true;
  7664. return;
  7665. }
  7666. entries.push_back(std::move(accept_entry));
  7667. });
  7668. // Return false if any invalid entry was found
  7669. if (has_invalid_entry) { return false; }
  7670. // Sort by quality (descending), then by original order (ascending)
  7671. std::sort(entries.begin(), entries.end(),
  7672. [](const AcceptEntry &a, const AcceptEntry &b) {
  7673. if (a.quality != b.quality) {
  7674. return a.quality > b.quality; // Higher quality first
  7675. }
  7676. return a.order < b.order; // Earlier order first for same quality
  7677. });
  7678. // Extract sorted media types
  7679. content_types.reserve(entries.size());
  7680. for (auto &entry : entries) {
  7681. content_types.push_back(std::move(entry.media_type));
  7682. }
  7683. return true;
  7684. }
  7685. class FormDataParser {
  7686. public:
  7687. FormDataParser() = default;
  7688. void set_boundary(std::string &&boundary) {
  7689. boundary_ = std::move(boundary);
  7690. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  7691. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  7692. }
  7693. bool is_valid() const { return is_valid_; }
  7694. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  7695. const ContentReceiver &content_callback) {
  7696. // Once the close delimiter has been seen the rest of the body is epilogue
  7697. // to be discarded (RFC 2046). Drop it without buffering so a large epilogue
  7698. // spread across reads is not copied in only to be erased right away.
  7699. if (state_ == 5) { return true; }
  7700. buf_append(buf, n);
  7701. while (buf_size() > 0) {
  7702. switch (state_) {
  7703. case 0: { // Initial boundary
  7704. auto pos = buf_find(dash_boundary_crlf_);
  7705. if (pos == buf_size()) {
  7706. // Not found yet: keep only a possible partial boundary at the tail so
  7707. // that a body which never contains the boundary cannot grow the
  7708. // buffer (and get rescanned from the start) without bound.
  7709. auto keep = dash_boundary_crlf_.size() - 1;
  7710. if (buf_size() > keep) { buf_erase(buf_size() - keep); }
  7711. return true;
  7712. }
  7713. buf_erase(pos + dash_boundary_crlf_.size());
  7714. state_ = 1;
  7715. break;
  7716. }
  7717. case 1: { // New entry
  7718. clear_file_info();
  7719. state_ = 2;
  7720. break;
  7721. }
  7722. case 2: { // Headers
  7723. auto pos = buf_find(crlf_);
  7724. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  7725. while (pos < buf_size()) {
  7726. // Empty line
  7727. if (pos == 0) {
  7728. if (!header_callback(file_)) {
  7729. is_valid_ = false;
  7730. return false;
  7731. }
  7732. buf_erase(crlf_.size());
  7733. state_ = 3;
  7734. break;
  7735. }
  7736. // Check header count limit
  7737. if (header_count_ >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  7738. is_valid_ = false;
  7739. return false;
  7740. }
  7741. header_count_++;
  7742. const auto header = buf_head(pos);
  7743. if (!parse_header(header.data(), header.data() + header.size(),
  7744. [&](const std::string &, const std::string &) {})) {
  7745. is_valid_ = false;
  7746. return false;
  7747. }
  7748. // Parse and emplace space trimmed headers into a map
  7749. if (!parse_header(
  7750. header.data(), header.data() + header.size(),
  7751. [&](const std::string &key, const std::string &val) {
  7752. file_.headers.emplace(key, val);
  7753. })) {
  7754. is_valid_ = false;
  7755. return false;
  7756. }
  7757. constexpr const char header_content_type[] = "Content-Type:";
  7758. if (start_with_case_ignore(header, header_content_type)) {
  7759. file_.content_type =
  7760. trim_copy(header.substr(str_len(header_content_type)));
  7761. } else {
  7762. std::string disposition_params;
  7763. if (parse_content_disposition(header, disposition_params)) {
  7764. Params params;
  7765. parse_disposition_params(disposition_params, params);
  7766. auto it = params.find("name");
  7767. if (it != params.end()) {
  7768. file_.name = it->second;
  7769. } else {
  7770. is_valid_ = false;
  7771. return false;
  7772. }
  7773. it = params.find("filename");
  7774. if (it != params.end()) { file_.filename = it->second; }
  7775. it = params.find("filename*");
  7776. if (it != params.end()) {
  7777. // RFC 5987: only UTF-8 encoding is allowed
  7778. const auto &val = it->second;
  7779. constexpr const char utf8_prefix[] = "UTF-8''";
  7780. constexpr size_t prefix_len = str_len(utf8_prefix);
  7781. if (val.size() > prefix_len &&
  7782. start_with_case_ignore(val, utf8_prefix)) {
  7783. file_.filename = decode_path_component(
  7784. val.substr(prefix_len)); // override...
  7785. } else {
  7786. is_valid_ = false;
  7787. return false;
  7788. }
  7789. }
  7790. }
  7791. }
  7792. buf_erase(pos + crlf_.size());
  7793. pos = buf_find(crlf_);
  7794. }
  7795. if (state_ != 3) { return true; }
  7796. break;
  7797. }
  7798. case 3: { // Body
  7799. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  7800. auto pos = buf_find(crlf_dash_boundary_);
  7801. if (pos < buf_size()) {
  7802. if (!content_callback(buf_data(), pos)) {
  7803. is_valid_ = false;
  7804. return false;
  7805. }
  7806. buf_erase(pos + crlf_dash_boundary_.size());
  7807. state_ = 4;
  7808. } else {
  7809. auto len = buf_size() - crlf_dash_boundary_.size();
  7810. if (len > 0) {
  7811. if (!content_callback(buf_data(), len)) {
  7812. is_valid_ = false;
  7813. return false;
  7814. }
  7815. buf_erase(len);
  7816. }
  7817. return true;
  7818. }
  7819. break;
  7820. }
  7821. case 4: { // Boundary
  7822. if (crlf_.size() > buf_size()) { return true; }
  7823. if (buf_start_with(crlf_)) {
  7824. buf_erase(crlf_.size());
  7825. state_ = 1;
  7826. } else if (buf_start_with(dash_)) {
  7827. buf_erase(dash_.size());
  7828. is_valid_ = true;
  7829. state_ = 5;
  7830. } else {
  7831. // Only CRLF (another part follows) and "--" (close-delimiter) are
  7832. // accepted after a boundary; RFC 2046 allows transport-padding in
  7833. // between, but this parser has never supported it. Either way the
  7834. // body is already destined to be rejected, so fail now instead of
  7835. // buffering the rest of it. Both are two bytes, so the check above
  7836. // already guarantees enough buffered data to decide.
  7837. is_valid_ = false;
  7838. return false;
  7839. }
  7840. break;
  7841. }
  7842. case 5: { // Epilogue
  7843. buf_erase(buf_size());
  7844. break;
  7845. }
  7846. }
  7847. }
  7848. return true;
  7849. }
  7850. private:
  7851. void clear_file_info() {
  7852. file_.name.clear();
  7853. file_.filename.clear();
  7854. file_.content_type.clear();
  7855. file_.headers.clear();
  7856. header_count_ = 0;
  7857. }
  7858. bool start_with_case_ignore(const std::string &a, const char *b,
  7859. size_t offset = 0) const {
  7860. const auto b_len = strlen(b);
  7861. if (a.size() < offset + b_len) { return false; }
  7862. for (size_t i = 0; i < b_len; i++) {
  7863. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  7864. return false;
  7865. }
  7866. }
  7867. return true;
  7868. }
  7869. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  7870. // Returns true if header matches, with the params portion in `params_out`.
  7871. bool parse_content_disposition(const std::string &header,
  7872. std::string &params_out) const {
  7873. constexpr const char prefix[] = "Content-Disposition:";
  7874. constexpr size_t prefix_len = str_len(prefix);
  7875. if (!start_with_case_ignore(header, prefix)) { return false; }
  7876. // Skip whitespace after "Content-Disposition:"
  7877. auto pos = prefix_len;
  7878. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  7879. pos++;
  7880. }
  7881. // Match "form-data;" (case-insensitive)
  7882. constexpr const char form_data[] = "form-data;";
  7883. constexpr size_t form_data_len = str_len(form_data);
  7884. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  7885. pos += form_data_len;
  7886. // Skip whitespace after "form-data;"
  7887. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  7888. pos++;
  7889. }
  7890. params_out = header.substr(pos);
  7891. return true;
  7892. }
  7893. const std::string dash_ = "--";
  7894. const std::string crlf_ = "\r\n";
  7895. std::string boundary_;
  7896. std::string dash_boundary_crlf_;
  7897. std::string crlf_dash_boundary_;
  7898. size_t state_ = 0;
  7899. bool is_valid_ = false;
  7900. FormData file_;
  7901. size_t header_count_ = 0;
  7902. // Buffer
  7903. bool start_with(const std::string &a, size_t spos, size_t epos,
  7904. const std::string &b) const {
  7905. if (epos - spos < b.size()) { return false; }
  7906. for (size_t i = 0; i < b.size(); i++) {
  7907. if (a[i + spos] != b[i]) { return false; }
  7908. }
  7909. return true;
  7910. }
  7911. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  7912. const char *buf_data() const { return &buf_[buf_spos_]; }
  7913. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  7914. bool buf_start_with(const std::string &s) const {
  7915. return start_with(buf_, buf_spos_, buf_epos_, s);
  7916. }
  7917. size_t buf_find(const std::string &s) const {
  7918. auto c = s.front();
  7919. size_t off = buf_spos_;
  7920. while (off < buf_epos_) {
  7921. auto pos = off;
  7922. while (true) {
  7923. if (pos == buf_epos_) { return buf_size(); }
  7924. if (buf_[pos] == c) { break; }
  7925. pos++;
  7926. }
  7927. auto remaining_size = buf_epos_ - pos;
  7928. if (s.size() > remaining_size) { return buf_size(); }
  7929. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  7930. off = pos + 1;
  7931. }
  7932. return buf_size();
  7933. }
  7934. void buf_append(const char *data, size_t n) {
  7935. auto remaining_size = buf_size();
  7936. if (remaining_size > 0 && buf_spos_ > 0) {
  7937. for (size_t i = 0; i < remaining_size; i++) {
  7938. buf_[i] = buf_[buf_spos_ + i];
  7939. }
  7940. }
  7941. buf_spos_ = 0;
  7942. buf_epos_ = remaining_size;
  7943. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  7944. for (size_t i = 0; i < n; i++) {
  7945. buf_[buf_epos_ + i] = data[i];
  7946. }
  7947. buf_epos_ += n;
  7948. }
  7949. void buf_erase(size_t size) { buf_spos_ += size; }
  7950. std::string buf_;
  7951. size_t buf_spos_ = 0;
  7952. size_t buf_epos_ = 0;
  7953. };
  7954. inline std::string random_string(size_t length) {
  7955. constexpr const char data[] =
  7956. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  7957. thread_local auto engine([]() {
  7958. // std::random_device might actually be deterministic on some
  7959. // platforms, but due to lack of support in the c++ standard library,
  7960. // doing better requires either some ugly hacks or breaking portability.
  7961. std::random_device seed_gen;
  7962. // Request 128 bits of entropy for initialization
  7963. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  7964. return std::mt19937(seed_sequence);
  7965. }());
  7966. std::string result;
  7967. for (size_t i = 0; i < length; i++) {
  7968. result += data[engine() % (sizeof(data) - 1)];
  7969. }
  7970. return result;
  7971. }
  7972. inline std::string make_multipart_data_boundary() {
  7973. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  7974. }
  7975. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  7976. auto valid = true;
  7977. for (size_t i = 0; i < boundary.size(); i++) {
  7978. auto c = boundary[i];
  7979. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  7980. valid = false;
  7981. break;
  7982. }
  7983. }
  7984. return valid;
  7985. }
  7986. // Escape a multipart field name/filename following the WHATWG HTML standard
  7987. // ("escape a multipart form-data name"), which is what browsers send:
  7988. // '"' -> %22, CR -> %0D, LF -> %0A
  7989. // With escape_quote = false, only CR and LF are escaped; this is for header
  7990. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  7991. inline std::string escape_multipart_field(const std::string &s,
  7992. bool escape_quote = true) {
  7993. std::string result;
  7994. result.reserve(s.size());
  7995. for (auto c : s) {
  7996. switch (c) {
  7997. case '"':
  7998. if (escape_quote) {
  7999. result += "%22";
  8000. } else {
  8001. result += c;
  8002. }
  8003. break;
  8004. case '\r': result += "%0D"; break;
  8005. case '\n': result += "%0A"; break;
  8006. default: result += c; break;
  8007. }
  8008. }
  8009. return result;
  8010. }
  8011. template <typename T>
  8012. inline std::string
  8013. serialize_multipart_formdata_item_begin(const T &item,
  8014. const std::string &boundary) {
  8015. std::string body = "--" + boundary + "\r\n";
  8016. body += "Content-Disposition: form-data; name=\"" +
  8017. escape_multipart_field(item.name) + "\"";
  8018. if (!item.filename.empty()) {
  8019. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  8020. }
  8021. body += "\r\n";
  8022. if (!item.content_type.empty()) {
  8023. body +=
  8024. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  8025. "\r\n";
  8026. }
  8027. body += "\r\n";
  8028. return body;
  8029. }
  8030. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  8031. inline std::string
  8032. serialize_multipart_formdata_finish(const std::string &boundary) {
  8033. return "--" + boundary + "--\r\n";
  8034. }
  8035. inline std::string
  8036. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  8037. return "multipart/form-data; boundary=" + boundary;
  8038. }
  8039. inline std::string
  8040. serialize_multipart_formdata(const UploadFormDataItems &items,
  8041. const std::string &boundary, bool finish = true) {
  8042. std::string body;
  8043. for (const auto &item : items) {
  8044. body += serialize_multipart_formdata_item_begin(item, boundary);
  8045. body += item.content + serialize_multipart_formdata_item_end();
  8046. }
  8047. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  8048. return body;
  8049. }
  8050. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  8051. const std::string &boundary) {
  8052. size_t total = 0;
  8053. for (const auto &item : items) {
  8054. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  8055. total += item.content.size();
  8056. total += serialize_multipart_formdata_item_end().size();
  8057. }
  8058. total += serialize_multipart_formdata_finish(boundary).size();
  8059. return total;
  8060. }
  8061. struct MultipartSegment {
  8062. const char *data;
  8063. size_t size;
  8064. };
  8065. // NOTE: items must outlive the returned ContentProvider
  8066. // (safe for synchronous use inside Post/Put/Patch)
  8067. inline ContentProvider
  8068. make_multipart_content_provider(const UploadFormDataItems &items,
  8069. const std::string &boundary) {
  8070. // Own the per-item header strings and the finish string
  8071. std::vector<std::string> owned;
  8072. owned.reserve(items.size() + 1);
  8073. for (const auto &item : items)
  8074. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  8075. owned.push_back(serialize_multipart_formdata_finish(boundary));
  8076. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  8077. std::vector<MultipartSegment> segs;
  8078. segs.reserve(items.size() * 3 + 1);
  8079. static const char crlf[] = "\r\n";
  8080. for (size_t i = 0; i < items.size(); i++) {
  8081. segs.push_back({owned[i].data(), owned[i].size()});
  8082. segs.push_back({items[i].content.data(), items[i].content.size()});
  8083. segs.push_back({crlf, 2});
  8084. }
  8085. segs.push_back({owned.back().data(), owned.back().size()});
  8086. struct MultipartState {
  8087. std::vector<std::string> owned;
  8088. std::vector<MultipartSegment> segs;
  8089. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  8090. };
  8091. auto state = std::make_shared<MultipartState>();
  8092. state->owned = std::move(owned);
  8093. // `segs` holds raw pointers into owned strings; std::string move preserves
  8094. // the data pointer, so these pointers remain valid after the move above.
  8095. state->segs = std::move(segs);
  8096. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  8097. // Buffer multiple small segments into fewer, larger writes to avoid
  8098. // excessive TCP packets when there are many form data items (#2410)
  8099. auto &buf = state->buf;
  8100. auto buf_size = buf.size();
  8101. size_t buf_len = 0;
  8102. size_t remaining = length;
  8103. // Find the first segment containing 'offset'
  8104. size_t pos = 0;
  8105. size_t seg_idx = 0;
  8106. for (; seg_idx < state->segs.size(); seg_idx++) {
  8107. const auto &seg = state->segs[seg_idx];
  8108. if (seg.size > 0 && offset - pos < seg.size) { break; }
  8109. pos += seg.size;
  8110. }
  8111. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  8112. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  8113. const auto &seg = state->segs[seg_idx];
  8114. size_t available = seg.size - seg_offset;
  8115. size_t to_copy = (std::min)(available, remaining);
  8116. const char *src = seg.data + seg_offset;
  8117. seg_offset = 0; // only the first segment has a non-zero offset
  8118. while (to_copy > 0) {
  8119. size_t space = buf_size - buf_len;
  8120. size_t chunk = (std::min)(to_copy, space);
  8121. std::memcpy(buf.data() + buf_len, src, chunk);
  8122. buf_len += chunk;
  8123. src += chunk;
  8124. to_copy -= chunk;
  8125. remaining -= chunk;
  8126. if (buf_len == buf_size) {
  8127. if (!sink.write(buf.data(), buf_len)) { return false; }
  8128. buf_len = 0;
  8129. }
  8130. }
  8131. }
  8132. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  8133. return true;
  8134. };
  8135. }
  8136. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  8137. if (ranges.size() <= 1) return;
  8138. // Sort ranges by start position
  8139. std::sort(ranges.begin(), ranges.end(),
  8140. [](const Range &a, const Range &b) { return a.first < b.first; });
  8141. Ranges coalesced;
  8142. coalesced.reserve(ranges.size());
  8143. for (auto &r : ranges) {
  8144. auto first_pos = r.first;
  8145. auto last_pos = r.second;
  8146. // Handle special cases like in range_error
  8147. if (first_pos == -1 && last_pos == -1) {
  8148. first_pos = 0;
  8149. last_pos = static_cast<ssize_t>(content_length);
  8150. }
  8151. if (first_pos == -1) {
  8152. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  8153. last_pos = static_cast<ssize_t>(content_length) - 1;
  8154. }
  8155. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  8156. last_pos = static_cast<ssize_t>(content_length) - 1;
  8157. }
  8158. // Skip invalid ranges
  8159. if (!(0 <= first_pos && first_pos <= last_pos &&
  8160. last_pos < static_cast<ssize_t>(content_length))) {
  8161. continue;
  8162. }
  8163. // Coalesce with previous range if overlapping or adjacent (but not
  8164. // identical)
  8165. if (!coalesced.empty()) {
  8166. auto &prev = coalesced.back();
  8167. // Check if current range overlaps or is adjacent to previous range
  8168. // but don't coalesce identical ranges (allow duplicates)
  8169. if (first_pos <= prev.second + 1 &&
  8170. !(first_pos == prev.first && last_pos == prev.second)) {
  8171. // Extend the previous range
  8172. prev.second = (std::max)(prev.second, last_pos);
  8173. continue;
  8174. }
  8175. }
  8176. // Add new range
  8177. coalesced.emplace_back(first_pos, last_pos);
  8178. }
  8179. ranges = std::move(coalesced);
  8180. }
  8181. inline bool range_error(Request &req, Response &res) {
  8182. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  8183. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  8184. req.ranges.clear();
  8185. if (res.status == StatusCode::PartialContent_206) {
  8186. res.status = StatusCode::OK_200;
  8187. }
  8188. return false;
  8189. }
  8190. ssize_t content_len = static_cast<ssize_t>(
  8191. res.content_length_ ? res.content_length_ : res.body.size());
  8192. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  8193. size_t overwrapping_count = 0;
  8194. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  8195. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  8196. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  8197. // Too many ranges
  8198. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  8199. for (auto &r : req.ranges) {
  8200. auto &first_pos = r.first;
  8201. auto &last_pos = r.second;
  8202. if (first_pos == -1 && last_pos == -1) {
  8203. first_pos = 0;
  8204. last_pos = content_len;
  8205. }
  8206. if (first_pos == -1) {
  8207. first_pos = content_len - last_pos;
  8208. last_pos = content_len - 1;
  8209. }
  8210. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  8211. // A client can limit the number of bytes requested without knowing the
  8212. // size of the selected representation. If the last-pos value is absent,
  8213. // or if the value is greater than or equal to the current length of the
  8214. // representation data, the byte range is interpreted as the remainder of
  8215. // the representation (i.e., the server replaces the value of last-pos
  8216. // with a value that is one less than the current length of the selected
  8217. // representation).
  8218. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  8219. if (last_pos == -1 || last_pos >= content_len) {
  8220. last_pos = content_len - 1;
  8221. }
  8222. // Range must be within content length
  8223. if (!(0 <= first_pos && first_pos <= last_pos &&
  8224. last_pos <= content_len - 1)) {
  8225. return true;
  8226. }
  8227. // Request must not have more than two overlapping ranges
  8228. for (const auto &processed_range : processed_ranges) {
  8229. if (!(last_pos < processed_range.first ||
  8230. first_pos > processed_range.second)) {
  8231. overwrapping_count++;
  8232. if (overwrapping_count > 2) { return true; }
  8233. break; // Only count once per range
  8234. }
  8235. }
  8236. processed_ranges.emplace_back(first_pos, last_pos);
  8237. }
  8238. // After validation, coalesce overlapping ranges as per RFC 9110
  8239. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  8240. }
  8241. return false;
  8242. }
  8243. inline std::pair<size_t, size_t>
  8244. get_range_offset_and_length(Range r, size_t content_length) {
  8245. assert(r.first != -1 && r.second != -1);
  8246. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  8247. assert(r.first <= r.second &&
  8248. r.second < static_cast<ssize_t>(content_length));
  8249. (void)(content_length);
  8250. return std::make_pair(static_cast<size_t>(r.first),
  8251. static_cast<size_t>(r.second - r.first) + 1);
  8252. }
  8253. inline std::string make_content_range_header_field(
  8254. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  8255. auto st = offset_and_length.first;
  8256. auto ed = st + offset_and_length.second - 1;
  8257. std::string field = "bytes ";
  8258. field += std::to_string(st);
  8259. field += '-';
  8260. field += std::to_string(ed);
  8261. field += '/';
  8262. field += std::to_string(content_length);
  8263. return field;
  8264. }
  8265. template <typename SToken, typename CToken, typename Content>
  8266. bool process_multipart_ranges_data(const Request &req,
  8267. const std::string &boundary,
  8268. const std::string &content_type,
  8269. size_t content_length, SToken stoken,
  8270. CToken ctoken, Content content) {
  8271. for (size_t i = 0; i < req.ranges.size(); i++) {
  8272. ctoken("--");
  8273. stoken(boundary);
  8274. ctoken("\r\n");
  8275. if (!content_type.empty()) {
  8276. ctoken("Content-Type: ");
  8277. stoken(content_type);
  8278. ctoken("\r\n");
  8279. }
  8280. auto offset_and_length =
  8281. get_range_offset_and_length(req.ranges[i], content_length);
  8282. ctoken("Content-Range: ");
  8283. stoken(make_content_range_header_field(offset_and_length, content_length));
  8284. ctoken("\r\n");
  8285. ctoken("\r\n");
  8286. if (!content(offset_and_length.first, offset_and_length.second)) {
  8287. return false;
  8288. }
  8289. ctoken("\r\n");
  8290. }
  8291. ctoken("--");
  8292. stoken(boundary);
  8293. ctoken("--");
  8294. return true;
  8295. }
  8296. inline void make_multipart_ranges_data(const Request &req, Response &res,
  8297. const std::string &boundary,
  8298. const std::string &content_type,
  8299. size_t content_length,
  8300. std::string &data) {
  8301. process_multipart_ranges_data(
  8302. req, boundary, content_type, content_length,
  8303. [&](const std::string &token) { data += token; },
  8304. [&](const std::string &token) { data += token; },
  8305. [&](size_t offset, size_t length) {
  8306. assert(offset + length <= content_length);
  8307. data += res.body.substr(offset, length);
  8308. return true;
  8309. });
  8310. }
  8311. inline size_t get_multipart_ranges_data_length(const Request &req,
  8312. const std::string &boundary,
  8313. const std::string &content_type,
  8314. size_t content_length) {
  8315. size_t data_length = 0;
  8316. process_multipart_ranges_data(
  8317. req, boundary, content_type, content_length,
  8318. [&](const std::string &token) { data_length += token.size(); },
  8319. [&](const std::string &token) { data_length += token.size(); },
  8320. [&](size_t /*offset*/, size_t length) {
  8321. data_length += length;
  8322. return true;
  8323. });
  8324. return data_length;
  8325. }
  8326. template <typename T>
  8327. inline bool
  8328. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  8329. const std::string &boundary,
  8330. const std::string &content_type,
  8331. size_t content_length, const T &is_shutting_down) {
  8332. return process_multipart_ranges_data(
  8333. req, boundary, content_type, content_length,
  8334. [&](const std::string &token) { strm.write(token); },
  8335. [&](const std::string &token) { strm.write(token); },
  8336. [&](size_t offset, size_t length) {
  8337. return write_content(strm, res.content_provider_, offset, length,
  8338. is_shutting_down);
  8339. });
  8340. }
  8341. inline bool has_framed_body(const Request &req) {
  8342. return is_chunked_transfer_encoding(req.headers) ||
  8343. req.get_header_value_u64("Content-Length") > 0;
  8344. }
  8345. inline bool is_connection_persistent(const Request &req) {
  8346. if (has_header_token(req.headers, "Connection", "close")) { return false; }
  8347. if (req.version == "HTTP/1.0" &&
  8348. !has_header_token(req.headers, "Connection", "keep-alive")) {
  8349. return false;
  8350. }
  8351. return true;
  8352. }
  8353. inline bool expect_content(const Request &req) {
  8354. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  8355. req.method == "DELETE") {
  8356. return true;
  8357. }
  8358. return has_framed_body(req);
  8359. }
  8360. #ifdef _WIN32
  8361. class WSInit {
  8362. public:
  8363. WSInit() {
  8364. WSADATA wsaData;
  8365. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  8366. }
  8367. ~WSInit() {
  8368. if (is_valid_) WSACleanup();
  8369. }
  8370. bool is_valid_ = false;
  8371. };
  8372. static WSInit wsinit_;
  8373. #endif
  8374. // RFC 9110 Section 11.6.1 defines a challenge list as
  8375. // WWW-Authenticate = #challenge
  8376. // challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
  8377. // auth-param = token BWS "=" BWS ( token / quoted-string )
  8378. // so a server may offer several schemes, each with its own comma-separated
  8379. // auth-param list, in either order and either as separate field lines or
  8380. // packed into one. Splitting on every comma would break apart a challenge's
  8381. // own param list; splitting only on the first space would miss a Digest
  8382. // challenge that isn't first. Split on commas that aren't inside a
  8383. // quoted-string instead, then track which scheme each resulting segment
  8384. // belongs to: a segment whose text before "=" contains whitespace (or that
  8385. // has no "=" at all) starts a new challenge named by its leading token.
  8386. inline std::vector<std::string> split_challenge_segments(const std::string &s) {
  8387. std::vector<std::string> segments;
  8388. size_t start = 0;
  8389. auto in_quotes = false;
  8390. for (size_t i = 0; i < s.size(); i++) {
  8391. auto c = s[i];
  8392. if (in_quotes) {
  8393. if (c == '\\' && i + 1 < s.size()) {
  8394. i++;
  8395. } else if (c == '"') {
  8396. in_quotes = false;
  8397. }
  8398. } else if (c == '"') {
  8399. in_quotes = true;
  8400. } else if (c == ',') {
  8401. segments.push_back(s.substr(start, i - start));
  8402. start = i + 1;
  8403. }
  8404. }
  8405. segments.push_back(s.substr(start));
  8406. return segments;
  8407. }
  8408. inline std::string unescape_quoted_pairs(const std::string &s) {
  8409. std::string out;
  8410. out.reserve(s.size());
  8411. for (size_t i = 0; i < s.size(); i++) {
  8412. if (s[i] == '\\' && i + 1 < s.size()) {
  8413. out += s[++i];
  8414. } else {
  8415. out += s[i];
  8416. }
  8417. }
  8418. return out;
  8419. }
  8420. inline bool parse_www_authenticate(const Response &res,
  8421. std::map<std::string, std::string> &auth,
  8422. bool is_proxy) {
  8423. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  8424. auto combined = get_combined_header_value(res.headers, auth_key);
  8425. if (combined.empty()) { return false; }
  8426. auto found_digest = false;
  8427. auto in_digest_challenge = false;
  8428. for (const auto &raw_segment : split_challenge_segments(combined)) {
  8429. auto segment = trim_copy(raw_segment);
  8430. if (segment.empty()) { continue; }
  8431. auto eq_pos = segment.find('=');
  8432. // BWS is allowed on both sides of "=", so the text naming the key (or,
  8433. // for the first segment of a challenge, "<scheme> <key>") must be
  8434. // trimmed before its boundaries are inspected.
  8435. auto key_part = trim_copy(
  8436. eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
  8437. auto space_pos = key_part.find_last_of(" \t");
  8438. if (space_pos != std::string::npos || eq_pos == std::string::npos) {
  8439. // "<scheme>[ <key>]" starts a new challenge.
  8440. auto scheme_end =
  8441. space_pos == std::string::npos ? key_part.size() : space_pos;
  8442. // RFC 7616 Section 3.7: a server may offer more than one Digest
  8443. // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
  8444. // from one challenge is never paired with another's algorithm.
  8445. in_digest_challenge =
  8446. !found_digest &&
  8447. case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
  8448. if (in_digest_challenge) { found_digest = true; }
  8449. if (space_pos == std::string::npos) {
  8450. // Bare scheme (or a token68), no auth-param on this segment.
  8451. continue;
  8452. }
  8453. key_part = key_part.substr(space_pos + 1);
  8454. }
  8455. if (!in_digest_challenge) { continue; }
  8456. auto val = trim_copy(segment.substr(eq_pos + 1));
  8457. auto unquoted = trim_double_quotes_copy(val);
  8458. if (unquoted.size() != val.size()) {
  8459. unquoted = unescape_quoted_pairs(unquoted);
  8460. }
  8461. auth[std::move(key_part)] = std::move(unquoted);
  8462. }
  8463. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
  8464. // make_digest_authentication_header() dereferences both unconditionally, so
  8465. // a challenge missing either can't produce a usable Authorization header.
  8466. // Treat it the same as no Digest challenge at all.
  8467. return found_digest && auth.find("realm") != auth.end() &&
  8468. auth.find("nonce") != auth.end();
  8469. }
  8470. class ContentProviderAdapter {
  8471. public:
  8472. explicit ContentProviderAdapter(
  8473. ContentProviderWithoutLength &&content_provider)
  8474. : content_provider_(std::move(content_provider)) {}
  8475. bool operator()(size_t offset, size_t, DataSink &sink) {
  8476. return content_provider_(offset, sink);
  8477. }
  8478. private:
  8479. ContentProviderWithoutLength content_provider_;
  8480. };
  8481. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  8482. namespace fields {
  8483. inline bool is_token_char(char c) {
  8484. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  8485. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  8486. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  8487. }
  8488. inline bool is_token(const std::string &s) {
  8489. if (s.empty()) { return false; }
  8490. for (auto c : s) {
  8491. if (!is_token_char(c)) { return false; }
  8492. }
  8493. return true;
  8494. }
  8495. inline bool is_field_name(const std::string &s) { return is_token(s); }
  8496. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  8497. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  8498. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  8499. inline bool is_field_content(const std::string &s) {
  8500. if (s.empty()) { return true; }
  8501. if (s.size() == 1) {
  8502. return is_field_vchar(s[0]);
  8503. } else if (s.size() == 2) {
  8504. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  8505. } else {
  8506. size_t i = 0;
  8507. if (!is_field_vchar(s[i])) { return false; }
  8508. i++;
  8509. while (i < s.size() - 1) {
  8510. auto c = s[i++];
  8511. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  8512. } else {
  8513. return false;
  8514. }
  8515. }
  8516. return is_field_vchar(s[i]);
  8517. }
  8518. }
  8519. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  8520. inline bool is_field_valid(const std::string &name, const std::string &value) {
  8521. return is_field_name(name) && is_field_value(value);
  8522. }
  8523. } // namespace fields
  8524. inline bool perform_websocket_handshake(Stream &strm, Request &req,
  8525. WebSocketUpgradeResponse &upgrade) {
  8526. // Generate random Sec-WebSocket-Key
  8527. thread_local std::mt19937 rng(std::random_device{}());
  8528. std::string key_bytes(16, '\0');
  8529. for (size_t i = 0; i < 16; i += 4) {
  8530. auto r = rng();
  8531. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  8532. }
  8533. auto client_key = base64_encode(key_bytes);
  8534. req.headers.erase("Upgrade");
  8535. req.headers.erase("Connection");
  8536. req.headers.erase("Sec-WebSocket-Key");
  8537. req.headers.erase("Sec-WebSocket-Version");
  8538. req.headers.emplace("Upgrade", "websocket");
  8539. req.headers.emplace("Connection", "Upgrade");
  8540. req.headers.emplace("Sec-WebSocket-Key", client_key);
  8541. req.headers.emplace("Sec-WebSocket-Version", "13");
  8542. // Build the request in memory first, like ClientImpl::write_request does.
  8543. // Writing straight to the socket would leak a request line onto the wire
  8544. // before check_and_write_headers gets a chance to reject an invalid header,
  8545. // and would emit one small write per header.
  8546. BufferStream bstrm;
  8547. if (write_request_line(bstrm, req.method, req.path) < 0) {
  8548. upgrade.error = Error::Write;
  8549. return false;
  8550. }
  8551. auto error = Error::Success;
  8552. if (!check_and_write_headers(bstrm, req.headers, write_headers, error)) {
  8553. upgrade.error = error;
  8554. return false;
  8555. }
  8556. const auto &data = bstrm.get_buffer();
  8557. if (!write_data(strm, data.data(), data.size())) {
  8558. upgrade.error = Error::Write;
  8559. return false;
  8560. }
  8561. // Verify 101 response and Sec-WebSocket-Accept header
  8562. auto expected_accept = websocket_accept_key(client_key);
  8563. return read_websocket_upgrade_response(strm, expected_accept, upgrade);
  8564. }
  8565. inline bool is_ip_address(const std::string &host) {
  8566. struct in_addr addr4;
  8567. struct in6_addr addr6;
  8568. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  8569. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  8570. }
  8571. // Resolve where a client should connect for `host`, honoring a user-supplied
  8572. // hostname-to-address map. `host` itself is never rewritten, so it keeps
  8573. // supplying the Host header and SNI; only the connection target changes.
  8574. //
  8575. // A mapped IP literal goes to `ip`, which keeps create_socket's AI_NUMERICHOST
  8576. // path. Anything else goes to `connect_host`, which create_socket resolves as
  8577. // a name, or uses as the socket path when the address family is AF_UNIX. An
  8578. // absent or empty mapping leaves `host` as the connection target; without the
  8579. // empty check the value would reach getaddrinfo as a null node and silently
  8580. // resolve to loopback.
  8581. inline void apply_addr_map(const std::map<std::string, std::string> &addr_map,
  8582. const std::string &host, std::string &connect_host,
  8583. std::string &ip) {
  8584. connect_host = host;
  8585. ip.clear();
  8586. auto it = addr_map.find(host);
  8587. if (it == addr_map.end() || it->second.empty()) { return; }
  8588. if (is_ip_address(it->second)) {
  8589. ip = it->second;
  8590. } else {
  8591. connect_host = it->second;
  8592. }
  8593. }
  8594. } // namespace detail
  8595. /*
  8596. * Group 2: detail namespace - SSL common utilities
  8597. */
  8598. #ifdef CPPHTTPLIB_SSL_ENABLED
  8599. namespace detail {
  8600. class SSLSocketStream final : public Stream {
  8601. public:
  8602. SSLSocketStream(
  8603. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8604. time_t read_timeout_usec, time_t write_timeout_sec,
  8605. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  8606. std::chrono::time_point<std::chrono::steady_clock> start_time =
  8607. (std::chrono::steady_clock::time_point::min)());
  8608. ~SSLSocketStream() override;
  8609. bool is_readable() const override;
  8610. bool wait_readable() const override;
  8611. bool wait_writable() const override;
  8612. bool is_peer_alive() const override;
  8613. ssize_t read(char *ptr, size_t size) override;
  8614. ssize_t write(const char *ptr, size_t size) override;
  8615. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8616. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8617. socket_t socket() const override;
  8618. time_t duration() const override;
  8619. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8620. // See SocketStream::set_readable_hint().
  8621. void set_readable_hint() { readable_hint_ = true; }
  8622. private:
  8623. bool ensure_readable();
  8624. socket_t sock_;
  8625. tls::session_t session_;
  8626. time_t read_timeout_sec_;
  8627. time_t read_timeout_usec_;
  8628. time_t write_timeout_sec_;
  8629. time_t write_timeout_usec_;
  8630. time_t max_timeout_msec_;
  8631. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8632. bool readable_hint_ = false;
  8633. };
  8634. // A TLS stream for WebSocket connections, where the receive path and the
  8635. // send path (application send() plus the heartbeat ping thread) run on
  8636. // different threads. A single TLS session must never be entered
  8637. // concurrently, so every call into the session is serialized by one mutex.
  8638. //
  8639. // Unlike SSLSocketStream, the socket is kept non-blocking for the stream's
  8640. // whole lifetime and each read()/write() performs a single non-blocking TLS
  8641. // call under the lock, then waits for readiness with select() outside the
  8642. // lock. The lock is therefore held only for CPU-bound work, so a reader
  8643. // blocked waiting for data never stalls a concurrent sender.
  8644. //
  8645. // This stream is used only for wss:// connections. Plain ws:// and ordinary
  8646. // HTTP/HTTPS keep using SocketStream/SSLSocketStream unchanged.
  8647. class WebSocketSSLStream final : public Stream {
  8648. public:
  8649. WebSocketSSLStream(socket_t sock, tls::session_t session,
  8650. time_t read_timeout_sec, time_t read_timeout_usec,
  8651. time_t write_timeout_sec, time_t write_timeout_usec);
  8652. ~WebSocketSSLStream() override;
  8653. bool is_readable() const override;
  8654. bool wait_readable() const override;
  8655. bool wait_writable() const override;
  8656. ssize_t read(char *ptr, size_t size) override;
  8657. ssize_t write(const char *ptr, size_t size) override;
  8658. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8659. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8660. socket_t socket() const override;
  8661. time_t duration() const override;
  8662. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8663. private:
  8664. mutable std::mutex session_mutex_;
  8665. socket_t sock_;
  8666. tls::session_t session_;
  8667. // WebSocket::close() shortens the read timeout from the closing thread
  8668. // while the receive thread is inside wait_readable(), so these two are read
  8669. // and written concurrently. The write timeouts are never mutated.
  8670. std::atomic<time_t> read_timeout_sec_;
  8671. std::atomic<time_t> read_timeout_usec_;
  8672. time_t write_timeout_sec_;
  8673. time_t write_timeout_usec_;
  8674. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8675. };
  8676. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8677. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  8678. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  8679. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  8680. unsigned int hash_length = 0;
  8681. unsigned char hash[EVP_MAX_MD_SIZE];
  8682. EVP_DigestInit_ex(context.get(), algo, nullptr);
  8683. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  8684. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  8685. std::stringstream ss;
  8686. for (auto i = 0u; i < hash_length; ++i) {
  8687. ss << std::hex << std::setw(2) << std::setfill('0')
  8688. << static_cast<unsigned int>(hash[i]);
  8689. }
  8690. return ss.str();
  8691. }
  8692. inline std::string MD5(const std::string &s) {
  8693. return message_digest(s, EVP_md5());
  8694. }
  8695. inline std::string SHA_256(const std::string &s) {
  8696. return message_digest(s, EVP_sha256());
  8697. }
  8698. inline std::string SHA_512(const std::string &s) {
  8699. return message_digest(s, EVP_sha512());
  8700. }
  8701. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  8702. namespace {
  8703. template <size_t N>
  8704. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8705. std::stringstream ss;
  8706. for (size_t i = 0; i < N; ++i) {
  8707. ss << std::hex << std::setw(2) << std::setfill('0')
  8708. << static_cast<unsigned int>(hash[i]);
  8709. }
  8710. return ss.str();
  8711. }
  8712. } // namespace
  8713. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8714. // Mbed TLS 4.x provides hashing (and TLS RNG) via PSA Crypto, which must be
  8715. // initialized once. PSA state is process-global; do not free it.
  8716. inline bool ensure_mbedtls_psa_crypto() {
  8717. static std::once_flag once;
  8718. static bool ok = false;
  8719. std::call_once(once, []() { ok = (psa_crypto_init() == PSA_SUCCESS); });
  8720. return ok;
  8721. }
  8722. inline bool psa_hash(psa_algorithm_t alg, const std::string &s,
  8723. unsigned char *out, size_t out_size) {
  8724. if (!ensure_mbedtls_psa_crypto()) { return false; }
  8725. size_t olen = 0;
  8726. return psa_hash_compute(alg, reinterpret_cast<const uint8_t *>(s.data()),
  8727. s.size(), out, out_size, &olen) == PSA_SUCCESS &&
  8728. olen == out_size;
  8729. }
  8730. #endif
  8731. inline std::string MD5(const std::string &s) {
  8732. unsigned char hash[16];
  8733. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8734. if (!psa_hash(PSA_ALG_MD5, s, hash, sizeof(hash))) { return {}; }
  8735. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8736. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8737. hash);
  8738. #else
  8739. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8740. hash);
  8741. #endif
  8742. return hash_to_hex(hash);
  8743. }
  8744. inline std::string SHA_256(const std::string &s) {
  8745. unsigned char hash[32];
  8746. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8747. if (!psa_hash(PSA_ALG_SHA_256, s, hash, sizeof(hash))) { return {}; }
  8748. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8749. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8750. hash, 0);
  8751. #else
  8752. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8753. s.size(), hash, 0);
  8754. #endif
  8755. return hash_to_hex(hash);
  8756. }
  8757. inline std::string SHA_512(const std::string &s) {
  8758. unsigned char hash[64];
  8759. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8760. if (!psa_hash(PSA_ALG_SHA_512, s, hash, sizeof(hash))) { return {}; }
  8761. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8762. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8763. hash, 0);
  8764. #else
  8765. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8766. s.size(), hash, 0);
  8767. #endif
  8768. return hash_to_hex(hash);
  8769. }
  8770. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  8771. namespace {
  8772. template <size_t N>
  8773. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8774. std::stringstream ss;
  8775. for (size_t i = 0; i < N; ++i) {
  8776. ss << std::hex << std::setw(2) << std::setfill('0')
  8777. << static_cast<unsigned int>(hash[i]);
  8778. }
  8779. return ss.str();
  8780. }
  8781. } // namespace
  8782. inline std::string MD5(const std::string &s) {
  8783. unsigned char hash[WC_MD5_DIGEST_SIZE];
  8784. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8785. static_cast<word32>(s.size()), hash);
  8786. return hash_to_hex(hash);
  8787. }
  8788. inline std::string SHA_256(const std::string &s) {
  8789. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  8790. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8791. static_cast<word32>(s.size()), hash);
  8792. return hash_to_hex(hash);
  8793. }
  8794. inline std::string SHA_512(const std::string &s) {
  8795. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  8796. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8797. static_cast<word32>(s.size()), hash);
  8798. return hash_to_hex(hash);
  8799. }
  8800. #endif
  8801. template <typename T>
  8802. inline bool process_server_socket_ssl(
  8803. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  8804. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8805. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8806. time_t write_timeout_usec, T callback) {
  8807. return process_server_socket_core(
  8808. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8809. [&](bool close_connection, bool &connection_closed) {
  8810. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  8811. write_timeout_sec, write_timeout_usec);
  8812. // See the non-TLS path in process_server_socket().
  8813. strm.set_readable_hint();
  8814. return callback(strm, close_connection, connection_closed);
  8815. });
  8816. }
  8817. template <typename T>
  8818. inline bool process_client_socket_ssl(
  8819. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  8820. time_t read_timeout_usec, time_t write_timeout_sec,
  8821. time_t write_timeout_usec, time_t max_timeout_msec,
  8822. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  8823. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  8824. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  8825. start_time);
  8826. return callback(strm);
  8827. }
  8828. inline std::pair<std::string, std::string> make_digest_authentication_header(
  8829. const Request &req, const std::map<std::string, std::string> &auth,
  8830. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  8831. const std::string &password, bool is_proxy = false) {
  8832. std::string nc;
  8833. {
  8834. std::stringstream ss;
  8835. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  8836. nc = ss.str();
  8837. }
  8838. std::string qop;
  8839. if (auth.find("qop") != auth.end()) {
  8840. qop = auth.at("qop");
  8841. if (qop.find("auth-int") != std::string::npos) {
  8842. qop = "auth-int";
  8843. } else if (qop.find("auth") != std::string::npos) {
  8844. qop = "auth";
  8845. } else {
  8846. qop.clear();
  8847. }
  8848. }
  8849. std::string algo = "MD5";
  8850. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  8851. std::string response;
  8852. {
  8853. auto H = algo == "SHA-256" ? detail::SHA_256
  8854. : algo == "SHA-512" ? detail::SHA_512
  8855. : detail::MD5;
  8856. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  8857. auto A2 = req.method + ":" + req.path;
  8858. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  8859. if (qop.empty()) {
  8860. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  8861. } else {
  8862. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  8863. ":" + qop + ":" + H(A2));
  8864. }
  8865. }
  8866. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  8867. auto field = "Digest username=\"" + username + "\", realm=\"" +
  8868. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  8869. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  8870. (qop.empty() ? ", response=\""
  8871. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  8872. cnonce + "\", response=\"") +
  8873. response + "\"" +
  8874. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  8875. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8876. return std::make_pair(key, field);
  8877. }
  8878. inline bool match_hostname(const std::string &pattern,
  8879. const std::string &hostname) {
  8880. // Exact match (case-insensitive)
  8881. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  8882. // Split both pattern and hostname into components by '.'
  8883. std::vector<std::string> pattern_components;
  8884. if (!pattern.empty()) {
  8885. split(pattern.data(), pattern.data() + pattern.size(), '.',
  8886. [&](const char *b, const char *e) {
  8887. pattern_components.emplace_back(b, e);
  8888. });
  8889. }
  8890. std::vector<std::string> host_components;
  8891. if (!hostname.empty()) {
  8892. split(hostname.data(), hostname.data() + hostname.size(), '.',
  8893. [&](const char *b, const char *e) {
  8894. host_components.emplace_back(b, e);
  8895. });
  8896. }
  8897. // Component count must match
  8898. if (host_components.size() != pattern_components.size()) { return false; }
  8899. // Compare each component with wildcard support
  8900. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  8901. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  8902. auto itr = pattern_components.begin();
  8903. for (const auto &h : host_components) {
  8904. auto &p = *itr;
  8905. if (!detail::case_ignore::equal(p, h) && p != "*") {
  8906. bool partial_match = false;
  8907. if (!p.empty() && p[p.size() - 1] == '*') {
  8908. const auto prefix_length = p.size() - 1;
  8909. if (prefix_length == 0) {
  8910. partial_match = true;
  8911. } else if (h.size() >= prefix_length) {
  8912. partial_match =
  8913. std::equal(p.begin(),
  8914. p.begin() + static_cast<std::string::difference_type>(
  8915. prefix_length),
  8916. h.begin(), [](const char ca, const char cb) {
  8917. return detail::case_ignore::to_lower(ca) ==
  8918. detail::case_ignore::to_lower(cb);
  8919. });
  8920. }
  8921. }
  8922. if (!partial_match) { return false; }
  8923. }
  8924. ++itr;
  8925. }
  8926. return true;
  8927. }
  8928. #ifdef _WIN32
  8929. // Verify certificate using Windows CertGetCertificateChain API.
  8930. // This provides real-time certificate validation with Windows Update
  8931. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  8932. inline bool
  8933. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  8934. const std::string &hostname,
  8935. bool verify_hostname, uint64_t &out_error) {
  8936. if (der_cert.empty()) { return false; }
  8937. out_error = 0;
  8938. // Create Windows certificate context from DER data
  8939. auto cert_context = CertCreateCertificateContext(
  8940. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  8941. static_cast<DWORD>(der_cert.size()));
  8942. if (!cert_context) {
  8943. out_error = GetLastError();
  8944. return false;
  8945. }
  8946. auto cert_guard =
  8947. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  8948. // Setup chain parameters
  8949. CERT_CHAIN_PARA chain_para = {};
  8950. chain_para.cbSize = sizeof(chain_para);
  8951. // Build certificate chain with revocation checking
  8952. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  8953. auto chain_result = CertGetCertificateChain(
  8954. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  8955. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  8956. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  8957. nullptr, &chain_context);
  8958. if (!chain_result || !chain_context) {
  8959. out_error = GetLastError();
  8960. return false;
  8961. }
  8962. auto chain_guard =
  8963. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  8964. // Check if chain has errors
  8965. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  8966. out_error = chain_context->TrustStatus.dwErrorStatus;
  8967. return false;
  8968. }
  8969. // Verify SSL policy
  8970. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  8971. extra_policy_para.cbSize = sizeof(extra_policy_para);
  8972. #ifdef AUTHTYPE_SERVER
  8973. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  8974. #endif
  8975. std::wstring whost;
  8976. if (verify_hostname) {
  8977. whost = u8string_to_wstring(hostname.c_str());
  8978. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  8979. }
  8980. CERT_CHAIN_POLICY_PARA policy_para = {};
  8981. policy_para.cbSize = sizeof(policy_para);
  8982. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  8983. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  8984. #else
  8985. policy_para.dwFlags = 0;
  8986. #endif
  8987. policy_para.pvExtraPolicyPara = &extra_policy_para;
  8988. CERT_CHAIN_POLICY_STATUS policy_status = {};
  8989. policy_status.cbSize = sizeof(policy_status);
  8990. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  8991. &policy_para, &policy_status)) {
  8992. out_error = GetLastError();
  8993. return false;
  8994. }
  8995. if (policy_status.dwError != 0) {
  8996. out_error = policy_status.dwError;
  8997. return false;
  8998. }
  8999. return true;
  9000. }
  9001. #endif // _WIN32
  9002. // Loads CA file/dir configuration and applies the system CA policy to a
  9003. // client TLS context. PEM data and native stores are applied to the context
  9004. // directly at set time; has_custom_store reflects them for the Auto policy
  9005. // decision.
  9006. inline bool load_client_ca_config(tls::ctx_t ctx,
  9007. const std::string &ca_cert_file_path,
  9008. const std::string &ca_cert_dir_path,
  9009. bool has_custom_store, SystemCAMode mode,
  9010. uint64_t &backend_error) {
  9011. auto ret = true;
  9012. if (!ca_cert_file_path.empty()) {
  9013. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  9014. backend_error = tls::get_error();
  9015. ret = false;
  9016. }
  9017. } else if (!ca_cert_dir_path.empty()) {
  9018. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  9019. backend_error = tls::get_error();
  9020. ret = false;
  9021. }
  9022. }
  9023. auto has_custom_ca = !ca_cert_file_path.empty() ||
  9024. !ca_cert_dir_path.empty() || has_custom_store;
  9025. if (mode == SystemCAMode::Enabled ||
  9026. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  9027. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  9028. }
  9029. return ret;
  9030. }
  9031. // The parts of session setup that only SSLClient needs, plus the handful
  9032. // WebSocketClient also exposes; everything else takes the defaults, which is
  9033. // what keeps the two clients on one implementation.
  9034. struct ClientTlsSessionOptions {
  9035. // Both SSLClient and WebSocketClient expose this independently of
  9036. // certificate verification.
  9037. bool server_hostname_verification = true;
  9038. std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
  9039. // When non-null, guards session creation against concurrent use of the
  9040. // context. A WebSocketClient is not safe to use from several threads to
  9041. // begin with, so it passes nothing.
  9042. std::mutex *ctx_mutex = nullptr;
  9043. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  9044. // The caller decides whether Schannel has anything to say about this
  9045. // connection; see SSLClient::initialize_ssl().
  9046. bool windows_cert_verification = false;
  9047. #endif
  9048. };
  9049. // Filled in on failure for callers that report error details.
  9050. struct ClientTlsSessionError {
  9051. Error error = Error::Success;
  9052. int ssl_error = 0;
  9053. uint64_t backend_error = 0;
  9054. };
  9055. // Establishes a client TLS session on an already connected socket. On failure
  9056. // the session is left for the caller to free: SSLClient frees it right away,
  9057. // WebSocketClient keeps it in a member that shutdown_and_close() cleans up.
  9058. inline bool setup_client_tls_session(
  9059. const std::string &host, tls::ctx_t ctx, tls::session_t &session,
  9060. socket_t sock, bool server_certificate_verification, time_t timeout_sec,
  9061. time_t timeout_usec, ClientTlsSessionError *out_error = nullptr,
  9062. const ClientTlsSessionOptions &options = ClientTlsSessionOptions()) {
  9063. using namespace tls;
  9064. auto fail = [&](Error error, int ssl_error, uint64_t backend_error) {
  9065. if (out_error) {
  9066. out_error->error = error;
  9067. out_error->ssl_error = ssl_error;
  9068. out_error->backend_error = backend_error;
  9069. }
  9070. return false;
  9071. };
  9072. if (!ctx) {
  9073. session = nullptr;
  9074. return fail(Error::SSLConnection, 0, 0);
  9075. }
  9076. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  9077. // Mbed TLS and wolfSSL need the verification mode set explicitly; OpenSSL
  9078. // uses SSL_VERIFY_NONE and does all verification post-handshake. Chain
  9079. // verification happens during the handshake even for IP hosts; the
  9080. // certificate identity is verified post-handshake via verify_hostname().
  9081. set_verify_client(ctx, server_certificate_verification);
  9082. #endif
  9083. {
  9084. std::unique_lock<std::mutex> guard;
  9085. if (options.ctx_mutex) {
  9086. guard = std::unique_lock<std::mutex>(*options.ctx_mutex);
  9087. }
  9088. session = create_session(ctx, sock);
  9089. }
  9090. if (!session) { return fail(Error::SSLConnection, 0, get_error()); }
  9091. // RFC 6066: SNI must not be set for IP addresses; skip it for IP hosts, so
  9092. // their identity is checked post-handshake below instead. On Mbed TLS and
  9093. // wolfSSL, set_sni also drives handshake-time hostname verification, so
  9094. // options.server_hostname_verification is threaded through here.
  9095. if (!is_ip_address(host)) {
  9096. if (!set_sni(session, host.c_str(), options.server_hostname_verification)) {
  9097. return fail(Error::SSLConnection, 0, get_error());
  9098. }
  9099. }
  9100. TlsError tls_err;
  9101. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec,
  9102. &tls_err)) {
  9103. auto error = Error::SSLConnection;
  9104. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  9105. error = Error::SSLServerVerification;
  9106. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  9107. error = Error::SSLServerHostnameVerification;
  9108. }
  9109. return fail(error, static_cast<int>(tls_err.code), tls_err.backend_code);
  9110. }
  9111. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  9112. if (options.session_verifier) {
  9113. verification_status = options.session_verifier(session);
  9114. }
  9115. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  9116. return fail(Error::SSLServerVerification, 0, get_error());
  9117. }
  9118. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  9119. server_certificate_verification) {
  9120. auto verify_result = get_verify_result(session);
  9121. if (verify_result != 0) {
  9122. return fail(Error::SSLServerVerification, 0,
  9123. static_cast<uint64_t>(verify_result));
  9124. }
  9125. auto server_cert = get_peer_cert(session);
  9126. if (!server_cert) {
  9127. return fail(Error::SSLServerVerification, 0, get_error());
  9128. }
  9129. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  9130. // Identity check against the peer certificate, post-handshake for all
  9131. // backends. For IP hosts this is the only identity verification, since no
  9132. // hostname is bound during the handshake.
  9133. if (options.server_hostname_verification) {
  9134. if (!verify_hostname(server_cert, host.c_str())) {
  9135. return fail(Error::SSLServerHostnameVerification, 0,
  9136. hostname_mismatch_code());
  9137. }
  9138. }
  9139. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  9140. // Additional Windows Schannel verification.
  9141. // This provides real-time certificate validation with Windows Update
  9142. // integration, working with both OpenSSL and MbedTLS backends.
  9143. if (options.windows_cert_verification) {
  9144. std::vector<unsigned char> der;
  9145. if (get_cert_der(server_cert, der)) {
  9146. uint64_t wincrypt_error = 0;
  9147. if (!verify_cert_with_windows_schannel(
  9148. der, host, options.server_hostname_verification,
  9149. wincrypt_error)) {
  9150. return fail(Error::SSLServerVerification, 0, wincrypt_error);
  9151. }
  9152. }
  9153. }
  9154. #endif
  9155. }
  9156. return true;
  9157. }
  9158. } // namespace detail
  9159. #endif // CPPHTTPLIB_SSL_ENABLED
  9160. /*
  9161. * Group 3: httplib namespace - Non-SSL public API implementations
  9162. */
  9163. inline void default_socket_options(socket_t sock) {
  9164. set_socket_opt(sock, SOL_SOCKET,
  9165. #ifdef SO_REUSEPORT
  9166. SO_REUSEPORT,
  9167. #else
  9168. SO_REUSEADDR,
  9169. #endif
  9170. 1);
  9171. }
  9172. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  9173. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  9174. sizeof(optval));
  9175. }
  9176. inline std::string get_bearer_token_auth(const Request &req) {
  9177. // The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
  9178. // than the prefix carries no token.
  9179. constexpr const char bearer_prefix[] = "Bearer ";
  9180. constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
  9181. auto value = req.get_header_value("Authorization");
  9182. if (value.size() >= bearer_prefix_len &&
  9183. detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
  9184. bearer_prefix)) {
  9185. return value.substr(bearer_prefix_len);
  9186. }
  9187. return "";
  9188. }
  9189. inline const char *status_message(int status) {
  9190. switch (status) {
  9191. case StatusCode::Continue_100: return "Continue";
  9192. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  9193. case StatusCode::Processing_102: return "Processing";
  9194. case StatusCode::EarlyHints_103: return "Early Hints";
  9195. case StatusCode::OK_200: return "OK";
  9196. case StatusCode::Created_201: return "Created";
  9197. case StatusCode::Accepted_202: return "Accepted";
  9198. case StatusCode::NonAuthoritativeInformation_203:
  9199. return "Non-Authoritative Information";
  9200. case StatusCode::NoContent_204: return "No Content";
  9201. case StatusCode::ResetContent_205: return "Reset Content";
  9202. case StatusCode::PartialContent_206: return "Partial Content";
  9203. case StatusCode::MultiStatus_207: return "Multi-Status";
  9204. case StatusCode::AlreadyReported_208: return "Already Reported";
  9205. case StatusCode::IMUsed_226: return "IM Used";
  9206. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  9207. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  9208. case StatusCode::Found_302: return "Found";
  9209. case StatusCode::SeeOther_303: return "See Other";
  9210. case StatusCode::NotModified_304: return "Not Modified";
  9211. case StatusCode::UseProxy_305: return "Use Proxy";
  9212. case StatusCode::unused_306: return "unused";
  9213. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  9214. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  9215. case StatusCode::BadRequest_400: return "Bad Request";
  9216. case StatusCode::Unauthorized_401: return "Unauthorized";
  9217. case StatusCode::PaymentRequired_402: return "Payment Required";
  9218. case StatusCode::Forbidden_403: return "Forbidden";
  9219. case StatusCode::NotFound_404: return "Not Found";
  9220. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  9221. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  9222. case StatusCode::ProxyAuthenticationRequired_407:
  9223. return "Proxy Authentication Required";
  9224. case StatusCode::RequestTimeout_408: return "Request Timeout";
  9225. case StatusCode::Conflict_409: return "Conflict";
  9226. case StatusCode::Gone_410: return "Gone";
  9227. case StatusCode::LengthRequired_411: return "Length Required";
  9228. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  9229. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  9230. case StatusCode::UriTooLong_414: return "URI Too Long";
  9231. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  9232. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  9233. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  9234. case StatusCode::ImATeapot_418: return "I'm a teapot";
  9235. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  9236. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  9237. case StatusCode::Locked_423: return "Locked";
  9238. case StatusCode::FailedDependency_424: return "Failed Dependency";
  9239. case StatusCode::TooEarly_425: return "Too Early";
  9240. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  9241. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  9242. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  9243. case StatusCode::RequestHeaderFieldsTooLarge_431:
  9244. return "Request Header Fields Too Large";
  9245. case StatusCode::UnavailableForLegalReasons_451:
  9246. return "Unavailable For Legal Reasons";
  9247. case StatusCode::NotImplemented_501: return "Not Implemented";
  9248. case StatusCode::BadGateway_502: return "Bad Gateway";
  9249. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  9250. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  9251. case StatusCode::HttpVersionNotSupported_505:
  9252. return "HTTP Version Not Supported";
  9253. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  9254. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  9255. case StatusCode::LoopDetected_508: return "Loop Detected";
  9256. case StatusCode::NotExtended_510: return "Not Extended";
  9257. case StatusCode::NetworkAuthenticationRequired_511:
  9258. return "Network Authentication Required";
  9259. default:
  9260. case StatusCode::InternalServerError_500: return "Internal Server Error";
  9261. }
  9262. }
  9263. inline std::string to_string(const Error error) {
  9264. switch (error) {
  9265. case Error::Success: return "Success (no error)";
  9266. case Error::Unknown: return "Unknown";
  9267. case Error::Connection: return "Could not establish connection";
  9268. case Error::BindIPAddress: return "Failed to bind IP address";
  9269. case Error::Read: return "Failed to read connection";
  9270. case Error::Write: return "Failed to write connection";
  9271. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  9272. case Error::Canceled: return "Connection handling canceled";
  9273. case Error::SSLConnection: return "SSL connection failed";
  9274. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  9275. case Error::SSLServerVerification: return "SSL server verification failed";
  9276. case Error::SSLServerHostnameVerification:
  9277. return "SSL server hostname verification failed";
  9278. case Error::UnsupportedMultipartBoundaryChars:
  9279. return "Unsupported HTTP multipart boundary characters";
  9280. case Error::Compression: return "Compression failed";
  9281. case Error::ConnectionTimeout: return "Connection timed out";
  9282. case Error::ProxyConnection: return "Proxy connection failed";
  9283. case Error::ConnectionClosed: return "Connection closed by server";
  9284. case Error::Timeout: return "Read timeout";
  9285. case Error::ResourceExhaustion: return "Resource exhaustion";
  9286. case Error::TooManyFormDataFiles: return "Too many form data files";
  9287. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  9288. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  9289. case Error::ExceedMaxSocketDescriptorCount:
  9290. return "Exceeded maximum socket descriptor count";
  9291. case Error::InvalidRequestLine: return "Invalid request line";
  9292. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  9293. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  9294. case Error::InvalidHeaders: return "Invalid headers";
  9295. case Error::MultipartParsing: return "Multipart parsing failed";
  9296. case Error::OpenFile: return "Failed to open file";
  9297. case Error::Listen: return "Failed to listen on socket";
  9298. case Error::GetSockName: return "Failed to get socket name";
  9299. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  9300. case Error::HTTPParsing: return "HTTP parsing failed";
  9301. case Error::InvalidRangeHeader: return "Invalid Range header";
  9302. case Error::UnsupportedContentEncoding: return "Unsupported Content-Encoding";
  9303. case Error::WebSocketHandshake: return "WebSocket handshake failed";
  9304. case Error::UserCallbackException: return "User callback threw an exception";
  9305. default: break;
  9306. }
  9307. return "Invalid";
  9308. }
  9309. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  9310. os << to_string(obj);
  9311. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  9312. return os;
  9313. }
  9314. inline std::string hosted_at(const std::string &hostname) {
  9315. std::vector<std::string> addrs;
  9316. hosted_at(hostname, addrs);
  9317. if (addrs.empty()) { return std::string(); }
  9318. return addrs[0];
  9319. }
  9320. inline void hosted_at(const std::string &hostname,
  9321. std::vector<std::string> &addrs) {
  9322. struct addrinfo hints;
  9323. struct addrinfo *result;
  9324. memset(&hints, 0, sizeof(struct addrinfo));
  9325. hints.ai_family = AF_UNSPEC;
  9326. hints.ai_socktype = SOCK_STREAM;
  9327. hints.ai_protocol = 0;
  9328. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  9329. &result, 0)) {
  9330. #if defined __linux__ && !defined __ANDROID__
  9331. res_init();
  9332. #endif
  9333. return;
  9334. }
  9335. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  9336. for (auto rp = result; rp; rp = rp->ai_next) {
  9337. const auto &addr =
  9338. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  9339. std::string ip;
  9340. auto dummy = -1;
  9341. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  9342. dummy)) {
  9343. addrs.emplace_back(std::move(ip));
  9344. }
  9345. }
  9346. }
  9347. inline std::string encode_uri_component(const std::string &value) {
  9348. std::ostringstream escaped;
  9349. escaped.fill('0');
  9350. escaped << std::hex;
  9351. for (auto c : value) {
  9352. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9353. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  9354. escaped << c;
  9355. } else {
  9356. escaped << std::uppercase;
  9357. escaped << '%' << std::setw(2)
  9358. << static_cast<int>(static_cast<unsigned char>(c));
  9359. escaped << std::nouppercase;
  9360. }
  9361. }
  9362. return escaped.str();
  9363. }
  9364. inline std::string encode_uri(const std::string &value) {
  9365. std::ostringstream escaped;
  9366. escaped.fill('0');
  9367. escaped << std::hex;
  9368. for (auto c : value) {
  9369. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9370. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  9371. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  9372. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  9373. escaped << c;
  9374. } else {
  9375. escaped << std::uppercase;
  9376. escaped << '%' << std::setw(2)
  9377. << static_cast<int>(static_cast<unsigned char>(c));
  9378. escaped << std::nouppercase;
  9379. }
  9380. }
  9381. return escaped.str();
  9382. }
  9383. inline std::string decode_uri_component(const std::string &value) {
  9384. std::string result;
  9385. for (size_t i = 0; i < value.size(); i++) {
  9386. if (value[i] == '%' && i + 2 < value.size()) {
  9387. auto val = 0;
  9388. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9389. result += static_cast<char>(val);
  9390. i += 2;
  9391. } else {
  9392. result += value[i];
  9393. }
  9394. } else {
  9395. result += value[i];
  9396. }
  9397. }
  9398. return result;
  9399. }
  9400. inline std::string decode_uri(const std::string &value) {
  9401. std::string result;
  9402. for (size_t i = 0; i < value.size(); i++) {
  9403. if (value[i] == '%' && i + 2 < value.size()) {
  9404. auto val = 0;
  9405. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9406. auto c = static_cast<char>(val);
  9407. // Keep escapes of the reserved characters that encode_uri leaves
  9408. // literal, so decode_uri is the inverse of encode_uri and an escaped
  9409. // delimiter is not promoted into a real one (as with JS decodeURI).
  9410. if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  9411. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' ||
  9412. c == '#') {
  9413. result += value[i];
  9414. result += value[i + 1];
  9415. result += value[i + 2];
  9416. } else {
  9417. result += c;
  9418. }
  9419. i += 2;
  9420. } else {
  9421. result += value[i];
  9422. }
  9423. } else {
  9424. result += value[i];
  9425. }
  9426. }
  9427. return result;
  9428. }
  9429. inline std::string encode_path_component(const std::string &component) {
  9430. std::string result;
  9431. result.reserve(component.size() * 3);
  9432. for (size_t i = 0; i < component.size(); i++) {
  9433. auto c = static_cast<unsigned char>(component[i]);
  9434. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  9435. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9436. c == '_' || c == '~') {
  9437. result += static_cast<char>(c);
  9438. }
  9439. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  9440. // "," / ";" / "="
  9441. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  9442. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  9443. c == '=') {
  9444. result += static_cast<char>(c);
  9445. }
  9446. // Colon is allowed in path segments except first segment
  9447. else if (c == ':') {
  9448. result += static_cast<char>(c);
  9449. }
  9450. // @ is allowed in path
  9451. else if (c == '@') {
  9452. result += static_cast<char>(c);
  9453. } else {
  9454. result += '%';
  9455. char hex[3];
  9456. snprintf(hex, sizeof(hex), "%02X", c);
  9457. result.append(hex, 2);
  9458. }
  9459. }
  9460. return result;
  9461. }
  9462. inline std::string decode_path_component(const std::string &component) {
  9463. std::string result;
  9464. result.reserve(component.size());
  9465. for (size_t i = 0; i < component.size(); i++) {
  9466. if (component[i] == '%' && i + 1 < component.size()) {
  9467. if (component[i + 1] == 'u') {
  9468. // Unicode %uXXXX encoding
  9469. auto val = 0;
  9470. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  9471. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  9472. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  9473. char buff[4];
  9474. size_t len = detail::to_utf8(val, buff);
  9475. if (len > 0) { result.append(buff, len); }
  9476. i += 5; // 'u0000'
  9477. } else {
  9478. result += component[i];
  9479. }
  9480. } else {
  9481. // Standard %XX encoding
  9482. auto val = 0;
  9483. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9484. // 2 digits hex codes
  9485. result += static_cast<char>(val);
  9486. i += 2; // 'XX'
  9487. } else {
  9488. result += component[i];
  9489. }
  9490. }
  9491. } else {
  9492. result += component[i];
  9493. }
  9494. }
  9495. return result;
  9496. }
  9497. inline std::string encode_query_component(const std::string &component,
  9498. bool space_as_plus) {
  9499. std::string result;
  9500. result.reserve(component.size() * 3);
  9501. for (size_t i = 0; i < component.size(); i++) {
  9502. auto c = static_cast<unsigned char>(component[i]);
  9503. // Unreserved characters per RFC 3986
  9504. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9505. c == '_' || c == '~') {
  9506. result += static_cast<char>(c);
  9507. }
  9508. // Space handling
  9509. else if (c == ' ') {
  9510. if (space_as_plus) {
  9511. result += '+';
  9512. } else {
  9513. result += "%20";
  9514. }
  9515. }
  9516. // Plus sign handling
  9517. else if (c == '+') {
  9518. if (space_as_plus) {
  9519. result += "%2B";
  9520. } else {
  9521. result += static_cast<char>(c);
  9522. }
  9523. }
  9524. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  9525. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  9526. c == '*' || c == ',' || c == ';') {
  9527. result += static_cast<char>(c);
  9528. }
  9529. // Colon and @ are allowed in query
  9530. else if (c == ':' || c == '@') {
  9531. result += static_cast<char>(c);
  9532. }
  9533. // Forward slash is allowed in query values
  9534. else if (c == '/') {
  9535. result += static_cast<char>(c);
  9536. }
  9537. // Question mark is allowed in query values (after first ?)
  9538. else if (c == '?') {
  9539. result += static_cast<char>(c);
  9540. } else {
  9541. result += '%';
  9542. char hex[3];
  9543. snprintf(hex, sizeof(hex), "%02X", c);
  9544. result.append(hex, 2);
  9545. }
  9546. }
  9547. return result;
  9548. }
  9549. inline std::string decode_query_component(const std::string &component,
  9550. bool plus_as_space) {
  9551. std::string result;
  9552. result.reserve(component.size());
  9553. for (size_t i = 0; i < component.size(); i++) {
  9554. if (component[i] == '%' && i + 2 < component.size()) {
  9555. auto val = 0;
  9556. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9557. result += static_cast<char>(val);
  9558. i += 2;
  9559. } else {
  9560. result += component[i];
  9561. }
  9562. } else if (component[i] == '+' && plus_as_space) {
  9563. result += ' '; // + becomes space in form-urlencoded
  9564. } else {
  9565. result += component[i];
  9566. }
  9567. }
  9568. return result;
  9569. }
  9570. inline std::string sanitize_filename(const std::string &filename) {
  9571. // Extract basename: find the last path separator (/ or \)
  9572. auto pos = filename.find_last_of("/\\");
  9573. auto result =
  9574. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  9575. // Strip null bytes
  9576. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  9577. // Trim whitespace
  9578. {
  9579. auto start = result.find_first_not_of(" \t");
  9580. auto end = result.find_last_not_of(" \t");
  9581. result = (start == std::string::npos)
  9582. ? ""
  9583. : result.substr(start, end - start + 1);
  9584. }
  9585. // Reject . and ..
  9586. if (result == "." || result == "..") { return ""; }
  9587. return result;
  9588. }
  9589. inline std::string append_query_params(const std::string &path,
  9590. const Params &params) {
  9591. std::string path_with_query = path;
  9592. thread_local const std::regex re("[^?]+\\?.*");
  9593. auto delm = std::regex_match(path, re) ? '&' : '?';
  9594. path_with_query += delm + detail::params_to_query_str(params);
  9595. return path_with_query;
  9596. }
  9597. // Header utilities
  9598. inline std::pair<std::string, std::string>
  9599. make_range_header(const Ranges &ranges) {
  9600. std::string field = "bytes=";
  9601. auto i = 0;
  9602. for (const auto &r : ranges) {
  9603. if (i != 0) { field += ", "; }
  9604. if (r.first != -1) { field += std::to_string(r.first); }
  9605. field += '-';
  9606. if (r.second != -1) { field += std::to_string(r.second); }
  9607. i++;
  9608. }
  9609. return std::make_pair("Range", std::move(field));
  9610. }
  9611. inline std::pair<std::string, std::string>
  9612. make_basic_authentication_header(const std::string &username,
  9613. const std::string &password, bool is_proxy) {
  9614. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  9615. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9616. return std::make_pair(key, std::move(field));
  9617. }
  9618. inline std::pair<std::string, std::string>
  9619. make_bearer_token_authentication_header(const std::string &token,
  9620. bool is_proxy = false) {
  9621. auto field = "Bearer " + token;
  9622. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9623. return std::make_pair(key, std::move(field));
  9624. }
  9625. // Request implementation
  9626. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  9627. size_t id) const {
  9628. return detail::get_header_value_u64(headers, key, def, id);
  9629. }
  9630. inline bool Request::has_header(const std::string &key) const {
  9631. return detail::has_header(headers, key);
  9632. }
  9633. inline std::string Request::get_header_value(const std::string &key,
  9634. const char *def, size_t id) const {
  9635. return detail::get_header_value(headers, key, def, id);
  9636. }
  9637. inline size_t Request::get_header_value_count(const std::string &key) const {
  9638. return detail::get_header_value_count(headers, key);
  9639. }
  9640. inline void Request::set_header(const std::string &key,
  9641. const std::string &val) {
  9642. detail::set_header(headers, key, val);
  9643. }
  9644. inline bool Request::has_trailer(const std::string &key) const {
  9645. return trailers.find(key) != trailers.end();
  9646. }
  9647. inline std::string Request::get_trailer_value(const std::string &key,
  9648. size_t id) const {
  9649. return detail::get_multimap_value(trailers, key, id);
  9650. }
  9651. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  9652. return trailers.count(key);
  9653. }
  9654. inline bool Request::has_param(const std::string &key) const {
  9655. return params.find(key) != params.end();
  9656. }
  9657. inline std::string Request::get_param_value(const std::string &key,
  9658. size_t id) const {
  9659. return detail::get_multimap_value(params, key, id);
  9660. }
  9661. inline std::vector<std::string>
  9662. Request::get_param_values(const std::string &key) const {
  9663. auto rng = params.equal_range(key);
  9664. std::vector<std::string> values;
  9665. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  9666. for (auto it = rng.first; it != rng.second; ++it) {
  9667. values.push_back(it->second);
  9668. }
  9669. return values;
  9670. }
  9671. inline size_t Request::get_param_value_count(const std::string &key) const {
  9672. return params.count(key);
  9673. }
  9674. inline bool Request::is_multipart_form_data() const {
  9675. const auto &content_type = get_header_value("Content-Type");
  9676. return detail::extract_media_type(content_type) == "multipart/form-data";
  9677. }
  9678. // Multipart FormData implementation
  9679. inline std::string MultipartFormData::get_field(const std::string &key,
  9680. size_t id) const {
  9681. auto rng = fields.equal_range(key);
  9682. auto it = rng.first;
  9683. std::advance(it, static_cast<ssize_t>(id));
  9684. if (it != rng.second) { return it->second.content; }
  9685. return std::string();
  9686. }
  9687. inline std::vector<std::string>
  9688. MultipartFormData::get_fields(const std::string &key) const {
  9689. std::vector<std::string> values;
  9690. auto rng = fields.equal_range(key);
  9691. for (auto it = rng.first; it != rng.second; it++) {
  9692. values.push_back(it->second.content);
  9693. }
  9694. return values;
  9695. }
  9696. inline bool MultipartFormData::has_field(const std::string &key) const {
  9697. return fields.find(key) != fields.end();
  9698. }
  9699. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  9700. return fields.count(key);
  9701. }
  9702. inline FormData MultipartFormData::get_file(const std::string &key,
  9703. size_t id) const {
  9704. return detail::get_multimap_value(files, key, id);
  9705. }
  9706. inline std::vector<FormData>
  9707. MultipartFormData::get_files(const std::string &key) const {
  9708. std::vector<FormData> values;
  9709. auto rng = files.equal_range(key);
  9710. for (auto it = rng.first; it != rng.second; it++) {
  9711. values.push_back(it->second);
  9712. }
  9713. return values;
  9714. }
  9715. inline bool MultipartFormData::has_file(const std::string &key) const {
  9716. return files.find(key) != files.end();
  9717. }
  9718. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  9719. return files.count(key);
  9720. }
  9721. // Multipart FormData writer implementation
  9722. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  9723. return detail::is_multipart_boundary_chars_valid(boundary);
  9724. }
  9725. inline MultipartFormDataWriter::MultipartFormDataWriter()
  9726. : boundary_(detail::make_multipart_data_boundary()) {}
  9727. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  9728. : boundary_(std::move(boundary)) {}
  9729. inline const std::string &MultipartFormDataWriter::boundary() const {
  9730. return boundary_;
  9731. }
  9732. inline std::string MultipartFormDataWriter::content_type() const {
  9733. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  9734. }
  9735. inline std::string
  9736. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  9737. return detail::serialize_multipart_formdata(items, boundary_);
  9738. }
  9739. inline size_t MultipartFormDataWriter::content_length(
  9740. const UploadFormDataItems &items) const {
  9741. return detail::get_multipart_content_length(items, boundary_);
  9742. }
  9743. inline std::string
  9744. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  9745. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  9746. }
  9747. inline std::string MultipartFormDataWriter::item_end() {
  9748. return detail::serialize_multipart_formdata_item_end();
  9749. }
  9750. inline std::string MultipartFormDataWriter::finish() const {
  9751. return detail::serialize_multipart_formdata_finish(boundary_);
  9752. }
  9753. // Response implementation
  9754. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  9755. size_t id) const {
  9756. return detail::get_header_value_u64(headers, key, def, id);
  9757. }
  9758. inline bool Response::has_header(const std::string &key) const {
  9759. return headers.find(key) != headers.end();
  9760. }
  9761. inline std::string Response::get_header_value(const std::string &key,
  9762. const char *def,
  9763. size_t id) const {
  9764. return detail::get_header_value(headers, key, def, id);
  9765. }
  9766. inline size_t Response::get_header_value_count(const std::string &key) const {
  9767. return detail::get_header_value_count(headers, key);
  9768. }
  9769. inline void Response::set_header(const std::string &key,
  9770. const std::string &val) {
  9771. detail::set_header(headers, key, val);
  9772. }
  9773. inline bool Response::has_trailer(const std::string &key) const {
  9774. return trailers.find(key) != trailers.end();
  9775. }
  9776. inline std::string Response::get_trailer_value(const std::string &key,
  9777. size_t id) const {
  9778. return detail::get_multimap_value(trailers, key, id);
  9779. }
  9780. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  9781. return trailers.count(key);
  9782. }
  9783. inline void Response::set_redirect(const std::string &url, int stat) {
  9784. if (detail::fields::is_field_value(url)) {
  9785. set_header("Location", url);
  9786. if (300 <= stat && stat < 400) {
  9787. this->status = stat;
  9788. } else {
  9789. this->status = StatusCode::Found_302;
  9790. }
  9791. }
  9792. }
  9793. inline void Response::set_content(const char *s, size_t n,
  9794. const std::string &content_type) {
  9795. body.assign(s, n);
  9796. auto rng = headers.equal_range("Content-Type");
  9797. headers.erase(rng.first, rng.second);
  9798. set_header("Content-Type", content_type);
  9799. content_coding_ = detail::EncodingType::None;
  9800. }
  9801. inline void Response::set_content(const std::string &s,
  9802. const std::string &content_type) {
  9803. set_content(s.data(), s.size(), content_type);
  9804. }
  9805. inline void Response::set_content(std::string &&s,
  9806. const std::string &content_type) {
  9807. body = std::move(s);
  9808. auto rng = headers.equal_range("Content-Type");
  9809. headers.erase(rng.first, rng.second);
  9810. set_header("Content-Type", content_type);
  9811. content_coding_ = detail::EncodingType::None;
  9812. }
  9813. inline void Response::set_content_provider(
  9814. size_t in_length, const std::string &content_type, ContentProvider provider,
  9815. ContentProviderResourceReleaser resource_releaser) {
  9816. set_header("Content-Type", content_type);
  9817. content_length_ = in_length;
  9818. if (in_length > 0) { content_provider_ = std::move(provider); }
  9819. content_provider_resource_releaser_ = std::move(resource_releaser);
  9820. is_chunked_content_provider_ = false;
  9821. content_coding_ = detail::EncodingType::None;
  9822. }
  9823. inline void Response::set_content_provider(
  9824. const std::string &content_type, ContentProviderWithoutLength provider,
  9825. ContentProviderResourceReleaser resource_releaser) {
  9826. set_header("Content-Type", content_type);
  9827. content_length_ = 0;
  9828. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  9829. content_provider_resource_releaser_ = std::move(resource_releaser);
  9830. is_chunked_content_provider_ = false;
  9831. content_coding_ = detail::EncodingType::None;
  9832. }
  9833. inline void Response::set_chunked_content_provider(
  9834. const std::string &content_type, ContentProviderWithoutLength provider,
  9835. ContentProviderResourceReleaser resource_releaser) {
  9836. set_header("Content-Type", content_type);
  9837. content_length_ = 0;
  9838. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  9839. content_provider_resource_releaser_ = std::move(resource_releaser);
  9840. is_chunked_content_provider_ = true;
  9841. content_coding_ = detail::EncodingType::None;
  9842. }
  9843. inline void Response::set_file_content(const std::string &path,
  9844. const std::string &content_type) {
  9845. file_content_path_ = path;
  9846. file_content_content_type_ = content_type;
  9847. }
  9848. inline void Response::set_file_content(const std::string &path) {
  9849. file_content_path_ = path;
  9850. }
  9851. // Result implementation
  9852. inline size_t Result::get_request_header_value_u64(const std::string &key,
  9853. size_t def,
  9854. size_t id) const {
  9855. return detail::get_header_value_u64(request_headers_, key, def, id);
  9856. }
  9857. inline bool Result::has_request_header(const std::string &key) const {
  9858. return request_headers_.find(key) != request_headers_.end();
  9859. }
  9860. inline std::string Result::get_request_header_value(const std::string &key,
  9861. const char *def,
  9862. size_t id) const {
  9863. return detail::get_header_value(request_headers_, key, def, id);
  9864. }
  9865. inline size_t
  9866. Result::get_request_header_value_count(const std::string &key) const {
  9867. return request_headers_.count(key);
  9868. }
  9869. // Stream implementation
  9870. inline ssize_t Stream::write(const char *ptr) {
  9871. return write(ptr, strlen(ptr));
  9872. }
  9873. inline ssize_t Stream::write(const std::string &s) {
  9874. return write(s.data(), s.size());
  9875. }
  9876. // BodyReader implementation
  9877. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  9878. if (!stream) {
  9879. last_error = Error::Connection;
  9880. return -1;
  9881. }
  9882. if (eof) { return 0; }
  9883. if (!chunked) {
  9884. // Content-Length based reading
  9885. if (has_content_length && bytes_read >= content_length) {
  9886. eof = true;
  9887. return 0;
  9888. }
  9889. auto to_read = len;
  9890. if (has_content_length) {
  9891. auto remaining = content_length - bytes_read;
  9892. to_read = (std::min)(len, remaining);
  9893. }
  9894. auto n = stream->read(buf, to_read);
  9895. if (n < 0) {
  9896. last_error = stream->get_error();
  9897. if (last_error == Error::Success) { last_error = Error::Read; }
  9898. eof = true;
  9899. return n;
  9900. }
  9901. if (n == 0) {
  9902. // Unexpected EOF before content_length
  9903. last_error = stream->get_error();
  9904. if (last_error == Error::Success) { last_error = Error::Read; }
  9905. eof = true;
  9906. return 0;
  9907. }
  9908. bytes_read += static_cast<size_t>(n);
  9909. if (has_content_length && bytes_read >= content_length) { eof = true; }
  9910. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  9911. last_error = Error::ExceedMaxPayloadSize;
  9912. eof = true;
  9913. return -1;
  9914. }
  9915. return n;
  9916. }
  9917. // Chunked transfer encoding: delegate to shared decoder instance.
  9918. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  9919. size_t chunk_offset = 0;
  9920. size_t chunk_total = 0;
  9921. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  9922. if (n < 0) {
  9923. last_error = stream->get_error();
  9924. if (last_error == Error::Success) { last_error = Error::Read; }
  9925. eof = true;
  9926. return n;
  9927. }
  9928. if (n == 0) {
  9929. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  9930. eof = true;
  9931. return 0;
  9932. }
  9933. bytes_read += static_cast<size_t>(n);
  9934. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  9935. last_error = Error::ExceedMaxPayloadSize;
  9936. eof = true;
  9937. return -1;
  9938. }
  9939. return n;
  9940. }
  9941. // ThreadPool implementation
  9942. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  9943. time_t idle_timeout_sec)
  9944. : base_thread_count_(n), max_queued_requests_(mqr),
  9945. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  9946. shutdown_(false) {
  9947. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9948. if (max_n != 0 && max_n < n) {
  9949. std::string msg = "max_threads must be >= base_threads";
  9950. throw std::invalid_argument(msg);
  9951. }
  9952. #endif
  9953. max_thread_count_ = max_n == 0 ? n : max_n;
  9954. threads_.reserve(base_thread_count_);
  9955. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9956. try {
  9957. #endif
  9958. for (size_t i = 0; i < base_thread_count_; i++) {
  9959. threads_.emplace_back(std::thread([this]() { worker(false); }));
  9960. }
  9961. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9962. } catch (...) {
  9963. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  9964. // signal the workers we already spawned to exit and join them so the
  9965. // vector destructor does not see joinable threads (which would call
  9966. // std::terminate). Then rethrow so the caller learns of the failure.
  9967. {
  9968. std::unique_lock<std::mutex> lock(mutex_);
  9969. shutdown_ = true;
  9970. }
  9971. cond_.notify_all();
  9972. for (auto &t : threads_) {
  9973. if (t.joinable()) { t.join(); }
  9974. }
  9975. throw;
  9976. }
  9977. #endif
  9978. }
  9979. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  9980. {
  9981. std::unique_lock<std::mutex> lock(mutex_);
  9982. if (shutdown_) { return false; }
  9983. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  9984. return false;
  9985. }
  9986. jobs_.push_back(std::move(fn));
  9987. // Spawn a dynamic thread if no idle threads and under max
  9988. if (idle_thread_count_ == 0 &&
  9989. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  9990. cleanup_finished_threads();
  9991. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  9992. }
  9993. }
  9994. cond_.notify_one();
  9995. return true;
  9996. }
  9997. inline void ThreadPool::shutdown() {
  9998. {
  9999. std::unique_lock<std::mutex> lock(mutex_);
  10000. shutdown_ = true;
  10001. }
  10002. cond_.notify_all();
  10003. for (auto &t : threads_) {
  10004. if (t.joinable()) { t.join(); }
  10005. }
  10006. // Move dynamic_threads_ to a local list under the lock to avoid racing
  10007. // with worker threads that call move_to_finished() concurrently.
  10008. std::list<std::thread> remaining_dynamic;
  10009. {
  10010. std::unique_lock<std::mutex> lock(mutex_);
  10011. remaining_dynamic = std::move(dynamic_threads_);
  10012. }
  10013. for (auto &t : remaining_dynamic) {
  10014. if (t.joinable()) { t.join(); }
  10015. }
  10016. std::unique_lock<std::mutex> lock(mutex_);
  10017. cleanup_finished_threads();
  10018. }
  10019. inline void ThreadPool::move_to_finished(std::thread::id id) {
  10020. // Must be called with mutex_ held
  10021. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  10022. if (it->get_id() == id) {
  10023. finished_threads_.push_back(std::move(*it));
  10024. dynamic_threads_.erase(it);
  10025. return;
  10026. }
  10027. }
  10028. }
  10029. inline void ThreadPool::cleanup_finished_threads() {
  10030. // Must be called with mutex_ held
  10031. for (auto &t : finished_threads_) {
  10032. if (t.joinable()) { t.join(); }
  10033. }
  10034. finished_threads_.clear();
  10035. }
  10036. inline void ThreadPool::worker(bool is_dynamic) {
  10037. for (;;) {
  10038. std::function<void()> fn;
  10039. {
  10040. std::unique_lock<std::mutex> lock(mutex_);
  10041. idle_thread_count_++;
  10042. if (is_dynamic) {
  10043. auto has_work =
  10044. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  10045. [&] { return !jobs_.empty() || shutdown_; });
  10046. if (!has_work) {
  10047. // Timed out with no work - exit this dynamic thread
  10048. idle_thread_count_--;
  10049. move_to_finished(std::this_thread::get_id());
  10050. break;
  10051. }
  10052. } else {
  10053. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  10054. }
  10055. idle_thread_count_--;
  10056. if (shutdown_ && jobs_.empty()) { break; }
  10057. fn = std::move(jobs_.front());
  10058. jobs_.pop_front();
  10059. }
  10060. assert(true == static_cast<bool>(fn));
  10061. fn();
  10062. }
  10063. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  10064. !defined(LIBRESSL_VERSION_NUMBER)
  10065. OPENSSL_thread_stop();
  10066. #endif
  10067. }
  10068. /*
  10069. * Group 1 (continued): detail namespace - Stream implementations
  10070. */
  10071. namespace detail {
  10072. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  10073. time_t timeout_sec, time_t timeout_usec,
  10074. time_t &actual_timeout_sec,
  10075. time_t &actual_timeout_usec) {
  10076. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  10077. auto actual_timeout_msec =
  10078. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  10079. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  10080. actual_timeout_sec = actual_timeout_msec / 1000;
  10081. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  10082. }
  10083. // Socket stream implementation
  10084. inline SocketStream::SocketStream(
  10085. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  10086. time_t write_timeout_sec, time_t write_timeout_usec,
  10087. time_t max_timeout_msec,
  10088. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10089. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  10090. read_timeout_usec_(read_timeout_usec),
  10091. write_timeout_sec_(write_timeout_sec),
  10092. write_timeout_usec_(write_timeout_usec),
  10093. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  10094. read_buff_(read_buff_size_, 0) {}
  10095. inline SocketStream::~SocketStream() = default;
  10096. inline bool SocketStream::is_readable() const {
  10097. return read_buff_off_ < read_buff_content_size_;
  10098. }
  10099. inline bool SocketStream::wait_readable() const {
  10100. if (max_timeout_msec_ <= 0) {
  10101. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10102. }
  10103. time_t read_timeout_sec;
  10104. time_t read_timeout_usec;
  10105. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10106. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10107. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10108. }
  10109. inline bool SocketStream::wait_writable() const {
  10110. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  10111. }
  10112. inline bool SocketStream::ensure_readable() {
  10113. if (readable_hint_) {
  10114. readable_hint_ = false;
  10115. return true;
  10116. }
  10117. return wait_readable();
  10118. }
  10119. inline const char *SocketStream::buffered_data(size_t &size) const {
  10120. size = read_buff_content_size_ - read_buff_off_;
  10121. return size ? read_buff_.data() + read_buff_off_ : nullptr;
  10122. }
  10123. inline void SocketStream::consume_buffered(size_t size) {
  10124. assert(size <= read_buff_content_size_ - read_buff_off_);
  10125. read_buff_off_ += size;
  10126. }
  10127. inline bool SocketStream::is_peer_alive() const {
  10128. return detail::is_socket_alive(sock_);
  10129. }
  10130. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  10131. #ifdef _WIN32
  10132. size =
  10133. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  10134. #else
  10135. size = (std::min)(size,
  10136. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  10137. #endif
  10138. if (read_buff_off_ < read_buff_content_size_) {
  10139. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  10140. if (size <= remaining_size) {
  10141. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  10142. read_buff_off_ += size;
  10143. return static_cast<ssize_t>(size);
  10144. } else {
  10145. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  10146. read_buff_off_ += remaining_size;
  10147. return static_cast<ssize_t>(remaining_size);
  10148. }
  10149. }
  10150. if (!ensure_readable()) {
  10151. error_ = Error::Timeout;
  10152. return -1;
  10153. }
  10154. read_buff_off_ = 0;
  10155. read_buff_content_size_ = 0;
  10156. if (size < read_buff_size_) {
  10157. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  10158. CPPHTTPLIB_RECV_FLAGS);
  10159. if (n <= 0) {
  10160. if (n == 0) {
  10161. error_ = Error::ConnectionClosed;
  10162. } else {
  10163. error_ = Error::Read;
  10164. }
  10165. return n;
  10166. } else if (n <= static_cast<ssize_t>(size)) {
  10167. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  10168. return n;
  10169. } else {
  10170. memcpy(ptr, read_buff_.data(), size);
  10171. read_buff_off_ = size;
  10172. read_buff_content_size_ = static_cast<size_t>(n);
  10173. return static_cast<ssize_t>(size);
  10174. }
  10175. } else {
  10176. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  10177. if (n <= 0) {
  10178. if (n == 0) {
  10179. error_ = Error::ConnectionClosed;
  10180. } else {
  10181. error_ = Error::Read;
  10182. }
  10183. }
  10184. return n;
  10185. }
  10186. }
  10187. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  10188. if (!wait_writable()) { return -1; }
  10189. #if defined(_WIN32) && !defined(_WIN64)
  10190. size =
  10191. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  10192. #endif
  10193. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  10194. }
  10195. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  10196. int &port) const {
  10197. return detail::get_remote_ip_and_port(sock_, ip, port);
  10198. }
  10199. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  10200. int &port) const {
  10201. return detail::get_local_ip_and_port(sock_, ip, port);
  10202. }
  10203. inline socket_t SocketStream::socket() const { return sock_; }
  10204. inline time_t SocketStream::duration() const {
  10205. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10206. std::chrono::steady_clock::now() - start_time_)
  10207. .count();
  10208. }
  10209. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  10210. read_timeout_sec_ = sec;
  10211. read_timeout_usec_ = usec;
  10212. }
  10213. // Buffer stream implementation
  10214. inline bool BufferStream::is_readable() const { return true; }
  10215. inline bool BufferStream::wait_readable() const { return true; }
  10216. inline bool BufferStream::wait_writable() const { return true; }
  10217. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  10218. #if defined(_MSC_VER) && _MSC_VER < 1910
  10219. auto len_read = buffer._Copy_s(ptr, size, size, position);
  10220. #else
  10221. auto len_read = buffer.copy(ptr, size, position);
  10222. #endif
  10223. position += static_cast<size_t>(len_read);
  10224. return static_cast<ssize_t>(len_read);
  10225. }
  10226. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  10227. buffer.append(ptr, size);
  10228. return static_cast<ssize_t>(size);
  10229. }
  10230. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  10231. int & /*port*/) const {}
  10232. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  10233. int & /*port*/) const {}
  10234. inline socket_t BufferStream::socket() const { return 0; }
  10235. inline time_t BufferStream::duration() const { return 0; }
  10236. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  10237. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  10238. : MatcherBase(pattern) {
  10239. constexpr const char marker[] = "/:";
  10240. // One past the last ending position of a path param substring
  10241. std::size_t last_param_end = 0;
  10242. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10243. // Needed to ensure that parameter names are unique during matcher
  10244. // construction
  10245. // If exceptions are disabled, only last duplicate path
  10246. // parameter will be set
  10247. std::unordered_set<std::string> param_name_set;
  10248. #endif
  10249. while (true) {
  10250. const auto marker_pos = pattern.find(
  10251. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  10252. if (marker_pos == std::string::npos) { break; }
  10253. static_fragments_.push_back(
  10254. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  10255. const auto param_name_start = marker_pos + str_len(marker);
  10256. auto sep_pos = pattern.find(separator, param_name_start);
  10257. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  10258. auto param_name =
  10259. pattern.substr(param_name_start, sep_pos - param_name_start);
  10260. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10261. if (param_name_set.find(param_name) != param_name_set.cend()) {
  10262. std::string msg = "Encountered path parameter '" + param_name +
  10263. "' multiple times in route pattern '" + pattern + "'.";
  10264. throw std::invalid_argument(msg);
  10265. }
  10266. #endif
  10267. param_names_.push_back(std::move(param_name));
  10268. last_param_end = sep_pos + 1;
  10269. }
  10270. if (last_param_end < pattern.length()) {
  10271. static_fragments_.push_back(pattern.substr(last_param_end));
  10272. }
  10273. }
  10274. inline bool PathParamsMatcher::match(Request &request) const {
  10275. request.matches = std::smatch();
  10276. request.path_params.clear();
  10277. // A pattern without parameters is just a literal path to compare against
  10278. if (param_names_.empty()) { return request.path == pattern(); }
  10279. request.path_params.reserve(param_names_.size());
  10280. // One past the position at which the path matched the pattern last time
  10281. std::size_t starting_pos = 0;
  10282. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  10283. const auto &fragment = static_fragments_[i];
  10284. if (starting_pos + fragment.length() > request.path.length()) {
  10285. return false;
  10286. }
  10287. // Avoid unnecessary allocation by using strncmp instead of substr +
  10288. // comparison
  10289. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  10290. fragment.length()) != 0) {
  10291. return false;
  10292. }
  10293. starting_pos += fragment.length();
  10294. // Should only happen when we have a static fragment after a param
  10295. // Example: '/users/:id/subscriptions'
  10296. // The 'subscriptions' fragment here does not have a corresponding param
  10297. if (i >= param_names_.size()) { continue; }
  10298. auto sep_pos = request.path.find(separator, starting_pos);
  10299. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  10300. const auto &param_name = param_names_[i];
  10301. request.path_params.emplace(
  10302. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  10303. // Mark everything up to '/' as matched
  10304. starting_pos = sep_pos + 1;
  10305. }
  10306. // Returns false if the path is longer than the pattern
  10307. return starting_pos >= request.path.length();
  10308. }
  10309. inline bool RegexMatcher::match(Request &request) const {
  10310. request.path_params.clear();
  10311. // See CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH: an overlong path is treated as
  10312. // a non-match rather than risking a stack overflow in std::regex_match.
  10313. if (request.path.length() > CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH) {
  10314. return false;
  10315. }
  10316. return std::regex_match(request.path, request.matches, regex_);
  10317. }
  10318. // Enclose IPv6 address in brackets if needed
  10319. inline std::string prepare_host_string(const std::string &host) {
  10320. // Enclose IPv6 address in brackets (but not if already enclosed)
  10321. if (host.find(':') == std::string::npos ||
  10322. (!host.empty() && host[0] == '[')) {
  10323. // IPv4, hostname, or already bracketed IPv6
  10324. return host;
  10325. } else {
  10326. // IPv6 address without brackets
  10327. return "[" + host + "]";
  10328. }
  10329. }
  10330. inline std::string make_host_and_port_string(const std::string &host, int port,
  10331. bool is_ssl) {
  10332. auto result = prepare_host_string(host);
  10333. // Append port if not default
  10334. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  10335. ; // do nothing
  10336. } else {
  10337. result += ":" + std::to_string(port);
  10338. }
  10339. return result;
  10340. }
  10341. // Create "host:port" string always including port number (for CONNECT method)
  10342. inline std::string
  10343. make_host_and_port_string_always_port(const std::string &host, int port) {
  10344. return prepare_host_string(host) + ":" + std::to_string(port);
  10345. }
  10346. // Value for the Host header a client sends when the caller supplied none.
  10347. // Only the value: callers decide where in their header list it goes.
  10348. inline std::string make_default_host_header_value(const std::string &host,
  10349. int port, bool is_ssl,
  10350. int address_family) {
  10351. if (address_family == AF_UNIX) { return "localhost"; }
  10352. return make_host_and_port_string(host, port, is_ssl);
  10353. }
  10354. inline void add_default_user_agent_header(Request &req) {
  10355. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10356. if (!req.has_header("User-Agent")) {
  10357. req.set_header("User-Agent",
  10358. std::string("cpp-httplib/") + CPPHTTPLIB_VERSION);
  10359. }
  10360. #else
  10361. (void)req;
  10362. #endif
  10363. }
  10364. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  10365. NormalizedTarget normalize_target(const std::string &host);
  10366. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  10367. bool host_matches_no_proxy(const NormalizedTarget &target,
  10368. const std::vector<NoProxyEntry> &entries);
  10369. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  10370. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  10371. if (prefix_bits == 0) { return true; }
  10372. int full_bytes = prefix_bits / 8;
  10373. int rem_bits = prefix_bits % 8;
  10374. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  10375. static_cast<size_t>(full_bytes)) != 0) {
  10376. return false;
  10377. }
  10378. if (rem_bits == 0) { return true; }
  10379. auto i = static_cast<size_t>(full_bytes);
  10380. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  10381. return (ip[i] & mask) == (net[i] & mask);
  10382. }
  10383. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  10384. if (token.empty()) { return false; }
  10385. if (token == "*") {
  10386. out.kind = NoProxyKind::Wildcard;
  10387. return true;
  10388. }
  10389. auto slash = token.find('/');
  10390. std::string addr_part =
  10391. (slash == std::string::npos) ? token : token.substr(0, slash);
  10392. std::string prefix_part =
  10393. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  10394. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  10395. // don't silently treat it as a /32 (or /128).
  10396. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  10397. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  10398. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  10399. // when brackets are present.
  10400. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  10401. addr_part.back() == ']';
  10402. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  10403. if (!bracketed) {
  10404. struct in_addr v4;
  10405. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  10406. int prefix = 32;
  10407. if (!prefix_part.empty()) {
  10408. auto r = from_chars(prefix_part.data(),
  10409. prefix_part.data() + prefix_part.size(), prefix);
  10410. if (r.ec != std::errc{} ||
  10411. r.ptr != prefix_part.data() + prefix_part.size()) {
  10412. return false;
  10413. }
  10414. if (prefix < 0 || prefix > 32) { return false; }
  10415. }
  10416. out.kind = NoProxyKind::IPv4Cidr;
  10417. std::memcpy(out.net.data(), &v4, sizeof(v4));
  10418. out.prefix_bits = prefix;
  10419. return true;
  10420. }
  10421. }
  10422. struct in6_addr v6;
  10423. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  10424. int prefix = 128;
  10425. if (!prefix_part.empty()) {
  10426. auto r = from_chars(prefix_part.data(),
  10427. prefix_part.data() + prefix_part.size(), prefix);
  10428. if (r.ec != std::errc{} ||
  10429. r.ptr != prefix_part.data() + prefix_part.size()) {
  10430. return false;
  10431. }
  10432. if (prefix < 0 || prefix > 128) { return false; }
  10433. }
  10434. out.kind = NoProxyKind::IPv6Cidr;
  10435. std::memcpy(out.net.data(), &v6, sizeof(v6));
  10436. out.prefix_bits = prefix;
  10437. return true;
  10438. }
  10439. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  10440. // the entry is malformed — don't fall through to the hostname branch.
  10441. if (bracketed) { return false; }
  10442. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  10443. if (slash != std::string::npos) { return false; }
  10444. // Port-specific entries (host:port) are not supported.
  10445. if (token.find(':') != std::string::npos) { return false; }
  10446. std::string hostname = case_ignore::to_lower(token);
  10447. while (!hostname.empty() && hostname.front() == '.') {
  10448. hostname.erase(hostname.begin());
  10449. }
  10450. while (!hostname.empty() && hostname.back() == '.') {
  10451. hostname.pop_back();
  10452. }
  10453. if (hostname.empty()) { return false; }
  10454. out.kind = NoProxyKind::HostnameSuffix;
  10455. out.hostname_pattern = std::move(hostname);
  10456. return true;
  10457. }
  10458. inline NormalizedTarget normalize_target(const std::string &host) {
  10459. NormalizedTarget t;
  10460. std::string h = host;
  10461. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  10462. h = h.substr(1, h.size() - 2);
  10463. }
  10464. // Strip a single trailing dot so "example.com." canonicalizes to
  10465. // "example.com".
  10466. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  10467. t.hostname = case_ignore::to_lower(h);
  10468. if (!t.hostname.empty()) {
  10469. struct in_addr v4;
  10470. struct in6_addr v6;
  10471. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  10472. t.is_ipv4 = true;
  10473. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  10474. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  10475. t.is_ipv6 = true;
  10476. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  10477. }
  10478. }
  10479. return t;
  10480. }
  10481. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  10482. const std::vector<NoProxyEntry> &entries) {
  10483. if (target.hostname.empty()) { return false; }
  10484. for (const auto &e : entries) {
  10485. switch (e.kind) {
  10486. case NoProxyKind::Wildcard: return true;
  10487. case NoProxyKind::IPv4Cidr:
  10488. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10489. return true;
  10490. }
  10491. break;
  10492. case NoProxyKind::IPv6Cidr:
  10493. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10494. return true;
  10495. }
  10496. break;
  10497. case NoProxyKind::HostnameSuffix:
  10498. if (target.is_ipv4 || target.is_ipv6) { break; }
  10499. if (target.hostname == e.hostname_pattern) { return true; }
  10500. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  10501. // an entry of "example.com".
  10502. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  10503. auto offset = target.hostname.size() - e.hostname_pattern.size();
  10504. if (target.hostname[offset - 1] == '.' &&
  10505. target.hostname.compare(offset, e.hostname_pattern.size(),
  10506. e.hostname_pattern) == 0) {
  10507. return true;
  10508. }
  10509. }
  10510. break;
  10511. }
  10512. }
  10513. return false;
  10514. }
  10515. template <typename T>
  10516. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  10517. T header_writer, Error &error) {
  10518. for (const auto &h : headers) {
  10519. if (!detail::fields::is_field_valid(h.first, h.second)) {
  10520. error = Error::InvalidHeaders;
  10521. return false;
  10522. }
  10523. }
  10524. if (header_writer(strm, headers) <= 0) {
  10525. error = Error::Write;
  10526. return false;
  10527. }
  10528. return true;
  10529. }
  10530. } // namespace detail
  10531. /*
  10532. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  10533. */
  10534. #ifdef CPPHTTPLIB_SSL_ENABLED
  10535. namespace detail {
  10536. // SSL socket stream implementation
  10537. inline SSLSocketStream::SSLSocketStream(
  10538. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  10539. time_t read_timeout_usec, time_t write_timeout_sec,
  10540. time_t write_timeout_usec, time_t max_timeout_msec,
  10541. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10542. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10543. read_timeout_usec_(read_timeout_usec),
  10544. write_timeout_sec_(write_timeout_sec),
  10545. write_timeout_usec_(write_timeout_usec),
  10546. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  10547. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10548. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  10549. // Note: create_session() also clears this, but SSLClient currently
  10550. // uses ssl_new() which does not. Until full TLS API migration is complete,
  10551. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  10552. // SSL session was created.
  10553. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  10554. #endif
  10555. }
  10556. inline SSLSocketStream::~SSLSocketStream() = default;
  10557. inline bool SSLSocketStream::is_readable() const {
  10558. return tls::pending(session_) > 0;
  10559. }
  10560. inline bool SSLSocketStream::wait_readable() const {
  10561. if (max_timeout_msec_ <= 0) {
  10562. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10563. }
  10564. time_t read_timeout_sec;
  10565. time_t read_timeout_usec;
  10566. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10567. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10568. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10569. }
  10570. inline bool SSLSocketStream::wait_writable() const {
  10571. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  10572. !tls::is_peer_closed(session_, sock_);
  10573. }
  10574. inline bool SSLSocketStream::ensure_readable() {
  10575. if (readable_hint_) {
  10576. readable_hint_ = false;
  10577. return true;
  10578. }
  10579. return wait_readable();
  10580. }
  10581. inline bool SSLSocketStream::is_peer_alive() const {
  10582. return !tls::is_peer_closed(session_, sock_);
  10583. }
  10584. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  10585. if (tls::pending(session_) > 0) {
  10586. tls::TlsError err;
  10587. auto ret = tls::read(session_, ptr, size, err);
  10588. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10589. error_ = Error::ConnectionClosed;
  10590. }
  10591. return ret;
  10592. } else if (ensure_readable()) {
  10593. tls::TlsError err;
  10594. auto ret = tls::read(session_, ptr, size, err);
  10595. if (ret < 0) {
  10596. auto n = 1000;
  10597. #ifdef _WIN32
  10598. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  10599. (err.code == tls::ErrorCode::SyscallError &&
  10600. WSAGetLastError() == WSAETIMEDOUT))) {
  10601. #else
  10602. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  10603. #endif
  10604. if (tls::pending(session_) > 0) {
  10605. return tls::read(session_, ptr, size, err);
  10606. } else if (wait_readable()) {
  10607. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10608. ret = tls::read(session_, ptr, size, err);
  10609. if (ret >= 0) { return ret; }
  10610. } else {
  10611. break;
  10612. }
  10613. }
  10614. assert(ret < 0);
  10615. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10616. error_ = Error::ConnectionClosed;
  10617. }
  10618. return ret;
  10619. } else {
  10620. error_ = Error::Timeout;
  10621. return -1;
  10622. }
  10623. }
  10624. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  10625. if (wait_writable()) {
  10626. auto handle_size =
  10627. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10628. tls::TlsError err;
  10629. auto ret = tls::write(session_, ptr, handle_size, err);
  10630. if (ret < 0) {
  10631. auto n = 1000;
  10632. #ifdef _WIN32
  10633. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  10634. (err.code == tls::ErrorCode::SyscallError &&
  10635. WSAGetLastError() == WSAETIMEDOUT))) {
  10636. #else
  10637. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  10638. #endif
  10639. if (wait_writable()) {
  10640. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10641. ret = tls::write(session_, ptr, handle_size, err);
  10642. if (ret >= 0) { return ret; }
  10643. } else {
  10644. break;
  10645. }
  10646. }
  10647. assert(ret < 0);
  10648. }
  10649. return ret;
  10650. }
  10651. return -1;
  10652. }
  10653. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  10654. int &port) const {
  10655. detail::get_remote_ip_and_port(sock_, ip, port);
  10656. }
  10657. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  10658. int &port) const {
  10659. detail::get_local_ip_and_port(sock_, ip, port);
  10660. }
  10661. inline socket_t SSLSocketStream::socket() const { return sock_; }
  10662. inline time_t SSLSocketStream::duration() const {
  10663. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10664. std::chrono::steady_clock::now() - start_time_)
  10665. .count();
  10666. }
  10667. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  10668. read_timeout_sec_ = sec;
  10669. read_timeout_usec_ = usec;
  10670. }
  10671. inline WebSocketSSLStream::WebSocketSSLStream(socket_t sock,
  10672. tls::session_t session,
  10673. time_t read_timeout_sec,
  10674. time_t read_timeout_usec,
  10675. time_t write_timeout_sec,
  10676. time_t write_timeout_usec)
  10677. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10678. read_timeout_usec_(read_timeout_usec),
  10679. write_timeout_sec_(write_timeout_sec),
  10680. write_timeout_usec_(write_timeout_usec),
  10681. start_time_(std::chrono::steady_clock::now()) {
  10682. // The receive and send paths run on different threads, so each TLS call is
  10683. // driven in non-blocking mode and readiness is awaited with select()
  10684. // outside the session lock. Set the socket non-blocking once here; it is
  10685. // never flipped back, so no thread races on the flag.
  10686. detail::set_nonblocking(sock_, true);
  10687. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10688. SSL_clear_mode(static_cast<SSL *>(session_), SSL_MODE_AUTO_RETRY);
  10689. #endif
  10690. }
  10691. inline WebSocketSSLStream::~WebSocketSSLStream() = default;
  10692. inline bool WebSocketSSLStream::is_readable() const {
  10693. std::lock_guard<std::mutex> guard(session_mutex_);
  10694. return tls::pending(session_) > 0;
  10695. }
  10696. inline bool WebSocketSSLStream::wait_readable() const {
  10697. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10698. }
  10699. inline bool WebSocketSSLStream::wait_writable() const {
  10700. // Unlike SSLSocketStream, this deliberately does not call is_peer_closed():
  10701. // that probe toggles the socket's blocking flag, which would race with the
  10702. // concurrent reader on a permanently non-blocking socket.
  10703. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  10704. }
  10705. inline ssize_t WebSocketSSLStream::read(char *ptr, size_t size) {
  10706. tls::TlsError err;
  10707. auto n = 1000;
  10708. while (--n >= 0) {
  10709. {
  10710. std::lock_guard<std::mutex> guard(session_mutex_);
  10711. auto ret = tls::read(session_, ptr, size, err);
  10712. if (ret > 0) { return ret; }
  10713. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10714. error_ = Error::ConnectionClosed;
  10715. return ret;
  10716. }
  10717. }
  10718. // ret < 0. On a non-blocking socket a TLS read can stop needing either
  10719. // direction: the send path shares this session, so output it left pending
  10720. // has to be flushed before more input can be decrypted. Anything else is
  10721. // a hard error.
  10722. auto needs_readable = err.code == tls::ErrorCode::WantRead;
  10723. #ifdef _WIN32
  10724. // On Windows a socket timeout surfaces as a syscall error, not WantRead.
  10725. needs_readable =
  10726. needs_readable || (err.code == tls::ErrorCode::SyscallError &&
  10727. WSAGetLastError() == WSAETIMEDOUT);
  10728. #endif
  10729. if (!needs_readable && err.code != tls::ErrorCode::WantWrite) {
  10730. error_ = Error::Read;
  10731. return -1;
  10732. }
  10733. if (!(needs_readable ? wait_readable() : wait_writable())) {
  10734. error_ = Error::Timeout;
  10735. return -1;
  10736. }
  10737. }
  10738. // Out of retries. Recording a reason matters: a caller that reads get_error()
  10739. // to tell a timeout from a close would otherwise see whatever the previous
  10740. // failure left behind (error_ is never cleared on success).
  10741. error_ = Error::Read;
  10742. return -1;
  10743. }
  10744. inline ssize_t WebSocketSSLStream::write(const char *ptr, size_t size) {
  10745. auto handle_size = std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10746. tls::TlsError err;
  10747. auto n = 1000;
  10748. while (--n >= 0) {
  10749. {
  10750. std::lock_guard<std::mutex> guard(session_mutex_);
  10751. auto ret = tls::write(session_, ptr, handle_size, err);
  10752. if (ret >= 0) { return ret; }
  10753. }
  10754. // ret < 0. As in read(), either direction can be needed: a renegotiation
  10755. // or a post-handshake message must be consumed before the record goes
  10756. // out. Anything else is a hard error.
  10757. auto needs_writable = err.code == tls::ErrorCode::WantWrite;
  10758. #ifdef _WIN32
  10759. // On Windows a socket timeout surfaces as a syscall error, not WantWrite.
  10760. needs_writable =
  10761. needs_writable || (err.code == tls::ErrorCode::SyscallError &&
  10762. WSAGetLastError() == WSAETIMEDOUT);
  10763. #endif
  10764. if (!needs_writable && err.code != tls::ErrorCode::WantRead) { return -1; }
  10765. if (!(needs_writable ? wait_writable() : wait_readable())) { return -1; }
  10766. }
  10767. return -1;
  10768. }
  10769. inline void WebSocketSSLStream::get_remote_ip_and_port(std::string &ip,
  10770. int &port) const {
  10771. detail::get_remote_ip_and_port(sock_, ip, port);
  10772. }
  10773. inline void WebSocketSSLStream::get_local_ip_and_port(std::string &ip,
  10774. int &port) const {
  10775. detail::get_local_ip_and_port(sock_, ip, port);
  10776. }
  10777. inline socket_t WebSocketSSLStream::socket() const { return sock_; }
  10778. inline time_t WebSocketSSLStream::duration() const {
  10779. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10780. std::chrono::steady_clock::now() - start_time_)
  10781. .count();
  10782. }
  10783. inline void WebSocketSSLStream::set_read_timeout(time_t sec, time_t usec) {
  10784. read_timeout_sec_ = sec;
  10785. read_timeout_usec_ = usec;
  10786. }
  10787. } // namespace detail
  10788. #endif // CPPHTTPLIB_SSL_ENABLED
  10789. /*
  10790. * Group 4: Server implementation
  10791. */
  10792. // HTTP server implementation
  10793. inline Server::Server()
  10794. : new_task_queue([] {
  10795. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  10796. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  10797. }) {
  10798. #ifndef _WIN32
  10799. signal(SIGPIPE, SIG_IGN);
  10800. #endif
  10801. }
  10802. inline Server::~Server() = default;
  10803. inline std::unique_ptr<detail::MatcherBase>
  10804. Server::make_matcher(const std::string &pattern) {
  10805. // Path params take precedence, so "/users/:id/(.*)" keeps being matched as
  10806. // a path params pattern
  10807. if (pattern.find("/:") != std::string::npos) {
  10808. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  10809. }
  10810. // A pattern with no regex metacharacter only has to be compared literally,
  10811. // which is what PathParamsMatcher already does when it captures no
  10812. // parameter, so std::regex is only worth building for the patterns that
  10813. // actually need it
  10814. if (pattern.find_first_of(".^$|()[]{}*+?\\") == std::string::npos) {
  10815. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  10816. }
  10817. return detail::make_unique<detail::RegexMatcher>(pattern);
  10818. }
  10819. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  10820. return add_handler(get_handlers_, pattern, std::move(handler));
  10821. }
  10822. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  10823. return add_handler(post_handlers_, pattern, std::move(handler));
  10824. }
  10825. inline Server &Server::Post(const std::string &pattern,
  10826. HandlerWithContentReader handler) {
  10827. return add_handler(post_handlers_for_content_reader_, pattern,
  10828. std::move(handler));
  10829. }
  10830. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  10831. return add_handler(put_handlers_, pattern, std::move(handler));
  10832. }
  10833. inline Server &Server::Put(const std::string &pattern,
  10834. HandlerWithContentReader handler) {
  10835. return add_handler(put_handlers_for_content_reader_, pattern,
  10836. std::move(handler));
  10837. }
  10838. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  10839. return add_handler(patch_handlers_, pattern, std::move(handler));
  10840. }
  10841. inline Server &Server::Patch(const std::string &pattern,
  10842. HandlerWithContentReader handler) {
  10843. return add_handler(patch_handlers_for_content_reader_, pattern,
  10844. std::move(handler));
  10845. }
  10846. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  10847. return add_handler(delete_handlers_, pattern, std::move(handler));
  10848. }
  10849. inline Server &Server::Delete(const std::string &pattern,
  10850. HandlerWithContentReader handler) {
  10851. return add_handler(delete_handlers_for_content_reader_, pattern,
  10852. std::move(handler));
  10853. }
  10854. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  10855. return add_handler(options_handlers_, pattern, std::move(handler));
  10856. }
  10857. inline const std::set<std::string> &Server::builtin_methods() {
  10858. thread_local const std::set<std::string> methods{
  10859. "GET", "HEAD", "POST", "PUT", "DELETE",
  10860. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10861. return methods;
  10862. }
  10863. inline Server::CustomHandlerEntry *
  10864. Server::custom_entry_for_registration(const std::string &method) {
  10865. // Built-in methods are refused for two different reasons. GET, HEAD, POST,
  10866. // PUT, DELETE, OPTIONS and PATCH are dispatched by the if/else chain in
  10867. // routing() before the custom tables are consulted, so a route registered
  10868. // for one of them could never fire. CONNECT, TRACE and PRI have no branch
  10869. // there and would be reachable, but they carry protocol-level meaning
  10870. // (tunnel setup, request echo, the HTTP/2 connection preface) that this
  10871. // library does not route.
  10872. if (!detail::fields::is_token(method) || builtin_methods().count(method)) {
  10873. output_error_log(Error::InvalidHTTPMethod, nullptr);
  10874. has_invalid_registration_ = true;
  10875. return nullptr;
  10876. }
  10877. return &custom_handlers_[method];
  10878. }
  10879. inline Server &Server::CustomRoute(const std::string &method,
  10880. const std::string &pattern,
  10881. Handler handler) {
  10882. auto *entry = custom_entry_for_registration(method);
  10883. if (!entry) { return *this; }
  10884. return add_handler(entry->handlers, pattern, std::move(handler));
  10885. }
  10886. inline Server &Server::CustomRoute(const std::string &method,
  10887. const std::string &pattern,
  10888. HandlerWithContentReader handler) {
  10889. auto *entry = custom_entry_for_registration(method);
  10890. if (!entry) { return *this; }
  10891. return add_handler(entry->handlers_for_content_reader, pattern,
  10892. std::move(handler));
  10893. }
  10894. inline const Server::CustomHandlerEntry *
  10895. Server::find_custom_entry(const std::string &method) const {
  10896. // find() alone would be correct here. The empty() check is what keeps the
  10897. // per-request cost off servers that never call CustomRoute(), which is the
  10898. // overwhelmingly common case; keep it rather than walking into the tree.
  10899. if (custom_handlers_.empty()) { return nullptr; }
  10900. auto it = custom_handlers_.find(method);
  10901. return it == custom_handlers_.end() ? nullptr : &it->second;
  10902. }
  10903. inline Server &Server::WebSocket(const std::string &pattern,
  10904. WebSocketHandler handler) {
  10905. websocket_handlers_.push_back(
  10906. {make_matcher(pattern), std::move(handler), nullptr});
  10907. return *this;
  10908. }
  10909. inline Server &Server::WebSocket(const std::string &pattern,
  10910. WebSocketHandler handler,
  10911. SubProtocolSelector sub_protocol_selector) {
  10912. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  10913. std::move(sub_protocol_selector)});
  10914. return *this;
  10915. }
  10916. inline bool Server::set_base_dir(const std::string &dir,
  10917. const std::string &mount_point) {
  10918. return set_mount_point(mount_point, dir);
  10919. }
  10920. inline bool Server::set_mount_point(const std::string &mount_point,
  10921. const std::string &dir, Headers headers) {
  10922. detail::FileStat stat(dir);
  10923. if (stat.is_dir()) {
  10924. std::string mnt = !mount_point.empty() ? mount_point : "/";
  10925. if (!mnt.empty() && mnt[0] == '/') {
  10926. std::string resolved_base;
  10927. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  10928. #if defined(_WIN32)
  10929. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  10930. resolved_base += '\\';
  10931. }
  10932. #else
  10933. if (resolved_base.back() != '/') { resolved_base += '/'; }
  10934. #endif
  10935. }
  10936. base_dirs_.push_back(
  10937. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  10938. return true;
  10939. }
  10940. }
  10941. return false;
  10942. }
  10943. inline bool Server::remove_mount_point(const std::string &mount_point) {
  10944. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  10945. if (it->mount_point == mount_point) {
  10946. base_dirs_.erase(it);
  10947. return true;
  10948. }
  10949. }
  10950. return false;
  10951. }
  10952. inline Server &
  10953. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  10954. const std::string &mime) {
  10955. file_extension_and_mimetype_map_[ext] = mime;
  10956. return *this;
  10957. }
  10958. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  10959. default_file_mimetype_ = mime;
  10960. return *this;
  10961. }
  10962. inline Server &Server::set_file_request_handler(Handler handler) {
  10963. file_request_handler_ = std::move(handler);
  10964. return *this;
  10965. }
  10966. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  10967. std::true_type) {
  10968. error_handler_ = std::move(handler);
  10969. return *this;
  10970. }
  10971. inline Server &Server::set_error_handler_core(Handler handler,
  10972. std::false_type) {
  10973. error_handler_ = [handler](const Request &req, Response &res) {
  10974. handler(req, res);
  10975. return HandlerResponse::Handled;
  10976. };
  10977. return *this;
  10978. }
  10979. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  10980. exception_handler_ = std::move(handler);
  10981. return *this;
  10982. }
  10983. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  10984. pre_routing_handler_ = std::move(handler);
  10985. return *this;
  10986. }
  10987. inline Server &Server::set_post_routing_handler(Handler handler) {
  10988. post_routing_handler_ = std::move(handler);
  10989. return *this;
  10990. }
  10991. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  10992. pre_request_handler_ = std::move(handler);
  10993. return *this;
  10994. }
  10995. inline Server &Server::set_logger(Logger logger) {
  10996. logger_ = std::move(logger);
  10997. return *this;
  10998. }
  10999. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  11000. error_logger_ = std::move(error_logger);
  11001. return *this;
  11002. }
  11003. inline Server &Server::set_pre_compression_logger(Logger logger) {
  11004. pre_compression_logger_ = std::move(logger);
  11005. return *this;
  11006. }
  11007. inline Server &
  11008. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  11009. expect_100_continue_handler_ = std::move(handler);
  11010. return *this;
  11011. }
  11012. inline Server &Server::set_start_handler(StartHandler handler) {
  11013. start_handler_ = std::move(handler);
  11014. return *this;
  11015. }
  11016. inline Server &Server::set_address_family(int family) {
  11017. address_family_ = family;
  11018. return *this;
  11019. }
  11020. inline Server &Server::set_tcp_nodelay(bool on) {
  11021. tcp_nodelay_ = on;
  11022. return *this;
  11023. }
  11024. inline Server &Server::set_ipv6_v6only(bool on) {
  11025. ipv6_v6only_ = on;
  11026. return *this;
  11027. }
  11028. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  11029. socket_options_ = std::move(socket_options);
  11030. return *this;
  11031. }
  11032. inline Server &Server::set_default_headers(Headers headers) {
  11033. default_headers_ = std::move(headers);
  11034. return *this;
  11035. }
  11036. inline Server &Server::set_header_writer(
  11037. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11038. header_writer_ = writer;
  11039. return *this;
  11040. }
  11041. inline Server &
  11042. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  11043. trusted_proxies_ = proxies;
  11044. return *this;
  11045. }
  11046. inline Server &Server::set_keep_alive_max_count(size_t count) {
  11047. keep_alive_max_count_ = count;
  11048. return *this;
  11049. }
  11050. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  11051. keep_alive_timeout_sec_ = sec;
  11052. return *this;
  11053. }
  11054. template <class Rep, class Period>
  11055. inline Server &Server::set_keep_alive_timeout(
  11056. const std::chrono::duration<Rep, Period> &duration) {
  11057. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  11058. set_keep_alive_timeout(sec);
  11059. });
  11060. return *this;
  11061. }
  11062. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  11063. read_timeout_sec_ = sec;
  11064. read_timeout_usec_ = usec;
  11065. return *this;
  11066. }
  11067. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  11068. write_timeout_sec_ = sec;
  11069. write_timeout_usec_ = usec;
  11070. return *this;
  11071. }
  11072. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  11073. idle_interval_sec_ = sec;
  11074. idle_interval_usec_ = usec;
  11075. return *this;
  11076. }
  11077. inline Server &Server::set_payload_max_length(size_t length) {
  11078. payload_max_length_ = length;
  11079. return *this;
  11080. }
  11081. inline Server &Server::set_static_file_compression(bool on) {
  11082. static_file_compression_ = on;
  11083. return *this;
  11084. }
  11085. inline Server &Server::set_static_file_compression_min_length(size_t length) {
  11086. static_file_compression_min_length_ = length;
  11087. return *this;
  11088. }
  11089. inline Server &Server::set_static_file_compression_max_length(size_t length) {
  11090. static_file_compression_max_length_ = length;
  11091. return *this;
  11092. }
  11093. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  11094. websocket_max_missed_pongs_ = count;
  11095. return *this;
  11096. }
  11097. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  11098. websocket_ping_interval_sec_ = sec;
  11099. return *this;
  11100. }
  11101. template <class Rep, class Period>
  11102. inline Server &Server::set_websocket_ping_interval(
  11103. const std::chrono::duration<Rep, Period> &duration) {
  11104. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  11105. set_websocket_ping_interval(sec);
  11106. });
  11107. return *this;
  11108. }
  11109. inline bool Server::bind_to_port(const std::string &host, int port,
  11110. int socket_flags) {
  11111. auto ret = bind_internal(host, port, socket_flags);
  11112. if (ret == -1) { is_decommissioned = true; }
  11113. return ret >= 0;
  11114. }
  11115. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  11116. auto ret = bind_internal(host, 0, socket_flags);
  11117. if (ret == -1) { is_decommissioned = true; }
  11118. return ret;
  11119. }
  11120. inline bool Server::listen_after_bind() { return listen_internal(); }
  11121. inline bool Server::listen(const std::string &host, int port,
  11122. int socket_flags) {
  11123. return bind_to_port(host, port, socket_flags) && listen_internal();
  11124. }
  11125. inline bool Server::is_running() const { return is_running_; }
  11126. inline void Server::wait_until_ready() const {
  11127. while (!is_running_ && !is_decommissioned) {
  11128. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  11129. }
  11130. }
  11131. inline void Server::stop() noexcept {
  11132. // Release the listening socket whether or not the accept loop is running:
  11133. // bind_to_port() without listen_after_bind() still owns the descriptor. The
  11134. // exchange is what makes this safe to call concurrently with the accept loop.
  11135. socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
  11136. if (sock != INVALID_SOCKET) {
  11137. detail::shutdown_socket(sock);
  11138. detail::close_socket(sock);
  11139. }
  11140. is_decommissioned = false;
  11141. }
  11142. inline void Server::decommission() { is_decommissioned = true; }
  11143. inline bool Server::parse_request_line(const char *s, Request &req) const {
  11144. auto len = strlen(s);
  11145. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  11146. len -= 2;
  11147. {
  11148. size_t count = 0;
  11149. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  11150. switch (count) {
  11151. case 0: req.method = std::string(b, e); break;
  11152. case 1: req.target = std::string(b, e); break;
  11153. case 2: req.version = std::string(b, e); break;
  11154. default: break;
  11155. }
  11156. count++;
  11157. });
  11158. if (count != 3) { return false; }
  11159. }
  11160. // A method outside the built-in set is accepted only when a handler has been
  11161. // registered for it with CustomRoute().
  11162. const auto &methods = builtin_methods();
  11163. if (methods.find(req.method) == methods.end() &&
  11164. !find_custom_entry(req.method)) {
  11165. output_error_log(Error::InvalidHTTPMethod, &req);
  11166. return false;
  11167. }
  11168. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  11169. output_error_log(Error::InvalidHTTPVersion, &req);
  11170. return false;
  11171. }
  11172. {
  11173. // Skip URL fragment
  11174. for (size_t i = 0; i < req.target.size(); i++) {
  11175. if (req.target[i] == '#') {
  11176. req.target.erase(i);
  11177. break;
  11178. }
  11179. }
  11180. detail::divide(req.target, '?',
  11181. [&](const char *lhs_data, std::size_t lhs_size,
  11182. const char *rhs_data, std::size_t rhs_size) {
  11183. req.path =
  11184. decode_path_component(std::string(lhs_data, lhs_size));
  11185. detail::parse_query_text(rhs_data, rhs_size, req.params);
  11186. });
  11187. }
  11188. return true;
  11189. }
  11190. inline bool Server::write_response(Stream &strm, bool close_connection,
  11191. Request &req, Response &res) {
  11192. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  11193. // incorrectly to the error content.
  11194. req.ranges.clear();
  11195. return write_response_core(strm, close_connection, req, res, false);
  11196. }
  11197. inline bool Server::write_response_with_content(Stream &strm,
  11198. bool close_connection,
  11199. const Request &req,
  11200. Response &res) {
  11201. return write_response_core(strm, close_connection, req, res, true);
  11202. }
  11203. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  11204. const Request &req, Response &res,
  11205. bool need_apply_ranges) {
  11206. assert(res.status != -1);
  11207. if (400 <= res.status && error_handler_ &&
  11208. error_handler_(req, res) == HandlerResponse::Handled) {
  11209. need_apply_ranges = true;
  11210. }
  11211. std::string content_type;
  11212. std::string boundary;
  11213. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  11214. // Prepare additional headers
  11215. if (close_connection ||
  11216. detail::has_header_token(req.headers, "Connection", "close") ||
  11217. 400 <= res.status) { // Don't leave connections open after errors
  11218. res.set_header("Connection", "close");
  11219. } else {
  11220. std::string s = "timeout=";
  11221. s += std::to_string(keep_alive_timeout_sec_);
  11222. s += ", max=";
  11223. s += std::to_string(keep_alive_max_count_);
  11224. res.set_header("Keep-Alive", s);
  11225. }
  11226. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  11227. !res.has_header("Content-Type")) {
  11228. res.set_header("Content-Type", "text/plain");
  11229. }
  11230. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  11231. !res.has_header("Content-Length")) {
  11232. res.set_header("Content-Length", "0");
  11233. }
  11234. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  11235. res.set_header("Accept-Ranges", "bytes");
  11236. }
  11237. if (post_routing_handler_) { post_routing_handler_(req, res); }
  11238. // Response line and headers
  11239. detail::BufferStream bstrm;
  11240. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  11241. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  11242. // Combine small body with headers to reduce write syscalls
  11243. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  11244. bstrm.write(res.body.data(), res.body.size());
  11245. }
  11246. // Log before writing to avoid race condition with client-side code that
  11247. // accesses logger-captured data immediately after receiving the response.
  11248. output_log(req, res);
  11249. // Flush buffer
  11250. auto &data = bstrm.get_buffer();
  11251. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  11252. // Streaming body
  11253. auto ret = true;
  11254. if (req.method != "HEAD" && res.content_provider_) {
  11255. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  11256. res.content_provider_success_ = true;
  11257. } else {
  11258. ret = false;
  11259. }
  11260. }
  11261. return ret;
  11262. }
  11263. inline bool
  11264. Server::write_content_with_provider(Stream &strm, const Request &req,
  11265. Response &res, const std::string &boundary,
  11266. const std::string &content_type) {
  11267. auto is_shutting_down = [this]() {
  11268. return this->svr_sock_ == INVALID_SOCKET;
  11269. };
  11270. if (res.content_length_ > 0) {
  11271. // Only a 206 response is served as a partial representation, matching the
  11272. // condition `apply_ranges()` used to decide the Content-Length and the
  11273. // multipart boundary. Since `detail::range_error()` validates `req.ranges`
  11274. // only for a 2xx status, slicing under any other status would write a body
  11275. // that disagrees with the header already sent, from an unchecked offset.
  11276. auto is_partial =
  11277. !req.ranges.empty() && res.status == StatusCode::PartialContent_206;
  11278. if (!is_partial) {
  11279. return detail::write_content(strm, res.content_provider_, 0,
  11280. res.content_length_, is_shutting_down);
  11281. } else if (req.ranges.size() == 1) {
  11282. auto offset_and_length = detail::get_range_offset_and_length(
  11283. req.ranges[0], res.content_length_);
  11284. return detail::write_content(strm, res.content_provider_,
  11285. offset_and_length.first,
  11286. offset_and_length.second, is_shutting_down);
  11287. } else {
  11288. return detail::write_multipart_ranges_data(
  11289. strm, req, res, boundary, content_type, res.content_length_,
  11290. is_shutting_down);
  11291. }
  11292. } else {
  11293. if (res.is_chunked_content_provider_) {
  11294. // Use the coding `apply_ranges()` chose when it wrote the headers;
  11295. // re-negotiating here would disagree with them, e.g. once a handler's
  11296. // own Content-Encoding header suppresses the negotiation.
  11297. auto compressor = detail::make_compressor(res.content_coding_);
  11298. if (!compressor) {
  11299. compressor = detail::make_unique<detail::nocompressor>();
  11300. }
  11301. return detail::write_content_chunked(strm, res.content_provider_,
  11302. is_shutting_down, *compressor);
  11303. } else {
  11304. return detail::write_content_without_length(strm, res.content_provider_,
  11305. is_shutting_down);
  11306. }
  11307. }
  11308. }
  11309. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  11310. FormFields::iterator cur_field;
  11311. FormFiles::iterator cur_file;
  11312. auto is_text_field = false;
  11313. size_t count = 0;
  11314. if (read_content_core(
  11315. strm, req, res,
  11316. // Regular
  11317. [&](const char *buf, size_t n) {
  11318. // Prevent arithmetic overflow when checking sizes.
  11319. // Avoid computing (req.body.size() + n) directly because
  11320. // adding two unsigned `size_t` values can wrap around and
  11321. // produce a small result instead of indicating overflow.
  11322. // Instead, check using subtraction: ensure `n` does not
  11323. // exceed the remaining capacity `max_size() - size()`.
  11324. if (req.body.size() >= req.body.max_size() ||
  11325. n > req.body.max_size() - req.body.size()) {
  11326. return false;
  11327. }
  11328. // Limit decompressed body size to payload_max_length_ to protect
  11329. // against "zip bomb" attacks where a small compressed payload
  11330. // decompresses to a massive size.
  11331. if (payload_max_length_ > 0 &&
  11332. (req.body.size() >= payload_max_length_ ||
  11333. n > payload_max_length_ - req.body.size())) {
  11334. return false;
  11335. }
  11336. req.body.append(buf, n);
  11337. return true;
  11338. },
  11339. // Multipart FormData
  11340. [&](const FormData &file) {
  11341. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  11342. output_error_log(Error::TooManyFormDataFiles, &req);
  11343. return false;
  11344. }
  11345. if (file.filename.empty()) {
  11346. cur_field = req.form.fields.emplace(
  11347. file.name, FormField{file.name, file.content, file.headers});
  11348. is_text_field = true;
  11349. } else {
  11350. cur_file = req.form.files.emplace(file.name, file);
  11351. is_text_field = false;
  11352. }
  11353. return true;
  11354. },
  11355. [&](const char *buf, size_t n) {
  11356. if (is_text_field) {
  11357. auto &content = cur_field->second.content;
  11358. if (content.size() + n > content.max_size()) { return false; }
  11359. content.append(buf, n);
  11360. } else {
  11361. auto &content = cur_file->second.content;
  11362. if (content.size() + n > content.max_size()) { return false; }
  11363. content.append(buf, n);
  11364. }
  11365. return true;
  11366. })) {
  11367. const auto &content_type = req.get_header_value("Content-Type");
  11368. if (detail::extract_media_type(content_type) ==
  11369. "application/x-www-form-urlencoded") {
  11370. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  11371. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  11372. output_error_log(Error::ExceedMaxPayloadSize, &req);
  11373. return false;
  11374. }
  11375. detail::parse_query_text(req.body, req.params);
  11376. }
  11377. return true;
  11378. }
  11379. return false;
  11380. }
  11381. inline bool Server::read_content_with_content_receiver(
  11382. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11383. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  11384. return read_content_core(strm, req, res, std::move(receiver),
  11385. std::move(multipart_header),
  11386. std::move(multipart_receiver));
  11387. }
  11388. inline bool Server::read_content_core(
  11389. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11390. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  11391. detail::FormDataParser multipart_form_data_parser;
  11392. ContentReceiverWithProgress out;
  11393. if (req.is_multipart_form_data()) {
  11394. const auto &content_type = req.get_header_value("Content-Type");
  11395. std::string boundary;
  11396. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  11397. res.status = StatusCode::BadRequest_400;
  11398. output_error_log(Error::MultipartParsing, &req);
  11399. return false;
  11400. }
  11401. multipart_form_data_parser.set_boundary(std::move(boundary));
  11402. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  11403. return multipart_form_data_parser.parse(buf, n, multipart_header,
  11404. multipart_receiver);
  11405. };
  11406. } else {
  11407. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  11408. size_t /*len*/) { return receiver(buf, n); };
  11409. }
  11410. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  11411. // For non-SSL builds we still scan non-persistent connections for stray
  11412. // body bytes so the payload limit is enforced (413). On keep-alive,
  11413. // pending bytes may be the next request (issue #2450), so skip.
  11414. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  11415. if (!req.has_header("Content-Length") &&
  11416. !detail::is_chunked_transfer_encoding(req.headers)) {
  11417. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  11418. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  11419. auto has_data = strm.is_readable();
  11420. if (!has_data) {
  11421. auto s = strm.socket();
  11422. if (s != INVALID_SOCKET) {
  11423. has_data = detail::select_read(s, 0, 0) > 0;
  11424. }
  11425. }
  11426. if (has_data) {
  11427. // Route through the same decompressing reader used by the
  11428. // length-framed and chunked paths below, so payload_max_length_ is
  11429. // enforced on the decompressed size here too instead of only on the
  11430. // compressed wire bytes.
  11431. return detail::read_content(strm, req, payload_max_length_, res.status,
  11432. nullptr, out, true);
  11433. }
  11434. }
  11435. return true;
  11436. }
  11437. #else
  11438. if (!req.has_header("Content-Length") &&
  11439. !detail::is_chunked_transfer_encoding(req.headers)) {
  11440. return true;
  11441. }
  11442. #endif
  11443. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  11444. out, true)) {
  11445. return false;
  11446. }
  11447. req.body_consumed_ = true;
  11448. if (req.is_multipart_form_data()) {
  11449. if (!multipart_form_data_parser.is_valid()) {
  11450. res.status = StatusCode::BadRequest_400;
  11451. output_error_log(Error::MultipartParsing, &req);
  11452. return false;
  11453. }
  11454. }
  11455. return true;
  11456. }
  11457. inline bool Server::handle_file_request(Request &req, Response &res) {
  11458. for (const auto &entry : base_dirs_) {
  11459. // Prefix match, on a path segment boundary. A mount point of "/mount"
  11460. // covers "/mount" and "/mount/...", but must not swallow "/mountdir/...".
  11461. // One that already ends in '/' (the root mount among them) carries its own
  11462. // boundary; set_mount_point() guarantees the mount point is not empty.
  11463. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point) &&
  11464. (entry.mount_point.back() == '/' ||
  11465. req.path.size() == entry.mount_point.size() ||
  11466. req.path[entry.mount_point.size()] == '/')) {
  11467. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  11468. if (detail::is_valid_path(sub_path)) {
  11469. auto path = entry.base_dir + sub_path;
  11470. if (path.back() == '/') { path += "index.html"; }
  11471. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  11472. // but symlinks/junctions can still escape the base directory.
  11473. if (!entry.resolved_base_dir.empty()) {
  11474. std::string resolved_path;
  11475. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  11476. !detail::is_path_within_base(resolved_path,
  11477. entry.resolved_base_dir)) {
  11478. res.status = StatusCode::Forbidden_403;
  11479. return true;
  11480. }
  11481. }
  11482. detail::FileStat stat(path);
  11483. if (stat.is_dir()) {
  11484. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  11485. return true;
  11486. }
  11487. if (stat.is_file()) {
  11488. for (const auto &kv : entry.headers) {
  11489. res.set_header(kv.first, kv.second);
  11490. }
  11491. auto content_type_of = [&]() {
  11492. return detail::find_content_type(
  11493. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  11494. };
  11495. // Only the ETag needs the content type this early, and only to name
  11496. // the coding. Deciding it here would otherwise put a regex in front
  11497. // of the 304 below, which serving a file never used to pay for.
  11498. std::string content_type;
  11499. auto encoding = detail::EncodingType::None;
  11500. if (static_file_compression_) {
  11501. content_type = content_type_of();
  11502. encoding =
  11503. static_file_encoding(req, res, content_type, stat.size());
  11504. }
  11505. // The ETag names the representation actually sent, so a client that
  11506. // cached the compressed form revalidates against the compressed ETag
  11507. // and still gets a 304, while one that took identity keeps the plain
  11508. // ETag.
  11509. auto etag = detail::compute_etag(
  11510. stat, encoding == detail::EncodingType::None
  11511. ? std::string()
  11512. : std::string("-") + detail::encoding_name(encoding));
  11513. if (!etag.empty()) { res.set_header("ETag", etag); }
  11514. auto mtime = stat.mtime();
  11515. auto last_modified = detail::file_mtime_to_http_date(mtime);
  11516. if (!last_modified.empty()) {
  11517. res.set_header("Last-Modified", last_modified);
  11518. }
  11519. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  11520. check_if_range(req, etag, mtime);
  11521. auto mm = std::make_shared<detail::mmap>(path.c_str());
  11522. if (!mm->is_open()) {
  11523. output_error_log(Error::OpenFile, &req);
  11524. return false;
  11525. }
  11526. if (!static_file_compression_) { content_type = content_type_of(); }
  11527. detail::set_file_content_provider(res, mm, content_type, encoding);
  11528. if (req.method != "HEAD" && file_request_handler_) {
  11529. file_request_handler_(req, res);
  11530. }
  11531. return true;
  11532. } else {
  11533. output_error_log(Error::OpenFile, &req);
  11534. }
  11535. }
  11536. }
  11537. }
  11538. return false;
  11539. }
  11540. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  11541. const std::string &etag,
  11542. time_t mtime) const {
  11543. // Handle conditional GET:
  11544. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  11545. // 2. If-Modified-Since is checked only when If-None-Match is absent
  11546. if (req.has_header("If-None-Match")) {
  11547. if (!etag.empty()) {
  11548. auto val =
  11549. detail::get_combined_header_value(req.headers, "If-None-Match");
  11550. // NOTE: We use exact string matching here. This works correctly
  11551. // because our server always generates weak ETags (W/"..."), and
  11552. // clients typically send back the same ETag they received.
  11553. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  11554. // If-None-Match, where W/"x" and "x" would match, but this
  11555. // simplified implementation requires exact matches.
  11556. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  11557. [&](const char *b, const char *e) {
  11558. auto seg_len = static_cast<size_t>(e - b);
  11559. return (seg_len == 1 && *b == '*') ||
  11560. (seg_len == etag.size() &&
  11561. std::equal(b, e, etag.begin()));
  11562. });
  11563. if (ret) {
  11564. res.status = StatusCode::NotModified_304;
  11565. return true;
  11566. }
  11567. }
  11568. } else if (req.has_header("If-Modified-Since")) {
  11569. auto val = req.get_header_value("If-Modified-Since");
  11570. auto t = detail::parse_http_date(val);
  11571. if (t != static_cast<time_t>(-1) && mtime <= t) {
  11572. res.status = StatusCode::NotModified_304;
  11573. return true;
  11574. }
  11575. }
  11576. return false;
  11577. }
  11578. inline bool Server::check_if_range(Request &req, const std::string &etag,
  11579. time_t mtime) const {
  11580. // Handle If-Range for partial content requests (RFC 9110
  11581. // Section 13.1.5). If-Range is only evaluated when Range header is
  11582. // present. If the validator matches, serve partial content; otherwise
  11583. // serve full content.
  11584. if (!req.ranges.empty() && req.has_header("If-Range")) {
  11585. auto val = req.get_header_value("If-Range");
  11586. auto is_valid_range = [&]() {
  11587. if (detail::is_strong_etag(val)) {
  11588. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  11589. // comparison.
  11590. return (!etag.empty() && val == etag);
  11591. } else if (detail::is_weak_etag(val)) {
  11592. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  11593. return false;
  11594. } else {
  11595. // HTTP-date comparison
  11596. auto t = detail::parse_http_date(val);
  11597. return (t != static_cast<time_t>(-1) && mtime <= t);
  11598. }
  11599. };
  11600. if (!is_valid_range()) {
  11601. // Validator doesn't match: ignore Range and serve full content
  11602. req.ranges.clear();
  11603. return false;
  11604. }
  11605. }
  11606. return true;
  11607. }
  11608. inline socket_t
  11609. Server::create_server_socket(const std::string &host, int port,
  11610. int socket_flags,
  11611. SocketOptions socket_options) const {
  11612. return detail::create_socket(
  11613. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  11614. ipv6_v6only_, std::move(socket_options),
  11615. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  11616. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  11617. output_error_log(Error::BindIPAddress, nullptr);
  11618. return false;
  11619. }
  11620. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  11621. output_error_log(Error::Listen, nullptr);
  11622. return false;
  11623. }
  11624. return true;
  11625. });
  11626. }
  11627. inline int Server::bind_internal(const std::string &host, int port,
  11628. int socket_flags) {
  11629. if (is_decommissioned) { return -1; }
  11630. if (!is_valid()) { return -1; }
  11631. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  11632. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  11633. if (port == 0) {
  11634. struct sockaddr_storage addr;
  11635. socklen_t addr_len = sizeof(addr);
  11636. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  11637. &addr_len) == -1) {
  11638. output_error_log(Error::GetSockName, nullptr);
  11639. return -1;
  11640. }
  11641. if (addr.ss_family == AF_INET) {
  11642. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  11643. } else if (addr.ss_family == AF_INET6) {
  11644. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  11645. } else {
  11646. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  11647. return -1;
  11648. }
  11649. } else {
  11650. return port;
  11651. }
  11652. }
  11653. inline bool Server::listen_internal() {
  11654. // A stop() between bind and listen leaves nothing to accept on. Report
  11655. // failure instead of returning success without ever serving, and mark the
  11656. // server decommissioned the way any failed listen does so that a concurrent
  11657. // wait_until_ready() wakes up instead of spinning forever.
  11658. if (is_decommissioned || svr_sock_ == INVALID_SOCKET) {
  11659. is_decommissioned = true;
  11660. return false;
  11661. }
  11662. auto ret = true;
  11663. is_running_ = true;
  11664. auto se = detail::scope_exit([&]() { is_running_ = false; });
  11665. if (start_handler_) { start_handler_(); }
  11666. {
  11667. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  11668. while (svr_sock_ != INVALID_SOCKET) {
  11669. #ifndef _WIN32
  11670. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  11671. #endif
  11672. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  11673. idle_interval_usec_);
  11674. if (val == 0) { // Timeout
  11675. task_queue->on_idle();
  11676. continue;
  11677. }
  11678. #ifndef _WIN32
  11679. }
  11680. #endif
  11681. #if defined _WIN32
  11682. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  11683. // OVERLAPPED
  11684. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  11685. #elif defined SOCK_CLOEXEC
  11686. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  11687. #else
  11688. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  11689. #endif
  11690. if (sock == INVALID_SOCKET) {
  11691. // NOTE: Winsock reports failures through WSAGetLastError() and never
  11692. // touches the CRT errno, so the two have to be asked platform by
  11693. // platform rather than by testing errno here.
  11694. if (detail::is_accept_resource_error()) {
  11695. // The per-process descriptor limit or the network stack's buffer
  11696. // space has been reached. Try to accept new connections after a
  11697. // short sleep.
  11698. std::this_thread::sleep_for(std::chrono::microseconds{1});
  11699. continue;
  11700. } else if (detail::is_accept_transient_error()) {
  11701. continue;
  11702. }
  11703. // Take the descriptor out of svr_sock_ before closing it: a later
  11704. // stop() would otherwise shutdown()/close() a value the OS may have
  11705. // reused, and keep_alive() watches svr_sock_ to notice the server is
  11706. // gone. The exchange also settles the race with a concurrent stop(),
  11707. // since whichever side takes the descriptor closes it exactly once.
  11708. auto listen_sock = svr_sock_.exchange(INVALID_SOCKET);
  11709. if (listen_sock != INVALID_SOCKET) {
  11710. detail::close_socket(listen_sock);
  11711. ret = false;
  11712. output_error_log(Error::Connection, nullptr);
  11713. } else {
  11714. ; // The server socket was closed by user.
  11715. }
  11716. break;
  11717. }
  11718. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  11719. read_timeout_sec_, read_timeout_usec_);
  11720. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  11721. write_timeout_sec_, write_timeout_usec_);
  11722. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  11723. if (!task_queue->enqueue(
  11724. [this, sock]() { process_and_close_socket(sock); })) {
  11725. output_error_log(Error::ResourceExhaustion, nullptr);
  11726. detail::shutdown_socket(sock);
  11727. detail::close_socket(sock);
  11728. }
  11729. }
  11730. task_queue->shutdown();
  11731. }
  11732. is_decommissioned = !ret;
  11733. return ret;
  11734. }
  11735. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  11736. if (pre_routing_handler_ &&
  11737. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  11738. return true;
  11739. }
  11740. // File handler
  11741. if ((req.method == "GET" || req.method == "HEAD") &&
  11742. handle_file_request(req, res)) {
  11743. return true;
  11744. }
  11745. const auto *custom = find_custom_entry(req.method);
  11746. // The second clause mirrors what expect_content() does unconditionally for
  11747. // POST/PUT/PATCH/DELETE: a content reader route fires even when the request
  11748. // carries no body. Without it a body-less PROPFIND (RFC 4918 treats one as
  11749. // `allprop`) would skip its handler and fall through to 404.
  11750. if (detail::expect_content(req) ||
  11751. (custom && !custom->handlers_for_content_reader.empty())) {
  11752. // Content reader handler
  11753. {
  11754. // Track whether the ContentReader was aborted due to the decompressed
  11755. // payload exceeding `payload_max_length_`.
  11756. // The user handler runs after the lambda returns, so we must restore the
  11757. // 413 status if the handler overwrites it.
  11758. bool content_reader_payload_too_large = false;
  11759. ContentReader reader(
  11760. [&](ContentReceiver receiver) {
  11761. auto result = read_content_with_content_receiver(
  11762. strm, req, res, std::move(receiver), nullptr, nullptr);
  11763. if (!result) {
  11764. output_error_log(Error::Read, &req);
  11765. if (res.status == StatusCode::PayloadTooLarge_413) {
  11766. content_reader_payload_too_large = true;
  11767. }
  11768. }
  11769. return result;
  11770. },
  11771. [&](FormDataHeader header, ContentReceiver receiver) {
  11772. auto result = read_content_with_content_receiver(
  11773. strm, req, res, nullptr, std::move(header),
  11774. std::move(receiver));
  11775. if (!result) {
  11776. output_error_log(Error::Read, &req);
  11777. if (res.status == StatusCode::PayloadTooLarge_413) {
  11778. content_reader_payload_too_large = true;
  11779. }
  11780. }
  11781. return result;
  11782. });
  11783. bool dispatched = false;
  11784. if (req.method == "POST") {
  11785. dispatched = dispatch_request_for_content_reader(
  11786. req, res, std::move(reader), post_handlers_for_content_reader_);
  11787. } else if (req.method == "PUT") {
  11788. dispatched = dispatch_request_for_content_reader(
  11789. req, res, std::move(reader), put_handlers_for_content_reader_);
  11790. } else if (req.method == "PATCH") {
  11791. dispatched = dispatch_request_for_content_reader(
  11792. req, res, std::move(reader), patch_handlers_for_content_reader_);
  11793. } else if (req.method == "DELETE") {
  11794. dispatched = dispatch_request_for_content_reader(
  11795. req, res, std::move(reader), delete_handlers_for_content_reader_);
  11796. } else if (custom) {
  11797. dispatched = dispatch_request_for_content_reader(
  11798. req, res, std::move(reader), custom->handlers_for_content_reader);
  11799. }
  11800. if (dispatched) {
  11801. if (content_reader_payload_too_large) {
  11802. // Enforce the limit: override any status the handler may have set
  11803. // and return false so the error path sends a plain 413 response.
  11804. res.status = StatusCode::PayloadTooLarge_413;
  11805. res.body.clear();
  11806. res.content_length_ = 0;
  11807. res.content_provider_ = nullptr;
  11808. return false;
  11809. }
  11810. return true;
  11811. }
  11812. }
  11813. // NOTE: `req.body` is not read here. For a regular handler the body is
  11814. // read inside dispatch_request(), after the route has matched and the
  11815. // pre-request handler has approved the request, so that a rejected
  11816. // request (e.g. failed authentication) never forces us to buffer a
  11817. // potentially large body.
  11818. }
  11819. // Regular handler
  11820. if (req.method == "GET" || req.method == "HEAD") {
  11821. return dispatch_request(req, res, get_handlers_, strm);
  11822. } else if (req.method == "POST") {
  11823. return dispatch_request(req, res, post_handlers_, strm);
  11824. } else if (req.method == "PUT") {
  11825. return dispatch_request(req, res, put_handlers_, strm);
  11826. } else if (req.method == "DELETE") {
  11827. return dispatch_request(req, res, delete_handlers_, strm);
  11828. } else if (req.method == "OPTIONS") {
  11829. return dispatch_request(req, res, options_handlers_, strm);
  11830. } else if (req.method == "PATCH") {
  11831. return dispatch_request(req, res, patch_handlers_, strm);
  11832. } else if (custom) {
  11833. return dispatch_request(req, res, custom->handlers, strm);
  11834. }
  11835. res.status = StatusCode::BadRequest_400;
  11836. return false;
  11837. }
  11838. inline bool Server::dispatch_request(Request &req, Response &res,
  11839. const Handlers &handlers, Stream &strm) {
  11840. for (const auto &x : handlers) {
  11841. const auto &matcher = x.first;
  11842. const auto &handler = x.second;
  11843. if (matcher->match(req)) {
  11844. req.matched_route = matcher->pattern();
  11845. // Run the pre-request handler before reading the body so a rejected
  11846. // request (e.g. failed authentication) never forces us to buffer a
  11847. // potentially large body. `req.matched_route` is available here.
  11848. if (pre_request_handler_ &&
  11849. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  11850. return true;
  11851. }
  11852. // The route matched and the request was approved; read the body now.
  11853. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  11854. output_error_log(Error::Read, &req);
  11855. return false;
  11856. }
  11857. handler(req, res);
  11858. return true;
  11859. }
  11860. }
  11861. return false;
  11862. }
  11863. // Decides the content coding for a response served straight from a file. Both
  11864. // the ETag, which has to name the representation actually sent, and
  11865. // `apply_static_file_compression()` go through this, so the two cannot drift
  11866. // apart.
  11867. inline detail::EncodingType
  11868. Server::static_file_encoding(const Request &req, const Response &res,
  11869. const std::string &content_type,
  11870. size_t length) const {
  11871. if (!static_file_compression_) { return detail::EncodingType::None; }
  11872. // Nothing to compress, and an empty file already answers with
  11873. // `Content-Length: 0`. Checked on its own so that a zero floor still cannot
  11874. // turn an empty body into a 20-byte gzip stream.
  11875. if (length == 0) { return detail::EncodingType::None; }
  11876. // A file that already fits in a single packet gains nothing from being made
  11877. // smaller, since it still travels in that one segment, and a file of a few
  11878. // bytes comes out larger than it went in.
  11879. if (length < static_file_compression_min_length_) {
  11880. return detail::EncodingType::None;
  11881. }
  11882. // RFC 9110 applies Range to the representation after content coding, so a
  11883. // compressed 206 would mean compressing the whole file and then slicing it.
  11884. // Serve ranges from the identity representation instead.
  11885. if (!req.ranges.empty()) { return detail::EncodingType::None; }
  11886. if (static_file_compression_max_length_ > 0 &&
  11887. length > static_file_compression_max_length_) {
  11888. return detail::EncodingType::None;
  11889. }
  11890. return detail::encoding_type(req, res, content_type);
  11891. }
  11892. // Compresses a file-backed content provider into `res.body` and takes over the
  11893. // framing headers. Returns false when the response is left untouched.
  11894. inline bool Server::apply_static_file_compression(const Request &req,
  11895. Response &res) const {
  11896. auto type = res.content_coding_;
  11897. if (type == detail::EncodingType::None || !res.content_provider_) {
  11898. return false;
  11899. }
  11900. auto compressor = detail::make_compressor(type);
  11901. if (!compressor) { return false; }
  11902. output_pre_compression_log(req, res);
  11903. std::string compressed;
  11904. if (!detail::compress_content_provider(res.content_provider_,
  11905. res.content_length_, *compressor,
  11906. compressed)) {
  11907. return false;
  11908. }
  11909. res.body.swap(compressed);
  11910. // The provider was consumed in full, so a resource releaser registered with
  11911. // it should hear about a success when the response goes away.
  11912. res.content_provider_success_ = true;
  11913. res.content_provider_ = nullptr;
  11914. res.content_length_ = 0;
  11915. res.content_coding_ = detail::EncodingType::None;
  11916. res.set_header("Content-Encoding", detail::encoding_name(type));
  11917. res.set_header("Vary", "Accept-Encoding");
  11918. res.set_header("Content-Length", std::to_string(res.body.size()));
  11919. return true;
  11920. }
  11921. inline void Server::apply_ranges(const Request &req, Response &res,
  11922. std::string &content_type,
  11923. std::string &boundary) const {
  11924. // A known-length content provider leaves `res.body` empty, so the compressor
  11925. // at the end of this function never runs for one (issue #2545). A file-backed
  11926. // provider is fully readable right here, so compress it and answer with an
  11927. // ordinary body: `Content-Length` and HEAD keep working, and the response
  11928. // takes the same path as `set_content()` from here on. Range requests never
  11929. // get a content coding, so `Content-Range` still names identity bytes and
  11930. // none of the framing below applies.
  11931. if (apply_static_file_compression(req, res)) { return; }
  11932. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  11933. auto it = res.headers.find("Content-Type");
  11934. if (it != res.headers.end()) {
  11935. content_type = it->second;
  11936. res.headers.erase(it);
  11937. }
  11938. boundary = detail::make_multipart_data_boundary();
  11939. res.set_header("Content-Type",
  11940. "multipart/byteranges; boundary=" + boundary);
  11941. }
  11942. auto type = detail::encoding_type(req, res);
  11943. if (res.body.empty()) {
  11944. if (res.content_length_ > 0) {
  11945. size_t length = 0;
  11946. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  11947. length = res.content_length_;
  11948. } else if (req.ranges.size() == 1) {
  11949. auto offset_and_length = detail::get_range_offset_and_length(
  11950. req.ranges[0], res.content_length_);
  11951. length = offset_and_length.second;
  11952. auto content_range = detail::make_content_range_header_field(
  11953. offset_and_length, res.content_length_);
  11954. res.set_header("Content-Range", content_range);
  11955. } else {
  11956. length = detail::get_multipart_ranges_data_length(
  11957. req, boundary, content_type, res.content_length_);
  11958. }
  11959. res.set_header("Content-Length", std::to_string(length));
  11960. } else {
  11961. if (res.content_provider_) {
  11962. if (res.is_chunked_content_provider_) {
  11963. res.set_header("Transfer-Encoding", "chunked");
  11964. res.content_coding_ = type;
  11965. if (type != detail::EncodingType::None) {
  11966. res.set_header("Content-Encoding", detail::encoding_name(type));
  11967. res.set_header("Vary", "Accept-Encoding");
  11968. }
  11969. }
  11970. }
  11971. }
  11972. } else {
  11973. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  11974. ;
  11975. } else if (req.ranges.size() == 1) {
  11976. auto offset_and_length =
  11977. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  11978. auto offset = offset_and_length.first;
  11979. auto length = offset_and_length.second;
  11980. auto content_range = detail::make_content_range_header_field(
  11981. offset_and_length, res.body.size());
  11982. res.set_header("Content-Range", content_range);
  11983. assert(offset + length <= res.body.size());
  11984. res.body = res.body.substr(offset, length);
  11985. } else {
  11986. std::string data;
  11987. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  11988. res.body.size(), data);
  11989. res.body.swap(data);
  11990. }
  11991. if (type != detail::EncodingType::None) {
  11992. output_pre_compression_log(req, res);
  11993. if (auto compressor = detail::make_compressor(type)) {
  11994. std::string compressed;
  11995. if (compressor->compress(res.body.data(), res.body.size(), true,
  11996. [&](const char *data, size_t data_len) {
  11997. compressed.append(data, data_len);
  11998. return true;
  11999. })) {
  12000. res.body.swap(compressed);
  12001. res.set_header("Content-Encoding", detail::encoding_name(type));
  12002. res.set_header("Vary", "Accept-Encoding");
  12003. }
  12004. }
  12005. }
  12006. res.content_length_ = res.body.size();
  12007. res.set_header("Content-Length", std::to_string(res.content_length_));
  12008. }
  12009. }
  12010. inline bool Server::dispatch_request_for_content_reader(
  12011. Request &req, Response &res, ContentReader content_reader,
  12012. const HandlersForContentReader &handlers) const {
  12013. for (const auto &x : handlers) {
  12014. const auto &matcher = x.first;
  12015. const auto &handler = x.second;
  12016. if (matcher->match(req)) {
  12017. req.matched_route = matcher->pattern();
  12018. if (!pre_request_handler_ ||
  12019. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  12020. handler(req, res, content_reader);
  12021. }
  12022. return true;
  12023. }
  12024. }
  12025. return false;
  12026. }
  12027. inline std::string
  12028. get_client_ip(const std::string &x_forwarded_for,
  12029. const std::vector<std::string> &trusted_proxies) {
  12030. // X-Forwarded-For is a comma-separated list per RFC 7239
  12031. std::vector<std::string> ip_list;
  12032. detail::split(x_forwarded_for.data(),
  12033. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  12034. [&](const char *b, const char *e) {
  12035. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  12036. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  12037. });
  12038. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  12039. // no segments. Signal "no client IP derived" with an empty string so the
  12040. // caller can fall back to the connection-level remote address.
  12041. if (ip_list.empty()) { return std::string(); }
  12042. // Each hop appends the address it received the request from, so the rightmost
  12043. // entries are the ones written by our own infrastructure while the leftmost
  12044. // are whatever the original client chose to send. Walk from the right and
  12045. // skip trusted proxies; the first address that is not a trusted proxy is the
  12046. // furthest point still attributable to a real hop, i.e. the client. Scanning
  12047. // from the left instead lets a client forge an arbitrary address by following
  12048. // it with a trusted proxy's address, which the left-to-right scan then
  12049. // returned as the client.
  12050. for (size_t i = ip_list.size(); i-- > 0;) {
  12051. const auto &ip = ip_list[i];
  12052. auto is_trusted_proxy =
  12053. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  12054. [&](const std::string &proxy) { return ip == proxy; });
  12055. if (!is_trusted_proxy) { return ip; }
  12056. }
  12057. // Every hop was a trusted proxy; fall back to the first entry.
  12058. return ip_list.front();
  12059. }
  12060. inline bool
  12061. Server::process_request(Stream &strm, const std::string &remote_addr,
  12062. int remote_port, const std::string &local_addr,
  12063. int local_port, bool close_connection,
  12064. bool &connection_closed,
  12065. const std::function<void(Request &)> &setup_request,
  12066. bool *websocket_upgraded) {
  12067. std::array<char, 2048> buf{};
  12068. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  12069. // Connection has been closed on client
  12070. if (!line_reader.getline()) { return false; }
  12071. Request req;
  12072. req.start_time_ = std::chrono::steady_clock::now();
  12073. req.remote_addr = remote_addr;
  12074. req.remote_port = remote_port;
  12075. req.local_addr = local_addr;
  12076. req.local_port = local_port;
  12077. Response res;
  12078. res.version = "HTTP/1.1";
  12079. res.headers = default_headers_;
  12080. // Request line and headers
  12081. if (!parse_request_line(line_reader.ptr(), req)) {
  12082. res.status = StatusCode::BadRequest_400;
  12083. output_error_log(Error::InvalidRequestLine, &req);
  12084. return write_response(strm, close_connection, req, res);
  12085. }
  12086. // Request headers
  12087. if (!detail::read_headers(strm, req.headers)) {
  12088. res.status = StatusCode::BadRequest_400;
  12089. output_error_log(Error::InvalidHeaders, &req);
  12090. return write_response(strm, close_connection, req, res);
  12091. }
  12092. // RFC 9112 §6.3: Reject requests whose framing is ambiguous, which would
  12093. // otherwise let an intermediary and this parser disagree on where the body
  12094. // ends and enable request smuggling. Two cases: a non-zero Content-Length
  12095. // alongside any Transfer-Encoding (Content-Length: 0 is tolerated for
  12096. // compatibility with existing clients), and a Transfer-Encoding whose final
  12097. // coding is not chunked, which leaves the body length undeterminable. The
  12098. // latter must not fall through to the "no body" path, or the body bytes are
  12099. // parsed as the next request on a persistent connection.
  12100. if (detail::has_conflicting_content_length(req.headers) ||
  12101. (req.has_header("Transfer-Encoding") &&
  12102. !detail::is_chunked_transfer_encoding(req.headers))) {
  12103. connection_closed = true;
  12104. res.status = StatusCode::BadRequest_400;
  12105. return write_response(strm, close_connection, req, res);
  12106. }
  12107. // Check if the request URI doesn't exceed the limit
  12108. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  12109. connection_closed = true;
  12110. res.status = StatusCode::UriTooLong_414;
  12111. output_error_log(Error::ExceedUriMaxLength, &req);
  12112. return write_response(strm, close_connection, req, res);
  12113. }
  12114. if (detail::has_header_token(req.headers, "Connection", "close")) {
  12115. connection_closed = true;
  12116. }
  12117. if (req.version == "HTTP/1.0" &&
  12118. !detail::has_header_token(req.headers, "Connection", "keep-alive")) {
  12119. connection_closed = true;
  12120. }
  12121. // Only honor X-Forwarded-For if the peer on the actual TCP connection is
  12122. // itself a trusted proxy. Otherwise any direct client could spoof
  12123. // remote_addr simply by sending an arbitrary X-Forwarded-For header.
  12124. auto is_trusted_peer = std::any_of(
  12125. trusted_proxies_.begin(), trusted_proxies_.end(),
  12126. [&](const std::string &proxy) { return proxy == remote_addr; });
  12127. if (is_trusted_peer && req.has_header("X-Forwarded-For")) {
  12128. // Some proxies append the address they observed as a separate
  12129. // X-Forwarded-For field line instead of extending the one the client sent
  12130. // (e.g. HAProxy's "option forwardfor"), so the whole combined value has to
  12131. // be scanned. Reading only the first occurrence would hand back the
  12132. // client-supplied, and therefore forgeable, value.
  12133. auto x_forwarded_for =
  12134. detail::get_combined_header_value(req.headers, "X-Forwarded-For");
  12135. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  12136. req.remote_addr = derived.empty() ? remote_addr : derived;
  12137. } else {
  12138. req.remote_addr = remote_addr;
  12139. }
  12140. req.remote_port = remote_port;
  12141. req.local_addr = local_addr;
  12142. req.local_port = local_port;
  12143. if (req.has_header("Accept")) {
  12144. auto accept_header =
  12145. detail::get_combined_header_value(req.headers, "Accept");
  12146. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  12147. connection_closed = true;
  12148. res.status = StatusCode::BadRequest_400;
  12149. output_error_log(Error::HTTPParsing, &req);
  12150. return write_response(strm, close_connection, req, res);
  12151. }
  12152. }
  12153. if (req.has_header("Range")) {
  12154. const auto &range_header_value = req.get_header_value("Range");
  12155. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  12156. connection_closed = true;
  12157. res.status = StatusCode::RangeNotSatisfiable_416;
  12158. output_error_log(Error::InvalidRangeHeader, &req);
  12159. return write_response(strm, close_connection, req, res);
  12160. }
  12161. }
  12162. if (setup_request) { setup_request(req); }
  12163. // RFC 9110 10.1.1: Expect is a comma-separated list whose value is
  12164. // case-insensitive, and a 100-continue expectation in an HTTP/1.0 request
  12165. // must be ignored. An expectation we do not recognize is left alone; the
  12166. // 417 the section allows for one is a MAY, not a requirement.
  12167. if (req.version != "HTTP/1.0" &&
  12168. detail::has_header_token(req.headers, "Expect", "100-continue")) {
  12169. int status = StatusCode::Continue_100;
  12170. if (expect_100_continue_handler_) {
  12171. status = expect_100_continue_handler_(req, res);
  12172. }
  12173. switch (status) {
  12174. case StatusCode::Continue_100:
  12175. case StatusCode::ExpectationFailed_417:
  12176. detail::write_response_line(strm, status);
  12177. strm.write("\r\n");
  12178. break;
  12179. default:
  12180. connection_closed = true;
  12181. return write_response(strm, true, req, res);
  12182. }
  12183. }
  12184. // Setup `is_connection_closed` method
  12185. auto sock = strm.socket();
  12186. req.is_connection_closed = [sock]() {
  12187. return !detail::is_socket_alive(sock);
  12188. };
  12189. // WebSocket upgrade
  12190. // Check pre_routing_handler_ before upgrading so that authentication
  12191. // and other middleware can reject the request with an HTTP response
  12192. // (e.g., 401) before the protocol switches.
  12193. if (detail::is_websocket_upgrade(req)) {
  12194. if (pre_routing_handler_ &&
  12195. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  12196. if (res.status == -1) { res.status = StatusCode::OK_200; }
  12197. return write_response(strm, close_connection, req, res);
  12198. }
  12199. // Find matching WebSocket handler
  12200. for (const auto &entry : websocket_handlers_) {
  12201. if (entry.matcher->match(req)) {
  12202. // Compute accept key
  12203. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  12204. auto accept_key = detail::websocket_accept_key(client_key);
  12205. // Negotiate subprotocol
  12206. std::string selected_subprotocol;
  12207. if (entry.sub_protocol_selector) {
  12208. auto protocol_header = detail::get_combined_header_value(
  12209. req.headers, "Sec-WebSocket-Protocol");
  12210. if (!protocol_header.empty()) {
  12211. std::vector<std::string> protocols;
  12212. detail::split(protocol_header.data(),
  12213. protocol_header.data() + protocol_header.size(), ',',
  12214. [&](const char *b, const char *e) {
  12215. protocols.emplace_back(b, e);
  12216. });
  12217. selected_subprotocol = entry.sub_protocol_selector(protocols);
  12218. }
  12219. }
  12220. // Send 101 Switching Protocols
  12221. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  12222. "Upgrade: websocket\r\n"
  12223. "Connection: Upgrade\r\n"
  12224. "Sec-WebSocket-Accept: " +
  12225. accept_key + "\r\n";
  12226. if (!selected_subprotocol.empty()) {
  12227. if (!detail::fields::is_field_value(selected_subprotocol)) {
  12228. return false;
  12229. }
  12230. handshake_response +=
  12231. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  12232. }
  12233. handshake_response += "\r\n";
  12234. if (strm.write(handshake_response.data(), handshake_response.size()) <
  12235. 0) {
  12236. return false;
  12237. }
  12238. connection_closed = true;
  12239. if (websocket_upgraded) { *websocket_upgraded = true; }
  12240. {
  12241. #ifdef CPPHTTPLIB_SSL_ENABLED
  12242. if (req.ssl) {
  12243. // wss: the heartbeat ping thread and the read path enter the same
  12244. // TLS session from different threads. Hand the WebSocket a stream
  12245. // that serializes every TLS call, so the shared SSLSocketStream on
  12246. // the plain HTTP/HTTPS paths stays untouched.
  12247. auto ws_strm =
  12248. std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  12249. strm.socket(), const_cast<tls::session_t>(req.ssl),
  12250. CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
  12251. write_timeout_sec_, write_timeout_usec_));
  12252. ws::WebSocket ws(std::move(ws_strm), req, true,
  12253. websocket_ping_interval_sec_,
  12254. websocket_max_missed_pongs_);
  12255. entry.handler(req, ws);
  12256. return true;
  12257. }
  12258. #endif
  12259. // Use WebSocket-specific read timeout instead of HTTP timeout
  12260. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND,
  12261. 0);
  12262. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  12263. websocket_max_missed_pongs_);
  12264. entry.handler(req, ws);
  12265. }
  12266. return true;
  12267. }
  12268. }
  12269. // No matching handler - fall through to 404
  12270. }
  12271. // Routing
  12272. auto routed = false;
  12273. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12274. routed = routing(req, res, strm);
  12275. #else
  12276. try {
  12277. routed = routing(req, res, strm);
  12278. } catch (std::exception &) {
  12279. if (exception_handler_) {
  12280. auto ep = std::current_exception();
  12281. exception_handler_(req, res, ep);
  12282. routed = true;
  12283. } else {
  12284. res.status = StatusCode::InternalServerError_500;
  12285. }
  12286. } catch (...) {
  12287. if (exception_handler_) {
  12288. auto ep = std::current_exception();
  12289. exception_handler_(req, res, ep);
  12290. routed = true;
  12291. } else {
  12292. res.status = StatusCode::InternalServerError_500;
  12293. }
  12294. }
  12295. #endif
  12296. auto ret = false;
  12297. if (routed) {
  12298. if (res.status == -1) {
  12299. res.status = req.ranges.empty() ? StatusCode::OK_200
  12300. : StatusCode::PartialContent_206;
  12301. }
  12302. // Serve file content by using a content provider
  12303. auto file_open_error = false;
  12304. if (!res.file_content_path_.empty()) {
  12305. const auto &path = res.file_content_path_;
  12306. auto mm = std::make_shared<detail::mmap>(path.c_str());
  12307. if (!mm->is_open()) {
  12308. res.body.clear();
  12309. res.content_length_ = 0;
  12310. res.content_provider_ = nullptr;
  12311. res.status = StatusCode::NotFound_404;
  12312. output_error_log(Error::OpenFile, &req);
  12313. file_open_error = true;
  12314. } else {
  12315. auto content_type = res.file_content_content_type_;
  12316. if (content_type.empty()) {
  12317. content_type = detail::find_content_type(
  12318. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  12319. }
  12320. detail::set_file_content_provider(
  12321. res, mm, content_type,
  12322. static_file_encoding(req, res, content_type, mm->size()));
  12323. }
  12324. }
  12325. if (file_open_error) {
  12326. ret = write_response(strm, close_connection, req, res);
  12327. } else if (detail::range_error(req, res)) {
  12328. res.body.clear();
  12329. res.content_length_ = 0;
  12330. res.content_provider_ = nullptr;
  12331. res.status = StatusCode::RangeNotSatisfiable_416;
  12332. ret = write_response(strm, close_connection, req, res);
  12333. } else {
  12334. ret = write_response_with_content(strm, close_connection, req, res);
  12335. }
  12336. } else {
  12337. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  12338. ret = write_response(strm, close_connection, req, res);
  12339. }
  12340. // Drain any unconsumed framed body to prevent request smuggling on
  12341. // keep-alive. Without framing there is no body to drain — reading would
  12342. // consume the next request (issue #2450). If the response has committed the
  12343. // connection to close, there is no next request to protect.
  12344. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  12345. if (detail::has_header_token(res.headers, "Connection", "close")) {
  12346. connection_closed = true;
  12347. } else {
  12348. int dummy_status;
  12349. if (!detail::read_content(
  12350. strm, req, payload_max_length_, dummy_status, nullptr,
  12351. [](const char *, size_t, size_t, size_t) { return true; },
  12352. false)) {
  12353. connection_closed = true;
  12354. }
  12355. }
  12356. }
  12357. return ret;
  12358. }
  12359. inline bool Server::is_valid() const { return !has_invalid_registration_; }
  12360. inline bool Server::process_and_close_socket(socket_t sock) {
  12361. std::string remote_addr;
  12362. int remote_port = 0;
  12363. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  12364. std::string local_addr;
  12365. int local_port = 0;
  12366. detail::get_local_ip_and_port(sock, local_addr, local_port);
  12367. bool websocket_upgraded = false;
  12368. auto ret = serve_guarded([&]() {
  12369. return detail::process_server_socket(
  12370. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  12371. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12372. write_timeout_usec_,
  12373. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  12374. return process_request(strm, remote_addr, remote_port, local_addr,
  12375. local_port, close_connection,
  12376. connection_closed, nullptr,
  12377. &websocket_upgraded);
  12378. });
  12379. });
  12380. detail::drain_and_close_socket(sock);
  12381. return ret;
  12382. }
  12383. inline void Server::output_log(const Request &req, const Response &res) const {
  12384. if (logger_) {
  12385. std::lock_guard<std::mutex> guard(logger_mutex_);
  12386. logger_(req, res);
  12387. }
  12388. }
  12389. inline void Server::output_pre_compression_log(const Request &req,
  12390. const Response &res) const {
  12391. if (pre_compression_logger_) {
  12392. std::lock_guard<std::mutex> guard(logger_mutex_);
  12393. pre_compression_logger_(req, res);
  12394. }
  12395. }
  12396. inline void Server::output_error_log(const Error &err,
  12397. const Request *req) const {
  12398. if (error_logger_) {
  12399. std::lock_guard<std::mutex> guard(logger_mutex_);
  12400. error_logger_(err, req);
  12401. }
  12402. }
  12403. /*
  12404. * Group 5: ClientImpl and Client (Universal) implementation
  12405. */
  12406. // HTTP client implementation
  12407. inline ClientImpl::ClientImpl(const std::string &host)
  12408. : ClientImpl(host, 80, std::string(), std::string()) {}
  12409. inline ClientImpl::ClientImpl(const std::string &host, int port)
  12410. : ClientImpl(host, port, std::string(), std::string()) {}
  12411. inline ClientImpl::ClientImpl(const std::string &host, int port,
  12412. const std::string &client_cert_path,
  12413. const std::string &client_key_path)
  12414. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  12415. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  12416. inline ClientImpl::~ClientImpl() {
  12417. // Wait until all the requests in flight are handled.
  12418. size_t retry_count = 10;
  12419. while (retry_count-- > 0) {
  12420. {
  12421. std::lock_guard<std::mutex> guard(socket_mutex_);
  12422. if (socket_requests_in_flight_ == 0) { break; }
  12423. }
  12424. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  12425. }
  12426. std::lock_guard<std::mutex> guard(socket_mutex_);
  12427. shutdown_socket(socket_);
  12428. close_socket(socket_);
  12429. }
  12430. inline bool ClientImpl::is_valid() const { return true; }
  12431. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  12432. client_cert_path_ = rhs.client_cert_path_;
  12433. client_key_path_ = rhs.client_key_path_;
  12434. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  12435. read_timeout_sec_ = rhs.read_timeout_sec_;
  12436. read_timeout_usec_ = rhs.read_timeout_usec_;
  12437. write_timeout_sec_ = rhs.write_timeout_sec_;
  12438. write_timeout_usec_ = rhs.write_timeout_usec_;
  12439. max_timeout_msec_ = rhs.max_timeout_msec_;
  12440. basic_auth_username_ = rhs.basic_auth_username_;
  12441. basic_auth_password_ = rhs.basic_auth_password_;
  12442. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  12443. keep_alive_ = rhs.keep_alive_;
  12444. follow_location_ = rhs.follow_location_;
  12445. path_encode_ = rhs.path_encode_;
  12446. address_family_ = rhs.address_family_;
  12447. tcp_nodelay_ = rhs.tcp_nodelay_;
  12448. ipv6_v6only_ = rhs.ipv6_v6only_;
  12449. socket_options_ = rhs.socket_options_;
  12450. compress_ = rhs.compress_;
  12451. decompress_ = rhs.decompress_;
  12452. payload_max_length_ = rhs.payload_max_length_;
  12453. has_payload_max_length_ = rhs.has_payload_max_length_;
  12454. interface_ = rhs.interface_;
  12455. proxy_host_ = rhs.proxy_host_;
  12456. proxy_port_ = rhs.proxy_port_;
  12457. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  12458. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  12459. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  12460. no_proxy_entries_ = rhs.no_proxy_entries_;
  12461. logger_ = rhs.logger_;
  12462. error_logger_ = rhs.error_logger_;
  12463. #ifdef CPPHTTPLIB_SSL_ENABLED
  12464. digest_auth_username_ = rhs.digest_auth_username_;
  12465. digest_auth_password_ = rhs.digest_auth_password_;
  12466. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  12467. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  12468. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  12469. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  12470. server_certificate_verification_ = rhs.server_certificate_verification_;
  12471. server_hostname_verification_ = rhs.server_hostname_verification_;
  12472. system_ca_mode_ = rhs.system_ca_mode_;
  12473. #endif
  12474. }
  12475. inline bool
  12476. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  12477. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  12478. if (no_proxy_entries_.empty()) { return true; }
  12479. // host_ is const so its normalized form is invariant; cache it. The
  12480. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  12481. if (host == host_) {
  12482. if (!host_normalized_valid_) {
  12483. host_normalized_ = detail::normalize_target(host_);
  12484. host_normalized_valid_ = true;
  12485. }
  12486. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  12487. }
  12488. auto target = detail::normalize_target(host);
  12489. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  12490. }
  12491. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  12492. if (is_proxy_enabled_for_host(host_)) {
  12493. return detail::create_client_socket(
  12494. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  12495. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  12496. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  12497. write_timeout_sec_, write_timeout_usec_, interface_, error);
  12498. }
  12499. // Check is custom IP or hostname specified for host_
  12500. std::string connect_host;
  12501. std::string ip;
  12502. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  12503. return detail::create_client_socket(
  12504. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  12505. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  12506. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12507. write_timeout_usec_, interface_, error);
  12508. }
  12509. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  12510. Error &error) {
  12511. auto sock = create_client_socket(error);
  12512. if (sock == INVALID_SOCKET) { return false; }
  12513. socket.sock = sock;
  12514. return true;
  12515. }
  12516. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  12517. return create_and_connect_socket(socket, error);
  12518. }
  12519. inline bool ClientImpl::setup_proxy_connection(
  12520. Socket & /*socket*/,
  12521. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  12522. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  12523. return true;
  12524. }
  12525. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  12526. bool /*shutdown_gracefully*/) {
  12527. // If there are any requests in flight from threads other than us, then it's
  12528. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  12529. assert(socket_requests_in_flight_ == 0 ||
  12530. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12531. }
  12532. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  12533. if (socket.sock == INVALID_SOCKET) { return; }
  12534. detail::shutdown_socket(socket.sock);
  12535. }
  12536. inline void ClientImpl::close_socket(Socket &socket) {
  12537. // If there are requests in flight in another thread, usually closing
  12538. // the socket will be fine and they will simply receive an error when
  12539. // using the closed socket, but it is still a bug since rarely the OS
  12540. // may reassign the socket id to be used for a new socket, and then
  12541. // suddenly they will be operating on a live socket that is different
  12542. // than the one they intended!
  12543. assert(socket_requests_in_flight_ == 0 ||
  12544. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12545. // It is also a bug if this happens while SSL is still active
  12546. #ifdef CPPHTTPLIB_SSL_ENABLED
  12547. assert(socket.ssl == nullptr);
  12548. #endif
  12549. if (socket.sock == INVALID_SOCKET) { return; }
  12550. detail::close_socket(socket.sock);
  12551. socket.sock = INVALID_SOCKET;
  12552. }
  12553. inline void ClientImpl::disconnect(bool gracefully) {
  12554. shutdown_ssl(socket_, gracefully);
  12555. shutdown_socket(socket_);
  12556. close_socket(socket_);
  12557. }
  12558. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  12559. Response &res,
  12560. bool skip_100_continue) const {
  12561. std::array<char, 2048> buf{};
  12562. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  12563. if (!line_reader.getline()) { return false; }
  12564. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12565. res.reason)) {
  12566. return req.method == "CONNECT";
  12567. }
  12568. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  12569. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  12570. if (!line_reader.getline()) { return false; } // CRLF
  12571. if (!line_reader.getline()) { return false; } // next response line
  12572. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12573. res.reason)) {
  12574. return false;
  12575. }
  12576. }
  12577. return true;
  12578. }
  12579. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  12580. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  12581. auto ret = send_(req, res, error);
  12582. if (error == Error::SSLPeerCouldBeClosed_) {
  12583. assert(!ret);
  12584. ret = send_(req, res, error);
  12585. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  12586. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  12587. }
  12588. return ret;
  12589. }
  12590. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  12591. {
  12592. std::lock_guard<std::mutex> guard(socket_mutex_);
  12593. // Set this to false immediately - if it ever gets set to true by the end
  12594. // of the request, we know another thread instructed us to close the
  12595. // socket.
  12596. socket_should_be_closed_when_request_is_done_ = false;
  12597. auto is_alive = false;
  12598. if (socket_.is_open()) {
  12599. is_alive = detail::is_socket_alive(socket_.sock);
  12600. #ifdef CPPHTTPLIB_SSL_ENABLED
  12601. if (is_alive && is_ssl()) {
  12602. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12603. is_alive = false;
  12604. }
  12605. }
  12606. #endif
  12607. if (!is_alive) {
  12608. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  12609. disconnect(/*gracefully=*/false);
  12610. }
  12611. }
  12612. if (!is_alive) {
  12613. if (!ensure_socket_connection(socket_, error)) {
  12614. output_error_log(error, &req);
  12615. return false;
  12616. }
  12617. {
  12618. auto success = true;
  12619. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  12620. error)) {
  12621. if (!success) { output_error_log(error, &req); }
  12622. return success;
  12623. }
  12624. }
  12625. }
  12626. // Mark the current socket as being in use so that it cannot be closed by
  12627. // anyone else while this request is ongoing, even though we will be
  12628. // releasing the mutex.
  12629. if (socket_requests_in_flight_ > 1) {
  12630. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  12631. }
  12632. socket_requests_in_flight_ += 1;
  12633. socket_requests_are_from_thread_ = std::this_thread::get_id();
  12634. }
  12635. for (const auto &header : default_headers_) {
  12636. if (req.headers.find(header.first) == req.headers.end()) {
  12637. req.headers.insert(header);
  12638. }
  12639. }
  12640. auto ret = false;
  12641. auto close_connection = !keep_alive_;
  12642. auto se = detail::scope_exit([&]() {
  12643. // Briefly lock mutex in order to mark that a request is no longer ongoing
  12644. std::lock_guard<std::mutex> guard(socket_mutex_);
  12645. socket_requests_in_flight_ -= 1;
  12646. if (socket_requests_in_flight_ <= 0) {
  12647. assert(socket_requests_in_flight_ == 0);
  12648. socket_requests_are_from_thread_ = std::thread::id();
  12649. }
  12650. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  12651. !ret) {
  12652. disconnect(/*gracefully=*/true);
  12653. }
  12654. });
  12655. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  12656. return handle_request(strm, req, res, close_connection, error);
  12657. });
  12658. if (!ret) {
  12659. if (error == Error::Success) {
  12660. error = Error::Unknown;
  12661. output_error_log(error, &req);
  12662. }
  12663. }
  12664. return ret;
  12665. }
  12666. inline Result ClientImpl::send(const Request &req) {
  12667. auto req2 = req;
  12668. return send_(std::move(req2));
  12669. }
  12670. inline Result ClientImpl::send_(Request &&req) {
  12671. auto res = detail::make_unique<Response>();
  12672. auto error = Error::Success;
  12673. auto ret = send(req, *res, error);
  12674. #ifdef CPPHTTPLIB_SSL_ENABLED
  12675. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  12676. last_ssl_error_, last_backend_error_};
  12677. #else
  12678. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  12679. #endif
  12680. }
  12681. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  12682. const std::string &ct) {
  12683. (void)for_stream;
  12684. // Default headers are meant for the origin and may carry its credentials, so
  12685. // keep them off the CONNECT request the proxy reads.
  12686. if (r.method != "CONNECT") {
  12687. for (const auto &header : default_headers_) {
  12688. if (!r.has_header(header.first)) { r.headers.insert(header); }
  12689. }
  12690. }
  12691. // RFC 9110 5.3 recommends sending control data such as Host first, so
  12692. // prepend it rather than appending it after the caller's own fields.
  12693. if (!r.has_header("Host")) {
  12694. r.headers.emplace_front(
  12695. "Host", detail::make_default_host_header_value(host_, port_, is_ssl(),
  12696. address_family_));
  12697. }
  12698. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  12699. if (!r.content_receiver) {
  12700. if (!r.has_header("Accept-Encoding")) {
  12701. std::string accept_encoding;
  12702. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12703. accept_encoding = "br";
  12704. #endif
  12705. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12706. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  12707. accept_encoding += "gzip, deflate";
  12708. #endif
  12709. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12710. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  12711. accept_encoding += "zstd";
  12712. #endif
  12713. r.set_header("Accept-Encoding", accept_encoding);
  12714. }
  12715. detail::add_default_user_agent_header(r);
  12716. }
  12717. if (!r.body.empty()) {
  12718. if (!ct.empty() && !r.has_header("Content-Type")) {
  12719. r.headers.emplace("Content-Type", ct);
  12720. }
  12721. if (!r.has_header("Content-Length")) {
  12722. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  12723. }
  12724. }
  12725. }
  12726. inline ClientImpl::StreamHandle
  12727. ClientImpl::open_stream(const std::string &method, const std::string &path,
  12728. const Params &params, const Headers &headers,
  12729. const std::string &body,
  12730. const std::string &content_type) {
  12731. StreamHandle handle;
  12732. handle.response = detail::make_unique<Response>();
  12733. handle.error = Error::Success;
  12734. // Encode the target exactly like the buffered send path does, so that the
  12735. // same `path` produces the same request line through either API.
  12736. auto raw_query_path =
  12737. params.empty() ? path : append_query_params(path, params);
  12738. auto query_path = detail::encode_request_target(raw_query_path, path_encode_);
  12739. handle.connection_ = detail::make_unique<ClientConnection>();
  12740. {
  12741. std::lock_guard<std::mutex> guard(socket_mutex_);
  12742. auto is_alive = false;
  12743. if (socket_.is_open()) {
  12744. is_alive = detail::is_socket_alive(socket_.sock);
  12745. #ifdef CPPHTTPLIB_SSL_ENABLED
  12746. if (is_alive && is_ssl()) {
  12747. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12748. is_alive = false;
  12749. }
  12750. }
  12751. #endif
  12752. if (!is_alive) { disconnect(/*gracefully=*/false); }
  12753. }
  12754. if (!is_alive) {
  12755. if (!ensure_socket_connection(socket_, handle.error)) {
  12756. handle.response.reset();
  12757. return handle;
  12758. }
  12759. {
  12760. auto success = true;
  12761. auto start_time = std::chrono::steady_clock::now();
  12762. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  12763. success, handle.error)) {
  12764. if (!success) { handle.response.reset(); }
  12765. return handle;
  12766. }
  12767. }
  12768. }
  12769. transfer_socket_ownership_to_handle(handle);
  12770. }
  12771. #ifdef CPPHTTPLIB_SSL_ENABLED
  12772. if (is_ssl() && handle.connection_->session) {
  12773. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  12774. handle.connection_->sock, handle.connection_->session,
  12775. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12776. write_timeout_usec_);
  12777. } else {
  12778. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  12779. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  12780. write_timeout_sec_, write_timeout_usec_);
  12781. }
  12782. #else
  12783. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  12784. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  12785. write_timeout_sec_, write_timeout_usec_);
  12786. #endif
  12787. handle.stream_ = handle.socket_stream_.get();
  12788. Request req;
  12789. req.method = method;
  12790. req.path = query_path;
  12791. req.headers = headers;
  12792. req.body = body;
  12793. prepare_default_headers(req, true, content_type);
  12794. auto &strm = *handle.stream_;
  12795. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  12796. handle.error = Error::Write;
  12797. handle.response.reset();
  12798. return handle;
  12799. }
  12800. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  12801. handle.error)) {
  12802. handle.response.reset();
  12803. return handle;
  12804. }
  12805. if (!body.empty()) {
  12806. if (strm.write(body.data(), body.size()) < 0) {
  12807. handle.error = Error::Write;
  12808. handle.response.reset();
  12809. return handle;
  12810. }
  12811. }
  12812. if (!read_response_line(strm, req, *handle.response) ||
  12813. !detail::read_headers(strm, handle.response->headers)) {
  12814. handle.error = Error::Read;
  12815. handle.response.reset();
  12816. return handle;
  12817. }
  12818. // Same framing check as ClientImpl::process_request(). A HEAD or bodyless
  12819. // (204/304) response legitimately carries framing headers with no body.
  12820. if (method != "HEAD" &&
  12821. handle.response->status != StatusCode::NoContent_204 &&
  12822. handle.response->status != StatusCode::NotModified_304 &&
  12823. detail::has_conflicting_content_length(handle.response->headers)) {
  12824. handle.error = Error::Read;
  12825. handle.response.reset();
  12826. return handle;
  12827. }
  12828. handle.body_reader_.stream = handle.stream_;
  12829. handle.body_reader_.payload_max_length = payload_max_length_;
  12830. if (handle.response->has_header("Content-Length")) {
  12831. bool is_invalid = false;
  12832. auto content_length = detail::get_header_value_u64(
  12833. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  12834. if (is_invalid) {
  12835. handle.error = Error::Read;
  12836. handle.response.reset();
  12837. return handle;
  12838. }
  12839. handle.body_reader_.has_content_length = true;
  12840. handle.body_reader_.content_length = content_length;
  12841. }
  12842. handle.body_reader_.chunked =
  12843. detail::is_chunked_transfer_encoding(handle.response->headers);
  12844. auto content_encoding = detail::get_combined_header_value(
  12845. handle.response->headers, "Content-Encoding");
  12846. if (!content_encoding.empty()) {
  12847. // Same policy as prepare_content_receiver(): reject a coding we know about
  12848. // but were not built with, pass an unrecognized one through as-is.
  12849. handle.decompressor_ = detail::create_decompressor(content_encoding);
  12850. if (!handle.decompressor_) {
  12851. if (detail::is_known_content_encoding(content_encoding)) {
  12852. handle.error = Error::UnsupportedContentEncoding;
  12853. handle.response.reset();
  12854. return handle;
  12855. }
  12856. } else if (!handle.decompressor_->is_valid()) {
  12857. handle.error = Error::Compression;
  12858. handle.response.reset();
  12859. return handle;
  12860. }
  12861. }
  12862. return handle;
  12863. }
  12864. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  12865. if (!is_valid() || !response) { return -1; }
  12866. if (decompressor_) { return read_with_decompression(buf, len); }
  12867. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  12868. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  12869. trailers_parsed_ = true;
  12870. if (body_reader_.chunked_decoder) {
  12871. if (!body_reader_.chunked_decoder->parse_trailers_into(
  12872. response->trailers, response->headers)) {
  12873. return n;
  12874. }
  12875. } else {
  12876. detail::ChunkedDecoder dec(*stream_);
  12877. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  12878. return n;
  12879. }
  12880. }
  12881. }
  12882. return n;
  12883. }
  12884. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  12885. size_t len) {
  12886. if (decompress_offset_ < decompress_buffer_.size()) {
  12887. auto available = decompress_buffer_.size() - decompress_offset_;
  12888. auto to_copy = (std::min)(len, available);
  12889. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  12890. decompress_offset_ += to_copy;
  12891. decompressed_bytes_read_ += to_copy;
  12892. return static_cast<ssize_t>(to_copy);
  12893. }
  12894. decompress_buffer_.clear();
  12895. decompress_offset_ = 0;
  12896. constexpr size_t kDecompressionBufferSize = 8192;
  12897. char compressed_buf[kDecompressionBufferSize];
  12898. while (true) {
  12899. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  12900. sizeof(compressed_buf));
  12901. if (n <= 0) { return n; }
  12902. bool decompress_ok = decompressor_->decompress(
  12903. compressed_buf, static_cast<size_t>(n),
  12904. [this](const char *data, size_t data_len) {
  12905. decompress_buffer_.append(data, data_len);
  12906. auto limit = body_reader_.payload_max_length;
  12907. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  12908. return false;
  12909. }
  12910. return true;
  12911. });
  12912. if (!decompress_ok) {
  12913. body_reader_.last_error = Error::Read;
  12914. return -1;
  12915. }
  12916. if (!decompress_buffer_.empty()) { break; }
  12917. }
  12918. auto to_copy = (std::min)(len, decompress_buffer_.size());
  12919. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  12920. decompress_offset_ = to_copy;
  12921. decompressed_bytes_read_ += to_copy;
  12922. return static_cast<ssize_t>(to_copy);
  12923. }
  12924. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  12925. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  12926. return;
  12927. }
  12928. trailers_parsed_ = true;
  12929. const auto bufsiz = 128;
  12930. char line_buf[bufsiz];
  12931. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  12932. if (!line_reader.getline()) { return; }
  12933. if (!detail::parse_trailers(line_reader, response->trailers,
  12934. response->headers)) {
  12935. return;
  12936. }
  12937. }
  12938. namespace detail {
  12939. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  12940. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  12941. size_t &out_chunk_offset,
  12942. size_t &out_chunk_total) {
  12943. if (finished) { return 0; }
  12944. if (chunk_remaining == 0) {
  12945. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  12946. if (!lr.getline()) { return -1; }
  12947. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  12948. const char *p = lr.ptr();
  12949. int v = 0;
  12950. if (!is_hex(*p, v)) { return -1; }
  12951. size_t chunk_len = 0;
  12952. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  12953. for (; is_hex(*p, v); ++p) {
  12954. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  12955. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  12956. }
  12957. while (is_space_or_tab(*p)) {
  12958. ++p;
  12959. }
  12960. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  12961. if (chunk_len == 0) {
  12962. chunk_remaining = 0;
  12963. finished = true;
  12964. out_chunk_offset = 0;
  12965. out_chunk_total = 0;
  12966. return 0;
  12967. }
  12968. chunk_remaining = chunk_len;
  12969. last_chunk_total = chunk_remaining;
  12970. last_chunk_offset = 0;
  12971. }
  12972. auto to_read = (std::min)(chunk_remaining, len);
  12973. auto n = strm.read(buf, to_read);
  12974. if (n <= 0) { return -1; }
  12975. auto offset_before = last_chunk_offset;
  12976. last_chunk_offset += static_cast<size_t>(n);
  12977. chunk_remaining -= static_cast<size_t>(n);
  12978. out_chunk_offset = offset_before;
  12979. out_chunk_total = last_chunk_total;
  12980. if (chunk_remaining == 0) {
  12981. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  12982. if (!lr.getline()) { return -1; }
  12983. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  12984. }
  12985. return n;
  12986. }
  12987. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  12988. const Headers &src_headers) {
  12989. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  12990. if (!lr.getline()) { return false; }
  12991. return parse_trailers(lr, dest, src_headers);
  12992. }
  12993. } // namespace detail
  12994. inline void
  12995. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  12996. handle.connection_->sock = socket_.sock;
  12997. #ifdef CPPHTTPLIB_SSL_ENABLED
  12998. handle.connection_->session = socket_.ssl;
  12999. socket_.ssl = nullptr;
  13000. #endif
  13001. socket_.sock = INVALID_SOCKET;
  13002. }
  13003. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  13004. Response &res, bool close_connection,
  13005. Error &error) {
  13006. if (req.path.empty()) {
  13007. error = Error::Connection;
  13008. output_error_log(error, &req);
  13009. return false;
  13010. }
  13011. auto req_save = req;
  13012. bool ret;
  13013. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  13014. auto req2 = req;
  13015. req2.path = "http://" +
  13016. detail::make_host_and_port_string(host_, port_, false) +
  13017. req.path;
  13018. ret = process_request(strm, req2, res, close_connection, error);
  13019. req = std::move(req2);
  13020. req.path = req_save.path;
  13021. } else {
  13022. ret = process_request(strm, req, res, close_connection, error);
  13023. }
  13024. if (!ret) { return false; }
  13025. if (detail::has_header_token(res.headers, "Connection", "close") ||
  13026. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  13027. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  13028. // for this to be safe.
  13029. // This is safe to call because handle_request is only called by send_
  13030. // which locks the request mutex during the process. It would be a bug
  13031. // to call it from a different thread since it's a thread-safety issue
  13032. // to do these things to the socket if another thread is using the socket.
  13033. std::lock_guard<std::mutex> guard(socket_mutex_);
  13034. disconnect(/*gracefully=*/true);
  13035. }
  13036. if (300 < res.status && res.status < 400 && follow_location_) {
  13037. req = std::move(req_save);
  13038. ret = redirect(req, res, error);
  13039. }
  13040. #ifdef CPPHTTPLIB_SSL_ENABLED
  13041. if ((res.status == StatusCode::Unauthorized_401 ||
  13042. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  13043. req.authorization_count_ < 5) {
  13044. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  13045. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  13046. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  13047. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  13048. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  13049. return ret;
  13050. }
  13051. const auto &username =
  13052. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  13053. const auto &password =
  13054. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  13055. if (!username.empty() && !password.empty()) {
  13056. std::map<std::string, std::string> auth;
  13057. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  13058. Request new_req = req;
  13059. new_req.authorization_count_ += 1;
  13060. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  13061. : "Authorization");
  13062. new_req.headers.insert(detail::make_digest_authentication_header(
  13063. req, auth, new_req.authorization_count_, detail::random_string(10),
  13064. username, password, is_proxy));
  13065. Response new_res;
  13066. ret = send(new_req, new_res, error);
  13067. if (ret) { res = std::move(new_res); }
  13068. }
  13069. }
  13070. }
  13071. #endif
  13072. return ret;
  13073. }
  13074. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  13075. if (req.redirect_count_ == 0) {
  13076. error = Error::ExceedRedirectCount;
  13077. output_error_log(error, &req);
  13078. return false;
  13079. }
  13080. auto location = res.get_header_value("location");
  13081. if (location.empty()) { return false; }
  13082. detail::UrlComponents uc;
  13083. if (!detail::parse_url(location, uc)) { return false; }
  13084. // Only follow http/https redirects
  13085. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  13086. return false;
  13087. }
  13088. auto scheme = is_ssl() ? "https" : "http";
  13089. auto next_scheme = std::move(uc.scheme);
  13090. auto next_host = std::move(uc.host);
  13091. auto port_str = std::move(uc.port);
  13092. auto next_path = std::move(uc.path);
  13093. auto next_query = std::move(uc.query);
  13094. auto next_port = port_;
  13095. if (!port_str.empty()) {
  13096. if (!detail::parse_port(port_str, next_port)) { return false; }
  13097. } else if (!next_scheme.empty()) {
  13098. next_port = next_scheme == "https" ? 443 : 80;
  13099. }
  13100. if (next_scheme.empty()) { next_scheme = scheme; }
  13101. if (next_host.empty()) { next_host = host_; }
  13102. if (next_path.empty()) { next_path = "/"; }
  13103. auto path = decode_path_component(next_path) + next_query;
  13104. // Same host redirect - use current client
  13105. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  13106. return detail::redirect(*this, req, res, path, location, error);
  13107. }
  13108. // Cross-host/scheme redirect - create new client with robust setup
  13109. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  13110. path, location, error);
  13111. }
  13112. // New method for robust redirect client creation
  13113. inline bool ClientImpl::create_redirect_client(
  13114. const std::string &scheme, const std::string &host, int port, Request &req,
  13115. Response &res, const std::string &path, const std::string &location,
  13116. Error &error) {
  13117. // Determine if we need SSL
  13118. auto need_ssl = (scheme == "https");
  13119. // Clean up request headers that are host/client specific
  13120. // Remove headers that should not be carried over to new host
  13121. auto headers_to_remove = std::vector<std::string>{
  13122. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  13123. for (const auto &header_name : headers_to_remove) {
  13124. auto it = req.headers.find(header_name);
  13125. while (it != req.headers.end()) {
  13126. it = req.headers.erase(it);
  13127. it = req.headers.find(header_name);
  13128. }
  13129. }
  13130. // Create appropriate client type and handle redirect
  13131. if (need_ssl) {
  13132. #ifdef CPPHTTPLIB_SSL_ENABLED
  13133. // Create SSL client for HTTPS redirect
  13134. SSLClient redirect_client(host, port);
  13135. // Setup basic client configuration first
  13136. setup_redirect_client(redirect_client);
  13137. redirect_client.enable_server_certificate_verification(
  13138. server_certificate_verification_);
  13139. redirect_client.enable_server_hostname_verification(
  13140. server_hostname_verification_);
  13141. redirect_client.system_ca_mode_ = system_ca_mode_;
  13142. // Transfer CA certificate to redirect client
  13143. if (!ca_cert_pem_.empty()) {
  13144. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  13145. ca_cert_pem_.size());
  13146. }
  13147. if (!ca_cert_file_path_.empty()) {
  13148. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  13149. }
  13150. // Client certificates are set through constructor for SSLClient
  13151. // NOTE: SSLClient constructor already takes client_cert_path and
  13152. // client_key_path so we need to create it properly if client certs are
  13153. // needed
  13154. // Execute the redirect
  13155. return detail::redirect(redirect_client, req, res, path, location, error);
  13156. #else
  13157. // SSL not supported - set appropriate error
  13158. error = Error::SSLConnection;
  13159. output_error_log(error, &req);
  13160. return false;
  13161. #endif
  13162. } else {
  13163. // HTTP redirect
  13164. ClientImpl redirect_client(host, port);
  13165. // Setup client with robust configuration
  13166. setup_redirect_client(redirect_client);
  13167. // Execute the redirect
  13168. return detail::redirect(redirect_client, req, res, path, location, error);
  13169. }
  13170. }
  13171. // New method for robust client setup (based on basic_manual_redirect.cpp
  13172. // logic)
  13173. template <typename ClientType>
  13174. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  13175. // Copy basic settings first
  13176. client.set_connection_timeout(connection_timeout_sec_);
  13177. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  13178. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  13179. client.set_keep_alive(keep_alive_);
  13180. client.set_follow_location(
  13181. true); // Enable redirects to handle multi-step redirects
  13182. client.set_path_encode(path_encode_);
  13183. client.set_compress(compress_);
  13184. client.set_decompress(decompress_);
  13185. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  13186. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  13187. // 15.4, credentials must not be forwarded when redirecting to a different
  13188. // host. This function is only called for cross-host redirects; same-host
  13189. // redirects are handled directly in ClientImpl::redirect().
  13190. // Copy the proxy configuration unconditionally; the per-target bypass is
  13191. // re-evaluated at send time, so a later hop to a non-bypassed host can
  13192. // still use the proxy.
  13193. client.no_proxy_entries_ = no_proxy_entries_;
  13194. if (!proxy_host_.empty() && proxy_port_ != -1) {
  13195. client.set_proxy(proxy_host_, proxy_port_);
  13196. if (!proxy_basic_auth_username_.empty()) {
  13197. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  13198. proxy_basic_auth_password_);
  13199. }
  13200. if (!proxy_bearer_token_auth_token_.empty()) {
  13201. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  13202. }
  13203. #ifdef CPPHTTPLIB_SSL_ENABLED
  13204. if (!proxy_digest_auth_username_.empty()) {
  13205. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  13206. proxy_digest_auth_password_);
  13207. }
  13208. #endif
  13209. }
  13210. // Copy network and socket settings
  13211. client.set_address_family(address_family_);
  13212. client.set_tcp_nodelay(tcp_nodelay_);
  13213. client.set_ipv6_v6only(ipv6_v6only_);
  13214. if (socket_options_) { client.set_socket_options(socket_options_); }
  13215. if (!interface_.empty()) { client.set_interface(interface_); }
  13216. // Copy logging and headers
  13217. if (logger_) { client.set_logger(logger_); }
  13218. if (error_logger_) { client.set_error_logger(error_logger_); }
  13219. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  13220. // Each new client should generate its own headers based on its target host
  13221. }
  13222. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  13223. const Request &req,
  13224. Error &error) const {
  13225. auto is_shutting_down = []() { return false; };
  13226. if (req.is_chunked_content_provider_) {
  13227. auto compressor = compress_ ? detail::create_compressor().first
  13228. : std::unique_ptr<detail::compressor>();
  13229. if (!compressor) {
  13230. compressor = detail::make_unique<detail::nocompressor>();
  13231. }
  13232. return detail::write_content_chunked(strm, req.content_provider_,
  13233. is_shutting_down, *compressor, error);
  13234. } else {
  13235. return detail::write_content_with_progress(
  13236. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  13237. req.upload_progress, error);
  13238. }
  13239. }
  13240. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  13241. bool close_connection, Error &error,
  13242. bool skip_body) {
  13243. // Prepare additional headers
  13244. if (close_connection) {
  13245. if (!req.has_header("Connection")) {
  13246. req.set_header("Connection", "close");
  13247. }
  13248. }
  13249. std::string ct_for_defaults;
  13250. if (!req.has_header("Content-Type") && !req.body.empty()) {
  13251. ct_for_defaults = "text/plain";
  13252. }
  13253. prepare_default_headers(req, false, ct_for_defaults);
  13254. if (req.body.empty()) {
  13255. if (req.content_provider_) {
  13256. if (!req.is_chunked_content_provider_) {
  13257. if (!req.has_header("Content-Length")) {
  13258. auto length = std::to_string(req.content_length_);
  13259. req.set_header("Content-Length", length);
  13260. }
  13261. }
  13262. } else {
  13263. if (req.method == "POST" || req.method == "PUT" ||
  13264. req.method == "PATCH") {
  13265. req.set_header("Content-Length", "0");
  13266. }
  13267. }
  13268. }
  13269. // A CONNECT request is read by the proxy; everything sent through the tunnel
  13270. // it opens is read by the origin. Each credential goes only to its own hop.
  13271. auto is_connect = req.method == "CONNECT";
  13272. if (!is_connect && !req.has_header("Authorization")) {
  13273. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  13274. req.headers.insert(make_basic_authentication_header(
  13275. basic_auth_username_, basic_auth_password_, false));
  13276. } else if (!bearer_token_auth_token_.empty()) {
  13277. req.headers.insert(make_bearer_token_authentication_header(
  13278. bearer_token_auth_token_, false));
  13279. }
  13280. }
  13281. // Proxy-Authorization is only sent when the proxy reads this message —
  13282. // otherwise NO_PROXY-matched requests, and requests inside a TLS tunnel,
  13283. // would leak proxy credentials to the destination server.
  13284. if (is_proxy_enabled_for_host(host_) && (!is_ssl() || is_connect)) {
  13285. if (!proxy_basic_auth_username_.empty() &&
  13286. !proxy_basic_auth_password_.empty() &&
  13287. !req.has_header("Proxy-Authorization")) {
  13288. req.headers.insert(make_basic_authentication_header(
  13289. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  13290. }
  13291. if (!proxy_bearer_token_auth_token_.empty() &&
  13292. !req.has_header("Proxy-Authorization")) {
  13293. req.headers.insert(make_bearer_token_authentication_header(
  13294. proxy_bearer_token_auth_token_, true));
  13295. }
  13296. }
  13297. // Request line and headers
  13298. {
  13299. detail::BufferStream bstrm;
  13300. // Extract the query from req.path. The encoding itself is delegated to
  13301. // `encode_request_target`; the raw query is still needed here to decide
  13302. // between populating `req.params` from it and falling back to building a
  13303. // query out of caller-supplied `req.params`.
  13304. auto query_pos = req.path.find('?');
  13305. auto query_part = query_pos == std::string::npos
  13306. ? std::string()
  13307. : req.path.substr(query_pos + 1);
  13308. auto path_with_query =
  13309. detail::encode_request_target(req.path, path_encode_);
  13310. if (!query_part.empty()) {
  13311. // The query already came in through `req.path`; still populate
  13312. // `req.params` for handlers/users who read them.
  13313. detail::parse_query_text(query_part, req.params);
  13314. } else if (!req.params.empty()) {
  13315. // No query in `req.path`; build one from `req.params` so existing
  13316. // callers that pass `Params` separately continue to work.
  13317. path_with_query = append_query_params(path_with_query, req.params);
  13318. }
  13319. // Write request line and headers
  13320. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  13321. // A rejected target (e.g. CR/LF smuggled in via a decoded redirect
  13322. // Location under set_path_encode(false)) must fail the request cleanly
  13323. // instead of emitting a request-line-less, header-injecting request.
  13324. error = Error::Write;
  13325. output_error_log(error, &req);
  13326. return false;
  13327. }
  13328. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  13329. error)) {
  13330. output_error_log(error, &req);
  13331. return false;
  13332. }
  13333. // Flush buffer
  13334. auto &data = bstrm.get_buffer();
  13335. if (!detail::write_data(strm, data.data(), data.size())) {
  13336. error = Error::Write;
  13337. output_error_log(error, &req);
  13338. return false;
  13339. }
  13340. }
  13341. // After sending request line and headers, wait briefly for an early server
  13342. // response (e.g. 4xx) and avoid sending a potentially large request body
  13343. // unnecessarily. This workaround is only enabled on Windows because Unix
  13344. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  13345. // buffering can accept large writes even when the peer already responded.
  13346. // Check the stream first (which covers SSL via `is_readable()`), then
  13347. // fall back to select on the socket. Only perform the wait for very large
  13348. // request bodies to avoid interfering with normal small requests and
  13349. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  13350. // response. Skip this check when using Expect: 100-continue, as the protocol
  13351. // handles early responses properly.
  13352. #if defined(_WIN32)
  13353. if (!skip_body &&
  13354. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  13355. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  13356. auto start = std::chrono::high_resolution_clock::now();
  13357. for (;;) {
  13358. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  13359. // from SSL internals. If the underlying socket is readable, assume an
  13360. // early response may be present.
  13361. auto sock = strm.socket();
  13362. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  13363. return false;
  13364. }
  13365. // Fallback to stream-level check for non-socket streams or when the
  13366. // socket isn't reporting readable. Avoid using `is_readable()` for
  13367. // SSL, since `SSL_pending()` may report buffered records that do not
  13368. // indicate a complete application-level response yet.
  13369. if (!is_ssl() && strm.is_readable()) { return false; }
  13370. auto now = std::chrono::high_resolution_clock::now();
  13371. auto elapsed =
  13372. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  13373. .count();
  13374. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  13375. break;
  13376. }
  13377. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  13378. }
  13379. }
  13380. #endif
  13381. // Body
  13382. if (skip_body) { return true; }
  13383. return write_request_body(strm, req, error);
  13384. }
  13385. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  13386. Error &error) {
  13387. if (req.body.empty()) {
  13388. return write_content_with_provider(strm, req, error);
  13389. }
  13390. if (req.upload_progress) {
  13391. auto body_size = req.body.size();
  13392. size_t written = 0;
  13393. auto data = req.body.data();
  13394. while (written < body_size) {
  13395. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  13396. if (!detail::write_data(strm, data + written, to_write)) {
  13397. error = Error::Write;
  13398. output_error_log(error, &req);
  13399. return false;
  13400. }
  13401. written += to_write;
  13402. if (!req.upload_progress(written, body_size)) {
  13403. error = Error::Canceled;
  13404. output_error_log(error, &req);
  13405. return false;
  13406. }
  13407. }
  13408. } else {
  13409. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  13410. error = Error::Write;
  13411. output_error_log(error, &req);
  13412. return false;
  13413. }
  13414. }
  13415. return true;
  13416. }
  13417. inline std::unique_ptr<Response>
  13418. ClientImpl::send_with_content_provider_and_receiver(
  13419. Request &req, const char *body, size_t content_length,
  13420. ContentProvider content_provider,
  13421. ContentProviderWithoutLength content_provider_without_length,
  13422. const std::string &content_type, ContentReceiver content_receiver,
  13423. Error &error) {
  13424. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  13425. auto enc = compress_
  13426. ? detail::create_compressor()
  13427. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  13428. nullptr, nullptr);
  13429. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  13430. if (enc.first && !content_provider_without_length) {
  13431. auto &compressor = enc.first;
  13432. if (content_provider) {
  13433. auto ok = true;
  13434. auto finished = false;
  13435. size_t offset = 0;
  13436. DataSink data_sink;
  13437. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  13438. if (ok) {
  13439. auto last = offset + data_len == content_length;
  13440. auto ret = compressor->compress(
  13441. data, data_len, last,
  13442. [&](const char *compressed_data, size_t compressed_data_len) {
  13443. req.body.append(compressed_data, compressed_data_len);
  13444. return true;
  13445. });
  13446. if (ret) {
  13447. offset += data_len;
  13448. } else {
  13449. ok = false;
  13450. }
  13451. }
  13452. return ok;
  13453. };
  13454. // As in detail::write_content_with_progress(): the body is framed by
  13455. // content_length, so a provider that finishes early has truncated it.
  13456. // Stop and report that instead of calling the provider forever.
  13457. data_sink.done = [&]() { finished = true; };
  13458. while (ok && !finished && offset < content_length) {
  13459. if (!content_provider(offset, content_length - offset, data_sink)) {
  13460. error = Error::Canceled;
  13461. output_error_log(error, &req);
  13462. return nullptr;
  13463. }
  13464. }
  13465. // A short body here means either the provider stopped early or the
  13466. // compressor gave up. The branch below reports a failing compressor as
  13467. // Error::Compression, so keep the two distinguishable.
  13468. if (offset < content_length) {
  13469. error = ok ? Error::Write : Error::Compression;
  13470. output_error_log(error, &req);
  13471. return nullptr;
  13472. }
  13473. } else {
  13474. if (!compressor->compress(body, content_length, true,
  13475. [&](const char *data, size_t data_len) {
  13476. req.body.append(data, data_len);
  13477. return true;
  13478. })) {
  13479. error = Error::Compression;
  13480. output_error_log(error, &req);
  13481. return nullptr;
  13482. }
  13483. }
  13484. } else {
  13485. if (content_provider) {
  13486. req.content_length_ = content_length;
  13487. req.content_provider_ = std::move(content_provider);
  13488. req.is_chunked_content_provider_ = false;
  13489. } else if (content_provider_without_length) {
  13490. req.content_length_ = 0;
  13491. req.content_provider_ = detail::ContentProviderAdapter(
  13492. std::move(content_provider_without_length));
  13493. req.is_chunked_content_provider_ = true;
  13494. req.set_header("Transfer-Encoding", "chunked");
  13495. } else {
  13496. req.body.assign(body, content_length);
  13497. }
  13498. }
  13499. if (content_receiver) {
  13500. req.content_receiver =
  13501. [content_receiver](const char *data, size_t data_length,
  13502. size_t /*offset*/, size_t /*total_length*/) {
  13503. return content_receiver(data, data_length);
  13504. };
  13505. }
  13506. auto res = detail::make_unique<Response>();
  13507. return send(req, *res, error) ? std::move(res) : nullptr;
  13508. }
  13509. inline Result ClientImpl::send_with_content_provider_and_receiver(
  13510. const std::string &method, const std::string &path, const Headers &headers,
  13511. const char *body, size_t content_length, ContentProvider content_provider,
  13512. ContentProviderWithoutLength content_provider_without_length,
  13513. const std::string &content_type, ContentReceiver content_receiver,
  13514. UploadProgress progress) {
  13515. Request req;
  13516. req.method = method;
  13517. req.headers = headers;
  13518. req.path = path;
  13519. req.upload_progress = std::move(progress);
  13520. if (max_timeout_msec_ > 0) {
  13521. req.start_time_ = std::chrono::steady_clock::now();
  13522. }
  13523. auto error = Error::Success;
  13524. auto res = send_with_content_provider_and_receiver(
  13525. req, body, content_length, std::move(content_provider),
  13526. std::move(content_provider_without_length), content_type,
  13527. std::move(content_receiver), error);
  13528. #ifdef CPPHTTPLIB_SSL_ENABLED
  13529. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  13530. last_backend_error_};
  13531. #else
  13532. return Result{std::move(res), error, std::move(req.headers)};
  13533. #endif
  13534. }
  13535. inline void ClientImpl::output_log(const Request &req,
  13536. const Response &res) const {
  13537. if (logger_) {
  13538. std::lock_guard<std::mutex> guard(logger_mutex_);
  13539. logger_(req, res);
  13540. }
  13541. }
  13542. inline void ClientImpl::output_error_log(const Error &err,
  13543. const Request *req) const {
  13544. if (error_logger_) {
  13545. std::lock_guard<std::mutex> guard(logger_mutex_);
  13546. error_logger_(err, req);
  13547. }
  13548. }
  13549. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  13550. Response &res, bool close_connection,
  13551. Error &error) {
  13552. // Auto-add Expect: 100-continue for large bodies
  13553. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  13554. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  13555. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  13556. req.set_header("Expect", "100-continue");
  13557. }
  13558. }
  13559. // Check for Expect: 100-continue
  13560. auto expect_100_continue =
  13561. detail::has_header_token(req.headers, "Expect", "100-continue");
  13562. // Send request (skip body if using Expect: 100-continue)
  13563. auto write_request_success =
  13564. write_request(strm, req, close_connection, error, expect_100_continue);
  13565. #ifdef CPPHTTPLIB_SSL_ENABLED
  13566. if (is_ssl() && !expect_100_continue) {
  13567. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  13568. if (!is_proxy_enabled) {
  13569. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  13570. error = Error::SSLPeerCouldBeClosed_;
  13571. output_error_log(error, &req);
  13572. return false;
  13573. }
  13574. }
  13575. }
  13576. #endif
  13577. // Handle Expect: 100-continue.
  13578. //
  13579. // Wait for an interim/early response by attempting to read the status line
  13580. // under a short timeout, instead of trusting raw socket readability. Over
  13581. // TLS, post-handshake records (e.g. session tickets) make the socket
  13582. // readable without any HTTP response being available; relying on
  13583. // `select_read` there caused the body to be withheld forever and the
  13584. // request to fail with `Read` (#2458). If no status line arrives within the
  13585. // timeout, send the body anyway (matching curl's behavior).
  13586. auto status_line_read = false;
  13587. if (expect_100_continue && write_request_success) {
  13588. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  13589. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  13590. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  13591. strm.set_read_timeout(sec, usec);
  13592. status_line_read = read_response_line(strm, req, res, false);
  13593. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  13594. }
  13595. if (!status_line_read) {
  13596. // No interim response within the timeout: send the body and handle the
  13597. // response as usual.
  13598. if (!write_request_body(strm, req, error)) { return false; }
  13599. expect_100_continue = false; // Switch to normal response handling
  13600. }
  13601. }
  13602. // Receive response and headers
  13603. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  13604. if ((!status_line_read &&
  13605. !read_response_line(strm, req, res, !expect_100_continue)) ||
  13606. !detail::read_headers(strm, res.headers)) {
  13607. if (write_request_success) { error = Error::Read; }
  13608. output_error_log(error, &req);
  13609. return false;
  13610. }
  13611. if (!write_request_success) { return false; }
  13612. // Handle Expect: 100-continue response
  13613. if (expect_100_continue) {
  13614. if (res.status == StatusCode::Continue_100) {
  13615. // Server accepted, send the body
  13616. if (!write_request_body(strm, req, error)) { return false; }
  13617. // Read the actual response
  13618. res.headers.clear();
  13619. res.body.clear();
  13620. if (!read_response_line(strm, req, res) ||
  13621. !detail::read_headers(strm, res.headers)) {
  13622. error = Error::Read;
  13623. output_error_log(error, &req);
  13624. return false;
  13625. }
  13626. }
  13627. // If not 100 Continue, server returned an error; proceed with that response
  13628. }
  13629. // Body
  13630. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  13631. req.method != "CONNECT") {
  13632. // Reject ambiguous framing (RFC 9112 §6.3). Unlike a request, a response
  13633. // whose final transfer coding is not chunked is not ambiguous: its body
  13634. // runs until the server closes the connection, so it is not rejected.
  13635. // HEAD/204 are excluded above and a 304 carries no body.
  13636. if (res.status != StatusCode::NotModified_304 &&
  13637. detail::has_conflicting_content_length(res.headers)) {
  13638. error = Error::Read;
  13639. output_error_log(error, &req);
  13640. return false;
  13641. }
  13642. auto redirect = 300 < res.status && res.status < 400 &&
  13643. res.status != StatusCode::NotModified_304 &&
  13644. follow_location_;
  13645. if (req.response_handler && !redirect) {
  13646. if (!req.response_handler(res)) {
  13647. error = Error::Canceled;
  13648. output_error_log(error, &req);
  13649. return false;
  13650. }
  13651. }
  13652. auto out =
  13653. req.content_receiver
  13654. ? static_cast<ContentReceiverWithProgress>(
  13655. [&](const char *buf, size_t n, size_t off, size_t len) {
  13656. if (redirect) { return true; }
  13657. auto ret = req.content_receiver(buf, n, off, len);
  13658. if (!ret) {
  13659. error = Error::Canceled;
  13660. output_error_log(error, &req);
  13661. }
  13662. return ret;
  13663. })
  13664. : static_cast<ContentReceiverWithProgress>(
  13665. [&](const char *buf, size_t n, size_t /*off*/,
  13666. size_t /*len*/) {
  13667. assert(res.body.size() + n <= res.body.max_size());
  13668. if (payload_max_length_ > 0 &&
  13669. (res.body.size() >= payload_max_length_ ||
  13670. n > payload_max_length_ - res.body.size())) {
  13671. return false;
  13672. }
  13673. res.body.append(buf, n);
  13674. return true;
  13675. });
  13676. auto progress = [&](size_t current, size_t total) {
  13677. if (!req.download_progress || redirect) { return true; }
  13678. auto ret = req.download_progress(current, total);
  13679. if (!ret) {
  13680. error = Error::Canceled;
  13681. output_error_log(error, &req);
  13682. }
  13683. return ret;
  13684. };
  13685. if (res.has_header("Content-Length")) {
  13686. if (!req.content_receiver) {
  13687. auto len = res.get_header_value_u64("Content-Length");
  13688. if (len > res.body.max_size()) {
  13689. error = Error::Read;
  13690. output_error_log(error, &req);
  13691. return false;
  13692. }
  13693. // Cap the reservation by payload_max_length_ to avoid OOM when a
  13694. // hostile or malformed server sends an enormous Content-Length.
  13695. // The actual body read below is bounded by payload_max_length_,
  13696. // so reserving more than that is never useful.
  13697. auto reserve_len = static_cast<size_t>(len);
  13698. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  13699. reserve_len = payload_max_length_;
  13700. }
  13701. res.body.reserve(reserve_len);
  13702. }
  13703. }
  13704. if (res.status != StatusCode::NotModified_304) {
  13705. auto content_status = 0;
  13706. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  13707. ? (std::numeric_limits<size_t>::max)()
  13708. : payload_max_length_;
  13709. if (!detail::read_content(strm, res, max_length, content_status,
  13710. std::move(progress), std::move(out),
  13711. decompress_)) {
  13712. if (error != Error::Canceled) {
  13713. // Tell the caller apart from a plain read failure when the body could
  13714. // not be decoded because of its Content-Encoding.
  13715. switch (content_status) {
  13716. case StatusCode::UnsupportedMediaType_415:
  13717. error = Error::UnsupportedContentEncoding;
  13718. break;
  13719. case StatusCode::InternalServerError_500:
  13720. error = Error::Compression;
  13721. break;
  13722. default: error = Error::Read; break;
  13723. }
  13724. }
  13725. output_error_log(error, &req);
  13726. return false;
  13727. }
  13728. }
  13729. }
  13730. // Log
  13731. output_log(req, res);
  13732. return true;
  13733. }
  13734. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  13735. const std::string &boundary, const UploadFormDataItems &items,
  13736. const FormDataProviderItems &provider_items) const {
  13737. size_t cur_item = 0;
  13738. size_t cur_start = 0;
  13739. // cur_item and cur_start are copied to within the std::function and
  13740. // maintain state between successive calls
  13741. return [&, cur_item, cur_start](size_t offset,
  13742. DataSink &sink) mutable -> bool {
  13743. if (!offset && !items.empty()) {
  13744. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  13745. return true;
  13746. } else if (cur_item < provider_items.size()) {
  13747. if (!cur_start) {
  13748. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  13749. provider_items[cur_item], boundary);
  13750. offset += begin.size();
  13751. cur_start = offset;
  13752. sink.os << begin;
  13753. }
  13754. DataSink cur_sink;
  13755. auto has_data = true;
  13756. cur_sink.write = sink.write;
  13757. // Forward is_writable so a provider item asking whether it may keep
  13758. // going gets the outer sink's answer rather than the default `true`.
  13759. cur_sink.is_writable = sink.is_writable;
  13760. cur_sink.done = [&]() { has_data = false; };
  13761. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  13762. return false;
  13763. }
  13764. if (!has_data) {
  13765. sink.os << detail::serialize_multipart_formdata_item_end();
  13766. cur_item++;
  13767. cur_start = 0;
  13768. }
  13769. return true;
  13770. } else {
  13771. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  13772. sink.done();
  13773. return true;
  13774. }
  13775. };
  13776. }
  13777. inline bool ClientImpl::process_socket(
  13778. const Socket &socket,
  13779. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13780. std::function<bool(Stream &strm)> callback) {
  13781. return detail::process_client_socket(
  13782. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13783. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  13784. }
  13785. inline bool ClientImpl::is_ssl() const { return false; }
  13786. inline Result ClientImpl::Get(const std::string &path,
  13787. DownloadProgress progress) {
  13788. return Get(path, Headers(), std::move(progress));
  13789. }
  13790. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13791. DownloadProgress progress) {
  13792. return Get(path, params, Headers(), std::move(progress));
  13793. }
  13794. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13795. const Headers &headers,
  13796. DownloadProgress progress) {
  13797. if (params.empty()) { return Get(path, headers); }
  13798. std::string path_with_query = append_query_params(path, params);
  13799. return Get(path_with_query, headers, std::move(progress));
  13800. }
  13801. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13802. DownloadProgress progress) {
  13803. Request req;
  13804. req.method = "GET";
  13805. req.path = path;
  13806. req.headers = headers;
  13807. req.download_progress = std::move(progress);
  13808. if (max_timeout_msec_ > 0) {
  13809. req.start_time_ = std::chrono::steady_clock::now();
  13810. }
  13811. return send_(std::move(req));
  13812. }
  13813. inline Result ClientImpl::Get(const std::string &path,
  13814. ContentReceiver content_receiver,
  13815. DownloadProgress progress) {
  13816. return Get(path, Headers(), nullptr, std::move(content_receiver),
  13817. std::move(progress));
  13818. }
  13819. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13820. ContentReceiver content_receiver,
  13821. DownloadProgress progress) {
  13822. return Get(path, headers, nullptr, std::move(content_receiver),
  13823. std::move(progress));
  13824. }
  13825. inline Result ClientImpl::Get(const std::string &path,
  13826. ResponseHandler response_handler,
  13827. ContentReceiver content_receiver,
  13828. DownloadProgress progress) {
  13829. return Get(path, Headers(), std::move(response_handler),
  13830. std::move(content_receiver), std::move(progress));
  13831. }
  13832. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13833. ResponseHandler response_handler,
  13834. ContentReceiver content_receiver,
  13835. DownloadProgress progress) {
  13836. Request req;
  13837. req.method = "GET";
  13838. req.path = path;
  13839. req.headers = headers;
  13840. req.response_handler = std::move(response_handler);
  13841. req.content_receiver =
  13842. [content_receiver](const char *data, size_t data_length,
  13843. size_t /*offset*/, size_t /*total_length*/) {
  13844. return content_receiver(data, data_length);
  13845. };
  13846. req.download_progress = std::move(progress);
  13847. if (max_timeout_msec_ > 0) {
  13848. req.start_time_ = std::chrono::steady_clock::now();
  13849. }
  13850. return send_(std::move(req));
  13851. }
  13852. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13853. const Headers &headers,
  13854. ContentReceiver content_receiver,
  13855. DownloadProgress progress) {
  13856. return Get(path, params, headers, nullptr, std::move(content_receiver),
  13857. std::move(progress));
  13858. }
  13859. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13860. const Headers &headers,
  13861. ResponseHandler response_handler,
  13862. ContentReceiver content_receiver,
  13863. DownloadProgress progress) {
  13864. if (params.empty()) {
  13865. return Get(path, headers, std::move(response_handler),
  13866. std::move(content_receiver), std::move(progress));
  13867. }
  13868. std::string path_with_query = append_query_params(path, params);
  13869. return Get(path_with_query, headers, std::move(response_handler),
  13870. std::move(content_receiver), std::move(progress));
  13871. }
  13872. inline Result ClientImpl::Head(const std::string &path) {
  13873. return Head(path, Headers());
  13874. }
  13875. inline Result ClientImpl::Head(const std::string &path,
  13876. const Headers &headers) {
  13877. Request req;
  13878. req.method = "HEAD";
  13879. req.headers = headers;
  13880. req.path = path;
  13881. if (max_timeout_msec_ > 0) {
  13882. req.start_time_ = std::chrono::steady_clock::now();
  13883. }
  13884. return send_(std::move(req));
  13885. }
  13886. inline Result ClientImpl::Post(const std::string &path) {
  13887. return Post(path, std::string(), std::string());
  13888. }
  13889. inline Result ClientImpl::Post(const std::string &path,
  13890. const Headers &headers) {
  13891. return Post(path, headers, nullptr, 0, std::string());
  13892. }
  13893. inline Result ClientImpl::Post(const std::string &path, const char *body,
  13894. size_t content_length,
  13895. const std::string &content_type,
  13896. UploadProgress progress) {
  13897. return Post(path, Headers(), body, content_length, content_type, progress);
  13898. }
  13899. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  13900. const std::string &content_type,
  13901. UploadProgress progress) {
  13902. return Post(path, Headers(), body, content_type, progress);
  13903. }
  13904. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  13905. return Post(path, Headers(), params);
  13906. }
  13907. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  13908. ContentProvider content_provider,
  13909. const std::string &content_type,
  13910. UploadProgress progress) {
  13911. return Post(path, Headers(), content_length, std::move(content_provider),
  13912. content_type, progress);
  13913. }
  13914. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  13915. ContentProvider content_provider,
  13916. const std::string &content_type,
  13917. ContentReceiver content_receiver,
  13918. UploadProgress progress) {
  13919. return Post(path, Headers(), content_length, std::move(content_provider),
  13920. content_type, std::move(content_receiver), progress);
  13921. }
  13922. inline Result ClientImpl::Post(const std::string &path,
  13923. ContentProviderWithoutLength content_provider,
  13924. const std::string &content_type,
  13925. UploadProgress progress) {
  13926. return Post(path, Headers(), std::move(content_provider), content_type,
  13927. progress);
  13928. }
  13929. inline Result ClientImpl::Post(const std::string &path,
  13930. ContentProviderWithoutLength content_provider,
  13931. const std::string &content_type,
  13932. ContentReceiver content_receiver,
  13933. UploadProgress progress) {
  13934. return Post(path, Headers(), std::move(content_provider), content_type,
  13935. std::move(content_receiver), progress);
  13936. }
  13937. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13938. const Params &params) {
  13939. auto query = detail::params_to_query_str(params);
  13940. return Post(path, headers, query, "application/x-www-form-urlencoded");
  13941. }
  13942. inline Result ClientImpl::Post(const std::string &path,
  13943. const UploadFormDataItems &items,
  13944. UploadProgress progress) {
  13945. return Post(path, Headers(), items, progress);
  13946. }
  13947. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13948. const UploadFormDataItems &items,
  13949. UploadProgress progress) {
  13950. const auto &boundary = detail::make_multipart_data_boundary();
  13951. const auto &content_type =
  13952. detail::serialize_multipart_formdata_get_content_type(boundary);
  13953. auto content_length = detail::get_multipart_content_length(items, boundary);
  13954. return Post(path, headers, content_length,
  13955. detail::make_multipart_content_provider(items, boundary),
  13956. content_type, progress);
  13957. }
  13958. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13959. const UploadFormDataItems &items,
  13960. const std::string &boundary,
  13961. UploadProgress progress) {
  13962. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  13963. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  13964. }
  13965. const auto &content_type =
  13966. detail::serialize_multipart_formdata_get_content_type(boundary);
  13967. auto content_length = detail::get_multipart_content_length(items, boundary);
  13968. return Post(path, headers, content_length,
  13969. detail::make_multipart_content_provider(items, boundary),
  13970. content_type, progress);
  13971. }
  13972. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13973. const char *body, size_t content_length,
  13974. const std::string &content_type,
  13975. UploadProgress progress) {
  13976. return send_with_content_provider_and_receiver(
  13977. "POST", path, headers, body, content_length, nullptr, nullptr,
  13978. content_type, nullptr, progress);
  13979. }
  13980. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13981. const std::string &body,
  13982. const std::string &content_type,
  13983. UploadProgress progress) {
  13984. return send_with_content_provider_and_receiver(
  13985. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  13986. content_type, nullptr, progress);
  13987. }
  13988. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13989. size_t content_length,
  13990. ContentProvider content_provider,
  13991. const std::string &content_type,
  13992. UploadProgress progress) {
  13993. return send_with_content_provider_and_receiver(
  13994. "POST", path, headers, nullptr, content_length,
  13995. std::move(content_provider), nullptr, content_type, nullptr, progress);
  13996. }
  13997. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  13998. size_t content_length,
  13999. ContentProvider content_provider,
  14000. const std::string &content_type,
  14001. ContentReceiver content_receiver,
  14002. DownloadProgress progress) {
  14003. return send_with_content_provider_and_receiver(
  14004. "POST", path, headers, nullptr, content_length,
  14005. std::move(content_provider), nullptr, content_type,
  14006. std::move(content_receiver), std::move(progress));
  14007. }
  14008. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14009. ContentProviderWithoutLength content_provider,
  14010. const std::string &content_type,
  14011. UploadProgress progress) {
  14012. return send_with_content_provider_and_receiver(
  14013. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14014. content_type, nullptr, progress);
  14015. }
  14016. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14017. ContentProviderWithoutLength content_provider,
  14018. const std::string &content_type,
  14019. ContentReceiver content_receiver,
  14020. DownloadProgress progress) {
  14021. return send_with_content_provider_and_receiver(
  14022. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14023. content_type, std::move(content_receiver), std::move(progress));
  14024. }
  14025. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14026. const UploadFormDataItems &items,
  14027. const FormDataProviderItems &provider_items,
  14028. UploadProgress progress) {
  14029. const auto &boundary = detail::make_multipart_data_boundary();
  14030. const auto &content_type =
  14031. detail::serialize_multipart_formdata_get_content_type(boundary);
  14032. return send_with_content_provider_and_receiver(
  14033. "POST", path, headers, nullptr, 0, nullptr,
  14034. get_multipart_content_provider(boundary, items, provider_items),
  14035. content_type, nullptr, progress);
  14036. }
  14037. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14038. const std::string &body,
  14039. const std::string &content_type,
  14040. ContentReceiver content_receiver,
  14041. DownloadProgress progress) {
  14042. Request req;
  14043. req.method = "POST";
  14044. req.path = path;
  14045. req.headers = headers;
  14046. req.body = body;
  14047. req.content_receiver =
  14048. [content_receiver](const char *data, size_t data_length,
  14049. size_t /*offset*/, size_t /*total_length*/) {
  14050. return content_receiver(data, data_length);
  14051. };
  14052. req.download_progress = std::move(progress);
  14053. if (max_timeout_msec_ > 0) {
  14054. req.start_time_ = std::chrono::steady_clock::now();
  14055. }
  14056. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14057. return send_(std::move(req));
  14058. }
  14059. inline Result ClientImpl::Put(const std::string &path) {
  14060. return Put(path, std::string(), std::string());
  14061. }
  14062. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  14063. return Put(path, headers, nullptr, 0, std::string());
  14064. }
  14065. inline Result ClientImpl::Put(const std::string &path, const char *body,
  14066. size_t content_length,
  14067. const std::string &content_type,
  14068. UploadProgress progress) {
  14069. return Put(path, Headers(), body, content_length, content_type, progress);
  14070. }
  14071. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  14072. const std::string &content_type,
  14073. UploadProgress progress) {
  14074. return Put(path, Headers(), body, content_type, progress);
  14075. }
  14076. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  14077. return Put(path, Headers(), params);
  14078. }
  14079. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  14080. ContentProvider content_provider,
  14081. const std::string &content_type,
  14082. UploadProgress progress) {
  14083. return Put(path, Headers(), content_length, std::move(content_provider),
  14084. content_type, progress);
  14085. }
  14086. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  14087. ContentProvider content_provider,
  14088. const std::string &content_type,
  14089. ContentReceiver content_receiver,
  14090. UploadProgress progress) {
  14091. return Put(path, Headers(), content_length, std::move(content_provider),
  14092. content_type, std::move(content_receiver), progress);
  14093. }
  14094. inline Result ClientImpl::Put(const std::string &path,
  14095. ContentProviderWithoutLength content_provider,
  14096. const std::string &content_type,
  14097. UploadProgress progress) {
  14098. return Put(path, Headers(), std::move(content_provider), content_type,
  14099. progress);
  14100. }
  14101. inline Result ClientImpl::Put(const std::string &path,
  14102. ContentProviderWithoutLength content_provider,
  14103. const std::string &content_type,
  14104. ContentReceiver content_receiver,
  14105. UploadProgress progress) {
  14106. return Put(path, Headers(), std::move(content_provider), content_type,
  14107. std::move(content_receiver), progress);
  14108. }
  14109. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14110. const Params &params) {
  14111. auto query = detail::params_to_query_str(params);
  14112. return Put(path, headers, query, "application/x-www-form-urlencoded");
  14113. }
  14114. inline Result ClientImpl::Put(const std::string &path,
  14115. const UploadFormDataItems &items,
  14116. UploadProgress progress) {
  14117. return Put(path, Headers(), items, progress);
  14118. }
  14119. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14120. const UploadFormDataItems &items,
  14121. UploadProgress progress) {
  14122. const auto &boundary = detail::make_multipart_data_boundary();
  14123. const auto &content_type =
  14124. detail::serialize_multipart_formdata_get_content_type(boundary);
  14125. auto content_length = detail::get_multipart_content_length(items, boundary);
  14126. return Put(path, headers, content_length,
  14127. detail::make_multipart_content_provider(items, boundary),
  14128. content_type, progress);
  14129. }
  14130. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14131. const UploadFormDataItems &items,
  14132. const std::string &boundary,
  14133. UploadProgress progress) {
  14134. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14135. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14136. }
  14137. const auto &content_type =
  14138. detail::serialize_multipart_formdata_get_content_type(boundary);
  14139. auto content_length = detail::get_multipart_content_length(items, boundary);
  14140. return Put(path, headers, content_length,
  14141. detail::make_multipart_content_provider(items, boundary),
  14142. content_type, progress);
  14143. }
  14144. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14145. const char *body, size_t content_length,
  14146. const std::string &content_type,
  14147. UploadProgress progress) {
  14148. return send_with_content_provider_and_receiver(
  14149. "PUT", path, headers, body, content_length, nullptr, nullptr,
  14150. content_type, nullptr, progress);
  14151. }
  14152. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14153. const std::string &body,
  14154. const std::string &content_type,
  14155. UploadProgress progress) {
  14156. return send_with_content_provider_and_receiver(
  14157. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  14158. content_type, nullptr, progress);
  14159. }
  14160. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14161. size_t content_length,
  14162. ContentProvider content_provider,
  14163. const std::string &content_type,
  14164. UploadProgress progress) {
  14165. return send_with_content_provider_and_receiver(
  14166. "PUT", path, headers, nullptr, content_length,
  14167. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14168. }
  14169. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14170. size_t content_length,
  14171. ContentProvider content_provider,
  14172. const std::string &content_type,
  14173. ContentReceiver content_receiver,
  14174. UploadProgress progress) {
  14175. return send_with_content_provider_and_receiver(
  14176. "PUT", path, headers, nullptr, content_length,
  14177. std::move(content_provider), nullptr, content_type,
  14178. std::move(content_receiver), progress);
  14179. }
  14180. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14181. ContentProviderWithoutLength content_provider,
  14182. const std::string &content_type,
  14183. UploadProgress progress) {
  14184. return send_with_content_provider_and_receiver(
  14185. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14186. content_type, nullptr, progress);
  14187. }
  14188. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14189. ContentProviderWithoutLength content_provider,
  14190. const std::string &content_type,
  14191. ContentReceiver content_receiver,
  14192. UploadProgress progress) {
  14193. return send_with_content_provider_and_receiver(
  14194. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14195. content_type, std::move(content_receiver), progress);
  14196. }
  14197. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14198. const UploadFormDataItems &items,
  14199. const FormDataProviderItems &provider_items,
  14200. UploadProgress progress) {
  14201. const auto &boundary = detail::make_multipart_data_boundary();
  14202. const auto &content_type =
  14203. detail::serialize_multipart_formdata_get_content_type(boundary);
  14204. return send_with_content_provider_and_receiver(
  14205. "PUT", path, headers, nullptr, 0, nullptr,
  14206. get_multipart_content_provider(boundary, items, provider_items),
  14207. content_type, nullptr, progress);
  14208. }
  14209. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14210. const std::string &body,
  14211. const std::string &content_type,
  14212. ContentReceiver content_receiver,
  14213. DownloadProgress progress) {
  14214. Request req;
  14215. req.method = "PUT";
  14216. req.path = path;
  14217. req.headers = headers;
  14218. req.body = body;
  14219. req.content_receiver =
  14220. [content_receiver](const char *data, size_t data_length,
  14221. size_t /*offset*/, size_t /*total_length*/) {
  14222. return content_receiver(data, data_length);
  14223. };
  14224. req.download_progress = std::move(progress);
  14225. if (max_timeout_msec_ > 0) {
  14226. req.start_time_ = std::chrono::steady_clock::now();
  14227. }
  14228. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14229. return send_(std::move(req));
  14230. }
  14231. inline Result ClientImpl::Patch(const std::string &path) {
  14232. return Patch(path, std::string(), std::string());
  14233. }
  14234. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14235. UploadProgress progress) {
  14236. return Patch(path, headers, nullptr, 0, std::string(), progress);
  14237. }
  14238. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  14239. size_t content_length,
  14240. const std::string &content_type,
  14241. UploadProgress progress) {
  14242. return Patch(path, Headers(), body, content_length, content_type, progress);
  14243. }
  14244. inline Result ClientImpl::Patch(const std::string &path,
  14245. const std::string &body,
  14246. const std::string &content_type,
  14247. UploadProgress progress) {
  14248. return Patch(path, Headers(), body, content_type, progress);
  14249. }
  14250. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  14251. return Patch(path, Headers(), params);
  14252. }
  14253. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  14254. ContentProvider content_provider,
  14255. const std::string &content_type,
  14256. UploadProgress progress) {
  14257. return Patch(path, Headers(), content_length, std::move(content_provider),
  14258. content_type, progress);
  14259. }
  14260. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  14261. ContentProvider content_provider,
  14262. const std::string &content_type,
  14263. ContentReceiver content_receiver,
  14264. UploadProgress progress) {
  14265. return Patch(path, Headers(), content_length, std::move(content_provider),
  14266. content_type, std::move(content_receiver), progress);
  14267. }
  14268. inline Result ClientImpl::Patch(const std::string &path,
  14269. ContentProviderWithoutLength content_provider,
  14270. const std::string &content_type,
  14271. UploadProgress progress) {
  14272. return Patch(path, Headers(), std::move(content_provider), content_type,
  14273. progress);
  14274. }
  14275. inline Result ClientImpl::Patch(const std::string &path,
  14276. ContentProviderWithoutLength content_provider,
  14277. const std::string &content_type,
  14278. ContentReceiver content_receiver,
  14279. UploadProgress progress) {
  14280. return Patch(path, Headers(), std::move(content_provider), content_type,
  14281. std::move(content_receiver), progress);
  14282. }
  14283. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14284. const Params &params) {
  14285. auto query = detail::params_to_query_str(params);
  14286. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  14287. }
  14288. inline Result ClientImpl::Patch(const std::string &path,
  14289. const UploadFormDataItems &items,
  14290. UploadProgress progress) {
  14291. return Patch(path, Headers(), items, progress);
  14292. }
  14293. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14294. const UploadFormDataItems &items,
  14295. UploadProgress progress) {
  14296. const auto &boundary = detail::make_multipart_data_boundary();
  14297. const auto &content_type =
  14298. detail::serialize_multipart_formdata_get_content_type(boundary);
  14299. auto content_length = detail::get_multipart_content_length(items, boundary);
  14300. return Patch(path, headers, content_length,
  14301. detail::make_multipart_content_provider(items, boundary),
  14302. content_type, progress);
  14303. }
  14304. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14305. const UploadFormDataItems &items,
  14306. const std::string &boundary,
  14307. UploadProgress progress) {
  14308. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14309. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14310. }
  14311. const auto &content_type =
  14312. detail::serialize_multipart_formdata_get_content_type(boundary);
  14313. auto content_length = detail::get_multipart_content_length(items, boundary);
  14314. return Patch(path, headers, content_length,
  14315. detail::make_multipart_content_provider(items, boundary),
  14316. content_type, progress);
  14317. }
  14318. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14319. const char *body, size_t content_length,
  14320. const std::string &content_type,
  14321. UploadProgress progress) {
  14322. return send_with_content_provider_and_receiver(
  14323. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  14324. content_type, nullptr, progress);
  14325. }
  14326. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14327. const std::string &body,
  14328. const std::string &content_type,
  14329. UploadProgress progress) {
  14330. return send_with_content_provider_and_receiver(
  14331. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  14332. content_type, nullptr, progress);
  14333. }
  14334. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14335. size_t content_length,
  14336. ContentProvider content_provider,
  14337. const std::string &content_type,
  14338. UploadProgress progress) {
  14339. return send_with_content_provider_and_receiver(
  14340. "PATCH", path, headers, nullptr, content_length,
  14341. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14342. }
  14343. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14344. size_t content_length,
  14345. ContentProvider content_provider,
  14346. const std::string &content_type,
  14347. ContentReceiver content_receiver,
  14348. UploadProgress progress) {
  14349. return send_with_content_provider_and_receiver(
  14350. "PATCH", path, headers, nullptr, content_length,
  14351. std::move(content_provider), nullptr, content_type,
  14352. std::move(content_receiver), progress);
  14353. }
  14354. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14355. ContentProviderWithoutLength content_provider,
  14356. const std::string &content_type,
  14357. UploadProgress progress) {
  14358. return send_with_content_provider_and_receiver(
  14359. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14360. content_type, nullptr, progress);
  14361. }
  14362. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14363. ContentProviderWithoutLength content_provider,
  14364. const std::string &content_type,
  14365. ContentReceiver content_receiver,
  14366. UploadProgress progress) {
  14367. return send_with_content_provider_and_receiver(
  14368. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14369. content_type, std::move(content_receiver), progress);
  14370. }
  14371. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14372. const UploadFormDataItems &items,
  14373. const FormDataProviderItems &provider_items,
  14374. UploadProgress progress) {
  14375. const auto &boundary = detail::make_multipart_data_boundary();
  14376. const auto &content_type =
  14377. detail::serialize_multipart_formdata_get_content_type(boundary);
  14378. return send_with_content_provider_and_receiver(
  14379. "PATCH", path, headers, nullptr, 0, nullptr,
  14380. get_multipart_content_provider(boundary, items, provider_items),
  14381. content_type, nullptr, progress);
  14382. }
  14383. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14384. const std::string &body,
  14385. const std::string &content_type,
  14386. ContentReceiver content_receiver,
  14387. DownloadProgress progress) {
  14388. Request req;
  14389. req.method = "PATCH";
  14390. req.path = path;
  14391. req.headers = headers;
  14392. req.body = body;
  14393. req.content_receiver =
  14394. [content_receiver](const char *data, size_t data_length,
  14395. size_t /*offset*/, size_t /*total_length*/) {
  14396. return content_receiver(data, data_length);
  14397. };
  14398. req.download_progress = std::move(progress);
  14399. if (max_timeout_msec_ > 0) {
  14400. req.start_time_ = std::chrono::steady_clock::now();
  14401. }
  14402. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14403. return send_(std::move(req));
  14404. }
  14405. inline Result ClientImpl::Delete(const std::string &path,
  14406. DownloadProgress progress) {
  14407. return Delete(path, Headers(), std::string(), std::string(), progress);
  14408. }
  14409. inline Result ClientImpl::Delete(const std::string &path,
  14410. const Headers &headers,
  14411. DownloadProgress progress) {
  14412. return Delete(path, headers, std::string(), std::string(), progress);
  14413. }
  14414. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  14415. size_t content_length,
  14416. const std::string &content_type,
  14417. DownloadProgress progress) {
  14418. return Delete(path, Headers(), body, content_length, content_type, progress);
  14419. }
  14420. inline Result ClientImpl::Delete(const std::string &path,
  14421. const std::string &body,
  14422. const std::string &content_type,
  14423. DownloadProgress progress) {
  14424. return Delete(path, Headers(), body.data(), body.size(), content_type,
  14425. progress);
  14426. }
  14427. inline Result ClientImpl::Delete(const std::string &path,
  14428. const Headers &headers,
  14429. const std::string &body,
  14430. const std::string &content_type,
  14431. DownloadProgress progress) {
  14432. return Delete(path, headers, body.data(), body.size(), content_type,
  14433. progress);
  14434. }
  14435. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  14436. DownloadProgress progress) {
  14437. return Delete(path, Headers(), params, progress);
  14438. }
  14439. inline Result ClientImpl::Delete(const std::string &path,
  14440. const Headers &headers, const Params &params,
  14441. DownloadProgress progress) {
  14442. auto query = detail::params_to_query_str(params);
  14443. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  14444. progress);
  14445. }
  14446. inline Result ClientImpl::Delete(const std::string &path,
  14447. const Headers &headers, const char *body,
  14448. size_t content_length,
  14449. const std::string &content_type,
  14450. DownloadProgress progress) {
  14451. Request req;
  14452. req.method = "DELETE";
  14453. req.headers = headers;
  14454. req.path = path;
  14455. req.download_progress = std::move(progress);
  14456. if (max_timeout_msec_ > 0) {
  14457. req.start_time_ = std::chrono::steady_clock::now();
  14458. }
  14459. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14460. req.body.assign(body, content_length);
  14461. return send_(std::move(req));
  14462. }
  14463. inline Result ClientImpl::Options(const std::string &path) {
  14464. return Options(path, Headers());
  14465. }
  14466. inline Result ClientImpl::Options(const std::string &path,
  14467. const Headers &headers) {
  14468. Request req;
  14469. req.method = "OPTIONS";
  14470. req.headers = headers;
  14471. req.path = path;
  14472. if (max_timeout_msec_ > 0) {
  14473. req.start_time_ = std::chrono::steady_clock::now();
  14474. }
  14475. return send_(std::move(req));
  14476. }
  14477. inline void ClientImpl::stop() {
  14478. std::lock_guard<std::mutex> guard(socket_mutex_);
  14479. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  14480. // do is to shutdown_socket, so that threads using this socket suddenly
  14481. // discover they can't read/write any more and error out. Everything else
  14482. // (closing the socket, shutting ssl down) is unsafe because these actions
  14483. // are not thread-safe.
  14484. if (socket_requests_in_flight_ > 0) {
  14485. shutdown_socket(socket_);
  14486. // Aside from that, we set a flag for the socket to be closed when we're
  14487. // done.
  14488. socket_should_be_closed_when_request_is_done_ = true;
  14489. return;
  14490. }
  14491. disconnect(/*gracefully=*/true);
  14492. }
  14493. inline std::string ClientImpl::host() const { return host_; }
  14494. inline int ClientImpl::port() const { return port_; }
  14495. inline size_t ClientImpl::is_socket_open() const {
  14496. std::lock_guard<std::mutex> guard(socket_mutex_);
  14497. return socket_.is_open();
  14498. }
  14499. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  14500. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  14501. connection_timeout_sec_ = sec;
  14502. connection_timeout_usec_ = usec;
  14503. }
  14504. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  14505. read_timeout_sec_ = sec;
  14506. read_timeout_usec_ = usec;
  14507. }
  14508. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  14509. write_timeout_sec_ = sec;
  14510. write_timeout_usec_ = usec;
  14511. }
  14512. inline void ClientImpl::set_max_timeout(time_t msec) {
  14513. max_timeout_msec_ = msec;
  14514. }
  14515. inline void ClientImpl::set_basic_auth(const std::string &username,
  14516. const std::string &password) {
  14517. basic_auth_username_ = username;
  14518. basic_auth_password_ = password;
  14519. }
  14520. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  14521. bearer_token_auth_token_ = token;
  14522. }
  14523. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  14524. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  14525. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  14526. inline void
  14527. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14528. addr_map_ = std::move(addr_map);
  14529. }
  14530. inline void ClientImpl::set_default_headers(Headers headers) {
  14531. default_headers_ = std::move(headers);
  14532. }
  14533. inline void ClientImpl::set_header_writer(
  14534. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14535. header_writer_ = writer;
  14536. }
  14537. inline void ClientImpl::set_address_family(int family) {
  14538. address_family_ = family;
  14539. }
  14540. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  14541. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  14542. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  14543. socket_options_ = std::move(socket_options);
  14544. }
  14545. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  14546. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  14547. inline void ClientImpl::set_payload_max_length(size_t length) {
  14548. payload_max_length_ = length;
  14549. has_payload_max_length_ = true;
  14550. }
  14551. inline void ClientImpl::set_interface(const std::string &intf) {
  14552. interface_ = intf;
  14553. }
  14554. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  14555. proxy_host_ = host;
  14556. proxy_port_ = port;
  14557. std::lock_guard<std::mutex> guard(socket_mutex_);
  14558. disconnect(/*gracefully=*/true);
  14559. }
  14560. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  14561. const std::string &password) {
  14562. proxy_basic_auth_username_ = username;
  14563. proxy_basic_auth_password_ = password;
  14564. }
  14565. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  14566. proxy_bearer_token_auth_token_ = token;
  14567. }
  14568. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  14569. std::vector<detail::NoProxyEntry> parsed;
  14570. parsed.reserve(patterns.size());
  14571. for (const auto &p : patterns) {
  14572. auto trimmed = detail::trim_copy(p);
  14573. if (trimmed.empty()) { continue; }
  14574. detail::NoProxyEntry entry;
  14575. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  14576. parsed.push_back(std::move(entry));
  14577. }
  14578. }
  14579. no_proxy_entries_ = std::move(parsed);
  14580. std::lock_guard<std::mutex> guard(socket_mutex_);
  14581. disconnect(/*gracefully=*/true);
  14582. }
  14583. #ifdef CPPHTTPLIB_SSL_ENABLED
  14584. inline void ClientImpl::set_digest_auth(const std::string &username,
  14585. const std::string &password) {
  14586. digest_auth_username_ = username;
  14587. digest_auth_password_ = password;
  14588. }
  14589. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  14590. const std::string &ca_cert_dir_path) {
  14591. ca_cert_file_path_ = ca_cert_file_path;
  14592. ca_cert_dir_path_ = ca_cert_dir_path;
  14593. }
  14594. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  14595. const std::string &password) {
  14596. proxy_digest_auth_username_ = username;
  14597. proxy_digest_auth_password_ = password;
  14598. }
  14599. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  14600. server_certificate_verification_ = enabled;
  14601. }
  14602. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  14603. server_hostname_verification_ = enabled;
  14604. }
  14605. inline void ClientImpl::enable_system_ca(bool enabled) {
  14606. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  14607. }
  14608. #endif
  14609. inline void ClientImpl::set_logger(Logger logger) {
  14610. logger_ = std::move(logger);
  14611. }
  14612. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  14613. error_logger_ = std::move(error_logger);
  14614. }
  14615. /*
  14616. * SSL/TLS Common Implementation
  14617. */
  14618. inline ClientConnection::~ClientConnection() {
  14619. #ifdef CPPHTTPLIB_SSL_ENABLED
  14620. if (session) {
  14621. tls::shutdown(session, true);
  14622. tls::free_session(session);
  14623. session = nullptr;
  14624. }
  14625. #endif
  14626. if (sock != INVALID_SOCKET) {
  14627. detail::close_socket(sock);
  14628. sock = INVALID_SOCKET;
  14629. }
  14630. }
  14631. // Universal client implementation
  14632. inline Client::Client(const std::string &scheme_host_port)
  14633. : Client(scheme_host_port, std::string(), std::string()) {}
  14634. inline Client::Client(const std::string &scheme_host_port,
  14635. const std::string &client_cert_path,
  14636. const std::string &client_key_path) {
  14637. detail::UrlComponents uc;
  14638. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  14639. auto &scheme = uc.scheme;
  14640. #ifdef CPPHTTPLIB_SSL_ENABLED
  14641. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  14642. #else
  14643. if (!scheme.empty() && scheme != "http") {
  14644. #endif
  14645. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14646. std::string msg = "'" + scheme + "' scheme is not supported.";
  14647. throw std::invalid_argument(msg);
  14648. #endif
  14649. return;
  14650. }
  14651. auto is_ssl = scheme == "https";
  14652. auto host = std::move(uc.host);
  14653. auto port = is_ssl ? 443 : 80;
  14654. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  14655. if (is_ssl) {
  14656. #ifdef CPPHTTPLIB_SSL_ENABLED
  14657. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  14658. client_key_path);
  14659. is_ssl_ = is_ssl;
  14660. #endif
  14661. } else {
  14662. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  14663. client_key_path);
  14664. }
  14665. } else {
  14666. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  14667. // if port param below changes.
  14668. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  14669. client_cert_path, client_key_path);
  14670. }
  14671. }
  14672. inline Client::Client(const std::string &host, int port)
  14673. : Client(host, port, std::string(), std::string()) {}
  14674. inline Client::Client(const std::string &host, int port,
  14675. const std::string &client_cert_path,
  14676. const std::string &client_key_path)
  14677. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  14678. client_key_path)) {}
  14679. inline Client::~Client() = default;
  14680. inline bool Client::is_valid() const {
  14681. return cli_ != nullptr && cli_->is_valid();
  14682. }
  14683. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  14684. return cli_->Get(path, std::move(progress));
  14685. }
  14686. inline Result Client::Get(const std::string &path, const Headers &headers,
  14687. DownloadProgress progress) {
  14688. return cli_->Get(path, headers, std::move(progress));
  14689. }
  14690. inline Result Client::Get(const std::string &path,
  14691. ContentReceiver content_receiver,
  14692. DownloadProgress progress) {
  14693. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  14694. }
  14695. inline Result Client::Get(const std::string &path, const Headers &headers,
  14696. ContentReceiver content_receiver,
  14697. DownloadProgress progress) {
  14698. return cli_->Get(path, headers, std::move(content_receiver),
  14699. std::move(progress));
  14700. }
  14701. inline Result Client::Get(const std::string &path,
  14702. ResponseHandler response_handler,
  14703. ContentReceiver content_receiver,
  14704. DownloadProgress progress) {
  14705. return cli_->Get(path, std::move(response_handler),
  14706. std::move(content_receiver), std::move(progress));
  14707. }
  14708. inline Result Client::Get(const std::string &path, const Headers &headers,
  14709. ResponseHandler response_handler,
  14710. ContentReceiver content_receiver,
  14711. DownloadProgress progress) {
  14712. return cli_->Get(path, headers, std::move(response_handler),
  14713. std::move(content_receiver), std::move(progress));
  14714. }
  14715. inline Result Client::Get(const std::string &path, const Params &params,
  14716. DownloadProgress progress) {
  14717. return cli_->Get(path, params, std::move(progress));
  14718. }
  14719. inline Result Client::Get(const std::string &path, const Params &params,
  14720. const Headers &headers, DownloadProgress progress) {
  14721. return cli_->Get(path, params, headers, std::move(progress));
  14722. }
  14723. inline Result Client::Get(const std::string &path, const Params &params,
  14724. const Headers &headers,
  14725. ContentReceiver content_receiver,
  14726. DownloadProgress progress) {
  14727. return cli_->Get(path, params, headers, std::move(content_receiver),
  14728. std::move(progress));
  14729. }
  14730. inline Result Client::Get(const std::string &path, const Params &params,
  14731. const Headers &headers,
  14732. ResponseHandler response_handler,
  14733. ContentReceiver content_receiver,
  14734. DownloadProgress progress) {
  14735. return cli_->Get(path, params, headers, std::move(response_handler),
  14736. std::move(content_receiver), std::move(progress));
  14737. }
  14738. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  14739. inline Result Client::Head(const std::string &path, const Headers &headers) {
  14740. return cli_->Head(path, headers);
  14741. }
  14742. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  14743. inline Result Client::Post(const std::string &path, const Headers &headers) {
  14744. return cli_->Post(path, headers);
  14745. }
  14746. inline Result Client::Post(const std::string &path, const char *body,
  14747. size_t content_length,
  14748. const std::string &content_type,
  14749. UploadProgress progress) {
  14750. return cli_->Post(path, body, content_length, content_type, progress);
  14751. }
  14752. inline Result Client::Post(const std::string &path, const Headers &headers,
  14753. const char *body, size_t content_length,
  14754. const std::string &content_type,
  14755. UploadProgress progress) {
  14756. return cli_->Post(path, headers, body, content_length, content_type,
  14757. progress);
  14758. }
  14759. inline Result Client::Post(const std::string &path, const std::string &body,
  14760. const std::string &content_type,
  14761. UploadProgress progress) {
  14762. return cli_->Post(path, body, content_type, progress);
  14763. }
  14764. inline Result Client::Post(const std::string &path, const Headers &headers,
  14765. const std::string &body,
  14766. const std::string &content_type,
  14767. UploadProgress progress) {
  14768. return cli_->Post(path, headers, body, content_type, progress);
  14769. }
  14770. inline Result Client::Post(const std::string &path, size_t content_length,
  14771. ContentProvider content_provider,
  14772. const std::string &content_type,
  14773. UploadProgress progress) {
  14774. return cli_->Post(path, content_length, std::move(content_provider),
  14775. content_type, progress);
  14776. }
  14777. inline Result Client::Post(const std::string &path, size_t content_length,
  14778. ContentProvider content_provider,
  14779. const std::string &content_type,
  14780. ContentReceiver content_receiver,
  14781. UploadProgress progress) {
  14782. return cli_->Post(path, content_length, std::move(content_provider),
  14783. content_type, std::move(content_receiver), progress);
  14784. }
  14785. inline Result Client::Post(const std::string &path,
  14786. ContentProviderWithoutLength content_provider,
  14787. const std::string &content_type,
  14788. UploadProgress progress) {
  14789. return cli_->Post(path, std::move(content_provider), content_type, progress);
  14790. }
  14791. inline Result Client::Post(const std::string &path,
  14792. ContentProviderWithoutLength content_provider,
  14793. const std::string &content_type,
  14794. ContentReceiver content_receiver,
  14795. UploadProgress progress) {
  14796. return cli_->Post(path, std::move(content_provider), content_type,
  14797. std::move(content_receiver), progress);
  14798. }
  14799. inline Result Client::Post(const std::string &path, const Headers &headers,
  14800. size_t content_length,
  14801. ContentProvider content_provider,
  14802. const std::string &content_type,
  14803. UploadProgress progress) {
  14804. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14805. content_type, progress);
  14806. }
  14807. inline Result Client::Post(const std::string &path, const Headers &headers,
  14808. size_t content_length,
  14809. ContentProvider content_provider,
  14810. const std::string &content_type,
  14811. ContentReceiver content_receiver,
  14812. DownloadProgress progress) {
  14813. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14814. content_type, std::move(content_receiver), progress);
  14815. }
  14816. inline Result Client::Post(const std::string &path, const Headers &headers,
  14817. ContentProviderWithoutLength content_provider,
  14818. const std::string &content_type,
  14819. UploadProgress progress) {
  14820. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14821. progress);
  14822. }
  14823. inline Result Client::Post(const std::string &path, const Headers &headers,
  14824. ContentProviderWithoutLength content_provider,
  14825. const std::string &content_type,
  14826. ContentReceiver content_receiver,
  14827. DownloadProgress progress) {
  14828. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14829. std::move(content_receiver), progress);
  14830. }
  14831. inline Result Client::Post(const std::string &path, const Params &params) {
  14832. return cli_->Post(path, params);
  14833. }
  14834. inline Result Client::Post(const std::string &path, const Headers &headers,
  14835. const Params &params) {
  14836. return cli_->Post(path, headers, params);
  14837. }
  14838. inline Result Client::Post(const std::string &path,
  14839. const UploadFormDataItems &items,
  14840. UploadProgress progress) {
  14841. return cli_->Post(path, items, progress);
  14842. }
  14843. inline Result Client::Post(const std::string &path, const Headers &headers,
  14844. const UploadFormDataItems &items,
  14845. UploadProgress progress) {
  14846. return cli_->Post(path, headers, items, progress);
  14847. }
  14848. inline Result Client::Post(const std::string &path, const Headers &headers,
  14849. const UploadFormDataItems &items,
  14850. const std::string &boundary,
  14851. UploadProgress progress) {
  14852. return cli_->Post(path, headers, items, boundary, progress);
  14853. }
  14854. inline Result Client::Post(const std::string &path, const Headers &headers,
  14855. const UploadFormDataItems &items,
  14856. const FormDataProviderItems &provider_items,
  14857. UploadProgress progress) {
  14858. return cli_->Post(path, headers, items, provider_items, progress);
  14859. }
  14860. inline Result Client::Post(const std::string &path, const Headers &headers,
  14861. const std::string &body,
  14862. const std::string &content_type,
  14863. ContentReceiver content_receiver,
  14864. DownloadProgress progress) {
  14865. return cli_->Post(path, headers, body, content_type,
  14866. std::move(content_receiver), progress);
  14867. }
  14868. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  14869. inline Result Client::Put(const std::string &path, const Headers &headers) {
  14870. return cli_->Put(path, headers);
  14871. }
  14872. inline Result Client::Put(const std::string &path, const char *body,
  14873. size_t content_length,
  14874. const std::string &content_type,
  14875. UploadProgress progress) {
  14876. return cli_->Put(path, body, content_length, content_type, progress);
  14877. }
  14878. inline Result Client::Put(const std::string &path, const Headers &headers,
  14879. const char *body, size_t content_length,
  14880. const std::string &content_type,
  14881. UploadProgress progress) {
  14882. return cli_->Put(path, headers, body, content_length, content_type, progress);
  14883. }
  14884. inline Result Client::Put(const std::string &path, const std::string &body,
  14885. const std::string &content_type,
  14886. UploadProgress progress) {
  14887. return cli_->Put(path, body, content_type, progress);
  14888. }
  14889. inline Result Client::Put(const std::string &path, const Headers &headers,
  14890. const std::string &body,
  14891. const std::string &content_type,
  14892. UploadProgress progress) {
  14893. return cli_->Put(path, headers, body, content_type, progress);
  14894. }
  14895. inline Result Client::Put(const std::string &path, size_t content_length,
  14896. ContentProvider content_provider,
  14897. const std::string &content_type,
  14898. UploadProgress progress) {
  14899. return cli_->Put(path, content_length, std::move(content_provider),
  14900. content_type, progress);
  14901. }
  14902. inline Result Client::Put(const std::string &path, size_t content_length,
  14903. ContentProvider content_provider,
  14904. const std::string &content_type,
  14905. ContentReceiver content_receiver,
  14906. UploadProgress progress) {
  14907. return cli_->Put(path, content_length, std::move(content_provider),
  14908. content_type, std::move(content_receiver), progress);
  14909. }
  14910. inline Result Client::Put(const std::string &path,
  14911. ContentProviderWithoutLength content_provider,
  14912. const std::string &content_type,
  14913. UploadProgress progress) {
  14914. return cli_->Put(path, std::move(content_provider), content_type, progress);
  14915. }
  14916. inline Result Client::Put(const std::string &path,
  14917. ContentProviderWithoutLength content_provider,
  14918. const std::string &content_type,
  14919. ContentReceiver content_receiver,
  14920. UploadProgress progress) {
  14921. return cli_->Put(path, std::move(content_provider), content_type,
  14922. std::move(content_receiver), progress);
  14923. }
  14924. inline Result Client::Put(const std::string &path, const Headers &headers,
  14925. size_t content_length,
  14926. ContentProvider content_provider,
  14927. const std::string &content_type,
  14928. UploadProgress progress) {
  14929. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14930. content_type, progress);
  14931. }
  14932. inline Result Client::Put(const std::string &path, const Headers &headers,
  14933. size_t content_length,
  14934. ContentProvider content_provider,
  14935. const std::string &content_type,
  14936. ContentReceiver content_receiver,
  14937. UploadProgress progress) {
  14938. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14939. content_type, std::move(content_receiver), progress);
  14940. }
  14941. inline Result Client::Put(const std::string &path, const Headers &headers,
  14942. ContentProviderWithoutLength content_provider,
  14943. const std::string &content_type,
  14944. UploadProgress progress) {
  14945. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14946. progress);
  14947. }
  14948. inline Result Client::Put(const std::string &path, const Headers &headers,
  14949. ContentProviderWithoutLength content_provider,
  14950. const std::string &content_type,
  14951. ContentReceiver content_receiver,
  14952. UploadProgress progress) {
  14953. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14954. std::move(content_receiver), progress);
  14955. }
  14956. inline Result Client::Put(const std::string &path, const Params &params) {
  14957. return cli_->Put(path, params);
  14958. }
  14959. inline Result Client::Put(const std::string &path, const Headers &headers,
  14960. const Params &params) {
  14961. return cli_->Put(path, headers, params);
  14962. }
  14963. inline Result Client::Put(const std::string &path,
  14964. const UploadFormDataItems &items,
  14965. UploadProgress progress) {
  14966. return cli_->Put(path, items, progress);
  14967. }
  14968. inline Result Client::Put(const std::string &path, const Headers &headers,
  14969. const UploadFormDataItems &items,
  14970. UploadProgress progress) {
  14971. return cli_->Put(path, headers, items, progress);
  14972. }
  14973. inline Result Client::Put(const std::string &path, const Headers &headers,
  14974. const UploadFormDataItems &items,
  14975. const std::string &boundary,
  14976. UploadProgress progress) {
  14977. return cli_->Put(path, headers, items, boundary, progress);
  14978. }
  14979. inline Result Client::Put(const std::string &path, const Headers &headers,
  14980. const UploadFormDataItems &items,
  14981. const FormDataProviderItems &provider_items,
  14982. UploadProgress progress) {
  14983. return cli_->Put(path, headers, items, provider_items, progress);
  14984. }
  14985. inline Result Client::Put(const std::string &path, const Headers &headers,
  14986. const std::string &body,
  14987. const std::string &content_type,
  14988. ContentReceiver content_receiver,
  14989. DownloadProgress progress) {
  14990. return cli_->Put(path, headers, body, content_type, content_receiver,
  14991. progress);
  14992. }
  14993. inline Result Client::Patch(const std::string &path) {
  14994. return cli_->Patch(path);
  14995. }
  14996. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  14997. return cli_->Patch(path, headers);
  14998. }
  14999. inline Result Client::Patch(const std::string &path, const char *body,
  15000. size_t content_length,
  15001. const std::string &content_type,
  15002. UploadProgress progress) {
  15003. return cli_->Patch(path, body, content_length, content_type, progress);
  15004. }
  15005. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15006. const char *body, size_t content_length,
  15007. const std::string &content_type,
  15008. UploadProgress progress) {
  15009. return cli_->Patch(path, headers, body, content_length, content_type,
  15010. progress);
  15011. }
  15012. inline Result Client::Patch(const std::string &path, const std::string &body,
  15013. const std::string &content_type,
  15014. UploadProgress progress) {
  15015. return cli_->Patch(path, body, content_type, progress);
  15016. }
  15017. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15018. const std::string &body,
  15019. const std::string &content_type,
  15020. UploadProgress progress) {
  15021. return cli_->Patch(path, headers, body, content_type, progress);
  15022. }
  15023. inline Result Client::Patch(const std::string &path, size_t content_length,
  15024. ContentProvider content_provider,
  15025. const std::string &content_type,
  15026. UploadProgress progress) {
  15027. return cli_->Patch(path, content_length, std::move(content_provider),
  15028. content_type, progress);
  15029. }
  15030. inline Result Client::Patch(const std::string &path, size_t content_length,
  15031. ContentProvider content_provider,
  15032. const std::string &content_type,
  15033. ContentReceiver content_receiver,
  15034. UploadProgress progress) {
  15035. return cli_->Patch(path, content_length, std::move(content_provider),
  15036. content_type, std::move(content_receiver), progress);
  15037. }
  15038. inline Result Client::Patch(const std::string &path,
  15039. ContentProviderWithoutLength content_provider,
  15040. const std::string &content_type,
  15041. UploadProgress progress) {
  15042. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  15043. }
  15044. inline Result Client::Patch(const std::string &path,
  15045. ContentProviderWithoutLength content_provider,
  15046. const std::string &content_type,
  15047. ContentReceiver content_receiver,
  15048. UploadProgress progress) {
  15049. return cli_->Patch(path, std::move(content_provider), content_type,
  15050. std::move(content_receiver), progress);
  15051. }
  15052. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15053. size_t content_length,
  15054. ContentProvider content_provider,
  15055. const std::string &content_type,
  15056. UploadProgress progress) {
  15057. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  15058. content_type, progress);
  15059. }
  15060. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15061. size_t content_length,
  15062. ContentProvider content_provider,
  15063. const std::string &content_type,
  15064. ContentReceiver content_receiver,
  15065. UploadProgress progress) {
  15066. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  15067. content_type, std::move(content_receiver), progress);
  15068. }
  15069. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15070. ContentProviderWithoutLength content_provider,
  15071. const std::string &content_type,
  15072. UploadProgress progress) {
  15073. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  15074. progress);
  15075. }
  15076. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15077. ContentProviderWithoutLength content_provider,
  15078. const std::string &content_type,
  15079. ContentReceiver content_receiver,
  15080. UploadProgress progress) {
  15081. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  15082. std::move(content_receiver), progress);
  15083. }
  15084. inline Result Client::Patch(const std::string &path, const Params &params) {
  15085. return cli_->Patch(path, params);
  15086. }
  15087. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15088. const Params &params) {
  15089. return cli_->Patch(path, headers, params);
  15090. }
  15091. inline Result Client::Patch(const std::string &path,
  15092. const UploadFormDataItems &items,
  15093. UploadProgress progress) {
  15094. return cli_->Patch(path, items, progress);
  15095. }
  15096. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15097. const UploadFormDataItems &items,
  15098. UploadProgress progress) {
  15099. return cli_->Patch(path, headers, items, progress);
  15100. }
  15101. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15102. const UploadFormDataItems &items,
  15103. const std::string &boundary,
  15104. UploadProgress progress) {
  15105. return cli_->Patch(path, headers, items, boundary, progress);
  15106. }
  15107. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15108. const UploadFormDataItems &items,
  15109. const FormDataProviderItems &provider_items,
  15110. UploadProgress progress) {
  15111. return cli_->Patch(path, headers, items, provider_items, progress);
  15112. }
  15113. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15114. const std::string &body,
  15115. const std::string &content_type,
  15116. ContentReceiver content_receiver,
  15117. DownloadProgress progress) {
  15118. return cli_->Patch(path, headers, body, content_type, content_receiver,
  15119. progress);
  15120. }
  15121. inline Result Client::Delete(const std::string &path,
  15122. DownloadProgress progress) {
  15123. return cli_->Delete(path, progress);
  15124. }
  15125. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15126. DownloadProgress progress) {
  15127. return cli_->Delete(path, headers, progress);
  15128. }
  15129. inline Result Client::Delete(const std::string &path, const char *body,
  15130. size_t content_length,
  15131. const std::string &content_type,
  15132. DownloadProgress progress) {
  15133. return cli_->Delete(path, body, content_length, content_type, progress);
  15134. }
  15135. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15136. const char *body, size_t content_length,
  15137. const std::string &content_type,
  15138. DownloadProgress progress) {
  15139. return cli_->Delete(path, headers, body, content_length, content_type,
  15140. progress);
  15141. }
  15142. inline Result Client::Delete(const std::string &path, const std::string &body,
  15143. const std::string &content_type,
  15144. DownloadProgress progress) {
  15145. return cli_->Delete(path, body, content_type, progress);
  15146. }
  15147. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15148. const std::string &body,
  15149. const std::string &content_type,
  15150. DownloadProgress progress) {
  15151. return cli_->Delete(path, headers, body, content_type, progress);
  15152. }
  15153. inline Result Client::Delete(const std::string &path, const Params &params,
  15154. DownloadProgress progress) {
  15155. return cli_->Delete(path, params, progress);
  15156. }
  15157. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15158. const Params &params, DownloadProgress progress) {
  15159. return cli_->Delete(path, headers, params, progress);
  15160. }
  15161. inline Result Client::Options(const std::string &path) {
  15162. return cli_->Options(path);
  15163. }
  15164. inline Result Client::Options(const std::string &path, const Headers &headers) {
  15165. return cli_->Options(path, headers);
  15166. }
  15167. inline ClientImpl::StreamHandle
  15168. Client::open_stream(const std::string &method, const std::string &path,
  15169. const Params &params, const Headers &headers,
  15170. const std::string &body, const std::string &content_type) {
  15171. return cli_->open_stream(method, path, params, headers, body, content_type);
  15172. }
  15173. inline bool Client::send(Request &req, Response &res, Error &error) {
  15174. return cli_->send(req, res, error);
  15175. }
  15176. inline Result Client::send(const Request &req) { return cli_->send(req); }
  15177. inline void Client::stop() { cli_->stop(); }
  15178. inline std::string Client::host() const { return cli_->host(); }
  15179. inline int Client::port() const { return cli_->port(); }
  15180. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  15181. inline socket_t Client::socket() const { return cli_->socket(); }
  15182. inline void
  15183. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  15184. cli_->set_hostname_addr_map(std::move(addr_map));
  15185. }
  15186. inline void Client::set_default_headers(Headers headers) {
  15187. cli_->set_default_headers(std::move(headers));
  15188. }
  15189. inline void Client::set_header_writer(
  15190. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  15191. cli_->set_header_writer(writer);
  15192. }
  15193. inline void Client::set_address_family(int family) {
  15194. cli_->set_address_family(family);
  15195. }
  15196. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  15197. inline void Client::set_socket_options(SocketOptions socket_options) {
  15198. cli_->set_socket_options(std::move(socket_options));
  15199. }
  15200. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  15201. cli_->set_connection_timeout(sec, usec);
  15202. }
  15203. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  15204. cli_->set_read_timeout(sec, usec);
  15205. }
  15206. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  15207. cli_->set_write_timeout(sec, usec);
  15208. }
  15209. inline void Client::set_basic_auth(const std::string &username,
  15210. const std::string &password) {
  15211. cli_->set_basic_auth(username, password);
  15212. }
  15213. inline void Client::set_bearer_token_auth(const std::string &token) {
  15214. cli_->set_bearer_token_auth(token);
  15215. }
  15216. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  15217. inline void Client::set_follow_location(bool on) {
  15218. cli_->set_follow_location(on);
  15219. }
  15220. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  15221. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  15222. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  15223. inline void Client::set_payload_max_length(size_t length) {
  15224. cli_->set_payload_max_length(length);
  15225. }
  15226. inline void Client::set_interface(const std::string &intf) {
  15227. cli_->set_interface(intf);
  15228. }
  15229. inline void Client::set_proxy(const std::string &host, int port) {
  15230. cli_->set_proxy(host, port);
  15231. }
  15232. inline void Client::set_proxy_basic_auth(const std::string &username,
  15233. const std::string &password) {
  15234. cli_->set_proxy_basic_auth(username, password);
  15235. }
  15236. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  15237. cli_->set_proxy_bearer_token_auth(token);
  15238. }
  15239. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  15240. cli_->set_no_proxy(patterns);
  15241. }
  15242. inline void Client::set_logger(Logger logger) {
  15243. cli_->set_logger(std::move(logger));
  15244. }
  15245. inline void Client::set_error_logger(ErrorLogger error_logger) {
  15246. cli_->set_error_logger(std::move(error_logger));
  15247. }
  15248. /*
  15249. * Group 6: SSL Server and Client implementation
  15250. */
  15251. #ifdef CPPHTTPLIB_SSL_ENABLED
  15252. // SSL HTTP server implementation
  15253. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  15254. const char *client_ca_cert_file_path,
  15255. const char *client_ca_cert_dir_path,
  15256. const char *private_key_password) {
  15257. using namespace tls;
  15258. ctx_ = create_server_context();
  15259. if (!ctx_) { return; }
  15260. // Load server certificate and private key
  15261. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  15262. private_key_password)) {
  15263. last_ssl_error_ = static_cast<int>(get_error());
  15264. free_context(ctx_);
  15265. ctx_ = nullptr;
  15266. return;
  15267. }
  15268. // Load client CA certificates for client authentication
  15269. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  15270. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  15271. client_ca_cert_dir_path)) {
  15272. last_ssl_error_ = static_cast<int>(get_error());
  15273. free_context(ctx_);
  15274. ctx_ = nullptr;
  15275. return;
  15276. }
  15277. // Enable client certificate verification
  15278. set_verify_client(ctx_, true);
  15279. }
  15280. }
  15281. inline SSLServer::SSLServer(const PemMemory &pem) {
  15282. using namespace tls;
  15283. ctx_ = create_server_context();
  15284. if (ctx_) {
  15285. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  15286. pem.private_key_password)) {
  15287. last_ssl_error_ = static_cast<int>(get_error());
  15288. free_context(ctx_);
  15289. ctx_ = nullptr;
  15290. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  15291. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  15292. last_ssl_error_ = static_cast<int>(get_error());
  15293. free_context(ctx_);
  15294. ctx_ = nullptr;
  15295. } else {
  15296. set_verify_client(ctx_, true);
  15297. }
  15298. }
  15299. }
  15300. }
  15301. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  15302. using namespace tls;
  15303. ctx_ = create_server_context();
  15304. if (ctx_) {
  15305. if (!setup_callback(ctx_)) {
  15306. free_context(ctx_);
  15307. ctx_ = nullptr;
  15308. }
  15309. }
  15310. }
  15311. inline SSLServer::~SSLServer() {
  15312. if (ctx_) { tls::free_context(ctx_); }
  15313. }
  15314. inline bool SSLServer::is_valid() const {
  15315. return ctx_ != nullptr && Server::is_valid();
  15316. }
  15317. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  15318. using namespace tls;
  15319. // Create TLS session with mutex protection
  15320. session_t session = nullptr;
  15321. {
  15322. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15323. session = create_session(static_cast<ctx_t>(ctx_), sock);
  15324. }
  15325. if (!session) {
  15326. last_ssl_error_ = static_cast<int>(get_error());
  15327. detail::shutdown_socket(sock);
  15328. detail::close_socket(sock);
  15329. return false;
  15330. }
  15331. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  15332. bool handshake_done = false;
  15333. bool ret = false;
  15334. bool websocket_upgraded = false;
  15335. auto cleanup = detail::scope_exit([&] {
  15336. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  15337. free_session(session);
  15338. detail::shutdown_socket(sock);
  15339. detail::close_socket(sock);
  15340. });
  15341. // Perform TLS accept handshake with timeout
  15342. TlsError tls_err;
  15343. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  15344. &tls_err)) {
  15345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15346. // Map TlsError to legacy ssl_error for backward compatibility
  15347. if (tls_err.code == ErrorCode::WantRead) {
  15348. last_ssl_error_ = SSL_ERROR_WANT_READ;
  15349. } else if (tls_err.code == ErrorCode::WantWrite) {
  15350. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  15351. } else {
  15352. last_ssl_error_ = SSL_ERROR_SSL;
  15353. }
  15354. #else
  15355. last_ssl_error_ = static_cast<int>(get_error());
  15356. #endif
  15357. return false;
  15358. }
  15359. handshake_done = true;
  15360. std::string remote_addr;
  15361. int remote_port = 0;
  15362. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  15363. std::string local_addr;
  15364. int local_port = 0;
  15365. detail::get_local_ip_and_port(sock, local_addr, local_port);
  15366. ret = serve_guarded([&]() {
  15367. return detail::process_server_socket_ssl(
  15368. svr_sock_, session, sock, keep_alive_max_count_,
  15369. keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
  15370. write_timeout_sec_, write_timeout_usec_,
  15371. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  15372. return process_request(
  15373. strm, remote_addr, remote_port, local_addr, local_port,
  15374. close_connection, connection_closed,
  15375. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  15376. });
  15377. });
  15378. return ret;
  15379. }
  15380. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  15381. const char *key_pem,
  15382. const char *client_ca_pem,
  15383. const char *password) {
  15384. if (!ctx_) { return false; }
  15385. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15386. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  15387. return false;
  15388. }
  15389. if (client_ca_pem) {
  15390. return tls::update_server_client_ca(ctx_, client_ca_pem);
  15391. }
  15392. return true;
  15393. }
  15394. // SSL HTTP client implementation
  15395. inline SSLClient::~SSLClient() {
  15396. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  15397. // base function rather than the derived function once we get to the
  15398. // base class destructor, and won't free the SSL (causing a leak).
  15399. // This must happen before the context is freed below: some backends
  15400. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  15401. // context, so freeing the context first leaves close_notify reading
  15402. // freed memory.
  15403. shutdown_ssl_impl(socket_, true);
  15404. if (ctx_) {
  15405. tls::free_context(ctx_);
  15406. ctx_ = nullptr;
  15407. }
  15408. }
  15409. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  15410. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  15411. shutdown_ssl_impl(socket, shutdown_gracefully);
  15412. }
  15413. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  15414. bool shutdown_gracefully) {
  15415. if (socket.sock == INVALID_SOCKET) {
  15416. assert(socket.ssl == nullptr);
  15417. return;
  15418. }
  15419. if (socket.ssl) {
  15420. tls::shutdown(socket.ssl, shutdown_gracefully);
  15421. {
  15422. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15423. tls::free_session(socket.ssl);
  15424. }
  15425. socket.ssl = nullptr;
  15426. }
  15427. assert(socket.ssl == nullptr);
  15428. }
  15429. inline bool SSLClient::process_socket(
  15430. const Socket &socket,
  15431. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15432. std::function<bool(Stream &strm)> callback) {
  15433. assert(socket.ssl);
  15434. return detail::process_client_socket_ssl(
  15435. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  15436. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  15437. std::move(callback));
  15438. }
  15439. inline bool SSLClient::is_ssl() const { return true; }
  15440. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  15441. if (!is_valid()) {
  15442. error = Error::SSLConnection;
  15443. return false;
  15444. }
  15445. return ClientImpl::create_and_connect_socket(socket, error);
  15446. }
  15447. inline bool SSLClient::setup_proxy_connection(
  15448. Socket &socket,
  15449. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15450. Response &res, bool &success, Error &error) {
  15451. if (!is_proxy_enabled_for_host(host_)) { return true; }
  15452. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  15453. return false;
  15454. }
  15455. if (!initialize_ssl(socket, error)) {
  15456. success = false;
  15457. return false;
  15458. }
  15459. return true;
  15460. }
  15461. // Assumes that socket_mutex_ is locked and that there are no requests in
  15462. // flight
  15463. inline bool SSLClient::connect_with_proxy(
  15464. Socket &socket,
  15465. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15466. Response &res, bool &success, Error &error) {
  15467. success = true;
  15468. Response proxy_res;
  15469. if (!detail::process_client_socket(
  15470. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15471. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15472. start_time, [&](Stream &strm) {
  15473. Request req2;
  15474. req2.method = "CONNECT";
  15475. req2.path =
  15476. detail::make_host_and_port_string_always_port(host_, port_);
  15477. if (max_timeout_msec_ > 0) {
  15478. req2.start_time_ = std::chrono::steady_clock::now();
  15479. }
  15480. return process_request(strm, req2, proxy_res, false, error);
  15481. })) {
  15482. // Thread-safe to close everything because we are assuming there are no
  15483. // requests in flight
  15484. shutdown_ssl(socket, true);
  15485. shutdown_socket(socket);
  15486. close_socket(socket);
  15487. success = false;
  15488. return false;
  15489. }
  15490. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  15491. if (!proxy_digest_auth_username_.empty() &&
  15492. !proxy_digest_auth_password_.empty()) {
  15493. std::map<std::string, std::string> auth;
  15494. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  15495. // Close the current socket and create a new one for the authenticated
  15496. // request
  15497. shutdown_ssl(socket, true);
  15498. shutdown_socket(socket);
  15499. close_socket(socket);
  15500. // Create a new socket for the authenticated CONNECT request
  15501. if (!ensure_socket_connection(socket, error)) {
  15502. success = false;
  15503. output_error_log(error, nullptr);
  15504. return false;
  15505. }
  15506. proxy_res = Response();
  15507. if (!detail::process_client_socket(
  15508. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15509. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15510. start_time, [&](Stream &strm) {
  15511. Request req3;
  15512. req3.method = "CONNECT";
  15513. req3.path = detail::make_host_and_port_string_always_port(
  15514. host_, port_);
  15515. req3.headers.insert(detail::make_digest_authentication_header(
  15516. req3, auth, 1, detail::random_string(10),
  15517. proxy_digest_auth_username_, proxy_digest_auth_password_,
  15518. true));
  15519. if (max_timeout_msec_ > 0) {
  15520. req3.start_time_ = std::chrono::steady_clock::now();
  15521. }
  15522. return process_request(strm, req3, proxy_res, false, error);
  15523. })) {
  15524. // Thread-safe to close everything because we are assuming there are
  15525. // no requests in flight
  15526. shutdown_ssl(socket, true);
  15527. shutdown_socket(socket);
  15528. close_socket(socket);
  15529. success = false;
  15530. return false;
  15531. }
  15532. }
  15533. }
  15534. }
  15535. // If status code is not 200, proxy request is failed.
  15536. // Set error to ProxyConnection and return proxy response
  15537. // as the response of the request
  15538. if (proxy_res.status != StatusCode::OK_200) {
  15539. error = Error::ProxyConnection;
  15540. output_error_log(error, nullptr);
  15541. res = std::move(proxy_res);
  15542. // Thread-safe to close everything because we are assuming there are
  15543. // no requests in flight
  15544. shutdown_ssl(socket, true);
  15545. shutdown_socket(socket);
  15546. close_socket(socket);
  15547. return false;
  15548. }
  15549. return true;
  15550. }
  15551. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  15552. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  15553. if (is_proxy_enabled_for_host(host_)) { return true; }
  15554. if (!initialize_ssl(socket, error)) {
  15555. shutdown_socket(socket);
  15556. close_socket(socket);
  15557. return false;
  15558. }
  15559. return true;
  15560. }
  15561. // SSL HTTP client implementation
  15562. inline SSLClient::SSLClient(const std::string &host)
  15563. : SSLClient(host, 443, std::string(), std::string()) {}
  15564. inline SSLClient::SSLClient(const std::string &host, int port)
  15565. : SSLClient(host, port, std::string(), std::string()) {}
  15566. inline void SSLClient::init_ctx() {
  15567. ctx_ = tls::create_client_context();
  15568. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  15569. }
  15570. inline void SSLClient::reset_ctx_on_error() {
  15571. last_backend_error_ = tls::get_error();
  15572. tls::free_context(ctx_);
  15573. ctx_ = nullptr;
  15574. }
  15575. inline SSLClient::SSLClient(const std::string &host, int port,
  15576. const std::string &client_cert_path,
  15577. const std::string &client_key_path,
  15578. const std::string &private_key_password)
  15579. : ClientImpl(host, port, client_cert_path, client_key_path) {
  15580. init_ctx();
  15581. if (!ctx_) { return; }
  15582. if (!client_cert_path.empty() && !client_key_path.empty()) {
  15583. const char *password =
  15584. private_key_password.empty() ? nullptr : private_key_password.c_str();
  15585. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  15586. client_key_path.c_str(), password)) {
  15587. reset_ctx_on_error();
  15588. }
  15589. }
  15590. }
  15591. inline SSLClient::SSLClient(const std::string &host, int port,
  15592. const PemMemory &pem)
  15593. : ClientImpl(host, port) {
  15594. init_ctx();
  15595. if (!ctx_) { return; }
  15596. if (pem.cert_pem && pem.key_pem) {
  15597. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  15598. pem.private_key_password)) {
  15599. reset_ctx_on_error();
  15600. }
  15601. }
  15602. }
  15603. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  15604. if (ca_cert_store && ctx_) {
  15605. // set_ca_store takes ownership of ca_cert_store
  15606. tls::set_ca_store(ctx_, ca_cert_store);
  15607. ca_cert_store_set_ = true;
  15608. } else if (ca_cert_store) {
  15609. tls::free_ca_store(ca_cert_store);
  15610. }
  15611. }
  15612. inline void
  15613. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  15614. if (!ctx_) { return; }
  15615. tls::set_verify_callback(ctx_, verifier);
  15616. }
  15617. inline void SSLClient::set_session_verifier(
  15618. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  15619. session_verifier_ = std::move(verifier);
  15620. }
  15621. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15622. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  15623. enable_windows_cert_verification_ = enabled;
  15624. }
  15625. #endif
  15626. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  15627. std::size_t size) {
  15628. if (ctx_ && ca_cert && size > 0) {
  15629. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  15630. tls::load_ca_pem(ctx_, ca_cert, size);
  15631. }
  15632. }
  15633. inline bool SSLClient::load_certs() {
  15634. auto ret = true;
  15635. // call_once rather than the plain flag WebSocketClient::create_stream() uses:
  15636. // one client is shared across concurrent requests here.
  15637. std::call_once(initialize_cert_, [&]() {
  15638. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15639. ret = detail::load_client_ca_config(
  15640. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  15641. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  15642. last_backend_error_);
  15643. });
  15644. return ret;
  15645. }
  15646. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  15647. // Load CA certificates if server verification is enabled
  15648. if (server_certificate_verification_) {
  15649. if (!load_certs()) {
  15650. error = Error::SSLLoadingCerts;
  15651. output_error_log(error, nullptr);
  15652. return false;
  15653. }
  15654. }
  15655. detail::ClientTlsSessionOptions options;
  15656. options.server_hostname_verification = server_hostname_verification_;
  15657. options.session_verifier = session_verifier_;
  15658. options.ctx_mutex = &ctx_mutex_;
  15659. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15660. // Skip Schannel when a custom CA cert is specified, as the Windows
  15661. // certificate store would not know about user-provided CA certificates.
  15662. // Also skip when system CA trust is explicitly disabled.
  15663. options.windows_cert_verification =
  15664. enable_windows_cert_verification_ &&
  15665. system_ca_mode_ != SystemCAMode::Disabled && ca_cert_file_path_.empty() &&
  15666. ca_cert_dir_path_.empty() && ca_cert_pem_.empty() && !ca_cert_store_set_;
  15667. #endif
  15668. tls::session_t session = nullptr;
  15669. // Use scope_exit to ensure session is freed on error paths
  15670. bool success = false;
  15671. auto session_guard = detail::scope_exit([&] {
  15672. if (!success) { tls::free_session(session); }
  15673. });
  15674. detail::ClientTlsSessionError tls_error;
  15675. if (!detail::setup_client_tls_session(
  15676. host_, ctx_, session, socket.sock, server_certificate_verification_,
  15677. connection_timeout_sec_, connection_timeout_usec_, &tls_error,
  15678. options)) {
  15679. error = tls_error.error;
  15680. last_ssl_error_ = tls_error.ssl_error;
  15681. last_backend_error_ = tls_error.backend_error;
  15682. output_error_log(error, nullptr);
  15683. return false;
  15684. }
  15685. success = true;
  15686. socket.ssl = session;
  15687. return true;
  15688. }
  15689. inline void Client::set_digest_auth(const std::string &username,
  15690. const std::string &password) {
  15691. cli_->set_digest_auth(username, password);
  15692. }
  15693. inline void Client::set_proxy_digest_auth(const std::string &username,
  15694. const std::string &password) {
  15695. cli_->set_proxy_digest_auth(username, password);
  15696. }
  15697. inline void Client::enable_server_certificate_verification(bool enabled) {
  15698. cli_->enable_server_certificate_verification(enabled);
  15699. }
  15700. inline void Client::enable_server_hostname_verification(bool enabled) {
  15701. cli_->enable_server_hostname_verification(enabled);
  15702. }
  15703. inline void Client::enable_system_ca(bool enabled) {
  15704. cli_->enable_system_ca(enabled);
  15705. }
  15706. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15707. inline void Client::enable_windows_certificate_verification(bool enabled) {
  15708. if (is_ssl_) {
  15709. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  15710. enabled);
  15711. }
  15712. }
  15713. #endif
  15714. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  15715. const std::string &ca_cert_dir_path) {
  15716. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  15717. }
  15718. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  15719. if (is_ssl_) {
  15720. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  15721. } else if (ca_cert_store) {
  15722. tls::free_ca_store(ca_cert_store);
  15723. }
  15724. }
  15725. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  15726. if (is_ssl_) {
  15727. // Use the PEM-based path so the CA data is retained for redirect transfer
  15728. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  15729. }
  15730. }
  15731. inline void
  15732. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  15733. if (is_ssl_) {
  15734. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  15735. std::move(verifier));
  15736. }
  15737. }
  15738. inline void Client::set_session_verifier(
  15739. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  15740. if (is_ssl_) {
  15741. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  15742. }
  15743. }
  15744. inline tls::ctx_t Client::tls_context() const {
  15745. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  15746. return nullptr;
  15747. }
  15748. #endif // CPPHTTPLIB_SSL_ENABLED
  15749. /*
  15750. * Group 7: TLS abstraction layer - Common API
  15751. */
  15752. #ifdef CPPHTTPLIB_SSL_ENABLED
  15753. namespace tls {
  15754. // Helper for PeerCert construction
  15755. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  15756. return PeerCert(get_peer_cert(session));
  15757. }
  15758. namespace impl {
  15759. inline VerifyCallback &get_verify_callback() {
  15760. static thread_local VerifyCallback callback;
  15761. return callback;
  15762. }
  15763. inline VerifyCallback &get_mbedtls_verify_callback() {
  15764. static thread_local VerifyCallback callback;
  15765. return callback;
  15766. }
  15767. // Check if a string is an IPv4 address
  15768. inline bool is_ipv4_address(const std::string &str) {
  15769. int dots = 0;
  15770. for (char c : str) {
  15771. if (c == '.') {
  15772. dots++;
  15773. } else if (!detail::is_ascii_digit(c)) {
  15774. return false;
  15775. }
  15776. }
  15777. return dots == 3;
  15778. }
  15779. // Parse IPv4 address string to bytes
  15780. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  15781. const char *p = str.c_str();
  15782. for (int i = 0; i < 4; i++) {
  15783. if (i > 0) {
  15784. if (*p != '.') { return false; }
  15785. p++;
  15786. }
  15787. int val = 0;
  15788. int digits = 0;
  15789. while (detail::is_ascii_digit(*p)) {
  15790. val = val * 10 + (*p - '0');
  15791. if (val > 255) { return false; }
  15792. p++;
  15793. digits++;
  15794. }
  15795. if (digits == 0) { return false; }
  15796. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  15797. if (digits > 1 && *(p - digits) == '0') { return false; }
  15798. out[i] = static_cast<unsigned char>(val);
  15799. }
  15800. return *p == '\0';
  15801. }
  15802. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  15803. // `out` must have room for at least 16 bytes. Returns the address length
  15804. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  15805. // literal. Used to match a host against iPAddress SANs the same way the
  15806. // OpenSSL backend does via X509_check_ip.
  15807. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  15808. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  15809. struct in6_addr addr6 = {};
  15810. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  15811. memcpy(out, &addr6, 16);
  15812. return 16;
  15813. }
  15814. return 0;
  15815. }
  15816. #ifdef _WIN32
  15817. // Enumerate Windows system certificates and call callback with DER data
  15818. template <typename Callback>
  15819. inline bool enumerate_windows_system_certs(Callback cb) {
  15820. bool loaded = false;
  15821. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  15822. for (auto store_name : store_names) {
  15823. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  15824. if (hStore) {
  15825. PCCERT_CONTEXT pContext = nullptr;
  15826. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  15827. nullptr) {
  15828. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  15829. loaded = true;
  15830. }
  15831. }
  15832. CertCloseStore(hStore, 0);
  15833. }
  15834. }
  15835. return loaded;
  15836. }
  15837. #endif
  15838. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15839. // Enumerate macOS Keychain certificates and call callback with DER data
  15840. template <typename Callback>
  15841. inline bool enumerate_macos_keychain_certs(Callback cb) {
  15842. bool loaded = false;
  15843. const SecTrustSettingsDomain domains[] = {
  15844. kSecTrustSettingsDomainSystem,
  15845. kSecTrustSettingsDomainAdmin,
  15846. kSecTrustSettingsDomainUser,
  15847. };
  15848. for (auto domain : domains) {
  15849. CFArrayRef certs = nullptr;
  15850. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  15851. if (status != errSecSuccess || !certs) {
  15852. if (certs) CFRelease(certs);
  15853. continue;
  15854. }
  15855. CFIndex count = CFArrayGetCount(certs);
  15856. for (CFIndex i = 0; i < count; i++) {
  15857. SecCertificateRef cert =
  15858. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  15859. CFDataRef data = SecCertificateCopyData(cert);
  15860. if (data) {
  15861. if (cb(CFDataGetBytePtr(data),
  15862. static_cast<size_t>(CFDataGetLength(data)))) {
  15863. loaded = true;
  15864. }
  15865. CFRelease(data);
  15866. }
  15867. }
  15868. CFRelease(certs);
  15869. }
  15870. return loaded;
  15871. }
  15872. #endif
  15873. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  15874. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  15875. // Common CA certificate file paths on Linux/Unix
  15876. inline const char **system_ca_paths() {
  15877. static const char *paths[] = {
  15878. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  15879. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  15880. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  15881. "/etc/pki/tls/cacert.pem", // OpenELEC
  15882. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  15883. nullptr};
  15884. return paths;
  15885. }
  15886. // Common CA certificate directory paths on Linux/Unix
  15887. inline const char **system_ca_dirs() {
  15888. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  15889. "/etc/pki/tls/certs", // RHEL/CentOS
  15890. "/usr/share/ca-certificates", // Other
  15891. nullptr};
  15892. return dirs;
  15893. }
  15894. #endif
  15895. } // namespace impl
  15896. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  15897. const char *ca_dir) {
  15898. if (!ctx) { return false; }
  15899. bool success = true;
  15900. if (ca_file && *ca_file) {
  15901. if (!load_ca_file(ctx, ca_file)) { success = false; }
  15902. }
  15903. if (ca_dir && *ca_dir) {
  15904. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  15905. }
  15906. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15907. // Set CA list for client certificate request (CertificateRequest message)
  15908. if (ca_file && *ca_file) {
  15909. auto list = SSL_load_client_CA_file(ca_file);
  15910. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  15911. }
  15912. #endif
  15913. return success;
  15914. }
  15915. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15916. const char *password) {
  15917. return set_client_cert_pem(ctx, cert, key, password);
  15918. }
  15919. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  15920. const char *key_path, const char *password) {
  15921. return set_client_cert_file(ctx, cert_path, key_path, password);
  15922. }
  15923. // PeerCert implementation
  15924. inline PeerCert::PeerCert() = default;
  15925. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  15926. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  15927. other.cert_ = nullptr;
  15928. }
  15929. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  15930. if (this != &other) {
  15931. if (cert_) { free_cert(cert_); }
  15932. cert_ = other.cert_;
  15933. other.cert_ = nullptr;
  15934. }
  15935. return *this;
  15936. }
  15937. inline PeerCert::~PeerCert() {
  15938. if (cert_) { free_cert(cert_); }
  15939. }
  15940. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  15941. inline std::string PeerCert::subject_cn() const {
  15942. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  15943. }
  15944. inline std::string PeerCert::issuer_name() const {
  15945. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  15946. }
  15947. inline bool PeerCert::check_hostname(const char *hostname) const {
  15948. return cert_ ? verify_hostname(cert_, hostname) : false;
  15949. }
  15950. inline std::vector<SanEntry> PeerCert::sans() const {
  15951. std::vector<SanEntry> result;
  15952. if (cert_) { get_cert_sans(cert_, result); }
  15953. return result;
  15954. }
  15955. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  15956. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  15957. }
  15958. inline std::string PeerCert::serial() const {
  15959. return cert_ ? get_cert_serial(cert_) : std::string();
  15960. }
  15961. // VerifyContext method implementations
  15962. inline std::string VerifyContext::subject_cn() const {
  15963. return cert ? get_cert_subject_cn(cert) : std::string();
  15964. }
  15965. inline std::string VerifyContext::issuer_name() const {
  15966. return cert ? get_cert_issuer_name(cert) : std::string();
  15967. }
  15968. inline bool VerifyContext::check_hostname(const char *hostname) const {
  15969. return cert ? verify_hostname(cert, hostname) : false;
  15970. }
  15971. inline std::vector<SanEntry> VerifyContext::sans() const {
  15972. std::vector<SanEntry> result;
  15973. if (cert) { get_cert_sans(cert, result); }
  15974. return result;
  15975. }
  15976. inline bool VerifyContext::validity(time_t &not_before,
  15977. time_t &not_after) const {
  15978. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  15979. }
  15980. inline std::string VerifyContext::serial() const {
  15981. return cert ? get_cert_serial(cert) : std::string();
  15982. }
  15983. // TlsError static method implementation
  15984. inline std::string TlsError::verify_error_to_string(long error_code) {
  15985. return verify_error_string(error_code);
  15986. }
  15987. } // namespace tls
  15988. // Request::peer_cert() implementation
  15989. inline tls::PeerCert Request::peer_cert() const {
  15990. return tls::get_peer_cert_from_session(ssl);
  15991. }
  15992. // Request::sni() implementation
  15993. inline std::string Request::sni() const {
  15994. if (!ssl) { return std::string(); }
  15995. const char *s = tls::get_sni(ssl);
  15996. return s ? std::string(s) : std::string();
  15997. }
  15998. #endif // CPPHTTPLIB_SSL_ENABLED
  15999. /*
  16000. * Group 8: TLS abstraction layer - OpenSSL backend
  16001. */
  16002. /*
  16003. * OpenSSL Backend Implementation
  16004. */
  16005. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16006. namespace tls {
  16007. namespace impl {
  16008. // Helper to map OpenSSL SSL_get_error to ErrorCode
  16009. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  16010. switch (ssl_error) {
  16011. case SSL_ERROR_NONE: return ErrorCode::Success;
  16012. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16013. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16014. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16015. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16016. case SSL_ERROR_SSL:
  16017. default: return ErrorCode::Fatal;
  16018. }
  16019. }
  16020. // Helper: Create client CA list from PEM string
  16021. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  16022. // Caller takes ownership of returned list
  16023. inline STACK_OF(X509_NAME) *
  16024. create_client_ca_list_from_pem(const char *ca_pem) {
  16025. if (!ca_pem) { return nullptr; }
  16026. auto ca_list = sk_X509_NAME_new_null();
  16027. if (!ca_list) { return nullptr; }
  16028. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  16029. if (!bio) {
  16030. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  16031. return nullptr;
  16032. }
  16033. X509 *cert = nullptr;
  16034. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  16035. nullptr) {
  16036. const X509_NAME *name = X509_get_subject_name(cert);
  16037. if (name) {
  16038. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  16039. }
  16040. X509_free(cert);
  16041. }
  16042. BIO_free(bio);
  16043. return ca_list;
  16044. }
  16045. // OpenSSL verify callback wrapper
  16046. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  16047. auto &callback = get_verify_callback();
  16048. if (!callback) { return preverify_ok; }
  16049. // Get SSL object from X509_STORE_CTX
  16050. auto ssl = static_cast<SSL *>(
  16051. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  16052. if (!ssl) { return preverify_ok; }
  16053. // Get current certificate and depth
  16054. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  16055. int depth = X509_STORE_CTX_get_error_depth(ctx);
  16056. int error = X509_STORE_CTX_get_error(ctx);
  16057. // Build context
  16058. VerifyContext verify_ctx;
  16059. verify_ctx.session = static_cast<session_t>(ssl);
  16060. verify_ctx.cert = static_cast<cert_t>(cert);
  16061. verify_ctx.depth = depth;
  16062. verify_ctx.preverify_ok = (preverify_ok != 0);
  16063. verify_ctx.error_code = error;
  16064. verify_ctx.error_string =
  16065. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  16066. return callback(verify_ctx) ? 1 : 0;
  16067. }
  16068. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  16069. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  16070. // that must be released with release_store_objects
  16071. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  16072. OPENSSL_VERSION_NUMBER >= 0x30300000L
  16073. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16074. #endif
  16075. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  16076. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16077. return X509_STORE_get1_objects(store);
  16078. #else
  16079. return X509_STORE_get0_objects(store);
  16080. #endif
  16081. }
  16082. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  16083. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16084. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  16085. #else
  16086. (void)objs; // get0 variant returns an internal pointer; nothing to free
  16087. #endif
  16088. }
  16089. } // namespace impl
  16090. inline ctx_t create_client_context() {
  16091. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  16092. if (ctx) {
  16093. // Disable auto-retry to properly handle non-blocking I/O
  16094. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  16095. // Set minimum TLS version
  16096. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  16097. }
  16098. return static_cast<ctx_t>(ctx);
  16099. }
  16100. inline void free_context(ctx_t ctx) {
  16101. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  16102. }
  16103. inline bool set_min_version(ctx_t ctx, Version version) {
  16104. if (!ctx) return false;
  16105. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  16106. static_cast<int>(version)) == 1;
  16107. }
  16108. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16109. if (!ctx || !pem || len == 0) return false;
  16110. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16111. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16112. if (!store) return false;
  16113. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  16114. if (!bio) return false;
  16115. bool ok = true;
  16116. X509 *cert = nullptr;
  16117. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  16118. nullptr) {
  16119. if (X509_STORE_add_cert(store, cert) != 1) {
  16120. // Ignore duplicate errors
  16121. auto err = ERR_peek_last_error();
  16122. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  16123. ok = false;
  16124. }
  16125. }
  16126. X509_free(cert);
  16127. if (!ok) break;
  16128. }
  16129. BIO_free(bio);
  16130. // Clear any "no more certificates" errors
  16131. ERR_clear_error();
  16132. return ok;
  16133. }
  16134. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16135. if (!ctx || !file_path) return false;
  16136. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  16137. nullptr) == 1;
  16138. }
  16139. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16140. if (!ctx || !dir_path) return false;
  16141. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  16142. dir_path) == 1;
  16143. }
  16144. inline bool load_system_certs(ctx_t ctx) {
  16145. if (!ctx) return false;
  16146. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16147. #ifdef _WIN32
  16148. // Windows: Load from system certificate store (ROOT and CA)
  16149. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16150. if (!store) return false;
  16151. bool loaded_any = false;
  16152. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  16153. for (auto store_name : store_names) {
  16154. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  16155. if (!hStore) continue;
  16156. PCCERT_CONTEXT pContext = nullptr;
  16157. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  16158. nullptr) {
  16159. const unsigned char *data = pContext->pbCertEncoded;
  16160. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  16161. if (x509) {
  16162. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  16163. X509_free(x509);
  16164. }
  16165. }
  16166. CertCloseStore(hStore, 0);
  16167. }
  16168. return loaded_any;
  16169. #elif defined(__APPLE__)
  16170. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16171. // macOS: Load from Keychain
  16172. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16173. if (!store) return false;
  16174. bool loaded_any = false;
  16175. const SecTrustSettingsDomain domains[] = {
  16176. kSecTrustSettingsDomainSystem,
  16177. kSecTrustSettingsDomainAdmin,
  16178. kSecTrustSettingsDomainUser,
  16179. };
  16180. for (auto domain : domains) {
  16181. CFArrayRef certs = nullptr;
  16182. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  16183. !certs) {
  16184. if (certs) CFRelease(certs);
  16185. continue;
  16186. }
  16187. auto count = CFArrayGetCount(certs);
  16188. for (CFIndex i = 0; i < count; i++) {
  16189. auto cert = reinterpret_cast<SecCertificateRef>(
  16190. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  16191. CFDataRef der = SecCertificateCopyData(cert);
  16192. if (der) {
  16193. const unsigned char *data = CFDataGetBytePtr(der);
  16194. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  16195. if (x509) {
  16196. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  16197. X509_free(x509);
  16198. }
  16199. CFRelease(der);
  16200. }
  16201. }
  16202. CFRelease(certs);
  16203. }
  16204. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16205. #else
  16206. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16207. #endif
  16208. #else
  16209. // Other Unix: use default verify paths
  16210. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16211. #endif
  16212. }
  16213. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16214. const char *password) {
  16215. if (!ctx || !cert || !key) return false;
  16216. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16217. // Load certificate
  16218. auto cert_bio = BIO_new_mem_buf(cert, -1);
  16219. if (!cert_bio) return false;
  16220. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  16221. BIO_free(cert_bio);
  16222. if (!x509) return false;
  16223. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  16224. X509_free(x509);
  16225. if (!cert_ok) return false;
  16226. // Load private key
  16227. auto key_bio = BIO_new_mem_buf(key, -1);
  16228. if (!key_bio) return false;
  16229. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  16230. password ? const_cast<char *>(password)
  16231. : nullptr);
  16232. BIO_free(key_bio);
  16233. if (!pkey) return false;
  16234. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  16235. EVP_PKEY_free(pkey);
  16236. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  16237. }
  16238. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16239. const char *key_path, const char *password) {
  16240. if (!ctx || !cert_path || !key_path) return false;
  16241. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16242. if (password && password[0] != '\0') {
  16243. SSL_CTX_set_default_passwd_cb_userdata(
  16244. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  16245. }
  16246. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  16247. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  16248. }
  16249. inline ctx_t create_server_context() {
  16250. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16251. if (ctx) {
  16252. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  16253. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  16254. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  16255. }
  16256. return static_cast<ctx_t>(ctx);
  16257. }
  16258. inline void set_verify_client(ctx_t ctx, bool require) {
  16259. if (!ctx) return;
  16260. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  16261. require
  16262. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  16263. : SSL_VERIFY_NONE,
  16264. nullptr);
  16265. }
  16266. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16267. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  16268. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16269. SSL *ssl = SSL_new(ssl_ctx);
  16270. if (!ssl) return nullptr;
  16271. // Disable auto-retry for proper non-blocking I/O handling
  16272. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  16273. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  16274. if (!bio) {
  16275. SSL_free(ssl);
  16276. return nullptr;
  16277. }
  16278. SSL_set_bio(ssl, bio, bio);
  16279. return static_cast<session_t>(ssl);
  16280. }
  16281. inline void free_session(session_t session) {
  16282. if (session) { SSL_free(static_cast<SSL *>(session)); }
  16283. }
  16284. inline bool set_sni(session_t session, const char *hostname,
  16285. bool /*verify_hostname*/) {
  16286. if (!session || !hostname) return false;
  16287. auto ssl = static_cast<SSL *>(session);
  16288. // Set SNI (Server Name Indication) only - does not enable verification.
  16289. // OpenSSL never binds identity checking to SNI (that happens post-
  16290. // handshake in setup_client_tls_session()), so verify_hostname is unused.
  16291. #if defined(OPENSSL_IS_BORINGSSL)
  16292. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  16293. #else
  16294. // Direct call instead of macro to suppress -Wold-style-cast warning
  16295. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  16296. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  16297. #endif
  16298. }
  16299. inline TlsError connect(session_t session) {
  16300. if (!session) { return TlsError(); }
  16301. auto ssl = static_cast<SSL *>(session);
  16302. auto ret = SSL_connect(ssl);
  16303. TlsError err;
  16304. if (ret == 1) {
  16305. err.code = ErrorCode::Success;
  16306. } else {
  16307. auto ssl_err = SSL_get_error(ssl, ret);
  16308. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16309. err.backend_code = ERR_get_error();
  16310. }
  16311. return err;
  16312. }
  16313. inline TlsError accept(session_t session) {
  16314. if (!session) { return TlsError(); }
  16315. auto ssl = static_cast<SSL *>(session);
  16316. auto ret = SSL_accept(ssl);
  16317. TlsError err;
  16318. if (ret == 1) {
  16319. err.code = ErrorCode::Success;
  16320. } else {
  16321. auto ssl_err = SSL_get_error(ssl, ret);
  16322. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16323. err.backend_code = ERR_get_error();
  16324. }
  16325. return err;
  16326. }
  16327. inline bool connect_nonblocking(session_t session, socket_t sock,
  16328. time_t timeout_sec, time_t timeout_usec,
  16329. TlsError *err) {
  16330. if (!session) {
  16331. if (err) { err->code = ErrorCode::Fatal; }
  16332. return false;
  16333. }
  16334. auto ssl = static_cast<SSL *>(session);
  16335. auto bio = SSL_get_rbio(ssl);
  16336. // Set non-blocking mode for handshake
  16337. detail::set_nonblocking(sock, true);
  16338. if (bio) { BIO_set_nbio(bio, 1); }
  16339. auto cleanup = detail::scope_exit([&]() {
  16340. // Restore blocking mode after handshake
  16341. if (bio) { BIO_set_nbio(bio, 0); }
  16342. detail::set_nonblocking(sock, false);
  16343. });
  16344. auto res = 0;
  16345. while ((res = SSL_connect(ssl)) != 1) {
  16346. auto ssl_err = SSL_get_error(ssl, res);
  16347. switch (ssl_err) {
  16348. case SSL_ERROR_WANT_READ:
  16349. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16350. continue;
  16351. }
  16352. break;
  16353. case SSL_ERROR_WANT_WRITE:
  16354. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16355. continue;
  16356. }
  16357. break;
  16358. default: break;
  16359. }
  16360. if (err) {
  16361. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  16362. err->backend_code = ERR_get_error();
  16363. }
  16364. return false;
  16365. }
  16366. if (err) { err->code = ErrorCode::Success; }
  16367. return true;
  16368. }
  16369. inline bool accept_nonblocking(session_t session, socket_t sock,
  16370. time_t timeout_sec, time_t timeout_usec,
  16371. TlsError *err) {
  16372. if (!session) {
  16373. if (err) { err->code = ErrorCode::Fatal; }
  16374. return false;
  16375. }
  16376. auto ssl = static_cast<SSL *>(session);
  16377. auto bio = SSL_get_rbio(ssl);
  16378. // Set non-blocking mode for handshake
  16379. detail::set_nonblocking(sock, true);
  16380. if (bio) { BIO_set_nbio(bio, 1); }
  16381. auto cleanup = detail::scope_exit([&]() {
  16382. // Restore blocking mode after handshake
  16383. if (bio) { BIO_set_nbio(bio, 0); }
  16384. detail::set_nonblocking(sock, false);
  16385. });
  16386. auto res = 0;
  16387. while ((res = SSL_accept(ssl)) != 1) {
  16388. auto ssl_err = SSL_get_error(ssl, res);
  16389. switch (ssl_err) {
  16390. case SSL_ERROR_WANT_READ:
  16391. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16392. continue;
  16393. }
  16394. break;
  16395. case SSL_ERROR_WANT_WRITE:
  16396. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16397. continue;
  16398. }
  16399. break;
  16400. default: break;
  16401. }
  16402. if (err) {
  16403. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  16404. err->backend_code = ERR_get_error();
  16405. }
  16406. return false;
  16407. }
  16408. if (err) { err->code = ErrorCode::Success; }
  16409. return true;
  16410. }
  16411. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16412. if (!session || !buf) {
  16413. err.code = ErrorCode::Fatal;
  16414. return -1;
  16415. }
  16416. auto ssl = static_cast<SSL *>(session);
  16417. constexpr auto max_len =
  16418. static_cast<size_t>((std::numeric_limits<int>::max)());
  16419. if (len > max_len) { len = max_len; }
  16420. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  16421. if (ret > 0) {
  16422. err.code = ErrorCode::Success;
  16423. return ret;
  16424. }
  16425. auto ssl_err = SSL_get_error(ssl, ret);
  16426. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16427. if (err.code == ErrorCode::PeerClosed) {
  16428. return 0;
  16429. } // Gracefully handle the peer closed state.
  16430. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  16431. return -1;
  16432. }
  16433. inline ssize_t write(session_t session, const void *buf, size_t len,
  16434. TlsError &err) {
  16435. if (!session || !buf) {
  16436. err.code = ErrorCode::Fatal;
  16437. return -1;
  16438. }
  16439. auto ssl = static_cast<SSL *>(session);
  16440. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  16441. if (ret > 0) {
  16442. err.code = ErrorCode::Success;
  16443. return ret;
  16444. }
  16445. auto ssl_err = SSL_get_error(ssl, ret);
  16446. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16447. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  16448. return -1;
  16449. }
  16450. inline int pending(const_session_t session) {
  16451. if (!session) return 0;
  16452. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  16453. }
  16454. inline void shutdown(session_t session, bool graceful) {
  16455. if (!session) return;
  16456. auto ssl = static_cast<SSL *>(session);
  16457. if (graceful) {
  16458. // First call sends close_notify
  16459. if (SSL_shutdown(ssl) == 0) {
  16460. // Second call waits for peer's close_notify
  16461. SSL_shutdown(ssl);
  16462. }
  16463. }
  16464. }
  16465. inline bool is_peer_closed(session_t session, socket_t sock) {
  16466. if (!session) return true;
  16467. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  16468. detail::set_nonblocking(sock, true);
  16469. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16470. auto ssl = static_cast<SSL *>(session);
  16471. char buf;
  16472. auto ret = SSL_peek(ssl, &buf, 1);
  16473. if (ret > 0) return false;
  16474. auto err = SSL_get_error(ssl, ret);
  16475. return err == SSL_ERROR_ZERO_RETURN;
  16476. }
  16477. inline cert_t get_peer_cert(const_session_t session) {
  16478. if (!session) return nullptr;
  16479. return static_cast<cert_t>(SSL_get1_peer_certificate(
  16480. static_cast<SSL *>(const_cast<void *>(session))));
  16481. }
  16482. inline void free_cert(cert_t cert) {
  16483. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  16484. }
  16485. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16486. if (!cert || !hostname) return false;
  16487. auto x509 = static_cast<X509 *>(cert);
  16488. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  16489. if (detail::is_ip_address(hostname)) {
  16490. return X509_check_ip_asc(x509, hostname, 0) == 1;
  16491. }
  16492. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  16493. }
  16494. inline uint64_t hostname_mismatch_code() {
  16495. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  16496. }
  16497. inline long get_verify_result(const_session_t session) {
  16498. if (!session) return X509_V_ERR_UNSPECIFIED;
  16499. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  16500. }
  16501. inline std::string get_cert_subject_cn(cert_t cert) {
  16502. if (!cert) return "";
  16503. auto x509 = static_cast<X509 *>(cert);
  16504. auto subject_name = X509_get_subject_name(x509);
  16505. if (!subject_name) return "";
  16506. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  16507. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  16508. if (idx < 0) return "";
  16509. auto entry = X509_NAME_get_entry(subject_name, idx);
  16510. if (!entry) return "";
  16511. auto data = X509_NAME_ENTRY_get_data(entry);
  16512. if (!data) return "";
  16513. return std::string(
  16514. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  16515. static_cast<size_t>(ASN1_STRING_length(data)));
  16516. }
  16517. inline std::string get_cert_issuer_name(cert_t cert) {
  16518. if (!cert) return "";
  16519. auto x509 = static_cast<X509 *>(cert);
  16520. auto issuer_name = X509_get_issuer_name(x509);
  16521. if (!issuer_name) return "";
  16522. char buf[256];
  16523. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  16524. return std::string(buf);
  16525. }
  16526. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16527. sans.clear();
  16528. if (!cert) return false;
  16529. auto x509 = static_cast<X509 *>(cert);
  16530. auto names = static_cast<GENERAL_NAMES *>(
  16531. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16532. if (!names) return true; // No SANs is valid
  16533. auto count = sk_GENERAL_NAME_num(names);
  16534. for (decltype(count) i = 0; i < count; i++) {
  16535. auto gen = sk_GENERAL_NAME_value(names, i);
  16536. if (!gen) continue;
  16537. SanEntry entry;
  16538. switch (gen->type) {
  16539. case GEN_DNS:
  16540. entry.type = SanType::DNS;
  16541. if (gen->d.dNSName) {
  16542. entry.value = std::string(
  16543. reinterpret_cast<const char *>(
  16544. ASN1_STRING_get0_data(gen->d.dNSName)),
  16545. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  16546. }
  16547. break;
  16548. case GEN_IPADD:
  16549. entry.type = SanType::IP;
  16550. if (gen->d.iPAddress) {
  16551. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  16552. auto len = ASN1_STRING_length(gen->d.iPAddress);
  16553. if (len == 4) {
  16554. // IPv4
  16555. char buf[INET_ADDRSTRLEN];
  16556. inet_ntop(AF_INET, data, buf, sizeof(buf));
  16557. entry.value = buf;
  16558. } else if (len == 16) {
  16559. // IPv6
  16560. char buf[INET6_ADDRSTRLEN];
  16561. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  16562. entry.value = buf;
  16563. }
  16564. }
  16565. break;
  16566. case GEN_EMAIL:
  16567. entry.type = SanType::EMAIL;
  16568. if (gen->d.rfc822Name) {
  16569. entry.value = std::string(
  16570. reinterpret_cast<const char *>(
  16571. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  16572. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  16573. }
  16574. break;
  16575. case GEN_URI:
  16576. entry.type = SanType::URI;
  16577. if (gen->d.uniformResourceIdentifier) {
  16578. entry.value = std::string(
  16579. reinterpret_cast<const char *>(
  16580. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  16581. static_cast<size_t>(
  16582. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  16583. }
  16584. break;
  16585. default: entry.type = SanType::OTHER; break;
  16586. }
  16587. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16588. }
  16589. GENERAL_NAMES_free(names);
  16590. return true;
  16591. }
  16592. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16593. time_t &not_after) {
  16594. if (!cert) return false;
  16595. auto x509 = static_cast<X509 *>(cert);
  16596. auto nb = X509_get0_notBefore(x509);
  16597. auto na = X509_get0_notAfter(x509);
  16598. if (!nb || !na) return false;
  16599. ASN1_TIME *epoch = ASN1_TIME_new();
  16600. if (!epoch) return false;
  16601. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  16602. if (!ASN1_TIME_set(epoch, 0)) return false;
  16603. int pday, psec;
  16604. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  16605. not_before = 86400 * (time_t)pday + psec;
  16606. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  16607. not_after = 86400 * (time_t)pday + psec;
  16608. return true;
  16609. }
  16610. inline std::string get_cert_serial(cert_t cert) {
  16611. if (!cert) return "";
  16612. auto x509 = static_cast<X509 *>(cert);
  16613. auto serial = X509_get_serialNumber(x509);
  16614. if (!serial) return "";
  16615. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  16616. if (!bn) return "";
  16617. auto hex = BN_bn2hex(bn);
  16618. BN_free(bn);
  16619. if (!hex) return "";
  16620. std::string result(hex);
  16621. OPENSSL_free(hex);
  16622. return result;
  16623. }
  16624. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16625. if (!cert) return false;
  16626. auto x509 = static_cast<X509 *>(cert);
  16627. auto len = i2d_X509(x509, nullptr);
  16628. if (len < 0) return false;
  16629. der.resize(static_cast<size_t>(len));
  16630. auto p = der.data();
  16631. i2d_X509(x509, &p);
  16632. return true;
  16633. }
  16634. inline const char *get_sni(const_session_t session) {
  16635. if (!session) return nullptr;
  16636. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  16637. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  16638. }
  16639. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  16640. inline uint64_t get_error() { return ERR_get_error(); }
  16641. inline std::string error_string(uint64_t code) {
  16642. char buf[256];
  16643. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  16644. return std::string(buf);
  16645. }
  16646. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16647. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  16648. if (!mem) { return nullptr; }
  16649. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  16650. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  16651. if (!inf) { return nullptr; }
  16652. auto store = X509_STORE_new();
  16653. if (store) {
  16654. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  16655. auto itmp = sk_X509_INFO_value(inf, i);
  16656. if (!itmp) { continue; }
  16657. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  16658. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  16659. }
  16660. }
  16661. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  16662. return static_cast<ca_store_t>(store);
  16663. }
  16664. inline void free_ca_store(ca_store_t store) {
  16665. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  16666. }
  16667. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16668. if (!ctx || !store) { return false; }
  16669. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16670. auto x509_store = static_cast<X509_STORE *>(store);
  16671. // Check if same store is already set
  16672. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  16673. // SSL_CTX_set_cert_store takes ownership and frees the old store
  16674. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  16675. return true;
  16676. }
  16677. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16678. certs.clear();
  16679. if (!ctx) { return 0; }
  16680. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16681. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16682. if (!store) { return 0; }
  16683. auto objs = impl::get_store_objects(store);
  16684. if (!objs) { return 0; }
  16685. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  16686. auto count = sk_X509_OBJECT_num(objs);
  16687. for (decltype(count) i = 0; i < count; i++) {
  16688. auto obj = sk_X509_OBJECT_value(objs, i);
  16689. if (!obj) { continue; }
  16690. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  16691. auto x509 = X509_OBJECT_get0_X509(obj);
  16692. if (x509) {
  16693. // Increment reference count so caller can free it
  16694. X509_up_ref(x509);
  16695. certs.push_back(static_cast<cert_t>(x509));
  16696. }
  16697. }
  16698. }
  16699. return certs.size();
  16700. }
  16701. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16702. std::vector<std::string> names;
  16703. if (!ctx) { return names; }
  16704. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16705. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16706. if (!store) { return names; }
  16707. auto objs = impl::get_store_objects(store);
  16708. if (!objs) { return names; }
  16709. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  16710. auto count = sk_X509_OBJECT_num(objs);
  16711. for (decltype(count) i = 0; i < count; i++) {
  16712. auto obj = sk_X509_OBJECT_value(objs, i);
  16713. if (!obj) { continue; }
  16714. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  16715. auto x509 = X509_OBJECT_get0_X509(obj);
  16716. if (x509) {
  16717. auto subject = X509_get_subject_name(x509);
  16718. if (subject) {
  16719. char buf[512];
  16720. X509_NAME_oneline(subject, buf, sizeof(buf));
  16721. names.push_back(buf);
  16722. }
  16723. }
  16724. }
  16725. }
  16726. return names;
  16727. }
  16728. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16729. const char *key_pem, const char *password) {
  16730. if (!ctx || !cert_pem || !key_pem) { return false; }
  16731. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16732. // Load certificate from PEM
  16733. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  16734. if (!cert_bio) { return false; }
  16735. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  16736. BIO_free(cert_bio);
  16737. if (!cert) { return false; }
  16738. // Load private key from PEM
  16739. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  16740. if (!key_bio) {
  16741. X509_free(cert);
  16742. return false;
  16743. }
  16744. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  16745. password ? const_cast<char *>(password)
  16746. : nullptr);
  16747. BIO_free(key_bio);
  16748. if (!key) {
  16749. X509_free(cert);
  16750. return false;
  16751. }
  16752. // Update certificate and key
  16753. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  16754. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  16755. X509_free(cert);
  16756. EVP_PKEY_free(key);
  16757. return ret;
  16758. }
  16759. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16760. if (!ctx || !ca_pem) { return false; }
  16761. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16762. // Create new X509_STORE from PEM
  16763. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  16764. if (!store) { return false; }
  16765. // SSL_CTX_set_cert_store takes ownership
  16766. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  16767. // Set client CA list for client certificate request
  16768. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  16769. if (ca_list) {
  16770. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  16771. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  16772. }
  16773. return true;
  16774. }
  16775. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16776. if (!ctx) { return false; }
  16777. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16778. impl::get_verify_callback() = std::move(callback);
  16779. if (impl::get_verify_callback()) {
  16780. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  16781. } else {
  16782. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  16783. }
  16784. return true;
  16785. }
  16786. inline long get_verify_error(const_session_t session) {
  16787. if (!session) { return -1; }
  16788. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  16789. return SSL_get_verify_result(ssl);
  16790. }
  16791. inline std::string verify_error_string(long error_code) {
  16792. if (error_code == X509_V_OK) { return ""; }
  16793. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  16794. return str ? str : "unknown error";
  16795. }
  16796. } // namespace tls
  16797. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  16798. /*
  16799. * Group 9: TLS abstraction layer - Mbed TLS backend
  16800. */
  16801. /*
  16802. * Mbed TLS Backend Implementation
  16803. */
  16804. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16805. namespace tls {
  16806. namespace impl {
  16807. // Mbed TLS session wrapper
  16808. struct MbedTlsSession {
  16809. mbedtls_ssl_context ssl;
  16810. socket_t sock = INVALID_SOCKET;
  16811. std::string hostname; // For client: set via set_sni
  16812. std::string sni_hostname; // For server: received from client via SNI callback
  16813. // Mbed TLS has no SSL_peek() equivalent, so is_peer_closed() must probe with
  16814. // a real 1-byte mbedtls_ssl_read(). If that probe lands on application data
  16815. // (e.g. a response that arrived while this side was still in its post-write
  16816. // check), the byte is pushed back here and served by the next read().
  16817. unsigned char peeked_byte = 0;
  16818. bool has_peeked_byte = false;
  16819. // Set by set_sni() when the caller disabled hostname verification, so the
  16820. // verify callback can clear the CN/SAN mismatch flag while still enforcing
  16821. // the rest of the chain (Mbed TLS ties SNI and identity checking together;
  16822. // OpenSSL and wolfSSL keep them independent).
  16823. bool suppress_hostname_mismatch = false;
  16824. // Copied from the owning MbedTlsContext at creation. set_sni() uses this to
  16825. // decide which verify callback to install when hostname verification is
  16826. // disabled: mbedtls_verify_callback() when a user callback is genuinely
  16827. // wired for this context, or a self-contained one otherwise, so a session
  16828. // that never opted into a callback never consults the process-wide
  16829. // set_verify_callback() slot (which some other, unrelated client may have
  16830. // populated).
  16831. bool has_verify_callback = false;
  16832. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  16833. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  16834. MbedTlsSession(const MbedTlsSession &) = delete;
  16835. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  16836. };
  16837. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  16838. // queue)
  16839. inline int &mbedtls_last_error() {
  16840. static thread_local int err = 0;
  16841. return err;
  16842. }
  16843. // Helper to map Mbed TLS error to ErrorCode
  16844. inline ErrorCode map_mbedtls_error(int ret, int &out_errno,
  16845. uint32_t verify_flags) {
  16846. if (ret == 0) { return ErrorCode::Success; }
  16847. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  16848. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  16849. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  16850. return ErrorCode::PeerClosed;
  16851. }
  16852. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  16853. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  16854. out_errno = errno;
  16855. return ErrorCode::SyscallError;
  16856. }
  16857. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  16858. // Unlike OpenSSL/wolfSSL, Mbed TLS folds the CN/SAN identity check into
  16859. // the handshake's chain verification (see set_sni()); a mismatch there
  16860. // is reported the same way as any other verify_flags bit. Report it as
  16861. // HostnameMismatch, matching the other backends and the post-handshake
  16862. // identity check below, but only when naming is the sole problem -
  16863. // if the chain itself is also untrusted/expired/etc., that takes
  16864. // priority over the naming detail.
  16865. if (verify_flags == static_cast<uint32_t>(hostname_mismatch_code())) {
  16866. return ErrorCode::HostnameMismatch;
  16867. }
  16868. return ErrorCode::CertVerifyFailed;
  16869. }
  16870. return ErrorCode::Fatal;
  16871. }
  16872. // Populates a TlsError from a failed (non-zero) mbedtls_ssl_handshake()
  16873. // return value, including the verify-flags-dependent HostnameMismatch
  16874. // mapping; shared by connect() and connect_nonblocking() so the
  16875. // backend_code policy for that mapping only lives in one place.
  16876. inline void fill_mbedtls_tls_error(TlsError &err, mbedtls_ssl_context &ssl,
  16877. int ret) {
  16878. auto verify_flags = mbedtls_ssl_get_verify_result(&ssl);
  16879. err.code = map_mbedtls_error(ret, err.sys_errno, verify_flags);
  16880. err.backend_code = err.code == ErrorCode::HostnameMismatch
  16881. ? static_cast<uint64_t>(verify_flags)
  16882. : static_cast<uint64_t>(-ret);
  16883. }
  16884. // A TLS 1.3 NewSessionTicket (signaled by default on Mbed TLS 4.x) is a
  16885. // non-fatal notification delivered between records, not an error and not
  16886. // application data, so I/O calls that see it should just be retried. Kept in
  16887. // one helper so the retry loops keep an intact "do { } while (...)" instead of
  16888. // splitting the closing brace across an #if.
  16889. inline bool mbedtls_is_session_ticket(int ret) {
  16890. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  16891. return ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
  16892. #else
  16893. (void)ret;
  16894. return false;
  16895. #endif
  16896. }
  16897. // BIO-like send callback for Mbed TLS
  16898. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  16899. size_t len) {
  16900. auto sock = *static_cast<socket_t *>(ctx);
  16901. #ifdef _WIN32
  16902. auto ret =
  16903. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  16904. if (ret == SOCKET_ERROR) {
  16905. int err = WSAGetLastError();
  16906. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  16907. return MBEDTLS_ERR_NET_SEND_FAILED;
  16908. }
  16909. #else
  16910. auto ret = send(sock, buf, len, 0);
  16911. if (ret < 0) {
  16912. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  16913. return MBEDTLS_ERR_SSL_WANT_WRITE;
  16914. }
  16915. return MBEDTLS_ERR_NET_SEND_FAILED;
  16916. }
  16917. #endif
  16918. return static_cast<int>(ret);
  16919. }
  16920. // BIO-like recv callback for Mbed TLS
  16921. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  16922. auto sock = *static_cast<socket_t *>(ctx);
  16923. #ifdef _WIN32
  16924. auto ret =
  16925. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  16926. if (ret == SOCKET_ERROR) {
  16927. int err = WSAGetLastError();
  16928. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  16929. return MBEDTLS_ERR_NET_RECV_FAILED;
  16930. }
  16931. #else
  16932. auto ret = recv(sock, buf, len, 0);
  16933. if (ret < 0) {
  16934. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  16935. return MBEDTLS_ERR_SSL_WANT_READ;
  16936. }
  16937. return MBEDTLS_ERR_NET_RECV_FAILED;
  16938. }
  16939. #endif
  16940. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  16941. return static_cast<int>(ret);
  16942. }
  16943. // MbedTlsContext constructor/destructor implementations
  16944. inline MbedTlsContext::MbedTlsContext() {
  16945. mbedtls_ssl_config_init(&conf);
  16946. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16947. mbedtls_entropy_init(&entropy);
  16948. mbedtls_ctr_drbg_init(&ctr_drbg);
  16949. #endif
  16950. mbedtls_x509_crt_init(&ca_chain);
  16951. mbedtls_x509_crt_init(&own_cert);
  16952. mbedtls_pk_init(&own_key);
  16953. }
  16954. inline MbedTlsContext::~MbedTlsContext() {
  16955. mbedtls_pk_free(&own_key);
  16956. mbedtls_x509_crt_free(&own_cert);
  16957. mbedtls_x509_crt_free(&ca_chain);
  16958. #ifndef CPPHTTPLIB_MBEDTLS_V4
  16959. mbedtls_ctr_drbg_free(&ctr_drbg);
  16960. mbedtls_entropy_free(&entropy);
  16961. #endif
  16962. mbedtls_ssl_config_free(&conf);
  16963. }
  16964. // Thread-local storage for SNI captured during handshake
  16965. // This is needed because the SNI callback doesn't have a way to pass
  16966. // session-specific data before the session is fully set up
  16967. inline std::string &mbedpending_sni() {
  16968. static thread_local std::string sni;
  16969. return sni;
  16970. }
  16971. // SNI callback for Mbed TLS server to capture client's SNI hostname
  16972. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  16973. const unsigned char *name, size_t name_len) {
  16974. (void)p_ctx;
  16975. (void)ssl;
  16976. // Store SNI name in thread-local storage
  16977. // It will be retrieved and stored in the session after handshake
  16978. if (name && name_len > 0) {
  16979. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  16980. } else {
  16981. mbedpending_sni().clear();
  16982. }
  16983. return 0; // Accept any SNI
  16984. }
  16985. inline void mbedtls_clear_cn_mismatch(uint32_t *flags) {
  16986. *flags &= ~static_cast<uint32_t>(hostname_mismatch_code());
  16987. }
  16988. // Verify callback used when hostname verification is disabled for a session
  16989. // that has no user-supplied verify callback of its own (MbedTlsSession::
  16990. // has_verify_callback is false). Deliberately does not consult
  16991. // get_verify_callback(): that slot is process-wide, so reading it here would
  16992. // pick up whatever another, unrelated client last installed there.
  16993. inline int mbedtls_mask_hostname_mismatch_callback(void *data,
  16994. mbedtls_x509_crt *, int,
  16995. uint32_t *flags) {
  16996. (void)data;
  16997. mbedtls_clear_cn_mismatch(flags);
  16998. return 0;
  16999. }
  17000. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  17001. int cert_depth, uint32_t *flags);
  17002. // MbedTLS verify callback wrapper
  17003. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  17004. int cert_depth, uint32_t *flags) {
  17005. // data points to the MbedTlsSession
  17006. auto *session = static_cast<MbedTlsSession *>(data);
  17007. // set_sni() disabled hostname verification for this session: drop the
  17008. // CN/SAN mismatch flag so it doesn't fail the chain check below, mirroring
  17009. // the OpenSSL/wolfSSL backends where identity checking is independent of
  17010. // SNI. The final pass/fail decision still comes from the remaining flags
  17011. // (or, below, from the user's own verify callback).
  17012. if (session && session->suppress_hostname_mismatch) {
  17013. mbedtls_clear_cn_mismatch(flags);
  17014. }
  17015. auto &callback = get_verify_callback();
  17016. if (!callback) { return 0; } // Continue with default verification
  17017. // Build context
  17018. VerifyContext verify_ctx;
  17019. verify_ctx.session = static_cast<session_t>(session);
  17020. verify_ctx.cert = static_cast<cert_t>(crt);
  17021. verify_ctx.depth = cert_depth;
  17022. verify_ctx.preverify_ok = (*flags == 0);
  17023. verify_ctx.error_code = static_cast<long>(*flags);
  17024. // Convert Mbed TLS flags to error string
  17025. static thread_local char error_buf[256];
  17026. if (*flags != 0) {
  17027. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  17028. verify_ctx.error_string = error_buf;
  17029. } else {
  17030. verify_ctx.error_string = nullptr;
  17031. }
  17032. bool accepted = callback(verify_ctx);
  17033. if (accepted) {
  17034. *flags = 0; // Clear all error flags
  17035. return 0;
  17036. }
  17037. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  17038. }
  17039. } // namespace impl
  17040. inline ctx_t create_client_context() {
  17041. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  17042. if (!ctx) { return nullptr; }
  17043. ctx->is_server = false;
  17044. #ifdef CPPHTTPLIB_MBEDTLS_V4
  17045. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  17046. if (!detail::ensure_mbedtls_psa_crypto()) {
  17047. delete ctx;
  17048. return nullptr;
  17049. }
  17050. int ret;
  17051. #else
  17052. // Seed the random number generator
  17053. const char *pers = "httplib_client";
  17054. int ret = mbedtls_ctr_drbg_seed(
  17055. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  17056. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  17057. if (ret != 0) {
  17058. impl::mbedtls_last_error() = ret;
  17059. delete ctx;
  17060. return nullptr;
  17061. }
  17062. #endif
  17063. // Set up SSL config for client
  17064. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  17065. MBEDTLS_SSL_TRANSPORT_STREAM,
  17066. MBEDTLS_SSL_PRESET_DEFAULT);
  17067. if (ret != 0) {
  17068. impl::mbedtls_last_error() = ret;
  17069. delete ctx;
  17070. return nullptr;
  17071. }
  17072. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17073. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  17074. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  17075. #endif
  17076. // Default: verify peer certificate
  17077. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17078. // Set minimum TLS version to 1.2
  17079. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17080. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17081. #else
  17082. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17083. MBEDTLS_SSL_MINOR_VERSION_3);
  17084. #endif
  17085. return static_cast<ctx_t>(ctx);
  17086. }
  17087. inline ctx_t create_server_context() {
  17088. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  17089. if (!ctx) { return nullptr; }
  17090. ctx->is_server = true;
  17091. #ifdef CPPHTTPLIB_MBEDTLS_V4
  17092. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  17093. if (!detail::ensure_mbedtls_psa_crypto()) {
  17094. delete ctx;
  17095. return nullptr;
  17096. }
  17097. int ret;
  17098. #else
  17099. // Seed the random number generator
  17100. const char *pers = "httplib_server";
  17101. int ret = mbedtls_ctr_drbg_seed(
  17102. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  17103. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  17104. if (ret != 0) {
  17105. impl::mbedtls_last_error() = ret;
  17106. delete ctx;
  17107. return nullptr;
  17108. }
  17109. #endif
  17110. // Set up SSL config for server
  17111. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  17112. MBEDTLS_SSL_TRANSPORT_STREAM,
  17113. MBEDTLS_SSL_PRESET_DEFAULT);
  17114. if (ret != 0) {
  17115. impl::mbedtls_last_error() = ret;
  17116. delete ctx;
  17117. return nullptr;
  17118. }
  17119. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17120. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  17121. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  17122. #endif
  17123. // Default: don't verify client
  17124. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  17125. // Set minimum TLS version to 1.2
  17126. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17127. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17128. #else
  17129. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17130. MBEDTLS_SSL_MINOR_VERSION_3);
  17131. #endif
  17132. // Set SNI callback to capture client's SNI hostname
  17133. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  17134. return static_cast<ctx_t>(ctx);
  17135. }
  17136. inline void free_context(ctx_t ctx) {
  17137. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  17138. }
  17139. inline bool set_min_version(ctx_t ctx, Version version) {
  17140. if (!ctx) { return false; }
  17141. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17142. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17143. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  17144. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  17145. if (version >= Version::TLS1_3) {
  17146. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  17147. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  17148. #endif
  17149. }
  17150. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  17151. #else
  17152. // Mbed TLS 2.x uses major/minor version numbers
  17153. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  17154. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  17155. if (version >= Version::TLS1_3) {
  17156. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  17157. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  17158. #else
  17159. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  17160. #endif
  17161. }
  17162. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  17163. #endif
  17164. return true;
  17165. }
  17166. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  17167. if (!ctx || !pem) { return false; }
  17168. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17169. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  17170. // Add null terminator if not present
  17171. std::string pem_str(pem, len);
  17172. int ret = mbedtls_x509_crt_parse(
  17173. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  17174. pem_str.size() + 1);
  17175. if (ret != 0) {
  17176. impl::mbedtls_last_error() = ret;
  17177. return false;
  17178. }
  17179. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17180. return true;
  17181. }
  17182. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  17183. if (!ctx || !file_path) { return false; }
  17184. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17185. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  17186. if (ret != 0) {
  17187. impl::mbedtls_last_error() = ret;
  17188. return false;
  17189. }
  17190. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17191. return true;
  17192. }
  17193. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  17194. if (!ctx || !dir_path) { return false; }
  17195. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17196. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  17197. if (ret < 0) { // Returns number of certs on success, negative on error
  17198. impl::mbedtls_last_error() = ret;
  17199. return false;
  17200. }
  17201. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17202. return true;
  17203. }
  17204. inline bool load_system_certs(ctx_t ctx) {
  17205. if (!ctx) { return false; }
  17206. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17207. bool loaded = false;
  17208. #ifdef _WIN32
  17209. loaded = impl::enumerate_windows_system_certs(
  17210. [&](const unsigned char *data, size_t len) {
  17211. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  17212. });
  17213. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  17214. loaded = impl::enumerate_macos_keychain_certs(
  17215. [&](const unsigned char *data, size_t len) {
  17216. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  17217. });
  17218. #else
  17219. for (auto path = impl::system_ca_paths(); *path; ++path) {
  17220. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  17221. loaded = true;
  17222. break;
  17223. }
  17224. }
  17225. if (!loaded) {
  17226. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  17227. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  17228. loaded = true;
  17229. break;
  17230. }
  17231. }
  17232. }
  17233. #endif
  17234. if (loaded) {
  17235. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17236. }
  17237. return loaded;
  17238. }
  17239. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  17240. const char *password) {
  17241. if (!ctx || !cert || !key) { return false; }
  17242. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17243. // Parse certificate
  17244. std::string cert_str(cert);
  17245. int ret = mbedtls_x509_crt_parse(
  17246. &mctx->own_cert,
  17247. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  17248. cert_str.size() + 1);
  17249. if (ret != 0) {
  17250. impl::mbedtls_last_error() = ret;
  17251. return false;
  17252. }
  17253. // Parse private key
  17254. std::string key_str(key);
  17255. const unsigned char *pwd =
  17256. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  17257. size_t pwd_len = password ? strlen(password) : 0;
  17258. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17259. ret = mbedtls_pk_parse_key(
  17260. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  17261. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  17262. &mctx->ctr_drbg);
  17263. #else
  17264. ret = mbedtls_pk_parse_key(
  17265. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  17266. key_str.size() + 1, pwd, pwd_len);
  17267. #endif
  17268. if (ret != 0) {
  17269. impl::mbedtls_last_error() = ret;
  17270. return false;
  17271. }
  17272. // Verify that the certificate and private key match.
  17273. // Mbed TLS 4.x: mbedtls_pk_check_pair() reports a spurious mismatch for
  17274. // PSA-backed keys, so skip it and let the handshake surface a real mismatch.
  17275. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17276. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17277. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  17278. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17279. #else
  17280. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  17281. #endif
  17282. if (ret != 0) {
  17283. impl::mbedtls_last_error() = ret;
  17284. return false;
  17285. }
  17286. #endif
  17287. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  17288. if (ret != 0) {
  17289. impl::mbedtls_last_error() = ret;
  17290. return false;
  17291. }
  17292. return true;
  17293. }
  17294. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  17295. const char *key_path, const char *password) {
  17296. if (!ctx || !cert_path || !key_path) { return false; }
  17297. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17298. // Parse certificate file
  17299. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  17300. if (ret != 0) {
  17301. impl::mbedtls_last_error() = ret;
  17302. return false;
  17303. }
  17304. // Parse private key file
  17305. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17306. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  17307. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17308. #else
  17309. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  17310. #endif
  17311. if (ret != 0) {
  17312. impl::mbedtls_last_error() = ret;
  17313. return false;
  17314. }
  17315. // Verify that the certificate and private key match.
  17316. // Mbed TLS 4.x: see set_client_cert() — skip the spurious check_pair.
  17317. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17318. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17319. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  17320. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17321. #else
  17322. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  17323. #endif
  17324. if (ret != 0) {
  17325. impl::mbedtls_last_error() = ret;
  17326. return false;
  17327. }
  17328. #endif
  17329. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  17330. if (ret != 0) {
  17331. impl::mbedtls_last_error() = ret;
  17332. return false;
  17333. }
  17334. return true;
  17335. }
  17336. inline void set_verify_client(ctx_t ctx, bool require) {
  17337. if (!ctx) { return; }
  17338. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17339. mctx->verify_client = require;
  17340. if (require) {
  17341. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17342. } else {
  17343. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  17344. // is called (matching OpenSSL behavior). Otherwise use NONE.
  17345. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  17346. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  17347. : MBEDTLS_SSL_VERIFY_NONE);
  17348. }
  17349. }
  17350. inline session_t create_session(ctx_t ctx, socket_t sock) {
  17351. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  17352. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17353. auto session = new (std::nothrow) impl::MbedTlsSession();
  17354. if (!session) { return nullptr; }
  17355. session->sock = sock;
  17356. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  17357. if (ret != 0) {
  17358. impl::mbedtls_last_error() = ret;
  17359. delete session;
  17360. return nullptr;
  17361. }
  17362. // Explicitly opt out of in-handshake hostname verification by default;
  17363. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  17364. // fails outright when no hostname was set. set_sni() installs the real
  17365. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  17366. // caller verifies the certificate identity post-handshake via
  17367. // verify_hostname().
  17368. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  17369. // Set BIO callbacks
  17370. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  17371. impl::mbedtls_net_recv_cb, nullptr);
  17372. // Set per-session verify callback with session pointer if callback is
  17373. // registered
  17374. session->has_verify_callback = mctx->has_verify_callback;
  17375. if (mctx->has_verify_callback) {
  17376. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  17377. session);
  17378. }
  17379. return static_cast<session_t>(session);
  17380. }
  17381. inline void free_session(session_t session) {
  17382. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  17383. }
  17384. inline bool set_sni(session_t session, const char *hostname,
  17385. bool verify_hostname) {
  17386. if (!session || !hostname) { return false; }
  17387. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17388. // mbedtls_ssl_set_hostname() both sends the SNI extension and binds the
  17389. // handshake-time CN/SAN check to `hostname`; the two can't be requested
  17390. // independently, so a disabled hostname check is handled below by masking
  17391. // the resulting mismatch flag instead of skipping this call.
  17392. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  17393. if (ret != 0) {
  17394. impl::mbedtls_last_error() = ret;
  17395. return false;
  17396. }
  17397. msession->hostname = hostname;
  17398. if (!verify_hostname) {
  17399. msession->suppress_hostname_mismatch = true;
  17400. // If a user verify callback is already wired for this session,
  17401. // mbedtls_verify_callback() masks the mismatch flag itself before
  17402. // consulting it (see suppress_hostname_mismatch above) - reinstalling it
  17403. // here would be redundant. Otherwise install the self-contained masking
  17404. // callback, which never touches the process-wide callback slot.
  17405. if (!msession->has_verify_callback) {
  17406. mbedtls_ssl_set_verify(&msession->ssl,
  17407. impl::mbedtls_mask_hostname_mismatch_callback,
  17408. msession);
  17409. }
  17410. }
  17411. return true;
  17412. }
  17413. inline TlsError connect(session_t session) {
  17414. TlsError err;
  17415. if (!session) {
  17416. err.code = ErrorCode::Fatal;
  17417. return err;
  17418. }
  17419. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17420. int ret;
  17421. do {
  17422. ret = mbedtls_ssl_handshake(&msession->ssl);
  17423. } while (impl::mbedtls_is_session_ticket(ret));
  17424. if (ret == 0) {
  17425. err.code = ErrorCode::Success;
  17426. } else {
  17427. impl::fill_mbedtls_tls_error(err, msession->ssl, ret);
  17428. impl::mbedtls_last_error() = ret;
  17429. }
  17430. return err;
  17431. }
  17432. inline TlsError accept(session_t session) {
  17433. // Same as connect for Mbed TLS - handshake works for both client and server
  17434. auto result = connect(session);
  17435. // After successful handshake, capture SNI from thread-local storage
  17436. if (result.code == ErrorCode::Success && session) {
  17437. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17438. msession->sni_hostname = std::move(impl::mbedpending_sni());
  17439. impl::mbedpending_sni().clear();
  17440. }
  17441. return result;
  17442. }
  17443. inline bool connect_nonblocking(session_t session, socket_t sock,
  17444. time_t timeout_sec, time_t timeout_usec,
  17445. TlsError *err) {
  17446. if (!session) {
  17447. if (err) { err->code = ErrorCode::Fatal; }
  17448. return false;
  17449. }
  17450. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17451. // Set socket to non-blocking mode
  17452. detail::set_nonblocking(sock, true);
  17453. auto cleanup =
  17454. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17455. int ret;
  17456. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  17457. // Non-fatal TLS 1.3 ticket; retry immediately.
  17458. if (impl::mbedtls_is_session_ticket(ret)) { continue; }
  17459. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  17460. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  17461. continue;
  17462. }
  17463. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  17464. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  17465. continue;
  17466. }
  17467. }
  17468. // TlsError or timeout
  17469. if (err) { impl::fill_mbedtls_tls_error(*err, msession->ssl, ret); }
  17470. impl::mbedtls_last_error() = ret;
  17471. return false;
  17472. }
  17473. if (err) { err->code = ErrorCode::Success; }
  17474. return true;
  17475. }
  17476. inline bool accept_nonblocking(session_t session, socket_t sock,
  17477. time_t timeout_sec, time_t timeout_usec,
  17478. TlsError *err) {
  17479. // Same implementation as connect for Mbed TLS
  17480. bool result =
  17481. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  17482. // After successful handshake, capture SNI from thread-local storage
  17483. if (result && session) {
  17484. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17485. msession->sni_hostname = std::move(impl::mbedpending_sni());
  17486. impl::mbedpending_sni().clear();
  17487. }
  17488. return result;
  17489. }
  17490. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  17491. if (!session || !buf) {
  17492. err.code = ErrorCode::Fatal;
  17493. return -1;
  17494. }
  17495. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17496. // Serve a byte consumed by the is_peer_closed() probe before reading more.
  17497. if (msession->has_peeked_byte) {
  17498. if (len == 0) { return 0; }
  17499. auto p = static_cast<unsigned char *>(buf);
  17500. p[0] = msession->peeked_byte;
  17501. msession->has_peeked_byte = false;
  17502. size_t n = 1;
  17503. // Top up with any already-decrypted bytes without risking a block.
  17504. if (len > 1 && mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17505. int extra = mbedtls_ssl_read(&msession->ssl, p + 1, len - 1);
  17506. if (extra > 0) { n += static_cast<size_t>(extra); }
  17507. }
  17508. err.code = ErrorCode::Success;
  17509. return static_cast<ssize_t>(n);
  17510. }
  17511. int ret;
  17512. do {
  17513. ret = mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf),
  17514. len);
  17515. } while (impl::mbedtls_is_session_ticket(ret));
  17516. if (ret > 0) {
  17517. err.code = ErrorCode::Success;
  17518. return static_cast<ssize_t>(ret);
  17519. }
  17520. if (ret == 0) {
  17521. err.code = ErrorCode::PeerClosed;
  17522. return 0;
  17523. }
  17524. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17525. err.backend_code = static_cast<uint64_t>(-ret);
  17526. impl::mbedtls_last_error() = ret;
  17527. // mbedTLS signals a clean close_notify via a negative error code rather
  17528. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  17529. if (err.code == ErrorCode::PeerClosed) { return 0; }
  17530. return -1;
  17531. }
  17532. inline ssize_t write(session_t session, const void *buf, size_t len,
  17533. TlsError &err) {
  17534. if (!session || !buf) {
  17535. err.code = ErrorCode::Fatal;
  17536. return -1;
  17537. }
  17538. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17539. int ret;
  17540. do {
  17541. ret = mbedtls_ssl_write(&msession->ssl,
  17542. static_cast<const unsigned char *>(buf), len);
  17543. } while (impl::mbedtls_is_session_ticket(ret));
  17544. if (ret > 0) {
  17545. err.code = ErrorCode::Success;
  17546. return static_cast<ssize_t>(ret);
  17547. }
  17548. if (ret == 0) {
  17549. err.code = ErrorCode::PeerClosed;
  17550. return 0;
  17551. }
  17552. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17553. err.backend_code = static_cast<uint64_t>(-ret);
  17554. impl::mbedtls_last_error() = ret;
  17555. return -1;
  17556. }
  17557. inline int pending(const_session_t session) {
  17558. if (!session) { return 0; }
  17559. auto msession =
  17560. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17561. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl)) +
  17562. (msession->has_peeked_byte ? 1 : 0);
  17563. }
  17564. inline void shutdown(session_t session, bool graceful) {
  17565. if (!session) { return; }
  17566. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17567. if (graceful) {
  17568. // Try to send close_notify, but don't block forever
  17569. int ret;
  17570. int attempts = 0;
  17571. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  17572. attempts < 3) {
  17573. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  17574. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  17575. break;
  17576. }
  17577. attempts++;
  17578. }
  17579. }
  17580. }
  17581. inline bool is_peer_closed(session_t session, socket_t sock) {
  17582. if (!session || sock == INVALID_SOCKET) { return true; }
  17583. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17584. // Check if there's already decrypted or pushed-back data available.
  17585. // If so, the connection is definitely alive.
  17586. if (msession->has_peeked_byte ||
  17587. mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17588. return false;
  17589. }
  17590. // Set socket to non-blocking to avoid blocking on read
  17591. detail::set_nonblocking(sock, true);
  17592. auto cleanup =
  17593. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17594. // Probe with a 1-byte read (Mbed TLS has no peek API). If the probe lands
  17595. // on application data — e.g. a response that already arrived — push the
  17596. // byte back so the next read() delivers it instead of losing it.
  17597. unsigned char buf;
  17598. int ret;
  17599. do {
  17600. ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  17601. } while (impl::mbedtls_is_session_ticket(ret));
  17602. // If we got data or WANT_READ (would block), connection is alive
  17603. if (ret > 0) {
  17604. msession->peeked_byte = buf;
  17605. msession->has_peeked_byte = true;
  17606. return false;
  17607. }
  17608. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  17609. // If we get a peer close notify or a connection reset, the peer is closed
  17610. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  17611. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  17612. }
  17613. inline cert_t get_peer_cert(const_session_t session) {
  17614. if (!session) { return nullptr; }
  17615. auto msession =
  17616. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17617. // Mbed TLS returns a pointer to the internal peer cert chain.
  17618. // WARNING: This pointer is only valid while the session is active.
  17619. // Do not use the certificate after calling free_session().
  17620. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  17621. return const_cast<mbedtls_x509_crt *>(cert);
  17622. }
  17623. inline void free_cert(cert_t cert) {
  17624. // Mbed TLS: peer certificate is owned by the SSL context.
  17625. // No-op here, but callers should still call this for cross-backend
  17626. // portability.
  17627. (void)cert;
  17628. }
  17629. inline bool verify_hostname(cert_t cert, const char *hostname) {
  17630. if (!cert || !hostname) { return false; }
  17631. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  17632. std::string host_str(hostname);
  17633. // Check if hostname is an IP address (IPv4 or IPv6)
  17634. unsigned char ip_bytes[16];
  17635. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  17636. auto is_ip = ip_len > 0;
  17637. // Check Subject Alternative Names (SAN)
  17638. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  17639. // - DNS names: raw string bytes
  17640. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  17641. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  17642. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  17643. const unsigned char *p = san->buf.p;
  17644. size_t len = san->buf.len;
  17645. if (is_ip) {
  17646. // For an IP host, only a matching iPAddress SAN of the same family
  17647. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  17648. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  17649. } else {
  17650. // Check if this SAN is a DNS name (printable ASCII string)
  17651. bool is_dns = len > 0;
  17652. for (size_t i = 0; i < len && is_dns; i++) {
  17653. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  17654. }
  17655. if (is_dns) {
  17656. std::string san_name(reinterpret_cast<const char *>(p), len);
  17657. if (detail::match_hostname(san_name, host_str)) { return true; }
  17658. }
  17659. }
  17660. san = san->next;
  17661. }
  17662. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  17663. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  17664. // the OpenSSL backend's X509_check_ip behaves the same way).
  17665. if (!is_ip) {
  17666. char cn[256];
  17667. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  17668. if (ret > 0) {
  17669. std::string cn_str(cn);
  17670. // Look for "CN=" in the DN string
  17671. size_t cn_pos = cn_str.find("CN=");
  17672. if (cn_pos != std::string::npos) {
  17673. size_t start = cn_pos + 3;
  17674. size_t end = cn_str.find(',', start);
  17675. std::string cn_value =
  17676. cn_str.substr(start, end == std::string::npos ? end : end - start);
  17677. if (detail::match_hostname(cn_value, host_str)) { return true; }
  17678. }
  17679. }
  17680. }
  17681. return false;
  17682. }
  17683. inline uint64_t hostname_mismatch_code() {
  17684. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  17685. }
  17686. inline long get_verify_result(const_session_t session) {
  17687. if (!session) { return -1; }
  17688. auto msession =
  17689. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17690. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  17691. // Return 0 (X509_V_OK equivalent) if verification passed
  17692. return flags == 0 ? 0 : static_cast<long>(flags);
  17693. }
  17694. inline std::string get_cert_subject_cn(cert_t cert) {
  17695. if (!cert) return "";
  17696. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17697. // Find the CN in the subject
  17698. const mbedtls_x509_name *name = &x509->subject;
  17699. while (name != nullptr) {
  17700. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  17701. return std::string(reinterpret_cast<const char *>(name->val.p),
  17702. name->val.len);
  17703. }
  17704. name = name->next;
  17705. }
  17706. return "";
  17707. }
  17708. inline std::string get_cert_issuer_name(cert_t cert) {
  17709. if (!cert) return "";
  17710. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17711. // Build a human-readable issuer name string
  17712. char buf[512];
  17713. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  17714. if (ret < 0) return "";
  17715. return std::string(buf);
  17716. }
  17717. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  17718. sans.clear();
  17719. if (!cert) return false;
  17720. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17721. // Parse the Subject Alternative Name extension
  17722. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  17723. while (cur != nullptr) {
  17724. if (cur->buf.len > 0) {
  17725. // Mbed TLS stores SAN as ASN.1 sequences
  17726. // The tag byte indicates the type
  17727. const unsigned char *p = cur->buf.p;
  17728. size_t len = cur->buf.len;
  17729. // First byte is the tag
  17730. unsigned char tag = *p;
  17731. p++;
  17732. len--;
  17733. // Parse length (simple single-byte length assumed)
  17734. if (len > 0 && *p < 0x80) {
  17735. size_t value_len = *p;
  17736. p++;
  17737. len--;
  17738. if (value_len <= len) {
  17739. SanEntry entry;
  17740. // ASN.1 context tags for GeneralName
  17741. switch (tag & 0x1F) {
  17742. case 2: // dNSName
  17743. entry.type = SanType::DNS;
  17744. entry.value =
  17745. std::string(reinterpret_cast<const char *>(p), value_len);
  17746. break;
  17747. case 7: // iPAddress
  17748. entry.type = SanType::IP;
  17749. if (value_len == 4) {
  17750. // IPv4
  17751. char buf[16];
  17752. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  17753. entry.value = buf;
  17754. } else if (value_len == 16) {
  17755. // IPv6
  17756. char buf[64];
  17757. snprintf(buf, sizeof(buf),
  17758. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  17759. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  17760. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  17761. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  17762. entry.value = buf;
  17763. }
  17764. break;
  17765. case 1: // rfc822Name (email)
  17766. entry.type = SanType::EMAIL;
  17767. entry.value =
  17768. std::string(reinterpret_cast<const char *>(p), value_len);
  17769. break;
  17770. case 6: // uniformResourceIdentifier
  17771. entry.type = SanType::URI;
  17772. entry.value =
  17773. std::string(reinterpret_cast<const char *>(p), value_len);
  17774. break;
  17775. default: entry.type = SanType::OTHER; break;
  17776. }
  17777. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17778. }
  17779. }
  17780. }
  17781. cur = cur->next;
  17782. }
  17783. return true;
  17784. }
  17785. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17786. time_t &not_after) {
  17787. if (!cert) return false;
  17788. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17789. // Convert mbedtls_x509_time to time_t
  17790. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  17791. struct tm tm_time = {};
  17792. tm_time.tm_year = t.year - 1900;
  17793. tm_time.tm_mon = t.mon - 1;
  17794. tm_time.tm_mday = t.day;
  17795. tm_time.tm_hour = t.hour;
  17796. tm_time.tm_min = t.min;
  17797. tm_time.tm_sec = t.sec;
  17798. #ifdef _WIN32
  17799. return _mkgmtime(&tm_time);
  17800. #else
  17801. return timegm(&tm_time);
  17802. #endif
  17803. };
  17804. not_before = to_time_t(x509->valid_from);
  17805. not_after = to_time_t(x509->valid_to);
  17806. return true;
  17807. }
  17808. inline std::string get_cert_serial(cert_t cert) {
  17809. if (!cert) return "";
  17810. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17811. // Convert serial number to hex string
  17812. std::string result;
  17813. result.reserve(x509->serial.len * 2);
  17814. for (size_t i = 0; i < x509->serial.len; i++) {
  17815. char hex[3];
  17816. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  17817. result += hex;
  17818. }
  17819. return result;
  17820. }
  17821. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17822. if (!cert) return false;
  17823. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  17824. if (!crt->raw.p || crt->raw.len == 0) return false;
  17825. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  17826. return true;
  17827. }
  17828. inline const char *get_sni(const_session_t session) {
  17829. if (!session) return nullptr;
  17830. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  17831. // For server: return SNI received from client during handshake
  17832. if (!msession->sni_hostname.empty()) {
  17833. return msession->sni_hostname.c_str();
  17834. }
  17835. // For client: return the hostname set via set_sni
  17836. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  17837. return nullptr;
  17838. }
  17839. inline uint64_t peek_error() {
  17840. // Mbed TLS doesn't have an error queue, return the last error
  17841. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  17842. }
  17843. inline uint64_t get_error() {
  17844. // Mbed TLS doesn't have an error queue, return and clear the last error
  17845. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  17846. impl::mbedtls_last_error() = 0;
  17847. return err;
  17848. }
  17849. inline std::string error_string(uint64_t code) {
  17850. char buf[256];
  17851. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  17852. return std::string(buf);
  17853. }
  17854. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17855. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  17856. if (!ca_chain) { return nullptr; }
  17857. mbedtls_x509_crt_init(ca_chain);
  17858. // mbedtls_x509_crt_parse expects null-terminated PEM
  17859. int ret = mbedtls_x509_crt_parse(ca_chain,
  17860. reinterpret_cast<const unsigned char *>(pem),
  17861. len + 1); // +1 for null terminator
  17862. if (ret != 0) {
  17863. // Try without +1 in case PEM is already null-terminated
  17864. ret = mbedtls_x509_crt_parse(
  17865. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  17866. if (ret != 0) {
  17867. mbedtls_x509_crt_free(ca_chain);
  17868. delete ca_chain;
  17869. return nullptr;
  17870. }
  17871. }
  17872. return static_cast<ca_store_t>(ca_chain);
  17873. }
  17874. inline void free_ca_store(ca_store_t store) {
  17875. if (store) {
  17876. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  17877. mbedtls_x509_crt_free(ca_chain);
  17878. delete ca_chain;
  17879. }
  17880. }
  17881. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17882. if (!ctx || !store) { return false; }
  17883. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17884. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  17885. // Free existing CA chain
  17886. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  17887. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  17888. // Copy the CA chain (deep copy)
  17889. // Parse from the raw data of the source cert
  17890. mbedtls_x509_crt *src = ca_chain;
  17891. while (src != nullptr) {
  17892. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  17893. src->raw.len);
  17894. if (ret != 0) {
  17895. free_ca_store(store);
  17896. return false;
  17897. }
  17898. src = src->next;
  17899. }
  17900. // This function takes ownership of the store; the chain was deep-copied
  17901. // above, so release the source
  17902. free_ca_store(store);
  17903. // Update the SSL config to use the new CA chain
  17904. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  17905. return true;
  17906. }
  17907. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17908. certs.clear();
  17909. if (!ctx) { return 0; }
  17910. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17911. // Iterate through the CA chain
  17912. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  17913. while (cert != nullptr && cert->raw.len > 0) {
  17914. // Create a copy of the certificate for the caller
  17915. auto *copy = new mbedtls_x509_crt;
  17916. mbedtls_x509_crt_init(copy);
  17917. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  17918. if (ret == 0) {
  17919. certs.push_back(static_cast<cert_t>(copy));
  17920. } else {
  17921. mbedtls_x509_crt_free(copy);
  17922. delete copy;
  17923. }
  17924. cert = cert->next;
  17925. }
  17926. return certs.size();
  17927. }
  17928. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17929. std::vector<std::string> names;
  17930. if (!ctx) { return names; }
  17931. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17932. // Iterate through the CA chain
  17933. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  17934. while (cert != nullptr && cert->raw.len > 0) {
  17935. char buf[512];
  17936. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  17937. if (ret > 0) { names.push_back(buf); }
  17938. cert = cert->next;
  17939. }
  17940. return names;
  17941. }
  17942. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17943. const char *key_pem, const char *password) {
  17944. if (!ctx || !cert_pem || !key_pem) { return false; }
  17945. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17946. // Free existing certificate and key
  17947. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  17948. mbedtls_pk_free(&mbed_ctx->own_key);
  17949. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  17950. mbedtls_pk_init(&mbed_ctx->own_key);
  17951. // Parse certificate PEM
  17952. int ret = mbedtls_x509_crt_parse(
  17953. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  17954. strlen(cert_pem) + 1);
  17955. if (ret != 0) {
  17956. impl::mbedtls_last_error() = ret;
  17957. return false;
  17958. }
  17959. // Parse private key PEM
  17960. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17961. ret = mbedtls_pk_parse_key(
  17962. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  17963. strlen(key_pem) + 1,
  17964. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  17965. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  17966. &mbed_ctx->ctr_drbg);
  17967. #else
  17968. ret = mbedtls_pk_parse_key(
  17969. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  17970. strlen(key_pem) + 1,
  17971. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  17972. password ? strlen(password) : 0);
  17973. #endif
  17974. if (ret != 0) {
  17975. impl::mbedtls_last_error() = ret;
  17976. return false;
  17977. }
  17978. // Configure SSL to use the new certificate and key
  17979. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  17980. &mbed_ctx->own_key);
  17981. if (ret != 0) {
  17982. impl::mbedtls_last_error() = ret;
  17983. return false;
  17984. }
  17985. return true;
  17986. }
  17987. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17988. if (!ctx || !ca_pem) { return false; }
  17989. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  17990. // Free existing CA chain
  17991. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  17992. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  17993. // Parse CA PEM
  17994. int ret = mbedtls_x509_crt_parse(
  17995. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  17996. strlen(ca_pem) + 1);
  17997. if (ret != 0) {
  17998. impl::mbedtls_last_error() = ret;
  17999. return false;
  18000. }
  18001. // Update SSL config to use new CA chain
  18002. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  18003. return true;
  18004. }
  18005. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  18006. if (!ctx) { return false; }
  18007. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18008. impl::get_verify_callback() = std::move(callback);
  18009. mbed_ctx->has_verify_callback =
  18010. static_cast<bool>(impl::get_verify_callback());
  18011. if (mbed_ctx->has_verify_callback) {
  18012. // Set OPTIONAL mode to ensure callback is called even when verification
  18013. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  18014. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  18015. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  18016. nullptr);
  18017. } else {
  18018. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  18019. }
  18020. return true;
  18021. }
  18022. inline long get_verify_error(const_session_t session) {
  18023. if (!session) { return -1; }
  18024. auto *msession =
  18025. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  18026. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  18027. }
  18028. inline std::string verify_error_string(long error_code) {
  18029. if (error_code == 0) { return ""; }
  18030. char buf[256];
  18031. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  18032. static_cast<uint32_t>(error_code));
  18033. // Remove trailing newline if present
  18034. std::string result(buf);
  18035. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  18036. result.pop_back();
  18037. }
  18038. return result;
  18039. }
  18040. } // namespace tls
  18041. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  18042. /*
  18043. * Group 10: TLS abstraction layer - wolfSSL backend
  18044. */
  18045. /*
  18046. * wolfSSL Backend Implementation
  18047. */
  18048. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  18049. namespace tls {
  18050. namespace impl {
  18051. // wolfSSL session wrapper
  18052. struct WolfSSLSession {
  18053. WOLFSSL *ssl = nullptr;
  18054. socket_t sock = INVALID_SOCKET;
  18055. std::string hostname; // For client: set via set_sni
  18056. std::string sni_hostname; // For server: received from client via SNI callback
  18057. WolfSSLSession() = default;
  18058. ~WolfSSLSession() {
  18059. if (ssl) { wolfSSL_free(ssl); }
  18060. }
  18061. WolfSSLSession(const WolfSSLSession &) = delete;
  18062. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  18063. };
  18064. // Thread-local error code accessor for wolfSSL
  18065. inline uint64_t &wolfssl_last_error() {
  18066. static thread_local uint64_t err = 0;
  18067. return err;
  18068. }
  18069. // Helper to map wolfSSL error to ErrorCode.
  18070. // ssl_error is the value from wolfSSL_get_error().
  18071. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  18072. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  18073. int &out_errno) {
  18074. switch (ssl_error) {
  18075. case SSL_ERROR_NONE: return ErrorCode::Success;
  18076. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  18077. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  18078. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  18079. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  18080. default:
  18081. if (ssl) {
  18082. // wolfSSL stores the low-level error code as a negative value.
  18083. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  18084. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  18085. if (low_err == DOMAIN_NAME_MISMATCH) {
  18086. return ErrorCode::HostnameMismatch;
  18087. }
  18088. // Check verify result to distinguish cert verification from generic SSL
  18089. // errors.
  18090. long vr = wolfSSL_get_verify_result(ssl);
  18091. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  18092. }
  18093. return ErrorCode::Fatal;
  18094. }
  18095. }
  18096. // WolfSSLContext constructor/destructor implementations
  18097. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  18098. inline WolfSSLContext::~WolfSSLContext() {
  18099. if (ctx) { wolfSSL_CTX_free(ctx); }
  18100. }
  18101. // Thread-local storage for SNI captured during handshake
  18102. inline std::string &wolfssl_pending_sni() {
  18103. static thread_local std::string sni;
  18104. return sni;
  18105. }
  18106. // SNI callback for wolfSSL server to capture client's SNI hostname
  18107. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  18108. (void)ret;
  18109. (void)exArg;
  18110. void *name_data = nullptr;
  18111. unsigned short name_len =
  18112. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  18113. if (name_data && name_len > 0) {
  18114. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  18115. name_len);
  18116. } else {
  18117. wolfssl_pending_sni().clear();
  18118. }
  18119. return 0; // Continue regardless
  18120. }
  18121. // wolfSSL verify callback wrapper
  18122. inline int wolfssl_verify_callback(int preverify_ok,
  18123. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  18124. auto &callback = get_verify_callback();
  18125. if (!callback) { return preverify_ok; }
  18126. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  18127. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  18128. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  18129. // Get the WOLFSSL object from the X509_STORE_CTX
  18130. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  18131. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  18132. VerifyContext verify_ctx;
  18133. verify_ctx.session = static_cast<session_t>(ssl);
  18134. verify_ctx.cert = static_cast<cert_t>(cert);
  18135. verify_ctx.depth = depth;
  18136. verify_ctx.preverify_ok = (preverify_ok != 0);
  18137. verify_ctx.error_code = static_cast<long>(err);
  18138. if (err != 0) {
  18139. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  18140. } else {
  18141. verify_ctx.error_string = nullptr;
  18142. }
  18143. bool accepted = callback(verify_ctx);
  18144. return accepted ? 1 : 0;
  18145. }
  18146. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  18147. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  18148. wolfSSL_CTX_set_default_passwd_cb(
  18149. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  18150. auto *pwd = static_cast<const char *>(userdata);
  18151. if (!pwd) return 0;
  18152. auto len = static_cast<int>(strlen(pwd));
  18153. if (len > size) len = size;
  18154. memcpy(buf, pwd, static_cast<size_t>(len));
  18155. return len;
  18156. });
  18157. }
  18158. } // namespace impl
  18159. inline ctx_t create_client_context() {
  18160. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  18161. if (!ctx) { return nullptr; }
  18162. ctx->is_server = false;
  18163. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  18164. if (!method) {
  18165. delete ctx;
  18166. return nullptr;
  18167. }
  18168. ctx->ctx = wolfSSL_CTX_new(method);
  18169. if (!ctx->ctx) {
  18170. delete ctx;
  18171. return nullptr;
  18172. }
  18173. // Default: verify peer certificate
  18174. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  18175. return static_cast<ctx_t>(ctx);
  18176. }
  18177. inline ctx_t create_server_context() {
  18178. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  18179. if (!ctx) { return nullptr; }
  18180. ctx->is_server = true;
  18181. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  18182. if (!method) {
  18183. delete ctx;
  18184. return nullptr;
  18185. }
  18186. ctx->ctx = wolfSSL_CTX_new(method);
  18187. if (!ctx->ctx) {
  18188. delete ctx;
  18189. return nullptr;
  18190. }
  18191. // Default: don't verify client
  18192. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  18193. // Enable SNI on server
  18194. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  18195. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  18196. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  18197. return static_cast<ctx_t>(ctx);
  18198. }
  18199. inline void free_context(ctx_t ctx) {
  18200. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  18201. }
  18202. inline bool set_min_version(ctx_t ctx, Version version) {
  18203. if (!ctx) { return false; }
  18204. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18205. int min_ver = WOLFSSL_TLSV1_2;
  18206. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  18207. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  18208. }
  18209. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  18210. if (!ctx || !pem) { return false; }
  18211. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18212. int ret = wolfSSL_CTX_load_verify_buffer(
  18213. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  18214. static_cast<long>(len), SSL_FILETYPE_PEM);
  18215. if (ret != SSL_SUCCESS) {
  18216. impl::wolfssl_last_error() =
  18217. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18218. return false;
  18219. }
  18220. wctx->ca_pem_data_.append(pem, len);
  18221. return true;
  18222. }
  18223. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  18224. if (!ctx || !file_path) { return false; }
  18225. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18226. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  18227. if (ret != SSL_SUCCESS) {
  18228. impl::wolfssl_last_error() =
  18229. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18230. return false;
  18231. }
  18232. return true;
  18233. }
  18234. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  18235. if (!ctx || !dir_path) { return false; }
  18236. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18237. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  18238. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  18239. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  18240. // immediately. Return true even on failure since the CA file may have
  18241. // already been loaded, matching OpenSSL's lenient behavior.
  18242. (void)ret;
  18243. return true;
  18244. }
  18245. inline bool load_system_certs(ctx_t ctx) {
  18246. if (!ctx) { return false; }
  18247. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18248. bool loaded = false;
  18249. #ifdef _WIN32
  18250. loaded = impl::enumerate_windows_system_certs(
  18251. [&](const unsigned char *data, size_t len) {
  18252. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  18253. static_cast<long>(len),
  18254. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  18255. });
  18256. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  18257. loaded = impl::enumerate_macos_keychain_certs(
  18258. [&](const unsigned char *data, size_t len) {
  18259. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  18260. static_cast<long>(len),
  18261. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  18262. });
  18263. #else
  18264. for (auto path = impl::system_ca_paths(); *path; ++path) {
  18265. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  18266. SSL_SUCCESS) {
  18267. loaded = true;
  18268. break;
  18269. }
  18270. }
  18271. if (!loaded) {
  18272. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  18273. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  18274. SSL_SUCCESS) {
  18275. loaded = true;
  18276. break;
  18277. }
  18278. }
  18279. }
  18280. #endif
  18281. return loaded;
  18282. }
  18283. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  18284. const char *password) {
  18285. if (!ctx || !cert || !key) { return false; }
  18286. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18287. // Load certificate
  18288. int ret = wolfSSL_CTX_use_certificate_buffer(
  18289. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  18290. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  18291. if (ret != SSL_SUCCESS) {
  18292. impl::wolfssl_last_error() =
  18293. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18294. return false;
  18295. }
  18296. // Set password callback if password is provided
  18297. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18298. // Load private key
  18299. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  18300. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  18301. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  18302. if (ret != SSL_SUCCESS) {
  18303. impl::wolfssl_last_error() =
  18304. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18305. return false;
  18306. }
  18307. // Verify that the certificate and private key match
  18308. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  18309. }
  18310. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  18311. const char *key_path, const char *password) {
  18312. if (!ctx || !cert_path || !key_path) { return false; }
  18313. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18314. // Load certificate file
  18315. int ret =
  18316. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  18317. if (ret != SSL_SUCCESS) {
  18318. impl::wolfssl_last_error() =
  18319. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18320. return false;
  18321. }
  18322. // Set password callback if password is provided
  18323. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18324. // Load private key file
  18325. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  18326. if (ret != SSL_SUCCESS) {
  18327. impl::wolfssl_last_error() =
  18328. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18329. return false;
  18330. }
  18331. // Verify that the certificate and private key match
  18332. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  18333. }
  18334. inline void set_verify_client(ctx_t ctx, bool require) {
  18335. if (!ctx) { return; }
  18336. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18337. wctx->verify_client = require;
  18338. if (require) {
  18339. wolfSSL_CTX_set_verify(
  18340. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  18341. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  18342. } else {
  18343. if (wctx->has_verify_callback) {
  18344. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  18345. impl::wolfssl_verify_callback);
  18346. } else {
  18347. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  18348. }
  18349. }
  18350. }
  18351. inline session_t create_session(ctx_t ctx, socket_t sock) {
  18352. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  18353. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18354. auto session = new (std::nothrow) impl::WolfSSLSession();
  18355. if (!session) { return nullptr; }
  18356. session->sock = sock;
  18357. session->ssl = wolfSSL_new(wctx->ctx);
  18358. if (!session->ssl) {
  18359. impl::wolfssl_last_error() =
  18360. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18361. delete session;
  18362. return nullptr;
  18363. }
  18364. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  18365. return static_cast<session_t>(session);
  18366. }
  18367. inline void free_session(session_t session) {
  18368. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  18369. }
  18370. inline bool set_sni(session_t session, const char *hostname,
  18371. bool verify_hostname) {
  18372. if (!session || !hostname) { return false; }
  18373. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18374. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  18375. static_cast<word16>(strlen(hostname)));
  18376. if (ret != WOLFSSL_SUCCESS) {
  18377. impl::wolfssl_last_error() =
  18378. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18379. return false;
  18380. }
  18381. // wolfSSL_check_domain_name binds identity checking to the handshake,
  18382. // separately from the SNI extension sent above; skip it when hostname
  18383. // verification is disabled so only the chain is checked, matching OpenSSL.
  18384. if (verify_hostname) { wolfSSL_check_domain_name(wsession->ssl, hostname); }
  18385. wsession->hostname = hostname;
  18386. return true;
  18387. }
  18388. inline TlsError connect(session_t session) {
  18389. TlsError err;
  18390. if (!session) {
  18391. err.code = ErrorCode::Fatal;
  18392. return err;
  18393. }
  18394. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18395. int ret = wolfSSL_connect(wsession->ssl);
  18396. if (ret == SSL_SUCCESS) {
  18397. err.code = ErrorCode::Success;
  18398. } else {
  18399. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18400. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18401. err.backend_code = static_cast<uint64_t>(ssl_error);
  18402. impl::wolfssl_last_error() = err.backend_code;
  18403. }
  18404. return err;
  18405. }
  18406. inline TlsError accept(session_t session) {
  18407. TlsError err;
  18408. if (!session) {
  18409. err.code = ErrorCode::Fatal;
  18410. return err;
  18411. }
  18412. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18413. int ret = wolfSSL_accept(wsession->ssl);
  18414. if (ret == SSL_SUCCESS) {
  18415. err.code = ErrorCode::Success;
  18416. // Capture SNI from thread-local storage after successful handshake
  18417. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  18418. impl::wolfssl_pending_sni().clear();
  18419. } else {
  18420. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18421. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18422. err.backend_code = static_cast<uint64_t>(ssl_error);
  18423. impl::wolfssl_last_error() = err.backend_code;
  18424. }
  18425. return err;
  18426. }
  18427. inline bool connect_nonblocking(session_t session, socket_t sock,
  18428. time_t timeout_sec, time_t timeout_usec,
  18429. TlsError *err) {
  18430. if (!session) {
  18431. if (err) { err->code = ErrorCode::Fatal; }
  18432. return false;
  18433. }
  18434. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18435. // Set socket to non-blocking mode
  18436. detail::set_nonblocking(sock, true);
  18437. auto cleanup =
  18438. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18439. int ret;
  18440. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  18441. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18442. if (ssl_error == SSL_ERROR_WANT_READ) {
  18443. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  18444. continue;
  18445. }
  18446. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18447. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18448. continue;
  18449. }
  18450. }
  18451. // Error or timeout
  18452. if (err) {
  18453. err->code =
  18454. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18455. err->backend_code = static_cast<uint64_t>(ssl_error);
  18456. }
  18457. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18458. return false;
  18459. }
  18460. if (err) { err->code = ErrorCode::Success; }
  18461. return true;
  18462. }
  18463. inline bool accept_nonblocking(session_t session, socket_t sock,
  18464. time_t timeout_sec, time_t timeout_usec,
  18465. TlsError *err) {
  18466. if (!session) {
  18467. if (err) { err->code = ErrorCode::Fatal; }
  18468. return false;
  18469. }
  18470. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18471. // Set socket to non-blocking mode
  18472. detail::set_nonblocking(sock, true);
  18473. auto cleanup =
  18474. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18475. int ret;
  18476. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  18477. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18478. if (ssl_error == SSL_ERROR_WANT_READ) {
  18479. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  18480. continue;
  18481. }
  18482. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18483. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18484. continue;
  18485. }
  18486. }
  18487. // Error or timeout
  18488. if (err) {
  18489. err->code =
  18490. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18491. err->backend_code = static_cast<uint64_t>(ssl_error);
  18492. }
  18493. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18494. return false;
  18495. }
  18496. if (err) { err->code = ErrorCode::Success; }
  18497. // Capture SNI from thread-local storage after successful handshake
  18498. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  18499. impl::wolfssl_pending_sni().clear();
  18500. return true;
  18501. }
  18502. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  18503. if (!session || !buf) {
  18504. err.code = ErrorCode::Fatal;
  18505. return -1;
  18506. }
  18507. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18508. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  18509. if (ret > 0) {
  18510. err.code = ErrorCode::Success;
  18511. return static_cast<ssize_t>(ret);
  18512. }
  18513. if (ret == 0) {
  18514. err.code = ErrorCode::PeerClosed;
  18515. return 0;
  18516. }
  18517. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18518. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18519. err.backend_code = static_cast<uint64_t>(ssl_error);
  18520. impl::wolfssl_last_error() = err.backend_code;
  18521. return -1;
  18522. }
  18523. inline ssize_t write(session_t session, const void *buf, size_t len,
  18524. TlsError &err) {
  18525. if (!session || !buf) {
  18526. err.code = ErrorCode::Fatal;
  18527. return -1;
  18528. }
  18529. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18530. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  18531. if (ret > 0) {
  18532. err.code = ErrorCode::Success;
  18533. return static_cast<ssize_t>(ret);
  18534. }
  18535. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  18536. // Treat this as an error (return -1) so callers don't spin in a
  18537. // write loop adding zero to the offset.
  18538. if (ret == 0) {
  18539. err.code = ErrorCode::PeerClosed;
  18540. return -1;
  18541. }
  18542. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18543. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18544. err.backend_code = static_cast<uint64_t>(ssl_error);
  18545. impl::wolfssl_last_error() = err.backend_code;
  18546. return -1;
  18547. }
  18548. inline int pending(const_session_t session) {
  18549. if (!session) { return 0; }
  18550. auto wsession =
  18551. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18552. return wolfSSL_pending(wsession->ssl);
  18553. }
  18554. inline void shutdown(session_t session, bool graceful) {
  18555. if (!session) { return; }
  18556. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18557. if (graceful) {
  18558. int ret;
  18559. int attempts = 0;
  18560. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  18561. attempts < 3) {
  18562. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18563. if (ssl_error != SSL_ERROR_WANT_READ &&
  18564. ssl_error != SSL_ERROR_WANT_WRITE) {
  18565. break;
  18566. }
  18567. attempts++;
  18568. }
  18569. } else {
  18570. wolfSSL_shutdown(wsession->ssl);
  18571. }
  18572. }
  18573. inline bool is_peer_closed(session_t session, socket_t sock) {
  18574. if (!session || sock == INVALID_SOCKET) { return true; }
  18575. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18576. // Check if there's already decrypted data available
  18577. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  18578. // Set socket to non-blocking to avoid blocking on read
  18579. detail::set_nonblocking(sock, true);
  18580. auto cleanup =
  18581. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18582. // Peek 1 byte to check connection status without consuming data
  18583. unsigned char buf;
  18584. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  18585. // If we got data or WANT_READ (would block), connection is alive
  18586. if (ret > 0) { return false; }
  18587. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18588. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  18589. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  18590. ret == 0;
  18591. }
  18592. inline cert_t get_peer_cert(const_session_t session) {
  18593. if (!session) { return nullptr; }
  18594. auto wsession =
  18595. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18596. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  18597. return static_cast<cert_t>(cert);
  18598. }
  18599. inline void free_cert(cert_t cert) {
  18600. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  18601. }
  18602. inline bool verify_hostname(cert_t cert, const char *hostname) {
  18603. if (!cert || !hostname) { return false; }
  18604. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18605. std::string host_str(hostname);
  18606. // Check if hostname is an IP address (IPv4 or IPv6)
  18607. unsigned char ip_bytes[16];
  18608. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  18609. auto is_ip = ip_len > 0;
  18610. // Check Subject Alternative Names
  18611. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  18612. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18613. if (san_names) {
  18614. int san_count = wolfSSL_sk_num(san_names);
  18615. for (int i = 0; i < san_count; i++) {
  18616. auto *names =
  18617. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  18618. if (!names) continue;
  18619. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  18620. // DNS name
  18621. unsigned char *dns_name = nullptr;
  18622. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  18623. if (dns_name && dns_len > 0) {
  18624. std::string san_name(reinterpret_cast<char *>(dns_name),
  18625. static_cast<size_t>(dns_len));
  18626. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  18627. if (detail::match_hostname(san_name, host_str)) {
  18628. wolfSSL_sk_free(san_names);
  18629. return true;
  18630. }
  18631. }
  18632. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  18633. // IP address: only an iPAddress SAN of the same family (4 bytes for
  18634. // IPv4, 16 bytes for IPv6) may authenticate the host.
  18635. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  18636. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  18637. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  18638. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  18639. wolfSSL_sk_free(san_names);
  18640. return true;
  18641. }
  18642. }
  18643. }
  18644. wolfSSL_sk_free(san_names);
  18645. }
  18646. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  18647. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  18648. // the OpenSSL backend's X509_check_ip behaves the same way).
  18649. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  18650. if (subject) {
  18651. char cn[256] = {};
  18652. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  18653. sizeof(cn));
  18654. if (cn_len > 0) {
  18655. std::string cn_str(cn, static_cast<size_t>(cn_len));
  18656. if (detail::match_hostname(cn_str, host_str)) { return true; }
  18657. }
  18658. }
  18659. return false;
  18660. }
  18661. inline uint64_t hostname_mismatch_code() {
  18662. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  18663. }
  18664. inline long get_verify_result(const_session_t session) {
  18665. if (!session) { return -1; }
  18666. auto wsession =
  18667. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18668. long result = wolfSSL_get_verify_result(wsession->ssl);
  18669. return result;
  18670. }
  18671. inline std::string get_cert_subject_cn(cert_t cert) {
  18672. if (!cert) return "";
  18673. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18674. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  18675. if (!subject) return "";
  18676. char cn[256] = {};
  18677. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  18678. sizeof(cn));
  18679. if (cn_len <= 0) return "";
  18680. return std::string(cn, static_cast<size_t>(cn_len));
  18681. }
  18682. inline std::string get_cert_issuer_name(cert_t cert) {
  18683. if (!cert) return "";
  18684. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18685. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  18686. if (!issuer) return "";
  18687. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  18688. if (!name_str) return "";
  18689. std::string result(name_str);
  18690. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  18691. return result;
  18692. }
  18693. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  18694. sans.clear();
  18695. if (!cert) return false;
  18696. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18697. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  18698. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18699. if (!san_names) return true; // No SANs is not an error
  18700. int count = wolfSSL_sk_num(san_names);
  18701. for (int i = 0; i < count; i++) {
  18702. auto *name =
  18703. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  18704. if (!name) continue;
  18705. SanEntry entry;
  18706. switch (name->type) {
  18707. case WOLFSSL_GEN_DNS: {
  18708. entry.type = SanType::DNS;
  18709. unsigned char *dns_name = nullptr;
  18710. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  18711. if (dns_name && dns_len > 0) {
  18712. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  18713. static_cast<size_t>(dns_len));
  18714. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  18715. }
  18716. break;
  18717. }
  18718. case WOLFSSL_GEN_IPADD: {
  18719. entry.type = SanType::IP;
  18720. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  18721. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  18722. if (ip_data && ip_len == 4) {
  18723. char buf[16];
  18724. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  18725. ip_data[2], ip_data[3]);
  18726. entry.value = buf;
  18727. } else if (ip_data && ip_len == 16) {
  18728. char buf[64];
  18729. snprintf(buf, sizeof(buf),
  18730. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  18731. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  18732. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  18733. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  18734. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  18735. ip_data[14], ip_data[15]);
  18736. entry.value = buf;
  18737. }
  18738. break;
  18739. }
  18740. case WOLFSSL_GEN_EMAIL:
  18741. entry.type = SanType::EMAIL;
  18742. {
  18743. unsigned char *email = nullptr;
  18744. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  18745. if (email && email_len > 0) {
  18746. entry.value = std::string(reinterpret_cast<char *>(email),
  18747. static_cast<size_t>(email_len));
  18748. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  18749. }
  18750. }
  18751. break;
  18752. case WOLFSSL_GEN_URI:
  18753. entry.type = SanType::URI;
  18754. {
  18755. unsigned char *uri = nullptr;
  18756. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  18757. &uri, name->d.uniformResourceIdentifier);
  18758. if (uri && uri_len > 0) {
  18759. entry.value = std::string(reinterpret_cast<char *>(uri),
  18760. static_cast<size_t>(uri_len));
  18761. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  18762. }
  18763. }
  18764. break;
  18765. default: entry.type = SanType::OTHER; break;
  18766. }
  18767. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  18768. }
  18769. wolfSSL_sk_free(san_names);
  18770. return true;
  18771. }
  18772. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  18773. time_t &not_after) {
  18774. if (!cert) return false;
  18775. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18776. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  18777. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  18778. if (!nb || !na) return false;
  18779. // wolfSSL_ASN1_TIME_to_tm is available
  18780. struct tm tm_nb = {}, tm_na = {};
  18781. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  18782. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  18783. #ifdef _WIN32
  18784. not_before = _mkgmtime(&tm_nb);
  18785. not_after = _mkgmtime(&tm_na);
  18786. #else
  18787. not_before = timegm(&tm_nb);
  18788. not_after = timegm(&tm_na);
  18789. #endif
  18790. return true;
  18791. }
  18792. inline std::string get_cert_serial(cert_t cert) {
  18793. if (!cert) return "";
  18794. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18795. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  18796. if (!serial_asn1) return "";
  18797. // Get the serial number data
  18798. int len = serial_asn1->length;
  18799. unsigned char *data = serial_asn1->data;
  18800. if (!data || len <= 0) return "";
  18801. std::string result;
  18802. result.reserve(static_cast<size_t>(len) * 2);
  18803. for (int i = 0; i < len; i++) {
  18804. char hex[3];
  18805. snprintf(hex, sizeof(hex), "%02X", data[i]);
  18806. result += hex;
  18807. }
  18808. return result;
  18809. }
  18810. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  18811. if (!cert) return false;
  18812. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18813. int der_len = 0;
  18814. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  18815. if (!der_data || der_len <= 0) return false;
  18816. der.assign(der_data, der_data + der_len);
  18817. return true;
  18818. }
  18819. inline const char *get_sni(const_session_t session) {
  18820. if (!session) return nullptr;
  18821. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  18822. // For server: return SNI received from client during handshake
  18823. if (!wsession->sni_hostname.empty()) {
  18824. return wsession->sni_hostname.c_str();
  18825. }
  18826. // For client: return the hostname set via set_sni
  18827. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  18828. return nullptr;
  18829. }
  18830. inline uint64_t peek_error() {
  18831. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18832. }
  18833. inline uint64_t get_error() {
  18834. uint64_t err = impl::wolfssl_last_error();
  18835. impl::wolfssl_last_error() = 0;
  18836. return err;
  18837. }
  18838. inline std::string error_string(uint64_t code) {
  18839. char buf[256];
  18840. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  18841. return std::string(buf);
  18842. }
  18843. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  18844. if (!pem || len == 0) { return nullptr; }
  18845. // Validate by attempting to load into a temporary ctx
  18846. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  18847. if (!tmp_ctx) { return nullptr; }
  18848. int ret = wolfSSL_CTX_load_verify_buffer(
  18849. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  18850. static_cast<long>(len), SSL_FILETYPE_PEM);
  18851. wolfSSL_CTX_free(tmp_ctx);
  18852. if (ret != SSL_SUCCESS) { return nullptr; }
  18853. return static_cast<ca_store_t>(
  18854. new impl::WolfSSLCAStore{std::string(pem, len)});
  18855. }
  18856. inline void free_ca_store(ca_store_t store) {
  18857. delete static_cast<impl::WolfSSLCAStore *>(store);
  18858. }
  18859. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  18860. if (!ctx || !store) { return false; }
  18861. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18862. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  18863. int ret = wolfSSL_CTX_load_verify_buffer(
  18864. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  18865. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  18866. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  18867. // This function takes ownership of the store; the PEM data was copied into
  18868. // the context, so release the source
  18869. free_ca_store(store);
  18870. return ret == SSL_SUCCESS;
  18871. }
  18872. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  18873. certs.clear();
  18874. if (!ctx) { return 0; }
  18875. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18876. if (wctx->ca_pem_data_.empty()) { return 0; }
  18877. const std::string &pem = wctx->ca_pem_data_;
  18878. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  18879. const std::string end_marker = "-----END CERTIFICATE-----";
  18880. size_t pos = 0;
  18881. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  18882. size_t end_pos = pem.find(end_marker, pos);
  18883. if (end_pos == std::string::npos) { break; }
  18884. end_pos += end_marker.size();
  18885. std::string cert_pem = pem.substr(pos, end_pos - pos);
  18886. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  18887. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  18888. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  18889. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  18890. pos = end_pos;
  18891. }
  18892. return certs.size();
  18893. }
  18894. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  18895. std::vector<std::string> names;
  18896. if (!ctx) { return names; }
  18897. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18898. if (wctx->ca_pem_data_.empty()) { return names; }
  18899. const std::string &pem = wctx->ca_pem_data_;
  18900. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  18901. const std::string end_marker = "-----END CERTIFICATE-----";
  18902. size_t pos = 0;
  18903. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  18904. size_t end_pos = pem.find(end_marker, pos);
  18905. if (end_pos == std::string::npos) { break; }
  18906. end_pos += end_marker.size();
  18907. std::string cert_pem = pem.substr(pos, end_pos - pos);
  18908. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  18909. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  18910. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  18911. if (x509) {
  18912. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  18913. if (subject) {
  18914. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  18915. if (name_str) {
  18916. names.push_back(name_str);
  18917. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  18918. }
  18919. }
  18920. wolfSSL_X509_free(x509);
  18921. }
  18922. pos = end_pos;
  18923. }
  18924. return names;
  18925. }
  18926. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  18927. const char *key_pem, const char *password) {
  18928. if (!ctx || !cert_pem || !key_pem) { return false; }
  18929. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18930. // Load new certificate
  18931. int ret = wolfSSL_CTX_use_certificate_buffer(
  18932. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  18933. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  18934. if (ret != SSL_SUCCESS) {
  18935. impl::wolfssl_last_error() =
  18936. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18937. return false;
  18938. }
  18939. // Set password if provided
  18940. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18941. // Load new private key
  18942. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  18943. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  18944. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  18945. if (ret != SSL_SUCCESS) {
  18946. impl::wolfssl_last_error() =
  18947. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18948. return false;
  18949. }
  18950. return true;
  18951. }
  18952. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  18953. if (!ctx || !ca_pem) { return false; }
  18954. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18955. int ret = wolfSSL_CTX_load_verify_buffer(
  18956. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  18957. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  18958. if (ret != SSL_SUCCESS) {
  18959. impl::wolfssl_last_error() =
  18960. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18961. return false;
  18962. }
  18963. return true;
  18964. }
  18965. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  18966. if (!ctx) { return false; }
  18967. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18968. impl::get_verify_callback() = std::move(callback);
  18969. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  18970. if (wctx->has_verify_callback) {
  18971. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  18972. impl::wolfssl_verify_callback);
  18973. } else {
  18974. wolfSSL_CTX_set_verify(
  18975. wctx->ctx,
  18976. wctx->verify_client
  18977. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  18978. : SSL_VERIFY_NONE,
  18979. nullptr);
  18980. }
  18981. return true;
  18982. }
  18983. inline long get_verify_error(const_session_t session) {
  18984. if (!session) { return -1; }
  18985. auto *wsession =
  18986. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18987. return wolfSSL_get_verify_result(wsession->ssl);
  18988. }
  18989. inline std::string verify_error_string(long error_code) {
  18990. if (error_code == 0) { return ""; }
  18991. const char *str =
  18992. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  18993. return str ? std::string(str) : std::string();
  18994. }
  18995. } // namespace tls
  18996. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  18997. // WebSocket implementation
  18998. namespace ws {
  18999. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  19000. bool fin) {
  19001. std::lock_guard<std::mutex> lock(write_mutex_);
  19002. if (closed_) { return false; }
  19003. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  19004. }
  19005. inline ReadResult WebSocket::read(std::string &msg) {
  19006. std::unique_lock<std::mutex> read_lock(read_mutex_);
  19007. while (!closed_) {
  19008. Opcode opcode;
  19009. std::string payload;
  19010. bool fin;
  19011. impl::FrameRead r =
  19012. impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  19013. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH);
  19014. // A timeout landed on a frame boundary: the connection is untouched and
  19015. // still usable, so hand control back without closing it. That is only
  19016. // useful to a caller who asked for the timeout; the compile-time default
  19017. // is a backstop against a peer gone quiet, and elapsing it closes the
  19018. // connection so a plain `while (ws.read(msg))` loop ends.
  19019. if (r == impl::FrameRead::Timeout && read_timeout_set_) { return Timeout; }
  19020. if (r != impl::FrameRead::Ok) {
  19021. closed_ = true;
  19022. return Fail;
  19023. }
  19024. switch (opcode) {
  19025. case Opcode::Ping: {
  19026. std::lock_guard<std::mutex> lock(write_mutex_);
  19027. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  19028. payload.size(), true, !is_server_);
  19029. continue;
  19030. }
  19031. case Opcode::Pong: {
  19032. std::lock_guard<std::mutex> lock(ping_mutex_);
  19033. unacked_pings_ = 0;
  19034. continue;
  19035. }
  19036. case Opcode::Close: {
  19037. if (!closed_.exchange(true)) {
  19038. // Echo close frame back
  19039. std::lock_guard<std::mutex> lock(write_mutex_);
  19040. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  19041. payload.size(), true, !is_server_);
  19042. }
  19043. return Fail;
  19044. }
  19045. case Opcode::Text:
  19046. case Opcode::Binary: {
  19047. auto result = opcode == Opcode::Text ? Text : Binary;
  19048. msg = std::move(payload);
  19049. // Handle fragmentation
  19050. if (!fin) {
  19051. while (true) {
  19052. Opcode cont_opcode;
  19053. std::string cont_payload;
  19054. bool cont_fin;
  19055. // A timeout is not reportable here: half of a fragmented message is
  19056. // already in `msg` and read() has no way to resume it, so it is a
  19057. // failure like any other. Timeouts are only ever seen on a message
  19058. // boundary.
  19059. if (impl::read_websocket_frame(
  19060. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  19061. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) !=
  19062. impl::FrameRead::Ok) {
  19063. closed_ = true;
  19064. return Fail;
  19065. }
  19066. if (cont_opcode == Opcode::Ping) {
  19067. std::lock_guard<std::mutex> lock(write_mutex_);
  19068. detail::write_websocket_frame(
  19069. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  19070. true, !is_server_);
  19071. continue;
  19072. }
  19073. if (cont_opcode == Opcode::Pong) {
  19074. std::lock_guard<std::mutex> lock(ping_mutex_);
  19075. unacked_pings_ = 0;
  19076. continue;
  19077. }
  19078. if (cont_opcode == Opcode::Close) {
  19079. if (!closed_.exchange(true)) {
  19080. std::lock_guard<std::mutex> lock(write_mutex_);
  19081. detail::write_websocket_frame(
  19082. strm_, Opcode::Close, cont_payload.data(),
  19083. cont_payload.size(), true, !is_server_);
  19084. }
  19085. return Fail;
  19086. }
  19087. // RFC 6455: continuation frames must use opcode 0x0
  19088. if (cont_opcode != Opcode::Continuation) {
  19089. closed_ = true;
  19090. return Fail;
  19091. }
  19092. msg += cont_payload;
  19093. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  19094. closed_ = true;
  19095. return Fail;
  19096. }
  19097. if (cont_fin) { break; }
  19098. }
  19099. }
  19100. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  19101. if (result == Text && !impl::is_valid_utf8(msg)) {
  19102. // close() takes the read lock to wait for the peer's Close reply, so
  19103. // it must not run while this thread still holds it.
  19104. read_lock.unlock();
  19105. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  19106. return Fail;
  19107. }
  19108. return result;
  19109. }
  19110. default: closed_ = true; return Fail;
  19111. }
  19112. }
  19113. return Fail;
  19114. }
  19115. inline bool WebSocket::send(const std::string &data) {
  19116. return send_frame(Opcode::Text, data.data(), data.size());
  19117. }
  19118. inline bool WebSocket::send(const char *data, size_t len) {
  19119. return send_frame(Opcode::Binary, data, len);
  19120. }
  19121. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  19122. if (closed_.exchange(true)) { return; }
  19123. ping_cv_.notify_all();
  19124. std::string payload;
  19125. auto code = static_cast<uint16_t>(status);
  19126. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  19127. payload.push_back(static_cast<char>(code & 0xFF));
  19128. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  19129. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  19130. payload += reason.substr(0, 123);
  19131. {
  19132. std::lock_guard<std::mutex> lock(write_mutex_);
  19133. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  19134. payload.size(), true, !is_server_);
  19135. }
  19136. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  19137. // Close response before closing the TCP connection.
  19138. //
  19139. // Wait only when no other thread is parsing frames. When one is, it is the
  19140. // thread positioned to see the peer's reply, and reading here would take
  19141. // bytes out of the message it is assembling. Bailing out also leaves the
  19142. // stream, including its read timeout, entirely to that thread.
  19143. std::unique_lock<std::mutex> read_lock(read_mutex_, std::try_to_lock);
  19144. if (!read_lock.owns_lock()) { return; }
  19145. // Use a short timeout to avoid hanging if the peer doesn't respond.
  19146. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  19147. Opcode op;
  19148. std::string resp;
  19149. bool fin;
  19150. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125) ==
  19151. impl::FrameRead::Ok) {
  19152. if (op == Opcode::Close) { break; }
  19153. }
  19154. }
  19155. inline WebSocket::~WebSocket() {
  19156. {
  19157. std::lock_guard<std::mutex> lock(ping_mutex_);
  19158. closed_ = true;
  19159. }
  19160. ping_cv_.notify_all();
  19161. if (ping_thread_.joinable()) { ping_thread_.join(); }
  19162. }
  19163. inline void WebSocket::start_heartbeat() {
  19164. if (ping_interval_sec_ == 0) { return; }
  19165. ping_thread_ = std::thread([this]() {
  19166. std::unique_lock<std::mutex> lock(ping_mutex_);
  19167. while (!closed_) {
  19168. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  19169. if (closed_) { break; }
  19170. // If the peer has failed to respond to the previous pings, give up.
  19171. // RFC 6455 does not define a pong-timeout mechanism; this is an
  19172. // opt-in liveness check controlled by max_missed_pongs_.
  19173. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  19174. lock.unlock();
  19175. close(CloseStatus::GoingAway, "pong timeout");
  19176. return;
  19177. }
  19178. lock.unlock();
  19179. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  19180. lock.lock();
  19181. closed_ = true;
  19182. break;
  19183. }
  19184. lock.lock();
  19185. unacked_pings_++;
  19186. }
  19187. });
  19188. }
  19189. inline const Request &WebSocket::request() const { return req_; }
  19190. inline bool WebSocket::is_open() const { return !closed_; }
  19191. inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
  19192. // 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
  19193. // poll(), where 0 would instead mean "return immediately", so hand it the
  19194. // negative poll uses for an unbounded wait.
  19195. if (sec == 0 && usec == 0) { sec = -1; }
  19196. strm_.set_read_timeout(sec, usec);
  19197. read_timeout_set_ = true;
  19198. }
  19199. // WebSocketClient implementation
  19200. inline WebSocketClient::WebSocketClient(
  19201. const std::string &scheme_host_port_path, const Headers &headers)
  19202. : headers_(headers) {
  19203. detail::UrlComponents uc;
  19204. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  19205. !uc.host.empty() && !uc.path.empty()) {
  19206. auto &scheme = uc.scheme;
  19207. #ifdef CPPHTTPLIB_SSL_ENABLED
  19208. if (scheme != "ws" && scheme != "wss") {
  19209. #else
  19210. if (scheme != "ws") {
  19211. #endif
  19212. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  19213. std::string msg = "'" + scheme + "' scheme is not supported.";
  19214. throw std::invalid_argument(msg);
  19215. #endif
  19216. return;
  19217. }
  19218. auto is_ssl = scheme == "wss";
  19219. host_ = std::move(uc.host);
  19220. port_ = is_ssl ? 443 : 80;
  19221. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  19222. path_ = std::move(uc.path);
  19223. if (!uc.query.empty()) { path_ += uc.query; }
  19224. #ifdef CPPHTTPLIB_SSL_ENABLED
  19225. is_ssl_ = is_ssl;
  19226. if (is_ssl_) {
  19227. // The context lives as long as the client so that CA configuration
  19228. // survives reconnects; sessions are created per connection.
  19229. tls_ctx_ = tls::create_client_context();
  19230. if (!tls_ctx_) { return; }
  19231. }
  19232. #else
  19233. if (is_ssl) { return; }
  19234. #endif
  19235. is_valid_ = true;
  19236. }
  19237. }
  19238. #ifdef CPPHTTPLIB_SSL_ENABLED
  19239. inline WebSocketClient::WebSocketClient(
  19240. const std::string &scheme_host_port_path, const PemMemory &pem,
  19241. const Headers &headers)
  19242. : WebSocketClient(scheme_host_port_path, headers) {
  19243. // For ws:// URLs the client certificate is silently ignored, consistent
  19244. // with the TLS-only setters such as set_ca_cert_path().
  19245. if (is_valid_ && is_ssl_ && pem.cert_pem && pem.key_pem) {
  19246. if (!tls::set_client_cert_pem(tls_ctx_, pem.cert_pem, pem.key_pem,
  19247. pem.private_key_password)) {
  19248. tls::free_context(tls_ctx_);
  19249. tls_ctx_ = nullptr;
  19250. is_valid_ = false;
  19251. }
  19252. }
  19253. }
  19254. #endif
  19255. inline WebSocketClient::~WebSocketClient() {
  19256. shutdown_and_close();
  19257. #ifdef CPPHTTPLIB_SSL_ENABLED
  19258. if (tls_ctx_) {
  19259. tls::free_context(tls_ctx_);
  19260. tls_ctx_ = nullptr;
  19261. }
  19262. #endif
  19263. }
  19264. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  19265. inline void WebSocketClient::shutdown_and_close() {
  19266. // Send the close frame while the TLS session is still alive: ws_ holds an
  19267. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  19268. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  19269. if (ws_ && ws_->is_open()) { ws_->close(); }
  19270. ws_.reset();
  19271. #ifdef CPPHTTPLIB_SSL_ENABLED
  19272. if (is_ssl_) {
  19273. if (tls_session_) {
  19274. tls::shutdown(tls_session_, true);
  19275. tls::free_session(tls_session_);
  19276. tls_session_ = nullptr;
  19277. }
  19278. }
  19279. #endif
  19280. if (sock_ != INVALID_SOCKET) {
  19281. detail::shutdown_socket(sock_);
  19282. detail::close_socket(sock_);
  19283. sock_ = INVALID_SOCKET;
  19284. }
  19285. }
  19286. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm,
  19287. Error &error, int &ssl_error,
  19288. uint64_t &ssl_backend_error) {
  19289. // A read timeout of 0 means "wait forever", the way SO_RCVTIMEO reads it.
  19290. // The streams wait with poll(), where 0 instead means "return immediately",
  19291. // so they are given the negative poll uses for an unbounded wait.
  19292. auto unbounded = read_timeout_sec_ == 0 && read_timeout_usec_ == 0;
  19293. time_t strm_read_sec = unbounded ? -1 : read_timeout_sec_;
  19294. time_t strm_read_usec = unbounded ? 0 : read_timeout_usec_;
  19295. // The handshake belongs to establishing the connection, so an unset read
  19296. // timeout leaves it bounded by the connection timeout instead of forever.
  19297. time_t hs_sec = unbounded ? connection_timeout_sec_ : read_timeout_sec_;
  19298. time_t hs_usec = unbounded ? connection_timeout_usec_ : read_timeout_usec_;
  19299. #ifdef CPPHTTPLIB_SSL_ENABLED
  19300. if (is_ssl_) {
  19301. // A plain flag rather than SSLClient::load_certs()'s call_once: connect()
  19302. // is not safe to call concurrently on one client to begin with, since
  19303. // nothing else here is guarded either.
  19304. if (server_certificate_verification_ && !certs_loaded_) {
  19305. uint64_t backend_error = 0;
  19306. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_,
  19307. ca_cert_dir_path_, custom_ca_loaded_,
  19308. system_ca_mode_, backend_error);
  19309. certs_loaded_ = true;
  19310. }
  19311. detail::ClientTlsSessionOptions options;
  19312. options.server_hostname_verification = server_hostname_verification_;
  19313. detail::ClientTlsSessionError tls_error;
  19314. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  19315. server_certificate_verification_,
  19316. hs_sec, hs_usec, &tls_error,
  19317. options)) {
  19318. error = tls_error.error;
  19319. ssl_error = tls_error.ssl_error;
  19320. ssl_backend_error = tls_error.backend_error;
  19321. return false;
  19322. }
  19323. strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  19324. sock_, tls_session_, strm_read_sec, strm_read_usec, write_timeout_sec_,
  19325. write_timeout_usec_));
  19326. return true;
  19327. }
  19328. #else
  19329. (void)error;
  19330. (void)ssl_error;
  19331. (void)ssl_backend_error;
  19332. (void)hs_sec;
  19333. (void)hs_usec;
  19334. #endif
  19335. strm = std::unique_ptr<Stream>(
  19336. new detail::SocketStream(sock_, strm_read_sec, strm_read_usec,
  19337. write_timeout_sec_, write_timeout_usec_));
  19338. return true;
  19339. }
  19340. inline void WebSocketClient::prepare_default_headers(Request &req) {
  19341. #ifdef CPPHTTPLIB_SSL_ENABLED
  19342. auto is_ssl = is_ssl_;
  19343. #else
  19344. auto is_ssl = false;
  19345. #endif
  19346. if (!req.has_header("Host")) {
  19347. req.headers.emplace("Host", detail::make_default_host_header_value(
  19348. host_, port_, is_ssl, address_family_));
  19349. }
  19350. detail::add_default_user_agent_header(req);
  19351. }
  19352. inline Result WebSocketClient::connect() {
  19353. if (!is_valid_) { return Result{Error::Connection, -1, Headers{}}; }
  19354. shutdown_and_close();
  19355. // Check is custom IP or hostname specified for host_
  19356. std::string connect_host;
  19357. std::string ip;
  19358. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  19359. auto error = Error::Success;
  19360. sock_ = detail::create_client_socket(
  19361. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  19362. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  19363. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  19364. write_timeout_usec_, interface_, error);
  19365. if (sock_ == INVALID_SOCKET) {
  19366. if (error == Error::Success) { error = Error::Connection; }
  19367. return Result{error, -1, Headers{}};
  19368. }
  19369. std::unique_ptr<Stream> strm;
  19370. auto stream_error = Error::SSLConnection;
  19371. int ssl_error = 0;
  19372. uint64_t ssl_backend_error = 0;
  19373. if (!create_stream(strm, stream_error, ssl_error, ssl_backend_error)) {
  19374. shutdown_and_close();
  19375. #ifdef CPPHTTPLIB_SSL_ENABLED
  19376. return Result{stream_error, -1, Headers{}, ssl_error, ssl_backend_error};
  19377. #else
  19378. return Result{stream_error, -1, Headers{}};
  19379. #endif
  19380. }
  19381. Request req;
  19382. req.method = "GET";
  19383. req.path = path_;
  19384. req.headers = headers_;
  19385. prepare_default_headers(req);
  19386. detail::WebSocketUpgradeResponse upgrade;
  19387. if (!detail::perform_websocket_handshake(*strm, req, upgrade)) {
  19388. shutdown_and_close();
  19389. return Result{upgrade.error, upgrade.status, std::move(upgrade.headers)};
  19390. }
  19391. subprotocol_ = std::move(upgrade.selected_subprotocol);
  19392. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  19393. websocket_ping_interval_sec_,
  19394. websocket_max_missed_pongs_));
  19395. // The stream was created with the timeout already; tell the WebSocket
  19396. // whether it came from the caller, so read() knows to report it as Timeout.
  19397. ws_->read_timeout_set_ = read_timeout_set_;
  19398. return Result{Error::Success, upgrade.status, std::move(upgrade.headers)};
  19399. }
  19400. inline ReadResult WebSocketClient::read(std::string &msg) {
  19401. if (!ws_) { return Fail; }
  19402. return ws_->read(msg);
  19403. }
  19404. inline bool WebSocketClient::send(const std::string &data) {
  19405. if (!ws_) { return false; }
  19406. return ws_->send(data);
  19407. }
  19408. inline bool WebSocketClient::send(const char *data, size_t len) {
  19409. if (!ws_) { return false; }
  19410. return ws_->send(data, len);
  19411. }
  19412. inline void WebSocketClient::close(CloseStatus status,
  19413. const std::string &reason) {
  19414. if (ws_) { ws_->close(status, reason); }
  19415. }
  19416. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  19417. inline const std::string &WebSocketClient::subprotocol() const {
  19418. return subprotocol_;
  19419. }
  19420. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  19421. read_timeout_sec_ = sec;
  19422. read_timeout_usec_ = usec;
  19423. read_timeout_set_ = true;
  19424. // The members above only seed the next connect(); read() consults the
  19425. // stream, so an already-open connection has to be told directly.
  19426. if (ws_) { ws_->set_read_timeout(sec, usec); }
  19427. }
  19428. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  19429. write_timeout_sec_ = sec;
  19430. write_timeout_usec_ = usec;
  19431. }
  19432. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  19433. websocket_ping_interval_sec_ = sec;
  19434. }
  19435. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  19436. websocket_max_missed_pongs_ = count;
  19437. }
  19438. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  19439. inline void WebSocketClient::set_address_family(int family) {
  19440. address_family_ = family;
  19441. }
  19442. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  19443. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  19444. socket_options_ = std::move(socket_options);
  19445. }
  19446. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  19447. connection_timeout_sec_ = sec;
  19448. connection_timeout_usec_ = usec;
  19449. }
  19450. inline void WebSocketClient::set_interface(const std::string &intf) {
  19451. interface_ = intf;
  19452. }
  19453. inline void WebSocketClient::set_hostname_addr_map(
  19454. std::map<std::string, std::string> addr_map) {
  19455. addr_map_ = std::move(addr_map);
  19456. }
  19457. #ifdef CPPHTTPLIB_SSL_ENABLED
  19458. inline void
  19459. WebSocketClient::set_ca_cert_path(const std::string &ca_cert_file_path,
  19460. const std::string &ca_cert_dir_path) {
  19461. ca_cert_file_path_ = ca_cert_file_path;
  19462. ca_cert_dir_path_ = ca_cert_dir_path;
  19463. }
  19464. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  19465. if (store && tls_ctx_) {
  19466. // set_ca_store takes ownership of store
  19467. tls::set_ca_store(tls_ctx_, store);
  19468. custom_ca_loaded_ = true;
  19469. } else if (store) {
  19470. tls::free_ca_store(store);
  19471. }
  19472. }
  19473. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  19474. std::size_t size) {
  19475. if (tls_ctx_ && ca_cert && size > 0) {
  19476. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  19477. custom_ca_loaded_ = true;
  19478. }
  19479. }
  19480. inline void
  19481. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  19482. server_certificate_verification_ = enabled;
  19483. }
  19484. inline void WebSocketClient::enable_server_hostname_verification(bool enabled) {
  19485. server_hostname_verification_ = enabled;
  19486. }
  19487. inline void WebSocketClient::enable_system_ca(bool enabled) {
  19488. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  19489. }
  19490. #endif // CPPHTTPLIB_SSL_ENABLED
  19491. } // namespace ws
  19492. // ----------------------------------------------------------------------------
  19493. } // namespace httplib
  19494. #endif // CPPHTTPLIB_HTTPLIB_H