httplib.h 784 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034
  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.58.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003a00"
  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. // Resolves a relative-path or query-only Location value against the path of
  790. // the request being redirected (RFC 3986 section 5.2). Absolute URIs and
  791. // references starting with '/' are returned unchanged.
  792. inline std::string resolve_relative_location(const std::string &location,
  793. const std::string &base) {
  794. if (location.empty() || location[0] == '/') { return location; }
  795. // A ':' in the first segment means the value has a scheme.
  796. if (location.find(':') < location.find_first_of("/?#")) { return location; }
  797. if (location[0] == '#') { return base.substr(0, base.find('#')) + location; }
  798. auto base_path = base.substr(0, base.find_first_of("?#"));
  799. if (location[0] == '?') { return base_path + location; }
  800. if (base_path.empty() || base_path[0] != '/') { base_path = "/"; }
  801. auto merged = base_path.substr(0, base_path.rfind('/') + 1) + location;
  802. // Remove "." and ".." segments from the merged path.
  803. auto path_end = (std::min)(merged.find_first_of("?#"), merged.size());
  804. std::string path;
  805. size_t i = 0;
  806. while (i < path_end) {
  807. auto next = (std::min)(merged.find('/', i + 1), path_end);
  808. auto segment = merged.substr(i + 1, next - i - 1);
  809. auto is_last = next == path_end;
  810. if (segment == "." || segment == "..") {
  811. if (segment == "..") {
  812. path.erase((std::min)(path.rfind('/'), path.size()));
  813. }
  814. if (is_last) { path += '/'; }
  815. } else {
  816. path += '/';
  817. path += segment;
  818. }
  819. i = next;
  820. }
  821. if (path.empty()) { path = "/"; }
  822. return path + merged.substr(path_end);
  823. }
  824. } // namespace detail
  825. enum class SSLVerifierResponse {
  826. // no decision has been made, use the built-in certificate verifier
  827. NoDecisionMade,
  828. // connection certificate is verified and accepted
  829. CertificateAccepted,
  830. // connection certificate was processed but is rejected
  831. CertificateRejected
  832. };
  833. // System CA loading policy for SSL clients. Auto (the default) loads system
  834. // CA certs only when no custom CA is configured; enable_system_ca() switches
  835. // to an explicit policy.
  836. enum class SystemCAMode { Auto, Enabled, Disabled };
  837. enum StatusCode {
  838. // Information responses
  839. Continue_100 = 100,
  840. SwitchingProtocol_101 = 101,
  841. Processing_102 = 102,
  842. EarlyHints_103 = 103,
  843. // Successful responses
  844. OK_200 = 200,
  845. Created_201 = 201,
  846. Accepted_202 = 202,
  847. NonAuthoritativeInformation_203 = 203,
  848. NoContent_204 = 204,
  849. ResetContent_205 = 205,
  850. PartialContent_206 = 206,
  851. MultiStatus_207 = 207,
  852. AlreadyReported_208 = 208,
  853. IMUsed_226 = 226,
  854. // Redirection messages
  855. MultipleChoices_300 = 300,
  856. MovedPermanently_301 = 301,
  857. Found_302 = 302,
  858. SeeOther_303 = 303,
  859. NotModified_304 = 304,
  860. UseProxy_305 = 305,
  861. unused_306 = 306,
  862. TemporaryRedirect_307 = 307,
  863. PermanentRedirect_308 = 308,
  864. // Client error responses
  865. BadRequest_400 = 400,
  866. Unauthorized_401 = 401,
  867. PaymentRequired_402 = 402,
  868. Forbidden_403 = 403,
  869. NotFound_404 = 404,
  870. MethodNotAllowed_405 = 405,
  871. NotAcceptable_406 = 406,
  872. ProxyAuthenticationRequired_407 = 407,
  873. RequestTimeout_408 = 408,
  874. Conflict_409 = 409,
  875. Gone_410 = 410,
  876. LengthRequired_411 = 411,
  877. PreconditionFailed_412 = 412,
  878. PayloadTooLarge_413 = 413,
  879. UriTooLong_414 = 414,
  880. UnsupportedMediaType_415 = 415,
  881. RangeNotSatisfiable_416 = 416,
  882. ExpectationFailed_417 = 417,
  883. ImATeapot_418 = 418,
  884. MisdirectedRequest_421 = 421,
  885. UnprocessableContent_422 = 422,
  886. Locked_423 = 423,
  887. FailedDependency_424 = 424,
  888. TooEarly_425 = 425,
  889. UpgradeRequired_426 = 426,
  890. PreconditionRequired_428 = 428,
  891. TooManyRequests_429 = 429,
  892. RequestHeaderFieldsTooLarge_431 = 431,
  893. UnavailableForLegalReasons_451 = 451,
  894. // Server error responses
  895. InternalServerError_500 = 500,
  896. NotImplemented_501 = 501,
  897. BadGateway_502 = 502,
  898. ServiceUnavailable_503 = 503,
  899. GatewayTimeout_504 = 504,
  900. HttpVersionNotSupported_505 = 505,
  901. VariantAlsoNegotiates_506 = 506,
  902. InsufficientStorage_507 = 507,
  903. LoopDetected_508 = 508,
  904. NotExtended_510 = 510,
  905. NetworkAuthenticationRequired_511 = 511,
  906. };
  907. namespace detail {
  908. // A multimap that keeps its entries in the order they were inserted.
  909. //
  910. // HTTP needs that order in two places. RFC 9110 5.3 makes the order of header
  911. // fields sharing a field name significant and forbids a proxy from reordering
  912. // them, and a query string's parameters are meaningful in the order the caller
  913. // wrote them. Neither standard container expresses it: std::unordered_multimap
  914. // gives no ordering guarantee at all for equivalent keys (libstdc++ yields
  915. // reverse insertion order, libc++ insertion order), and std::multimap sorts by
  916. // key, which would drop control data such as Host behind whatever else the
  917. // message carries and alphabetise a query string.
  918. //
  919. // Entries are therefore kept in a flat vector, in order. Lookup is a linear
  920. // scan, which beats hashing for the handful of entries a message carries
  921. // (headers are capped at CPPHTTPLIB_HEADER_MAX_COUNT).
  922. //
  923. // KeyEqual compares keys; it is what makes Headers case-insensitive and
  924. // Params, whose parameter names are case-sensitive, not.
  925. template <typename Mapped, typename KeyEqual> class insertion_ordered_multimap {
  926. public:
  927. using key_type = std::string;
  928. using mapped_type = Mapped;
  929. using value_type = std::pair<std::string, Mapped>;
  930. using size_type = std::size_t;
  931. using difference_type = std::ptrdiff_t;
  932. using reference = value_type &;
  933. using const_reference = const value_type &;
  934. private:
  935. static size_type npos() { return static_cast<size_type>(-1); }
  936. static bool keys_equal(const std::string &a, const std::string &b) {
  937. return KeyEqual()(a, b);
  938. }
  939. // Iterating yields every entry in insertion order, but equal_range() and
  940. // find() have to walk only the entries sharing one key, which are not
  941. // adjacent. Both are the same iterator type: key_idx_ selects between the
  942. // two traversals, and since equality compares only the position, an iterator
  943. // restricted to one key still compares equal to end().
  944. template <typename V> class iterator_t {
  945. public:
  946. using iterator_category = std::bidirectional_iterator_tag;
  947. using value_type = insertion_ordered_multimap::value_type;
  948. using difference_type = insertion_ordered_multimap::difference_type;
  949. using pointer = V *;
  950. using reference = V &;
  951. iterator_t() : data_(nullptr), idx_(0), size_(0), key_idx_(npos()) {}
  952. template <typename U,
  953. typename std::enable_if<std::is_convertible<U *, V *>::value,
  954. int>::type = 0>
  955. iterator_t(const iterator_t<U> &rhs)
  956. : data_(rhs.data_), idx_(rhs.idx_), size_(rhs.size_),
  957. key_idx_(rhs.key_idx_) {}
  958. reference operator*() const { return data_[idx_]; }
  959. pointer operator->() const { return data_ + idx_; }
  960. iterator_t &operator++() {
  961. // Saturating, so that advancing past the last entry of a key (which
  962. // get_multimap_value() does when asked for an out-of-range id) stays at
  963. // end() instead of running off the container.
  964. if (idx_ >= size_) { return *this; }
  965. ++idx_;
  966. if (key_idx_ != npos()) {
  967. while (idx_ < size_ && !matches(idx_)) {
  968. ++idx_;
  969. }
  970. }
  971. return *this;
  972. }
  973. iterator_t operator++(int) {
  974. auto tmp = *this;
  975. ++*this;
  976. return tmp;
  977. }
  978. iterator_t &operator--() {
  979. if (idx_ == 0) { return *this; }
  980. --idx_;
  981. if (key_idx_ != npos()) {
  982. while (idx_ > 0 && !matches(idx_)) {
  983. --idx_;
  984. }
  985. }
  986. return *this;
  987. }
  988. iterator_t operator--(int) {
  989. auto tmp = *this;
  990. --*this;
  991. return tmp;
  992. }
  993. template <typename U> bool operator==(const iterator_t<U> &rhs) const {
  994. return idx_ == rhs.idx_;
  995. }
  996. template <typename U> bool operator!=(const iterator_t<U> &rhs) const {
  997. return idx_ != rhs.idx_;
  998. }
  999. private:
  1000. friend class insertion_ordered_multimap;
  1001. template <typename> friend class iterator_t;
  1002. iterator_t(V *data, size_type idx, size_type size, size_type key_idx)
  1003. : data_(data), idx_(idx), size_(size), key_idx_(key_idx) {}
  1004. bool matches(size_type i) const {
  1005. return keys_equal(data_[i].first, data_[key_idx_].first);
  1006. }
  1007. V *data_;
  1008. size_type idx_;
  1009. size_type size_;
  1010. size_type key_idx_;
  1011. };
  1012. public:
  1013. using iterator = iterator_t<value_type>;
  1014. using const_iterator = iterator_t<const value_type>;
  1015. insertion_ordered_multimap() = default;
  1016. insertion_ordered_multimap(std::initializer_list<value_type> il)
  1017. : entries_(il) {}
  1018. template <typename InputIt>
  1019. insertion_ordered_multimap(InputIt first, InputIt last)
  1020. : entries_(first, last) {}
  1021. iterator begin() { return make_iter(0, npos()); }
  1022. iterator end() { return make_iter(entries_.size(), npos()); }
  1023. const_iterator begin() const { return make_citer(0, npos()); }
  1024. const_iterator end() const { return make_citer(entries_.size(), npos()); }
  1025. const_iterator cbegin() const { return begin(); }
  1026. const_iterator cend() const { return end(); }
  1027. bool empty() const { return entries_.empty(); }
  1028. size_type size() const { return entries_.size(); }
  1029. void clear() { entries_.clear(); }
  1030. void swap(insertion_ordered_multimap &rhs) { entries_.swap(rhs.entries_); }
  1031. iterator insert(const value_type &val) {
  1032. entries_.push_back(val);
  1033. return make_iter(entries_.size() - 1, npos());
  1034. }
  1035. iterator insert(value_type &&val) {
  1036. entries_.push_back(std::move(val));
  1037. return make_iter(entries_.size() - 1, npos());
  1038. }
  1039. template <typename... Args> iterator emplace(Args &&...args) {
  1040. entries_.emplace_back(std::forward<Args>(args)...);
  1041. return make_iter(entries_.size() - 1, npos());
  1042. }
  1043. // For entries that have to lead the message, such as the Host header field
  1044. // (RFC 9110 5.3 recommends sending control data first).
  1045. template <typename... Args> iterator emplace_front(Args &&...args) {
  1046. entries_.emplace(entries_.begin(), std::forward<Args>(args)...);
  1047. return make_iter(0, npos());
  1048. }
  1049. iterator find(const std::string &key) {
  1050. auto i = index_of(key);
  1051. return i == npos() ? end() : make_iter(i, i);
  1052. }
  1053. const_iterator find(const std::string &key) const {
  1054. auto i = index_of(key);
  1055. return i == npos() ? end() : make_citer(i, i);
  1056. }
  1057. size_type count(const std::string &key) const {
  1058. size_type n = 0;
  1059. for (const auto &entry : entries_) {
  1060. if (keys_equal(entry.first, key)) { n++; }
  1061. }
  1062. return n;
  1063. }
  1064. std::pair<iterator, iterator> equal_range(const std::string &key) {
  1065. auto i = index_of(key);
  1066. return i == npos() ? std::make_pair(end(), end())
  1067. : std::make_pair(make_iter(i, i), end());
  1068. }
  1069. std::pair<const_iterator, const_iterator>
  1070. equal_range(const std::string &key) const {
  1071. auto i = index_of(key);
  1072. return i == npos() ? std::make_pair(end(), end())
  1073. : std::make_pair(make_citer(i, i), end());
  1074. }
  1075. size_type erase(const std::string &key) {
  1076. auto before = entries_.size();
  1077. entries_.erase(std::remove_if(entries_.begin(), entries_.end(),
  1078. [&](const value_type &entry) {
  1079. return keys_equal(entry.first, key);
  1080. }),
  1081. entries_.end());
  1082. return before - entries_.size();
  1083. }
  1084. iterator erase(const_iterator pos) {
  1085. entries_.erase(entries_.begin() + static_cast<difference_type>(pos.idx_));
  1086. return make_iter(pos.idx_, npos());
  1087. }
  1088. // Erases what iterating [first, last) would actually visit, so erasing an
  1089. // equal_range() removes only the entries with that key, not everything
  1090. // positioned between them.
  1091. iterator erase(const_iterator first, const_iterator last) {
  1092. auto from = first.idx_;
  1093. auto to = last.idx_;
  1094. if (from >= to) { return make_iter(from, npos()); }
  1095. auto begin_it = entries_.begin();
  1096. auto from_it = begin_it + static_cast<difference_type>(from);
  1097. auto to_it = begin_it + static_cast<difference_type>(to);
  1098. if (first.key_idx_ == npos()) {
  1099. entries_.erase(from_it, to_it);
  1100. } else {
  1101. auto key = entries_[first.key_idx_].first;
  1102. auto keep = from_it;
  1103. for (auto it = from_it; it != to_it; ++it) {
  1104. if (!keys_equal(it->first, key)) {
  1105. if (keep != it) { *keep = std::move(*it); }
  1106. ++keep;
  1107. }
  1108. }
  1109. if (keep != to_it) {
  1110. keep = std::move(to_it, entries_.end(), keep);
  1111. } else {
  1112. keep = entries_.end();
  1113. }
  1114. entries_.erase(keep, entries_.end());
  1115. }
  1116. return make_iter(from, npos());
  1117. }
  1118. friend bool operator==(const insertion_ordered_multimap &lhs,
  1119. const insertion_ordered_multimap &rhs) {
  1120. return lhs.entries_ == rhs.entries_;
  1121. }
  1122. friend bool operator!=(const insertion_ordered_multimap &lhs,
  1123. const insertion_ordered_multimap &rhs) {
  1124. return !(lhs == rhs);
  1125. }
  1126. private:
  1127. size_type index_of(const std::string &key) const {
  1128. for (size_type i = 0; i < entries_.size(); i++) {
  1129. if (keys_equal(entries_[i].first, key)) { return i; }
  1130. }
  1131. return npos();
  1132. }
  1133. iterator make_iter(size_type idx, size_type key_idx) {
  1134. return iterator(entries_.data(), idx, entries_.size(), key_idx);
  1135. }
  1136. const_iterator make_citer(size_type idx, size_type key_idx) const {
  1137. return const_iterator(entries_.data(), idx, entries_.size(), key_idx);
  1138. }
  1139. std::vector<value_type> entries_;
  1140. };
  1141. } // namespace detail
  1142. using Headers =
  1143. detail::insertion_ordered_multimap<std::string,
  1144. detail::case_ignore::equal_to>;
  1145. // Query parameter names are case-sensitive, unlike header field names.
  1146. using Params =
  1147. detail::insertion_ordered_multimap<std::string, std::equal_to<std::string>>;
  1148. using Match = std::smatch;
  1149. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  1150. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  1151. /*
  1152. * detail: type-erased storage used by UserData.
  1153. * ABI-stable regardless of C++ standard — always uses this custom
  1154. * implementation instead of std::any.
  1155. */
  1156. namespace detail {
  1157. using any_type_id = const void *;
  1158. template <typename T> any_type_id any_typeid() noexcept {
  1159. static const char id = 0;
  1160. return &id;
  1161. }
  1162. struct any_storage {
  1163. virtual ~any_storage() = default;
  1164. virtual std::unique_ptr<any_storage> clone() const = 0;
  1165. virtual any_type_id type_id() const noexcept = 0;
  1166. };
  1167. template <typename T> struct any_value final : any_storage {
  1168. T value;
  1169. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  1170. std::unique_ptr<any_storage> clone() const override {
  1171. return std::unique_ptr<any_storage>(new any_value<T>(value));
  1172. }
  1173. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  1174. };
  1175. } // namespace detail
  1176. class UserData {
  1177. public:
  1178. UserData() = default;
  1179. UserData(UserData &&) noexcept = default;
  1180. UserData &operator=(UserData &&) noexcept = default;
  1181. UserData(const UserData &o) {
  1182. for (const auto &e : o.entries_) {
  1183. if (e.second) { entries_[e.first] = e.second->clone(); }
  1184. }
  1185. }
  1186. UserData &operator=(const UserData &o) {
  1187. if (this != &o) {
  1188. entries_.clear();
  1189. for (const auto &e : o.entries_) {
  1190. if (e.second) { entries_[e.first] = e.second->clone(); }
  1191. }
  1192. }
  1193. return *this;
  1194. }
  1195. template <typename T> void set(const std::string &key, T &&value) {
  1196. using D = typename std::decay<T>::type;
  1197. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  1198. }
  1199. template <typename T> T *get(const std::string &key) noexcept {
  1200. auto it = entries_.find(key);
  1201. if (it == entries_.end() || !it->second) { return nullptr; }
  1202. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1203. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  1204. }
  1205. template <typename T> const T *get(const std::string &key) const noexcept {
  1206. auto it = entries_.find(key);
  1207. if (it == entries_.end() || !it->second) { return nullptr; }
  1208. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  1209. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  1210. }
  1211. bool has(const std::string &key) const noexcept {
  1212. return entries_.find(key) != entries_.end();
  1213. }
  1214. void erase(const std::string &key) { entries_.erase(key); }
  1215. void clear() noexcept { entries_.clear(); }
  1216. private:
  1217. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  1218. entries_;
  1219. };
  1220. struct Response;
  1221. using ResponseHandler = std::function<bool(const Response &response)>;
  1222. struct FormData {
  1223. std::string name;
  1224. std::string content;
  1225. std::string filename;
  1226. std::string content_type;
  1227. Headers headers;
  1228. };
  1229. struct FormField {
  1230. std::string name;
  1231. std::string content;
  1232. Headers headers;
  1233. };
  1234. // RFC 7578 5.2: a form processor "SHOULD send back results in order" and
  1235. // "Intermediaries MUST NOT reorder the results", so a handler walking these
  1236. // should see the parts as they were sent. A std::multimap sorts by field name
  1237. // and loses that. Field names are case-sensitive, hence std::equal_to rather
  1238. // than the case-insensitive predicate Headers uses.
  1239. using FormFields =
  1240. detail::insertion_ordered_multimap<FormField, std::equal_to<std::string>>;
  1241. using FormFiles =
  1242. detail::insertion_ordered_multimap<FormData, std::equal_to<std::string>>;
  1243. struct MultipartFormData {
  1244. FormFields fields; // Text fields from multipart
  1245. FormFiles files; // Files from multipart
  1246. // Text field access
  1247. std::string get_field(const std::string &key, size_t id = 0) const;
  1248. std::vector<std::string> get_fields(const std::string &key) const;
  1249. bool has_field(const std::string &key) const;
  1250. size_t get_field_count(const std::string &key) const;
  1251. // File access
  1252. FormData get_file(const std::string &key, size_t id = 0) const;
  1253. std::vector<FormData> get_files(const std::string &key) const;
  1254. bool has_file(const std::string &key) const;
  1255. size_t get_file_count(const std::string &key) const;
  1256. };
  1257. struct UploadFormData {
  1258. std::string name;
  1259. std::string content;
  1260. std::string filename;
  1261. std::string content_type;
  1262. };
  1263. using UploadFormDataItems = std::vector<UploadFormData>;
  1264. class DataSink {
  1265. public:
  1266. DataSink() : os(&sb_), sb_(*this) {}
  1267. DataSink(const DataSink &) = delete;
  1268. DataSink &operator=(const DataSink &) = delete;
  1269. DataSink(DataSink &&) = delete;
  1270. DataSink &operator=(DataSink &&) = delete;
  1271. std::function<bool(const char *data, size_t data_len)> write;
  1272. // Only `write` is mandatory. The rest are defaulted so that a provider
  1273. // calling one on a writer that does not set it gets sensible behaviour
  1274. // rather than std::bad_function_call thrown from a worker thread. Capturing
  1275. // `this` is safe: DataSink is neither copyable nor movable.
  1276. std::function<bool()> is_writable = []() { return true; };
  1277. std::function<void()> done = []() {};
  1278. std::function<void(const Headers &trailer)> done_with_trailer =
  1279. [this](const Headers & /*trailer*/) { done(); };
  1280. std::ostream os;
  1281. private:
  1282. class data_sink_streambuf final : public std::streambuf {
  1283. public:
  1284. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  1285. protected:
  1286. std::streamsize xsputn(const char *s, std::streamsize n) override {
  1287. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  1288. return 0;
  1289. }
  1290. private:
  1291. DataSink &sink_;
  1292. };
  1293. data_sink_streambuf sb_;
  1294. };
  1295. using ContentProvider =
  1296. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  1297. using ContentProviderWithoutLength =
  1298. std::function<bool(size_t offset, DataSink &sink)>;
  1299. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  1300. struct FormDataProvider {
  1301. std::string name;
  1302. ContentProviderWithoutLength provider;
  1303. std::string filename;
  1304. std::string content_type;
  1305. };
  1306. using FormDataProviderItems = std::vector<FormDataProvider>;
  1307. inline FormDataProvider
  1308. make_file_provider(const std::string &name, const std::string &filepath,
  1309. const std::string &filename = std::string(),
  1310. const std::string &content_type = std::string()) {
  1311. FormDataProvider fdp;
  1312. fdp.name = name;
  1313. fdp.filename = filename.empty() ? filepath : filename;
  1314. fdp.content_type = content_type;
  1315. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  1316. std::ifstream f(filepath, std::ios::binary);
  1317. if (!f) { return false; }
  1318. if (offset > 0) {
  1319. f.seekg(static_cast<std::streamoff>(offset));
  1320. if (!f.good()) {
  1321. sink.done();
  1322. return true;
  1323. }
  1324. }
  1325. char buf[8192];
  1326. f.read(buf, sizeof(buf));
  1327. auto n = static_cast<size_t>(f.gcount());
  1328. if (n > 0) { return sink.write(buf, n); }
  1329. sink.done(); // EOF
  1330. return true;
  1331. };
  1332. return fdp;
  1333. }
  1334. inline std::pair<size_t, ContentProvider>
  1335. make_file_body(const std::string &filepath) {
  1336. size_t size = 0;
  1337. {
  1338. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  1339. if (!f) { return {0, ContentProvider{}}; }
  1340. size = static_cast<size_t>(f.tellg());
  1341. }
  1342. ContentProvider provider = [filepath](size_t offset, size_t length,
  1343. DataSink &sink) -> bool {
  1344. std::ifstream f(filepath, std::ios::binary);
  1345. if (!f) { return false; }
  1346. f.seekg(static_cast<std::streamoff>(offset));
  1347. if (!f.good()) { return false; }
  1348. char buf[8192];
  1349. while (length > 0) {
  1350. auto to_read = (std::min)(sizeof(buf), length);
  1351. f.read(buf, static_cast<std::streamsize>(to_read));
  1352. auto n = static_cast<size_t>(f.gcount());
  1353. // The file is shorter than the size make_file_body() measured, which the
  1354. // caller has already committed to as Content-Length. The body cannot be
  1355. // completed, so fail as every other error here does.
  1356. if (n == 0) { return false; }
  1357. if (!sink.write(buf, n)) { return false; }
  1358. length -= n;
  1359. }
  1360. return true;
  1361. };
  1362. return {size, std::move(provider)};
  1363. }
  1364. using ContentReceiverWithProgress = std::function<bool(
  1365. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1366. using ContentReceiver =
  1367. std::function<bool(const char *data, size_t data_length)>;
  1368. using FormDataHeader = std::function<bool(const FormData &file)>;
  1369. class ContentReader {
  1370. public:
  1371. using Reader = std::function<bool(ContentReceiver receiver)>;
  1372. using FormDataReader =
  1373. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1374. ContentReader(Reader reader, FormDataReader multipart_reader)
  1375. : reader_(std::move(reader)),
  1376. formdata_reader_(std::move(multipart_reader)) {}
  1377. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1378. return formdata_reader_(std::move(header), std::move(receiver));
  1379. }
  1380. bool operator()(ContentReceiver receiver) const {
  1381. return reader_(std::move(receiver));
  1382. }
  1383. Reader reader_;
  1384. FormDataReader formdata_reader_;
  1385. };
  1386. using Range = std::pair<ssize_t, ssize_t>;
  1387. using Ranges = std::vector<Range>;
  1388. #ifdef CPPHTTPLIB_SSL_ENABLED
  1389. // TLS abstraction layer - public type definitions and API
  1390. namespace tls {
  1391. // Opaque handles (defined as void* for abstraction)
  1392. using ctx_t = void *;
  1393. using session_t = void *;
  1394. using const_session_t = const void *; // For read-only session access
  1395. using cert_t = void *;
  1396. using ca_store_t = void *;
  1397. // TLS versions
  1398. enum class Version {
  1399. TLS1_2 = 0x0303,
  1400. TLS1_3 = 0x0304,
  1401. };
  1402. // Subject Alternative Names (SAN) entry types
  1403. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1404. // SAN entry structure
  1405. struct SanEntry {
  1406. SanType type;
  1407. std::string value;
  1408. };
  1409. // Verification context for certificate verification callback
  1410. struct VerifyContext {
  1411. session_t session; // TLS session handle
  1412. cert_t cert; // Current certificate being verified
  1413. int depth; // Certificate chain depth (0 = leaf)
  1414. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1415. long error_code; // Backend-specific error code (0 = no error)
  1416. const char *error_string; // Human-readable error description
  1417. // Certificate introspection methods
  1418. std::string subject_cn() const;
  1419. std::string issuer_name() const;
  1420. bool check_hostname(const char *hostname) const;
  1421. std::vector<SanEntry> sans() const;
  1422. bool validity(time_t &not_before, time_t &not_after) const;
  1423. std::string serial() const;
  1424. };
  1425. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1426. // TlsError codes for TLS operations (backend-independent)
  1427. enum class ErrorCode : int {
  1428. Success = 0,
  1429. WantRead, // Non-blocking: need to wait for read
  1430. WantWrite, // Non-blocking: need to wait for write
  1431. PeerClosed, // Peer closed the connection
  1432. Fatal, // Unrecoverable error
  1433. SyscallError, // System call error (check sys_errno)
  1434. CertVerifyFailed, // Certificate verification failed
  1435. HostnameMismatch, // Hostname verification failed
  1436. };
  1437. // TLS error information
  1438. struct TlsError {
  1439. ErrorCode code = ErrorCode::Fatal;
  1440. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1441. int sys_errno = 0; // errno when SyscallError
  1442. // Convert verification error code to human-readable string
  1443. static std::string verify_error_to_string(long error_code);
  1444. };
  1445. // RAII wrapper for peer certificate
  1446. class PeerCert {
  1447. public:
  1448. PeerCert();
  1449. PeerCert(PeerCert &&other) noexcept;
  1450. PeerCert &operator=(PeerCert &&other) noexcept;
  1451. ~PeerCert();
  1452. PeerCert(const PeerCert &) = delete;
  1453. PeerCert &operator=(const PeerCert &) = delete;
  1454. explicit operator bool() const;
  1455. std::string subject_cn() const;
  1456. std::string issuer_name() const;
  1457. bool check_hostname(const char *hostname) const;
  1458. std::vector<SanEntry> sans() const;
  1459. bool validity(time_t &not_before, time_t &not_after) const;
  1460. std::string serial() const;
  1461. private:
  1462. explicit PeerCert(cert_t cert);
  1463. cert_t cert_ = nullptr;
  1464. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1465. };
  1466. // Callback for TLS context setup (used by SSLServer constructor)
  1467. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1468. } // namespace tls
  1469. #endif
  1470. struct Request {
  1471. std::string method;
  1472. std::string path;
  1473. std::string matched_route;
  1474. Params params;
  1475. Headers headers;
  1476. Headers trailers;
  1477. std::string body;
  1478. std::string remote_addr;
  1479. int remote_port = -1;
  1480. std::string local_addr;
  1481. int local_port = -1;
  1482. // for server
  1483. std::string version;
  1484. std::string target;
  1485. MultipartFormData form;
  1486. Ranges ranges;
  1487. Match matches;
  1488. std::unordered_map<std::string, std::string> path_params;
  1489. std::function<bool()> is_connection_closed = []() { return true; };
  1490. // for client
  1491. std::vector<std::string> accept_content_types;
  1492. ResponseHandler response_handler;
  1493. ContentReceiverWithProgress content_receiver;
  1494. DownloadProgress download_progress;
  1495. UploadProgress upload_progress;
  1496. bool has_header(const std::string &key) const;
  1497. std::string get_header_value(const std::string &key, const char *def = "",
  1498. size_t id = 0) const;
  1499. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1500. size_t id = 0) const;
  1501. size_t get_header_value_count(const std::string &key) const;
  1502. void set_header(const std::string &key, const std::string &val);
  1503. bool has_trailer(const std::string &key) const;
  1504. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1505. size_t get_trailer_value_count(const std::string &key) const;
  1506. bool has_param(const std::string &key) const;
  1507. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1508. std::vector<std::string> get_param_values(const std::string &key) const;
  1509. size_t get_param_value_count(const std::string &key) const;
  1510. bool is_multipart_form_data() const;
  1511. // private members...
  1512. bool body_consumed_ = false;
  1513. bool expect_100_continue_pending_ = false;
  1514. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1515. size_t content_length_ = 0;
  1516. ContentProvider content_provider_;
  1517. bool is_chunked_content_provider_ = false;
  1518. size_t authorization_count_ = 0;
  1519. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1520. (std::chrono::steady_clock::time_point::min)();
  1521. #ifdef CPPHTTPLIB_SSL_ENABLED
  1522. tls::const_session_t ssl = nullptr;
  1523. tls::PeerCert peer_cert() const;
  1524. std::string sni() const;
  1525. #endif
  1526. };
  1527. namespace detail {
  1528. // Declared up here, away from the rest of the compression helpers, because
  1529. // `Response` stores one.
  1530. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1531. } // namespace detail
  1532. struct Response {
  1533. std::string version;
  1534. int status = -1;
  1535. std::string reason;
  1536. Headers headers;
  1537. Headers trailers;
  1538. std::string body;
  1539. std::string location; // Redirect location
  1540. // User-defined context — set by pre-routing/pre-request handlers and read
  1541. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1542. UserData user_data;
  1543. bool has_header(const std::string &key) const;
  1544. std::string get_header_value(const std::string &key, const char *def = "",
  1545. size_t id = 0) const;
  1546. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1547. size_t id = 0) const;
  1548. size_t get_header_value_count(const std::string &key) const;
  1549. void set_header(const std::string &key, const std::string &val);
  1550. bool has_trailer(const std::string &key) const;
  1551. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1552. size_t get_trailer_value_count(const std::string &key) const;
  1553. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1554. void set_content(const char *s, size_t n, const std::string &content_type);
  1555. void set_content(const std::string &s, const std::string &content_type);
  1556. void set_content(std::string &&s, const std::string &content_type);
  1557. void set_content_provider(
  1558. size_t length, const std::string &content_type, ContentProvider provider,
  1559. ContentProviderResourceReleaser resource_releaser = nullptr);
  1560. void set_content_provider(
  1561. const std::string &content_type, ContentProviderWithoutLength provider,
  1562. ContentProviderResourceReleaser resource_releaser = nullptr);
  1563. void set_chunked_content_provider(
  1564. const std::string &content_type, ContentProviderWithoutLength provider,
  1565. ContentProviderResourceReleaser resource_releaser = nullptr);
  1566. void set_file_content(const std::string &path,
  1567. const std::string &content_type);
  1568. void set_file_content(const std::string &path);
  1569. Response() = default;
  1570. Response(const Response &) = default;
  1571. Response &operator=(const Response &) = default;
  1572. Response(Response &&) = default;
  1573. Response &operator=(Response &&) = default;
  1574. ~Response() {
  1575. if (content_provider_resource_releaser_) {
  1576. content_provider_resource_releaser_(content_provider_success_);
  1577. }
  1578. }
  1579. // private members...
  1580. size_t content_length_ = 0;
  1581. ContentProvider content_provider_;
  1582. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1583. bool is_chunked_content_provider_ = false;
  1584. bool is_file_content_provider_ = false;
  1585. bool content_provider_success_ = false;
  1586. std::string file_content_path_;
  1587. std::string file_content_content_type_;
  1588. // Content coding chosen for the response body, decided once so that the
  1589. // headers and the body cannot disagree: where the file is opened for a
  1590. // file-backed content provider (keeping the ETag honest), and in
  1591. // `apply_ranges()` for a chunked content provider. `EncodingType::None`
  1592. // for every other kind of response.
  1593. detail::EncodingType content_coding_ = detail::EncodingType::None;
  1594. };
  1595. enum class Error {
  1596. Success = 0,
  1597. Unknown,
  1598. Connection,
  1599. BindIPAddress,
  1600. Read,
  1601. Write,
  1602. ExceedRedirectCount,
  1603. Canceled,
  1604. SSLConnection,
  1605. SSLLoadingCerts,
  1606. SSLServerVerification,
  1607. SSLServerHostnameVerification,
  1608. UnsupportedMultipartBoundaryChars,
  1609. Compression,
  1610. ConnectionTimeout,
  1611. ProxyConnection,
  1612. ConnectionClosed,
  1613. Timeout,
  1614. ResourceExhaustion,
  1615. TooManyFormDataFiles,
  1616. ExceedMaxPayloadSize,
  1617. ExceedUriMaxLength,
  1618. ExceedMaxSocketDescriptorCount,
  1619. InvalidRequestLine,
  1620. InvalidHTTPMethod,
  1621. InvalidHTTPVersion,
  1622. InvalidHeaders,
  1623. MultipartParsing,
  1624. OpenFile,
  1625. Listen,
  1626. GetSockName,
  1627. UnsupportedAddressFamily,
  1628. HTTPParsing,
  1629. InvalidRangeHeader,
  1630. UnsupportedContentEncoding,
  1631. WebSocketHandshake,
  1632. UserCallbackException,
  1633. // For internal use only
  1634. SSLPeerCouldBeClosed_,
  1635. };
  1636. std::string to_string(Error error);
  1637. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1638. class Stream {
  1639. public:
  1640. virtual ~Stream() = default;
  1641. virtual bool is_readable() const = 0;
  1642. virtual bool wait_readable() const = 0;
  1643. virtual bool wait_writable() const = 0;
  1644. virtual bool is_peer_alive() const { return wait_writable(); }
  1645. virtual ssize_t read(char *ptr, size_t size) = 0;
  1646. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1647. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1648. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1649. virtual socket_t socket() const = 0;
  1650. virtual time_t duration() const = 0;
  1651. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1652. (void)sec;
  1653. (void)usec;
  1654. }
  1655. // Bytes already pulled off the socket and sitting in this stream's own
  1656. // buffer. Exposing them lets a line reader scan for a terminator in one
  1657. // pass instead of asking for a byte at a time. A stream that does no
  1658. // buffering of its own reports none, and readers fall back to read().
  1659. virtual const char *buffered_data(size_t &size) const {
  1660. size = 0;
  1661. return nullptr;
  1662. }
  1663. // Discards `size` bytes previously returned by buffered_data().
  1664. virtual void consume_buffered(size_t size) { (void)size; }
  1665. ssize_t write(const char *ptr);
  1666. ssize_t write(const std::string &s);
  1667. Error get_error() const { return error_; }
  1668. protected:
  1669. Error error_ = Error::Success;
  1670. };
  1671. class TaskQueue {
  1672. public:
  1673. TaskQueue() = default;
  1674. virtual ~TaskQueue() = default;
  1675. virtual bool enqueue(std::function<void()> fn) = 0;
  1676. virtual void shutdown() = 0;
  1677. virtual void on_idle() {}
  1678. };
  1679. class ThreadPool final : public TaskQueue {
  1680. public:
  1681. explicit ThreadPool(
  1682. size_t n, size_t max_n = 0, size_t mqr = 0,
  1683. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1684. ThreadPool(const ThreadPool &) = delete;
  1685. ~ThreadPool() override = default;
  1686. bool enqueue(std::function<void()> fn) override;
  1687. void shutdown() override;
  1688. private:
  1689. void worker(bool is_dynamic);
  1690. void move_to_finished(std::thread::id id);
  1691. void cleanup_finished_threads();
  1692. size_t base_thread_count_;
  1693. size_t max_thread_count_;
  1694. size_t max_queued_requests_;
  1695. time_t idle_timeout_sec_;
  1696. size_t idle_thread_count_;
  1697. bool shutdown_;
  1698. std::list<std::function<void()>> jobs_;
  1699. std::vector<std::thread> threads_; // base threads
  1700. std::list<std::thread> dynamic_threads_; // dynamic threads
  1701. std::vector<std::thread>
  1702. finished_threads_; // exited dynamic threads awaiting join
  1703. std::condition_variable cond_;
  1704. std::mutex mutex_;
  1705. };
  1706. using Logger = std::function<void(const Request &, const Response &)>;
  1707. // Forward declaration for Error type
  1708. enum class Error;
  1709. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1710. using SocketOptions = std::function<void(socket_t sock)>;
  1711. void default_socket_options(socket_t sock);
  1712. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1713. const char *status_message(int status);
  1714. std::string to_string(Error error);
  1715. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1716. std::string get_bearer_token_auth(const Request &req);
  1717. namespace detail {
  1718. class MatcherBase {
  1719. public:
  1720. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1721. virtual ~MatcherBase() = default;
  1722. const std::string &pattern() const { return pattern_; }
  1723. // Match request path and populate its matches and
  1724. virtual bool match(Request &request) const = 0;
  1725. private:
  1726. std::string pattern_;
  1727. };
  1728. /**
  1729. * Captures parameters in request path and stores them in Request::path_params
  1730. *
  1731. * Capture name is a substring of a pattern from : to /.
  1732. * The rest of the pattern is matched against the request path directly
  1733. * Parameters are captured starting from the next character after
  1734. * the end of the last matched static pattern fragment until the next /.
  1735. *
  1736. * Example pattern:
  1737. * "/path/fragments/:capture/more/fragments/:second_capture"
  1738. * Static fragments:
  1739. * "/path/fragments/", "more/fragments/"
  1740. *
  1741. * Given the following request path:
  1742. * "/path/fragments/:1/more/fragments/:2"
  1743. * the resulting capture will be
  1744. * {{"capture", "1"}, {"second_capture", "2"}}
  1745. */
  1746. class PathParamsMatcher final : public MatcherBase {
  1747. public:
  1748. PathParamsMatcher(const std::string &pattern);
  1749. bool match(Request &request) const override;
  1750. private:
  1751. // Treat segment separators as the end of path parameter capture
  1752. // Does not need to handle query parameters as they are parsed before path
  1753. // matching
  1754. static constexpr char separator = '/';
  1755. // Contains static path fragments to match against, excluding the '/' after
  1756. // path params
  1757. // Fragments are separated by path params
  1758. std::vector<std::string> static_fragments_;
  1759. // Stores the names of the path parameters to be used as keys in the
  1760. // Request::path_params map
  1761. std::vector<std::string> param_names_;
  1762. };
  1763. /**
  1764. * Performs std::regex_match on request path
  1765. * and stores the result in Request::matches
  1766. *
  1767. * Note that regex match is performed directly on the whole request.
  1768. * This means that wildcard patterns may match multiple path segments with /:
  1769. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1770. */
  1771. class RegexMatcher final : public MatcherBase {
  1772. public:
  1773. RegexMatcher(const std::string &pattern)
  1774. : MatcherBase(pattern), regex_(pattern) {}
  1775. bool match(Request &request) const override;
  1776. private:
  1777. std::regex regex_;
  1778. };
  1779. int close_socket(socket_t sock) noexcept;
  1780. bool is_accept_resource_error();
  1781. bool is_accept_transient_error();
  1782. ssize_t write_headers(Stream &strm, const Headers &headers);
  1783. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1784. time_t usec);
  1785. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1786. const std::string &boundary);
  1787. ContentProvider
  1788. make_multipart_content_provider(const UploadFormDataItems &items,
  1789. const std::string &boundary);
  1790. } // namespace detail
  1791. bool is_valid_multipart_boundary(const std::string &boundary);
  1792. // Serializer for multipart/form-data request bodies. The boundary is owned
  1793. // by the writer so that per-part framing and the final terminator always
  1794. // agree. Field names and filenames are escaped following the WHATWG HTML
  1795. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1796. // in content types.
  1797. class MultipartFormDataWriter {
  1798. public:
  1799. MultipartFormDataWriter();
  1800. // precondition: is_valid_multipart_boundary(boundary)
  1801. explicit MultipartFormDataWriter(std::string boundary);
  1802. const std::string &boundary() const;
  1803. std::string content_type() const;
  1804. // In-memory items -> whole body (known length)
  1805. std::string serialize(const UploadFormDataItems &items) const;
  1806. size_t content_length(const UploadFormDataItems &items) const;
  1807. // Per-part framing for streaming via a content provider
  1808. std::string item_begin(const UploadFormData &item) const;
  1809. static std::string item_end();
  1810. std::string finish() const;
  1811. private:
  1812. std::string boundary_;
  1813. };
  1814. class Server {
  1815. public:
  1816. using Handler = std::function<void(const Request &, Response &)>;
  1817. using ExceptionHandler =
  1818. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1819. enum class HandlerResponse {
  1820. Handled,
  1821. Unhandled,
  1822. };
  1823. using HandlerWithResponse =
  1824. std::function<HandlerResponse(const Request &, Response &)>;
  1825. using HandlerWithContentReader = std::function<void(
  1826. const Request &, Response &, const ContentReader &content_reader)>;
  1827. using Expect100ContinueHandler =
  1828. std::function<int(const Request &, Response &)>;
  1829. using StartHandler = std::function<void()>;
  1830. using WebSocketHandler =
  1831. std::function<void(const Request &, ws::WebSocket &)>;
  1832. using SubProtocolSelector =
  1833. std::function<std::string(const std::vector<std::string> &protocols)>;
  1834. Server();
  1835. virtual ~Server();
  1836. virtual bool is_valid() const;
  1837. Server &Get(const std::string &pattern, Handler handler);
  1838. Server &Post(const std::string &pattern, Handler handler);
  1839. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1840. Server &Put(const std::string &pattern, Handler handler);
  1841. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1842. Server &Patch(const std::string &pattern, Handler handler);
  1843. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1844. Server &Delete(const std::string &pattern, Handler handler);
  1845. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1846. Server &Options(const std::string &pattern, Handler handler);
  1847. // Register a handler for an HTTP method outside the built-in set (e.g. the
  1848. // WebDAV methods from RFC 4918). Registering a method here is what makes the
  1849. // server accept it; an unregistered method is still rejected with 400.
  1850. // `method` must be a valid HTTP method token and must not be one of the
  1851. // built-in methods, which have their own registration functions above. A
  1852. // rejected registration makes is_valid() return false, so listen() fails.
  1853. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1854. Handler handler);
  1855. Server &CustomRoute(const std::string &method, const std::string &pattern,
  1856. HandlerWithContentReader handler);
  1857. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1858. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1859. SubProtocolSelector sub_protocol_selector);
  1860. bool set_base_dir(const std::string &dir,
  1861. const std::string &mount_point = std::string());
  1862. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1863. Headers headers = Headers());
  1864. bool remove_mount_point(const std::string &mount_point);
  1865. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1866. const std::string &mime);
  1867. Server &set_default_file_mimetype(const std::string &mime);
  1868. Server &set_file_request_handler(Handler handler);
  1869. template <class ErrorHandlerFunc>
  1870. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1871. return set_error_handler_core(
  1872. std::forward<ErrorHandlerFunc>(handler),
  1873. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1874. }
  1875. Server &set_exception_handler(ExceptionHandler handler);
  1876. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1877. Server &set_post_routing_handler(Handler handler);
  1878. Server &set_pre_request_handler(HandlerWithResponse handler);
  1879. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1880. Server &set_start_handler(StartHandler handler);
  1881. Server &set_logger(Logger logger);
  1882. Server &set_pre_compression_logger(Logger logger);
  1883. Server &set_error_logger(ErrorLogger error_logger);
  1884. Server &set_address_family(int family);
  1885. Server &set_tcp_nodelay(bool on);
  1886. Server &set_ipv6_v6only(bool on);
  1887. Server &set_socket_options(SocketOptions socket_options);
  1888. Server &set_default_headers(Headers headers);
  1889. Server &
  1890. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1891. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1892. Server &set_keep_alive_max_count(size_t count);
  1893. Server &set_keep_alive_timeout(time_t sec);
  1894. template <class Rep, class Period>
  1895. Server &
  1896. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1897. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1898. template <class Rep, class Period>
  1899. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1900. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1901. template <class Rep, class Period>
  1902. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1903. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1904. template <class Rep, class Period>
  1905. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1906. Server &set_payload_max_length(size_t length);
  1907. Server &set_static_file_compression(bool on);
  1908. Server &set_static_file_compression_min_length(size_t length);
  1909. Server &set_static_file_compression_max_length(size_t length);
  1910. Server &set_websocket_ping_interval(time_t sec);
  1911. template <class Rep, class Period>
  1912. Server &set_websocket_ping_interval(
  1913. const std::chrono::duration<Rep, Period> &duration);
  1914. Server &set_websocket_max_missed_pongs(int count);
  1915. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1916. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1917. bool listen_after_bind();
  1918. bool listen(const std::string &host, int port, int socket_flags = 0);
  1919. bool is_running() const;
  1920. void wait_until_ready() const;
  1921. void stop() noexcept;
  1922. void decommission();
  1923. std::function<TaskQueue *(void)> new_task_queue;
  1924. protected:
  1925. bool process_request(Stream &strm, const std::string &remote_addr,
  1926. int remote_port, const std::string &local_addr,
  1927. int local_port, bool close_connection,
  1928. bool &connection_closed,
  1929. const std::function<void(Request &)> &setup_request,
  1930. bool *websocket_upgraded = nullptr);
  1931. // Runs the per-connection serving loop and stops an exception thrown by a
  1932. // user callback from escaping the worker thread.
  1933. //
  1934. // process_request() wraps only routing() in a try/catch. Content providers,
  1935. // the post-routing, error, logging and expect-100 handlers and WebSocket
  1936. // handlers all run outside it, and the task queue calls the job without a
  1937. // catch, so an exception from any of those would terminate the process.
  1938. //
  1939. // No 500 is possible here: by the time a content provider runs, the status
  1940. // line and headers are already on the wire. Report it through the error
  1941. // logger and drop the connection, which is what the peer observes either
  1942. // way. Other connections are unaffected.
  1943. template <typename Serve> bool serve_guarded(Serve &&serve) const {
  1944. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  1945. return serve();
  1946. #else
  1947. try {
  1948. return serve();
  1949. } catch (...) {
  1950. // The error logger is a user callback too, so it must not be able to
  1951. // throw the guard back open.
  1952. try {
  1953. output_error_log(Error::UserCallbackException, nullptr);
  1954. } catch (...) {}
  1955. return false;
  1956. }
  1957. #endif
  1958. }
  1959. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1960. std::vector<std::string> trusted_proxies_;
  1961. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1962. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1963. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1964. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1965. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1966. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1967. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1968. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1969. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1970. bool static_file_compression_ = false;
  1971. size_t static_file_compression_min_length_ =
  1972. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH;
  1973. size_t static_file_compression_max_length_ =
  1974. CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH;
  1975. time_t websocket_ping_interval_sec_ =
  1976. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1977. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1978. private:
  1979. using Handlers =
  1980. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1981. using HandlersForContentReader =
  1982. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1983. HandlerWithContentReader>>;
  1984. // Both handler tables for one custom method live in a single entry, so that
  1985. // routing() needs only one map lookup per request to reach either of them.
  1986. struct CustomHandlerEntry {
  1987. Handlers handlers;
  1988. HandlersForContentReader handlers_for_content_reader;
  1989. };
  1990. using CustomHandlers = std::map<std::string, CustomHandlerEntry>;
  1991. static std::unique_ptr<detail::MatcherBase>
  1992. make_matcher(const std::string &pattern);
  1993. static const std::set<std::string> &builtin_methods();
  1994. CustomHandlerEntry *custom_entry_for_registration(const std::string &method);
  1995. const CustomHandlerEntry *find_custom_entry(const std::string &method) const;
  1996. template <typename H>
  1997. Server &add_handler(
  1998. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1999. const std::string &pattern, H handler) {
  2000. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  2001. return *this;
  2002. }
  2003. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  2004. Server &set_error_handler_core(Handler handler, std::false_type);
  2005. socket_t create_server_socket(const std::string &host, int port,
  2006. int socket_flags,
  2007. SocketOptions socket_options) const;
  2008. int bind_internal(const std::string &host, int port, int socket_flags);
  2009. bool listen_internal();
  2010. bool routing(Request &req, Response &res, Stream &strm);
  2011. bool handle_file_request(Request &req, Response &res);
  2012. bool check_if_not_modified(const Request &req, Response &res,
  2013. const std::string &etag, time_t mtime) const;
  2014. bool check_if_range(Request &req, const std::string &etag,
  2015. time_t mtime) const;
  2016. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  2017. Stream &strm);
  2018. bool dispatch_request_for_content_reader(
  2019. Request &req, Response &res, ContentReader content_reader,
  2020. const HandlersForContentReader &handlers) const;
  2021. bool parse_request_line(const char *s, Request &req) const;
  2022. detail::EncodingType static_file_encoding(const Request &req,
  2023. const Response &res,
  2024. const std::string &content_type,
  2025. size_t length) const;
  2026. bool apply_static_file_compression(const Request &req, Response &res) const;
  2027. void apply_ranges(const Request &req, Response &res,
  2028. std::string &content_type, std::string &boundary) const;
  2029. bool write_response(Stream &strm, bool close_connection, Request &req,
  2030. Response &res);
  2031. bool write_response_with_content(Stream &strm, bool close_connection,
  2032. const Request &req, Response &res);
  2033. bool write_response_core(Stream &strm, bool close_connection,
  2034. const Request &req, Response &res,
  2035. bool need_apply_ranges);
  2036. bool write_content_with_provider(Stream &strm, const Request &req,
  2037. Response &res, const std::string &boundary,
  2038. const std::string &content_type);
  2039. bool read_content(Stream &strm, Request &req, Response &res);
  2040. bool read_content_with_content_receiver(Stream &strm, Request &req,
  2041. Response &res,
  2042. ContentReceiver receiver,
  2043. FormDataHeader multipart_header,
  2044. ContentReceiver multipart_receiver);
  2045. bool read_content_core(Stream &strm, Request &req, Response &res,
  2046. ContentReceiver receiver,
  2047. FormDataHeader multipart_header,
  2048. ContentReceiver multipart_receiver) const;
  2049. virtual bool process_and_close_socket(socket_t sock);
  2050. void output_log(const Request &req, const Response &res) const;
  2051. void output_pre_compression_log(const Request &req,
  2052. const Response &res) const;
  2053. void output_error_log(const Error &err, const Request *req) const;
  2054. std::atomic<bool> is_running_{false};
  2055. std::atomic<bool> is_decommissioned{false};
  2056. // Set when CustomRoute() refuses a registration. Written before listen(),
  2057. // read by is_valid() on the same thread, so it needs no synchronization.
  2058. bool has_invalid_registration_ = false;
  2059. struct MountPointEntry {
  2060. std::string mount_point;
  2061. std::string base_dir;
  2062. std::string resolved_base_dir;
  2063. Headers headers;
  2064. };
  2065. std::vector<MountPointEntry> base_dirs_;
  2066. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  2067. std::string default_file_mimetype_ = "application/octet-stream";
  2068. Handler file_request_handler_;
  2069. Handlers get_handlers_;
  2070. Handlers post_handlers_;
  2071. HandlersForContentReader post_handlers_for_content_reader_;
  2072. Handlers put_handlers_;
  2073. HandlersForContentReader put_handlers_for_content_reader_;
  2074. Handlers patch_handlers_;
  2075. HandlersForContentReader patch_handlers_for_content_reader_;
  2076. Handlers delete_handlers_;
  2077. HandlersForContentReader delete_handlers_for_content_reader_;
  2078. Handlers options_handlers_;
  2079. CustomHandlers custom_handlers_;
  2080. struct WebSocketHandlerEntry {
  2081. std::unique_ptr<detail::MatcherBase> matcher;
  2082. WebSocketHandler handler;
  2083. SubProtocolSelector sub_protocol_selector;
  2084. };
  2085. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  2086. WebSocketHandlers websocket_handlers_;
  2087. HandlerWithResponse error_handler_;
  2088. ExceptionHandler exception_handler_;
  2089. HandlerWithResponse pre_routing_handler_;
  2090. Handler post_routing_handler_;
  2091. HandlerWithResponse pre_request_handler_;
  2092. Expect100ContinueHandler expect_100_continue_handler_;
  2093. StartHandler start_handler_;
  2094. mutable std::mutex logger_mutex_;
  2095. Logger logger_;
  2096. Logger pre_compression_logger_;
  2097. ErrorLogger error_logger_;
  2098. int address_family_ = AF_UNSPEC;
  2099. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2100. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2101. SocketOptions socket_options_ = default_socket_options;
  2102. Headers default_headers_;
  2103. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2104. detail::write_headers;
  2105. };
  2106. class Result {
  2107. public:
  2108. Result() = default;
  2109. Result(std::unique_ptr<Response> &&res, Error err,
  2110. Headers &&request_headers = Headers{})
  2111. : res_(std::move(res)), err_(err),
  2112. request_headers_(std::move(request_headers)) {}
  2113. // Response
  2114. operator bool() const { return res_ != nullptr; }
  2115. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  2116. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  2117. const Response &value() const { return *res_; }
  2118. Response &value() { return *res_; }
  2119. const Response &operator*() const { return *res_; }
  2120. Response &operator*() { return *res_; }
  2121. const Response *operator->() const { return res_.get(); }
  2122. Response *operator->() { return res_.get(); }
  2123. // Error
  2124. Error error() const { return err_; }
  2125. // Request Headers
  2126. bool has_request_header(const std::string &key) const;
  2127. std::string get_request_header_value(const std::string &key,
  2128. const char *def = "",
  2129. size_t id = 0) const;
  2130. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  2131. size_t id = 0) const;
  2132. size_t get_request_header_value_count(const std::string &key) const;
  2133. private:
  2134. std::unique_ptr<Response> res_;
  2135. Error err_ = Error::Unknown;
  2136. Headers request_headers_;
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. public:
  2139. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2140. int ssl_error)
  2141. : res_(std::move(res)), err_(err),
  2142. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  2143. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  2144. int ssl_error, uint64_t ssl_backend_error)
  2145. : res_(std::move(res)), err_(err),
  2146. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  2147. ssl_backend_error_(ssl_backend_error) {}
  2148. int ssl_error() const { return ssl_error_; }
  2149. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  2150. private:
  2151. int ssl_error_ = 0;
  2152. uint64_t ssl_backend_error_ = 0;
  2153. #endif
  2154. };
  2155. struct ClientConnection {
  2156. socket_t sock = INVALID_SOCKET;
  2157. bool is_open() const { return sock != INVALID_SOCKET; }
  2158. ClientConnection() = default;
  2159. ~ClientConnection();
  2160. ClientConnection(const ClientConnection &) = delete;
  2161. ClientConnection &operator=(const ClientConnection &) = delete;
  2162. ClientConnection(ClientConnection &&other) noexcept
  2163. : sock(other.sock)
  2164. #ifdef CPPHTTPLIB_SSL_ENABLED
  2165. ,
  2166. session(other.session)
  2167. #endif
  2168. {
  2169. other.sock = INVALID_SOCKET;
  2170. #ifdef CPPHTTPLIB_SSL_ENABLED
  2171. other.session = nullptr;
  2172. #endif
  2173. }
  2174. ClientConnection &operator=(ClientConnection &&other) noexcept {
  2175. if (this != &other) {
  2176. sock = other.sock;
  2177. other.sock = INVALID_SOCKET;
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. session = other.session;
  2180. other.session = nullptr;
  2181. #endif
  2182. }
  2183. return *this;
  2184. }
  2185. #ifdef CPPHTTPLIB_SSL_ENABLED
  2186. tls::session_t session = nullptr;
  2187. #endif
  2188. };
  2189. namespace detail {
  2190. struct ChunkedDecoder;
  2191. struct BodyReader {
  2192. Stream *stream = nullptr;
  2193. bool has_content_length = false;
  2194. size_t content_length = 0;
  2195. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2196. size_t bytes_read = 0;
  2197. bool chunked = false;
  2198. bool eof = false;
  2199. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  2200. Error last_error = Error::Success;
  2201. ssize_t read(char *buf, size_t len);
  2202. bool has_error() const { return last_error != Error::Success; }
  2203. };
  2204. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  2205. size_t len) {
  2206. (void)stream;
  2207. return br.read(buf, len);
  2208. }
  2209. class decompressor;
  2210. enum class NoProxyKind {
  2211. Wildcard, // "*"
  2212. HostnameSuffix, // "example.com" or ".example.com"
  2213. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  2214. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  2215. };
  2216. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  2217. // Lets one CIDR matcher cover both families.
  2218. using IPBytes = std::array<uint8_t, 16>;
  2219. struct NoProxyEntry {
  2220. NoProxyKind kind = NoProxyKind::Wildcard;
  2221. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  2222. IPBytes net{};
  2223. int prefix_bits = 0;
  2224. };
  2225. struct NormalizedTarget {
  2226. std::string hostname; // lowercase; brackets and trailing dot removed
  2227. bool is_ipv4 = false;
  2228. bool is_ipv6 = false;
  2229. IPBytes ip{};
  2230. };
  2231. } // namespace detail
  2232. class ClientImpl {
  2233. public:
  2234. explicit ClientImpl(const std::string &host);
  2235. explicit ClientImpl(const std::string &host, int port);
  2236. explicit ClientImpl(const std::string &host, int port,
  2237. const std::string &client_cert_path,
  2238. const std::string &client_key_path);
  2239. virtual ~ClientImpl();
  2240. virtual bool is_valid() const;
  2241. struct StreamHandle {
  2242. std::unique_ptr<Response> response;
  2243. Error error = Error::Success;
  2244. StreamHandle() = default;
  2245. StreamHandle(const StreamHandle &) = delete;
  2246. StreamHandle &operator=(const StreamHandle &) = delete;
  2247. StreamHandle(StreamHandle &&) = default;
  2248. StreamHandle &operator=(StreamHandle &&) = default;
  2249. ~StreamHandle() = default;
  2250. bool is_valid() const {
  2251. return response != nullptr && error == Error::Success;
  2252. }
  2253. ssize_t read(char *buf, size_t len);
  2254. void parse_trailers_if_needed();
  2255. Error get_read_error() const { return body_reader_.last_error; }
  2256. bool has_read_error() const { return body_reader_.has_error(); }
  2257. bool trailers_parsed_ = false;
  2258. private:
  2259. friend class ClientImpl;
  2260. ssize_t read_with_decompression(char *buf, size_t len);
  2261. std::unique_ptr<ClientConnection> connection_;
  2262. std::unique_ptr<Stream> socket_stream_;
  2263. Stream *stream_ = nullptr;
  2264. detail::BodyReader body_reader_;
  2265. std::unique_ptr<detail::decompressor> decompressor_;
  2266. std::string decompress_buffer_;
  2267. size_t decompress_offset_ = 0;
  2268. size_t decompressed_bytes_read_ = 0;
  2269. };
  2270. // clang-format off
  2271. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2272. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2273. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2274. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2275. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2276. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2277. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2278. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2279. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2280. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2281. Result Head(const std::string &path);
  2282. Result Head(const std::string &path, const Headers &headers);
  2283. Result Post(const std::string &path);
  2284. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2285. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2286. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2287. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2288. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2289. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2290. Result Post(const std::string &path, const Params &params);
  2291. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2292. Result Post(const std::string &path, const Headers &headers);
  2293. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2294. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2295. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2296. 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);
  2297. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2298. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2299. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2300. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2301. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2302. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2303. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2304. Result Put(const std::string &path);
  2305. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2306. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2307. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2308. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2309. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2310. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2311. Result Put(const std::string &path, const Params &params);
  2312. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2313. Result Put(const std::string &path, const Headers &headers);
  2314. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2315. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2316. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2317. 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);
  2318. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2319. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2320. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2321. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2322. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2323. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2324. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2325. Result Patch(const std::string &path);
  2326. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2327. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2328. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2329. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2330. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2331. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2332. Result Patch(const std::string &path, const Params &params);
  2333. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2334. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  2335. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2336. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2337. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2338. 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);
  2339. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2340. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2341. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2342. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2343. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2344. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2345. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2346. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2347. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2348. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2349. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2350. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2351. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2352. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2353. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2354. Result Options(const std::string &path);
  2355. Result Options(const std::string &path, const Headers &headers);
  2356. // clang-format on
  2357. // Streaming API: Open a stream for reading response body incrementally
  2358. // Socket ownership is transferred to StreamHandle for true streaming
  2359. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2360. StreamHandle open_stream(const std::string &method, const std::string &path,
  2361. const Params &params = {},
  2362. const Headers &headers = {},
  2363. const std::string &body = {},
  2364. const std::string &content_type = {});
  2365. bool send(Request &req, Response &res, Error &error);
  2366. Result send(const Request &req);
  2367. void stop();
  2368. std::string host() const;
  2369. int port() const;
  2370. size_t is_socket_open() const;
  2371. socket_t socket() const;
  2372. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2373. void set_default_headers(Headers headers);
  2374. void
  2375. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2376. void set_address_family(int family);
  2377. void set_tcp_nodelay(bool on);
  2378. void set_ipv6_v6only(bool on);
  2379. void set_socket_options(SocketOptions socket_options);
  2380. void set_connection_timeout(time_t sec, time_t usec = 0);
  2381. template <class Rep, class Period>
  2382. void
  2383. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2384. void set_read_timeout(time_t sec, time_t usec = 0);
  2385. template <class Rep, class Period>
  2386. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2387. void set_write_timeout(time_t sec, time_t usec = 0);
  2388. template <class Rep, class Period>
  2389. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2390. void set_max_timeout(time_t msec);
  2391. template <class Rep, class Period>
  2392. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2393. void set_basic_auth(const std::string &username, const std::string &password);
  2394. void set_bearer_token_auth(const std::string &token);
  2395. void set_keep_alive(bool on);
  2396. void set_follow_location(bool on);
  2397. void set_path_encode(bool on);
  2398. void set_compress(bool on);
  2399. void set_decompress(bool on);
  2400. void set_payload_max_length(size_t length);
  2401. void set_interface(const std::string &intf);
  2402. void set_proxy(const std::string &host, int port);
  2403. void set_proxy_basic_auth(const std::string &username,
  2404. const std::string &password);
  2405. void set_proxy_bearer_token_auth(const std::string &token);
  2406. void set_no_proxy(const std::vector<std::string> &patterns);
  2407. void set_logger(Logger logger);
  2408. void set_error_logger(ErrorLogger error_logger);
  2409. protected:
  2410. struct Socket {
  2411. socket_t sock = INVALID_SOCKET;
  2412. // For Mbed TLS compatibility: start_time for request timeout tracking
  2413. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2414. bool is_open() const { return sock != INVALID_SOCKET; }
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. tls::session_t ssl = nullptr;
  2417. #endif
  2418. };
  2419. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  2420. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  2421. virtual bool setup_proxy_connection(
  2422. Socket &socket,
  2423. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2424. Response &res, bool &success, Error &error);
  2425. bool is_proxy_enabled_for_host(const std::string &host) const;
  2426. // All of:
  2427. // shutdown_ssl
  2428. // shutdown_socket
  2429. // close_socket
  2430. // disconnect
  2431. // should ONLY be called when socket_mutex_ is locked, and only when
  2432. // no other thread is using the socket.
  2433. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  2434. void shutdown_socket(Socket &socket) const;
  2435. void close_socket(Socket &socket);
  2436. void disconnect(bool gracefully);
  2437. bool process_request(Stream &strm, Request &req, Response &res,
  2438. bool close_connection, Error &error);
  2439. bool write_content_with_provider(Stream &strm, const Request &req,
  2440. Error &error) const;
  2441. void copy_settings(const ClientImpl &rhs);
  2442. void output_log(const Request &req, const Response &res) const;
  2443. void output_error_log(const Error &err, const Request *req) const;
  2444. // Socket endpoint information
  2445. const std::string host_;
  2446. const int port_;
  2447. // Current open socket
  2448. Socket socket_;
  2449. mutable std::mutex socket_mutex_;
  2450. std::recursive_mutex request_mutex_;
  2451. // These are all protected under socket_mutex
  2452. size_t socket_requests_in_flight_ = 0;
  2453. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2454. bool socket_should_be_closed_when_request_is_done_ = false;
  2455. // Hostname to connection target map. The value is an IP literal or another
  2456. // hostname; only the connection target changes, never the identity.
  2457. std::map<std::string, std::string> addr_map_;
  2458. // Default headers
  2459. Headers default_headers_;
  2460. // Header writer
  2461. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2462. detail::write_headers;
  2463. // Settings
  2464. std::string client_cert_path_;
  2465. std::string client_key_path_;
  2466. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2467. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2468. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2469. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2470. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2471. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2472. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2473. std::string basic_auth_username_;
  2474. std::string basic_auth_password_;
  2475. std::string bearer_token_auth_token_;
  2476. bool keep_alive_ = false;
  2477. bool follow_location_ = false;
  2478. bool path_encode_ = true;
  2479. int address_family_ = AF_UNSPEC;
  2480. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2481. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2482. SocketOptions socket_options_ = nullptr;
  2483. bool compress_ = false;
  2484. bool decompress_ = true;
  2485. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2486. bool has_payload_max_length_ = false;
  2487. std::string interface_;
  2488. std::string proxy_host_;
  2489. int proxy_port_ = -1;
  2490. std::string proxy_basic_auth_username_;
  2491. std::string proxy_basic_auth_password_;
  2492. std::string proxy_bearer_token_auth_token_;
  2493. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2494. mutable detail::NormalizedTarget host_normalized_;
  2495. mutable bool host_normalized_valid_ = false;
  2496. mutable std::mutex logger_mutex_;
  2497. Logger logger_;
  2498. ErrorLogger error_logger_;
  2499. private:
  2500. bool send_(Request &req, Response &res, Error &error);
  2501. Result send_(Request &&req);
  2502. socket_t create_client_socket(Error &error) const;
  2503. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2504. bool skip_100_continue = true) const;
  2505. bool write_request(Stream &strm, Request &req, bool close_connection,
  2506. Error &error, bool skip_body, bool &rejected_locally);
  2507. bool write_request_body(Stream &strm, Request &req, Error &error);
  2508. void prepare_default_headers(Request &r, bool for_stream,
  2509. const std::string &ct);
  2510. bool redirect(Request &req, Response &res, Error &error);
  2511. bool create_redirect_client(const std::string &scheme,
  2512. const std::string &host, int port, Request &req,
  2513. Response &res, const std::string &path,
  2514. const std::string &location, Error &error);
  2515. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2516. bool handle_request(Stream &strm, Request &req, Response &res,
  2517. bool close_connection, Error &error);
  2518. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2519. Request &req, const char *body, size_t content_length,
  2520. ContentProvider content_provider,
  2521. ContentProviderWithoutLength content_provider_without_length,
  2522. const std::string &content_type, ContentReceiver content_receiver,
  2523. Error &error);
  2524. Result send_with_content_provider_and_receiver(
  2525. const std::string &method, const std::string &path,
  2526. const Headers &headers, const char *body, size_t content_length,
  2527. ContentProvider content_provider,
  2528. ContentProviderWithoutLength content_provider_without_length,
  2529. const std::string &content_type, ContentReceiver content_receiver,
  2530. UploadProgress progress);
  2531. ContentProviderWithoutLength get_multipart_content_provider(
  2532. const std::string &boundary, const UploadFormDataItems &items,
  2533. const FormDataProviderItems &provider_items) const;
  2534. virtual bool
  2535. process_socket(const Socket &socket,
  2536. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2537. std::function<bool(Stream &strm)> callback);
  2538. virtual bool is_ssl() const;
  2539. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2540. #ifdef CPPHTTPLIB_SSL_ENABLED
  2541. public:
  2542. void set_digest_auth(const std::string &username,
  2543. const std::string &password);
  2544. void set_proxy_digest_auth(const std::string &username,
  2545. const std::string &password);
  2546. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2547. const std::string &ca_cert_dir_path = std::string());
  2548. void enable_server_certificate_verification(bool enabled);
  2549. void enable_server_hostname_verification(bool enabled);
  2550. void enable_system_ca(bool enabled);
  2551. protected:
  2552. std::string digest_auth_username_;
  2553. std::string digest_auth_password_;
  2554. std::string proxy_digest_auth_username_;
  2555. std::string proxy_digest_auth_password_;
  2556. std::string ca_cert_file_path_;
  2557. std::string ca_cert_dir_path_;
  2558. bool server_certificate_verification_ = true;
  2559. bool server_hostname_verification_ = true;
  2560. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2561. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2562. int last_ssl_error_ = 0;
  2563. uint64_t last_backend_error_ = 0;
  2564. #endif
  2565. };
  2566. class Client {
  2567. public:
  2568. // Universal interface
  2569. explicit Client(const std::string &scheme_host_port);
  2570. explicit Client(const std::string &scheme_host_port,
  2571. const std::string &client_cert_path,
  2572. const std::string &client_key_path);
  2573. // HTTP only interface
  2574. explicit Client(const std::string &host, int port);
  2575. explicit Client(const std::string &host, int port,
  2576. const std::string &client_cert_path,
  2577. const std::string &client_key_path);
  2578. Client(Client &&) = default;
  2579. Client &operator=(Client &&) = default;
  2580. ~Client();
  2581. bool is_valid() const;
  2582. // clang-format off
  2583. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2584. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2585. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2586. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2587. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2588. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2589. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2590. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2591. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2592. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2593. Result Head(const std::string &path);
  2594. Result Head(const std::string &path, const Headers &headers);
  2595. Result Post(const std::string &path);
  2596. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2597. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2598. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2599. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2600. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2601. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2602. Result Post(const std::string &path, const Params &params);
  2603. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2604. Result Post(const std::string &path, const Headers &headers);
  2605. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2606. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2607. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2608. 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);
  2609. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2610. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2611. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2612. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2613. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2614. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2615. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2616. Result Put(const std::string &path);
  2617. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2618. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2619. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2620. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2621. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2622. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2623. Result Put(const std::string &path, const Params &params);
  2624. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2625. Result Put(const std::string &path, const Headers &headers);
  2626. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2627. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2628. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2629. 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);
  2630. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2631. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2632. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2633. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2634. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2635. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2636. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2637. Result Patch(const std::string &path);
  2638. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2639. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2640. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2641. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2642. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2643. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2644. Result Patch(const std::string &path, const Params &params);
  2645. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2646. Result Patch(const std::string &path, const Headers &headers);
  2647. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2648. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2649. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2650. 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);
  2651. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2652. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2653. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2654. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2655. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2656. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2657. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2658. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2659. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2660. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2661. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2662. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2663. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2664. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2665. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2666. Result Options(const std::string &path);
  2667. Result Options(const std::string &path, const Headers &headers);
  2668. // clang-format on
  2669. // Streaming API: Open a stream for reading response body incrementally
  2670. // Socket ownership is transferred to StreamHandle for true streaming
  2671. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2672. ClientImpl::StreamHandle open_stream(const std::string &method,
  2673. const std::string &path,
  2674. const Params &params = {},
  2675. const Headers &headers = {},
  2676. const std::string &body = {},
  2677. const std::string &content_type = {});
  2678. bool send(Request &req, Response &res, Error &error);
  2679. Result send(const Request &req);
  2680. void stop();
  2681. std::string host() const;
  2682. int port() const;
  2683. size_t is_socket_open() const;
  2684. socket_t socket() const;
  2685. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2686. void set_default_headers(Headers headers);
  2687. void
  2688. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2689. void set_address_family(int family);
  2690. void set_tcp_nodelay(bool on);
  2691. void set_socket_options(SocketOptions socket_options);
  2692. void set_connection_timeout(time_t sec, time_t usec = 0);
  2693. template <class Rep, class Period>
  2694. void
  2695. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2696. void set_read_timeout(time_t sec, time_t usec = 0);
  2697. template <class Rep, class Period>
  2698. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2699. void set_write_timeout(time_t sec, time_t usec = 0);
  2700. template <class Rep, class Period>
  2701. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2702. void set_max_timeout(time_t msec);
  2703. template <class Rep, class Period>
  2704. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2705. void set_basic_auth(const std::string &username, const std::string &password);
  2706. void set_bearer_token_auth(const std::string &token);
  2707. void set_keep_alive(bool on);
  2708. void set_follow_location(bool on);
  2709. void set_path_encode(bool on);
  2710. void set_compress(bool on);
  2711. void set_decompress(bool on);
  2712. void set_payload_max_length(size_t length);
  2713. void set_interface(const std::string &intf);
  2714. void set_proxy(const std::string &host, int port);
  2715. void set_proxy_basic_auth(const std::string &username,
  2716. const std::string &password);
  2717. void set_proxy_bearer_token_auth(const std::string &token);
  2718. void set_no_proxy(const std::vector<std::string> &patterns);
  2719. void set_logger(Logger logger);
  2720. void set_error_logger(ErrorLogger error_logger);
  2721. private:
  2722. std::unique_ptr<ClientImpl> cli_;
  2723. #ifdef CPPHTTPLIB_SSL_ENABLED
  2724. public:
  2725. void set_digest_auth(const std::string &username,
  2726. const std::string &password);
  2727. void set_proxy_digest_auth(const std::string &username,
  2728. const std::string &password);
  2729. void enable_server_certificate_verification(bool enabled);
  2730. void enable_server_hostname_verification(bool enabled);
  2731. void enable_system_ca(bool enabled);
  2732. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2733. const std::string &ca_cert_dir_path = std::string());
  2734. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2735. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2736. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2737. void set_session_verifier(
  2738. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2739. tls::ctx_t tls_context() const;
  2740. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2741. void enable_windows_certificate_verification(bool enabled);
  2742. #endif
  2743. private:
  2744. bool is_ssl_ = false;
  2745. #endif
  2746. };
  2747. #ifdef CPPHTTPLIB_SSL_ENABLED
  2748. class SSLServer : public Server {
  2749. public:
  2750. SSLServer(const char *cert_path, const char *private_key_path,
  2751. const char *client_ca_cert_file_path = nullptr,
  2752. const char *client_ca_cert_dir_path = nullptr,
  2753. const char *private_key_password = nullptr);
  2754. struct PemMemory {
  2755. const char *cert_pem;
  2756. size_t cert_pem_len;
  2757. const char *key_pem;
  2758. size_t key_pem_len;
  2759. const char *client_ca_pem;
  2760. size_t client_ca_pem_len;
  2761. const char *private_key_password;
  2762. };
  2763. explicit SSLServer(const PemMemory &pem);
  2764. // The callback receives the ctx_t handle which can be cast to the
  2765. // appropriate backend type (SSL_CTX* for OpenSSL,
  2766. // tls::impl::MbedTlsContext* for Mbed TLS)
  2767. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2768. ~SSLServer() override;
  2769. bool is_valid() const override;
  2770. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2771. const char *client_ca_pem = nullptr,
  2772. const char *password = nullptr);
  2773. tls::ctx_t tls_context() const { return ctx_; }
  2774. int ssl_last_error() const { return last_ssl_error_; }
  2775. private:
  2776. bool process_and_close_socket(socket_t sock) override;
  2777. tls::ctx_t ctx_ = nullptr;
  2778. std::mutex ctx_mutex_;
  2779. int last_ssl_error_ = 0;
  2780. };
  2781. class SSLClient final : public ClientImpl {
  2782. public:
  2783. explicit SSLClient(const std::string &host);
  2784. explicit SSLClient(const std::string &host, int port);
  2785. explicit SSLClient(const std::string &host, int port,
  2786. const std::string &client_cert_path,
  2787. const std::string &client_key_path,
  2788. const std::string &private_key_password = std::string());
  2789. struct PemMemory {
  2790. const char *cert_pem;
  2791. size_t cert_pem_len;
  2792. const char *key_pem;
  2793. size_t key_pem_len;
  2794. const char *private_key_password;
  2795. };
  2796. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2797. ~SSLClient() override;
  2798. bool is_valid() const override;
  2799. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2800. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2801. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2802. // Post-handshake session verifier (backend-independent)
  2803. void set_session_verifier(
  2804. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2805. tls::ctx_t tls_context() const { return ctx_; }
  2806. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2807. void enable_windows_certificate_verification(bool enabled);
  2808. #endif
  2809. private:
  2810. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2811. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2812. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2813. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2814. bool
  2815. process_socket(const Socket &socket,
  2816. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2817. std::function<bool(Stream &strm)> callback) override;
  2818. bool is_ssl() const override;
  2819. bool setup_proxy_connection(
  2820. Socket &socket,
  2821. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2822. Response &res, bool &success, Error &error) override;
  2823. bool connect_with_proxy(
  2824. Socket &sock,
  2825. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2826. Response &res, bool &success, Error &error);
  2827. bool initialize_ssl(Socket &socket, Error &error);
  2828. void init_ctx();
  2829. void reset_ctx_on_error();
  2830. bool load_certs();
  2831. tls::ctx_t ctx_ = nullptr;
  2832. std::mutex ctx_mutex_;
  2833. std::once_flag initialize_cert_;
  2834. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2835. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2836. // Used to keep custom CA configuration exclusive with system CA loading.
  2837. bool ca_cert_store_set_ = false;
  2838. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2839. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2840. bool enable_windows_cert_verification_ = true;
  2841. #endif
  2842. friend class ClientImpl;
  2843. };
  2844. #endif // CPPHTTPLIB_SSL_ENABLED
  2845. namespace detail {
  2846. template <typename T, typename U>
  2847. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2848. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2849. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2850. duration - std::chrono::seconds(sec))
  2851. .count();
  2852. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2853. }
  2854. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2855. return N - 1;
  2856. }
  2857. inline bool is_numeric(const std::string &str) {
  2858. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2859. }
  2860. inline size_t get_header_value_u64(const Headers &headers,
  2861. const std::string &key, size_t def,
  2862. size_t id, bool &is_invalid_value) {
  2863. is_invalid_value = false;
  2864. auto rng = headers.equal_range(key);
  2865. auto it = rng.first;
  2866. std::advance(it, static_cast<ssize_t>(id));
  2867. if (it != rng.second) {
  2868. if (is_numeric(it->second)) {
  2869. // Parse at size_t width so an out-of-range Content-Length is reported
  2870. // rather than silently saturated/truncated (a value above 2^32 would
  2871. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  2872. // and return SIZE_MAX so the existing oversized-value guards reject it.
  2873. size_t val = 0;
  2874. const auto &s = it->second;
  2875. auto r = from_chars(s.data(), s.data() + s.size(), val);
  2876. if (r.ec == std::errc::result_out_of_range) {
  2877. is_invalid_value = true;
  2878. return (std::numeric_limits<size_t>::max)();
  2879. }
  2880. return val;
  2881. } else {
  2882. is_invalid_value = true;
  2883. }
  2884. }
  2885. return def;
  2886. }
  2887. inline size_t get_header_value_u64(const Headers &headers,
  2888. const std::string &key, size_t def,
  2889. size_t id) {
  2890. auto dummy = false;
  2891. return get_header_value_u64(headers, key, def, id, dummy);
  2892. }
  2893. } // namespace detail
  2894. template <class Rep, class Period>
  2895. inline Server &
  2896. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2897. detail::duration_to_sec_and_usec(
  2898. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2899. return *this;
  2900. }
  2901. template <class Rep, class Period>
  2902. inline Server &
  2903. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2904. detail::duration_to_sec_and_usec(
  2905. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2906. return *this;
  2907. }
  2908. template <class Rep, class Period>
  2909. inline Server &
  2910. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2911. detail::duration_to_sec_and_usec(
  2912. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2913. return *this;
  2914. }
  2915. template <class Rep, class Period>
  2916. inline void ClientImpl::set_connection_timeout(
  2917. const std::chrono::duration<Rep, Period> &duration) {
  2918. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2919. set_connection_timeout(sec, usec);
  2920. });
  2921. }
  2922. template <class Rep, class Period>
  2923. inline void ClientImpl::set_read_timeout(
  2924. const std::chrono::duration<Rep, Period> &duration) {
  2925. detail::duration_to_sec_and_usec(
  2926. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2927. }
  2928. template <class Rep, class Period>
  2929. inline void ClientImpl::set_write_timeout(
  2930. const std::chrono::duration<Rep, Period> &duration) {
  2931. detail::duration_to_sec_and_usec(
  2932. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2933. }
  2934. template <class Rep, class Period>
  2935. inline void ClientImpl::set_max_timeout(
  2936. const std::chrono::duration<Rep, Period> &duration) {
  2937. auto msec =
  2938. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2939. set_max_timeout(msec);
  2940. }
  2941. template <class Rep, class Period>
  2942. inline void Client::set_connection_timeout(
  2943. const std::chrono::duration<Rep, Period> &duration) {
  2944. cli_->set_connection_timeout(duration);
  2945. }
  2946. template <class Rep, class Period>
  2947. inline void
  2948. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2949. cli_->set_read_timeout(duration);
  2950. }
  2951. template <class Rep, class Period>
  2952. inline void
  2953. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2954. cli_->set_write_timeout(duration);
  2955. }
  2956. inline void Client::set_max_timeout(time_t msec) {
  2957. cli_->set_max_timeout(msec);
  2958. }
  2959. template <class Rep, class Period>
  2960. inline void
  2961. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2962. cli_->set_max_timeout(duration);
  2963. }
  2964. /*
  2965. * Forward declarations and types that will be part of the .h file if split into
  2966. * .h + .cc.
  2967. */
  2968. std::string hosted_at(const std::string &hostname);
  2969. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2970. // JavaScript-style URL encoding/decoding functions
  2971. std::string encode_uri_component(const std::string &value);
  2972. std::string encode_uri(const std::string &value);
  2973. std::string decode_uri_component(const std::string &value);
  2974. std::string decode_uri(const std::string &value);
  2975. // RFC 3986 compliant URL component encoding/decoding functions
  2976. std::string encode_path_component(const std::string &component);
  2977. std::string decode_path_component(const std::string &component);
  2978. std::string encode_query_component(const std::string &component,
  2979. bool space_as_plus = true);
  2980. std::string decode_query_component(const std::string &component,
  2981. bool plus_as_space = true);
  2982. std::string sanitize_filename(const std::string &filename);
  2983. std::string append_query_params(const std::string &path, const Params &params);
  2984. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2985. std::pair<std::string, std::string>
  2986. make_basic_authentication_header(const std::string &username,
  2987. const std::string &password,
  2988. bool is_proxy = false);
  2989. namespace detail {
  2990. #if defined(_WIN32)
  2991. inline std::wstring u8string_to_wstring(const char *s) {
  2992. if (!s) { return std::wstring(); }
  2993. auto len = static_cast<int>(strlen(s));
  2994. if (!len) { return std::wstring(); }
  2995. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2996. if (!wlen) { return std::wstring(); }
  2997. std::wstring ws;
  2998. ws.resize(wlen);
  2999. wlen = ::MultiByteToWideChar(
  3000. CP_UTF8, 0, s, len,
  3001. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  3002. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  3003. return ws;
  3004. }
  3005. #endif
  3006. struct FileStat {
  3007. FileStat(const std::string &path);
  3008. bool is_file() const;
  3009. bool is_dir() const;
  3010. time_t mtime() const;
  3011. size_t size() const;
  3012. private:
  3013. #if defined(_WIN32)
  3014. struct _stat st_;
  3015. #else
  3016. struct stat st_;
  3017. #endif
  3018. int ret_ = -1;
  3019. };
  3020. std::string make_host_and_port_string(const std::string &host, int port,
  3021. bool is_ssl);
  3022. template <typename T>
  3023. bool check_and_write_headers(Stream &strm, Headers &headers, T header_writer,
  3024. Error &error);
  3025. std::string trim_copy(const std::string &s);
  3026. void divide(
  3027. const char *data, std::size_t size, char d,
  3028. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3029. fn);
  3030. void divide(
  3031. const std::string &str, char d,
  3032. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3033. fn);
  3034. void split(const char *b, const char *e, char d,
  3035. std::function<void(const char *, const char *)> fn);
  3036. void split(const char *b, const char *e, char d, size_t m,
  3037. std::function<void(const char *, const char *)> fn);
  3038. bool split_find(const char *b, const char *e, char d,
  3039. std::function<bool(const char *, const char *)> fn);
  3040. bool has_header_token(const Headers &headers, const std::string &key,
  3041. const std::string &token);
  3042. std::string websocket_accept_key(const std::string &client_key);
  3043. bool is_websocket_upgrade(const Request &req);
  3044. bool process_client_socket(
  3045. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3046. time_t write_timeout_sec, time_t write_timeout_usec,
  3047. time_t max_timeout_msec,
  3048. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3049. std::function<bool(Stream &)> callback);
  3050. socket_t create_client_socket(const std::string &host, const std::string &ip,
  3051. int port, int address_family, bool tcp_nodelay,
  3052. bool ipv6_v6only, SocketOptions socket_options,
  3053. time_t connection_timeout_sec,
  3054. time_t connection_timeout_usec,
  3055. time_t read_timeout_sec, time_t read_timeout_usec,
  3056. time_t write_timeout_sec,
  3057. time_t write_timeout_usec,
  3058. const std::string &intf, Error &error);
  3059. const char *get_header_value(const Headers &headers, const std::string &key,
  3060. const char *def, size_t id);
  3061. std::string get_combined_header_value(const Headers &headers,
  3062. const std::string &key);
  3063. std::string params_to_query_str(const Params &params);
  3064. void parse_query_text(const char *data, std::size_t size, Params &params);
  3065. void parse_query_text(const std::string &s, Params &params);
  3066. bool parse_multipart_boundary(const std::string &content_type,
  3067. std::string &boundary);
  3068. bool parse_range_header(const std::string &s, Ranges &ranges);
  3069. bool parse_accept_header(const std::string &s,
  3070. std::vector<std::string> &content_types);
  3071. void parse_disposition_params(const std::string &s, Params &params);
  3072. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  3073. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  3074. EncodingType encoding_type(const Request &req, const std::string &content_type);
  3075. EncodingType encoding_type(const Request &req, const Response &res,
  3076. const std::string &content_type);
  3077. EncodingType encoding_type(const Request &req, const Response &res);
  3078. class BufferStream final : public Stream {
  3079. public:
  3080. BufferStream() = default;
  3081. ~BufferStream() override = default;
  3082. bool is_readable() const override;
  3083. bool wait_readable() const override;
  3084. bool wait_writable() const override;
  3085. ssize_t read(char *ptr, size_t size) override;
  3086. ssize_t write(const char *ptr, size_t size) override;
  3087. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3088. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3089. socket_t socket() const override;
  3090. time_t duration() const override;
  3091. const std::string &get_buffer() const;
  3092. private:
  3093. std::string buffer;
  3094. size_t position = 0;
  3095. };
  3096. class compressor {
  3097. public:
  3098. virtual ~compressor() = default;
  3099. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3100. virtual bool compress(const char *data, size_t data_length, bool last,
  3101. Callback callback) = 0;
  3102. };
  3103. class decompressor {
  3104. public:
  3105. virtual ~decompressor() = default;
  3106. virtual bool is_valid() const = 0;
  3107. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  3108. virtual bool decompress(const char *data, size_t data_length,
  3109. Callback callback) = 0;
  3110. };
  3111. class nocompressor final : public compressor {
  3112. public:
  3113. ~nocompressor() override = default;
  3114. bool compress(const char *data, size_t data_length, bool /*last*/,
  3115. Callback callback) override;
  3116. };
  3117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3118. class gzip_compressor final : public compressor {
  3119. public:
  3120. gzip_compressor();
  3121. ~gzip_compressor() override;
  3122. bool compress(const char *data, size_t data_length, bool last,
  3123. Callback callback) override;
  3124. private:
  3125. bool is_valid_ = false;
  3126. z_stream strm_;
  3127. };
  3128. class gzip_decompressor final : public decompressor {
  3129. public:
  3130. gzip_decompressor();
  3131. ~gzip_decompressor() override;
  3132. bool is_valid() const override;
  3133. bool decompress(const char *data, size_t data_length,
  3134. Callback callback) override;
  3135. private:
  3136. bool is_valid_ = false;
  3137. z_stream strm_;
  3138. };
  3139. #endif
  3140. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3141. class brotli_compressor final : public compressor {
  3142. public:
  3143. brotli_compressor();
  3144. ~brotli_compressor();
  3145. bool compress(const char *data, size_t data_length, bool last,
  3146. Callback callback) override;
  3147. private:
  3148. BrotliEncoderState *state_ = nullptr;
  3149. };
  3150. class brotli_decompressor final : public decompressor {
  3151. public:
  3152. brotli_decompressor();
  3153. ~brotli_decompressor();
  3154. bool is_valid() const override;
  3155. bool decompress(const char *data, size_t data_length,
  3156. Callback callback) override;
  3157. private:
  3158. BrotliDecoderResult decoder_r;
  3159. BrotliDecoderState *decoder_s = nullptr;
  3160. };
  3161. #endif
  3162. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3163. class zstd_compressor : public compressor {
  3164. public:
  3165. zstd_compressor();
  3166. ~zstd_compressor();
  3167. bool compress(const char *data, size_t data_length, bool last,
  3168. Callback callback) override;
  3169. private:
  3170. ZSTD_CCtx *ctx_ = nullptr;
  3171. };
  3172. class zstd_decompressor : public decompressor {
  3173. public:
  3174. zstd_decompressor();
  3175. ~zstd_decompressor();
  3176. bool is_valid() const override;
  3177. bool decompress(const char *data, size_t data_length,
  3178. Callback callback) override;
  3179. private:
  3180. ZSTD_DCtx *ctx_ = nullptr;
  3181. };
  3182. #endif
  3183. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  3184. // to store data. The call can set memory on stack for performance.
  3185. class stream_line_reader {
  3186. public:
  3187. stream_line_reader(Stream &strm, char *fixed_buffer,
  3188. size_t fixed_buffer_size);
  3189. const char *ptr() const;
  3190. size_t size() const;
  3191. bool end_with_crlf() const;
  3192. bool getline();
  3193. private:
  3194. void append(char c);
  3195. void append(const char *data, size_t size);
  3196. Stream &strm_;
  3197. char *fixed_buffer_;
  3198. const size_t fixed_buffer_size_;
  3199. size_t fixed_buffer_used_size_ = 0;
  3200. std::string growable_buffer_;
  3201. };
  3202. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3203. const Headers &src_headers);
  3204. struct ChunkedDecoder {
  3205. Stream &strm;
  3206. size_t chunk_remaining = 0;
  3207. bool finished = false;
  3208. char line_buf[64];
  3209. size_t last_chunk_total = 0;
  3210. size_t last_chunk_offset = 0;
  3211. explicit ChunkedDecoder(Stream &s);
  3212. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  3213. size_t &out_chunk_total);
  3214. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  3215. };
  3216. class mmap {
  3217. public:
  3218. mmap(const char *path);
  3219. ~mmap();
  3220. bool open(const char *path);
  3221. void close();
  3222. bool is_open() const;
  3223. size_t size() const;
  3224. const char *data() const;
  3225. private:
  3226. #if defined(_WIN32)
  3227. HANDLE hFile_ = NULL;
  3228. HANDLE hMapping_ = NULL;
  3229. #else
  3230. int fd_ = -1;
  3231. #endif
  3232. size_t size_ = 0;
  3233. void *addr_ = nullptr;
  3234. bool is_open_empty_file = false;
  3235. };
  3236. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  3237. namespace fields {
  3238. bool is_token_char(char c);
  3239. bool is_token(const std::string &s);
  3240. bool is_field_name(const std::string &s);
  3241. bool is_vchar(char c);
  3242. bool is_obs_text(char c);
  3243. bool is_field_vchar(char c);
  3244. bool is_field_content(const std::string &s);
  3245. bool is_field_value(const std::string &s);
  3246. bool is_field_valid(const std::string &name, const std::string &value);
  3247. bool is_request_target(const std::string &s);
  3248. } // namespace fields
  3249. } // namespace detail
  3250. /*
  3251. * TLS Abstraction Layer Declarations
  3252. */
  3253. #ifdef CPPHTTPLIB_SSL_ENABLED
  3254. // TLS abstraction layer - backend-specific type declarations
  3255. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  3256. namespace tls {
  3257. namespace impl {
  3258. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  3259. // cert/key). This struct is accessible via tls::impl for use in SSL context
  3260. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  3261. struct MbedTlsContext {
  3262. mbedtls_ssl_config conf;
  3263. #ifndef CPPHTTPLIB_MBEDTLS_V4
  3264. // Mbed TLS 4.x uses PSA Crypto's internal RNG; no explicit entropy/DRBG.
  3265. mbedtls_entropy_context entropy;
  3266. mbedtls_ctr_drbg_context ctr_drbg;
  3267. #endif
  3268. mbedtls_x509_crt ca_chain;
  3269. mbedtls_x509_crt own_cert;
  3270. mbedtls_pk_context own_key;
  3271. bool is_server = false;
  3272. bool verify_client = false;
  3273. bool has_verify_callback = false;
  3274. MbedTlsContext();
  3275. ~MbedTlsContext();
  3276. MbedTlsContext(const MbedTlsContext &) = delete;
  3277. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  3278. };
  3279. } // namespace impl
  3280. } // namespace tls
  3281. #endif
  3282. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  3283. namespace tls {
  3284. namespace impl {
  3285. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  3286. // This struct is accessible via tls::impl for use in SSL context
  3287. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  3288. struct WolfSSLContext {
  3289. WOLFSSL_CTX *ctx = nullptr;
  3290. bool is_server = false;
  3291. bool verify_client = false;
  3292. bool has_verify_callback = false;
  3293. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  3294. WolfSSLContext();
  3295. ~WolfSSLContext();
  3296. WolfSSLContext(const WolfSSLContext &) = delete;
  3297. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  3298. };
  3299. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  3300. struct WolfSSLCAStore {
  3301. std::string pem_data;
  3302. };
  3303. } // namespace impl
  3304. } // namespace tls
  3305. #endif
  3306. #endif // CPPHTTPLIB_SSL_ENABLED
  3307. namespace stream {
  3308. class Result {
  3309. public:
  3310. Result();
  3311. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  3312. Result(Result &&other) noexcept;
  3313. Result &operator=(Result &&other) noexcept;
  3314. Result(const Result &) = delete;
  3315. Result &operator=(const Result &) = delete;
  3316. // Response info
  3317. bool is_valid() const;
  3318. explicit operator bool() const;
  3319. int status() const;
  3320. const Headers &headers() const;
  3321. std::string get_header_value(const std::string &key,
  3322. const char *def = "") const;
  3323. bool has_header(const std::string &key) const;
  3324. Error error() const;
  3325. Error read_error() const;
  3326. bool has_read_error() const;
  3327. // Stream reading
  3328. bool next();
  3329. const char *data() const;
  3330. size_t size() const;
  3331. std::string read_all();
  3332. private:
  3333. ClientImpl::StreamHandle handle_;
  3334. std::string buffer_;
  3335. size_t current_size_ = 0;
  3336. size_t chunk_size_;
  3337. bool finished_ = false;
  3338. };
  3339. // GET
  3340. template <typename ClientType>
  3341. inline Result Get(ClientType &cli, const std::string &path,
  3342. size_t chunk_size = 8192) {
  3343. return Result{cli.open_stream("GET", path), chunk_size};
  3344. }
  3345. template <typename ClientType>
  3346. inline Result Get(ClientType &cli, const std::string &path,
  3347. const Headers &headers, size_t chunk_size = 8192) {
  3348. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  3349. }
  3350. template <typename ClientType>
  3351. inline Result Get(ClientType &cli, const std::string &path,
  3352. const Params &params, size_t chunk_size = 8192) {
  3353. return Result{cli.open_stream("GET", path, params), chunk_size};
  3354. }
  3355. template <typename ClientType>
  3356. inline Result Get(ClientType &cli, const std::string &path,
  3357. const Params &params, const Headers &headers,
  3358. size_t chunk_size = 8192) {
  3359. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  3360. }
  3361. // POST
  3362. template <typename ClientType>
  3363. inline Result Post(ClientType &cli, const std::string &path,
  3364. const std::string &body, const std::string &content_type,
  3365. size_t chunk_size = 8192) {
  3366. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  3367. chunk_size};
  3368. }
  3369. template <typename ClientType>
  3370. inline Result Post(ClientType &cli, const std::string &path,
  3371. const Headers &headers, const std::string &body,
  3372. const std::string &content_type, size_t chunk_size = 8192) {
  3373. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  3374. chunk_size};
  3375. }
  3376. template <typename ClientType>
  3377. inline Result Post(ClientType &cli, const std::string &path,
  3378. const Params &params, const std::string &body,
  3379. const std::string &content_type, size_t chunk_size = 8192) {
  3380. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  3381. chunk_size};
  3382. }
  3383. template <typename ClientType>
  3384. inline Result Post(ClientType &cli, const std::string &path,
  3385. const Params &params, const Headers &headers,
  3386. const std::string &body, const std::string &content_type,
  3387. size_t chunk_size = 8192) {
  3388. return Result{
  3389. cli.open_stream("POST", path, params, headers, body, content_type),
  3390. chunk_size};
  3391. }
  3392. // PUT
  3393. template <typename ClientType>
  3394. inline Result Put(ClientType &cli, const std::string &path,
  3395. const std::string &body, const std::string &content_type,
  3396. size_t chunk_size = 8192) {
  3397. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  3398. chunk_size};
  3399. }
  3400. template <typename ClientType>
  3401. inline Result Put(ClientType &cli, const std::string &path,
  3402. const Headers &headers, const std::string &body,
  3403. const std::string &content_type, size_t chunk_size = 8192) {
  3404. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  3405. chunk_size};
  3406. }
  3407. template <typename ClientType>
  3408. inline Result Put(ClientType &cli, const std::string &path,
  3409. const Params &params, const std::string &body,
  3410. const std::string &content_type, size_t chunk_size = 8192) {
  3411. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  3412. chunk_size};
  3413. }
  3414. template <typename ClientType>
  3415. inline Result Put(ClientType &cli, const std::string &path,
  3416. const Params &params, const Headers &headers,
  3417. const std::string &body, const std::string &content_type,
  3418. size_t chunk_size = 8192) {
  3419. return Result{
  3420. cli.open_stream("PUT", path, params, headers, body, content_type),
  3421. chunk_size};
  3422. }
  3423. // PATCH
  3424. template <typename ClientType>
  3425. inline Result Patch(ClientType &cli, const std::string &path,
  3426. const std::string &body, const std::string &content_type,
  3427. size_t chunk_size = 8192) {
  3428. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  3429. chunk_size};
  3430. }
  3431. template <typename ClientType>
  3432. inline Result Patch(ClientType &cli, const std::string &path,
  3433. const Headers &headers, const std::string &body,
  3434. const std::string &content_type, size_t chunk_size = 8192) {
  3435. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  3436. chunk_size};
  3437. }
  3438. template <typename ClientType>
  3439. inline Result Patch(ClientType &cli, const std::string &path,
  3440. const Params &params, const std::string &body,
  3441. const std::string &content_type, size_t chunk_size = 8192) {
  3442. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  3443. chunk_size};
  3444. }
  3445. template <typename ClientType>
  3446. inline Result Patch(ClientType &cli, const std::string &path,
  3447. const Params &params, const Headers &headers,
  3448. const std::string &body, const std::string &content_type,
  3449. size_t chunk_size = 8192) {
  3450. return Result{
  3451. cli.open_stream("PATCH", path, params, headers, body, content_type),
  3452. chunk_size};
  3453. }
  3454. // DELETE
  3455. template <typename ClientType>
  3456. inline Result Delete(ClientType &cli, const std::string &path,
  3457. size_t chunk_size = 8192) {
  3458. return Result{cli.open_stream("DELETE", path), chunk_size};
  3459. }
  3460. template <typename ClientType>
  3461. inline Result Delete(ClientType &cli, const std::string &path,
  3462. const Headers &headers, size_t chunk_size = 8192) {
  3463. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  3464. }
  3465. template <typename ClientType>
  3466. inline Result Delete(ClientType &cli, const std::string &path,
  3467. const std::string &body, const std::string &content_type,
  3468. size_t chunk_size = 8192) {
  3469. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3470. chunk_size};
  3471. }
  3472. template <typename ClientType>
  3473. inline Result Delete(ClientType &cli, const std::string &path,
  3474. const Headers &headers, const std::string &body,
  3475. const std::string &content_type,
  3476. size_t chunk_size = 8192) {
  3477. return Result{
  3478. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3479. chunk_size};
  3480. }
  3481. template <typename ClientType>
  3482. inline Result Delete(ClientType &cli, const std::string &path,
  3483. const Params &params, size_t chunk_size = 8192) {
  3484. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3485. }
  3486. template <typename ClientType>
  3487. inline Result Delete(ClientType &cli, const std::string &path,
  3488. const Params &params, const Headers &headers,
  3489. size_t chunk_size = 8192) {
  3490. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3491. }
  3492. template <typename ClientType>
  3493. inline Result Delete(ClientType &cli, const std::string &path,
  3494. const Params &params, const std::string &body,
  3495. const std::string &content_type,
  3496. size_t chunk_size = 8192) {
  3497. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3498. chunk_size};
  3499. }
  3500. template <typename ClientType>
  3501. inline Result Delete(ClientType &cli, const std::string &path,
  3502. const Params &params, const Headers &headers,
  3503. const std::string &body, const std::string &content_type,
  3504. size_t chunk_size = 8192) {
  3505. return Result{
  3506. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3507. chunk_size};
  3508. }
  3509. // HEAD
  3510. template <typename ClientType>
  3511. inline Result Head(ClientType &cli, const std::string &path,
  3512. size_t chunk_size = 8192) {
  3513. return Result{cli.open_stream("HEAD", path), chunk_size};
  3514. }
  3515. template <typename ClientType>
  3516. inline Result Head(ClientType &cli, const std::string &path,
  3517. const Headers &headers, size_t chunk_size = 8192) {
  3518. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3519. }
  3520. template <typename ClientType>
  3521. inline Result Head(ClientType &cli, const std::string &path,
  3522. const Params &params, size_t chunk_size = 8192) {
  3523. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3524. }
  3525. template <typename ClientType>
  3526. inline Result Head(ClientType &cli, const std::string &path,
  3527. const Params &params, const Headers &headers,
  3528. size_t chunk_size = 8192) {
  3529. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3530. }
  3531. // OPTIONS
  3532. template <typename ClientType>
  3533. inline Result Options(ClientType &cli, const std::string &path,
  3534. size_t chunk_size = 8192) {
  3535. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3536. }
  3537. template <typename ClientType>
  3538. inline Result Options(ClientType &cli, const std::string &path,
  3539. const Headers &headers, size_t chunk_size = 8192) {
  3540. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3541. }
  3542. template <typename ClientType>
  3543. inline Result Options(ClientType &cli, const std::string &path,
  3544. const Params &params, size_t chunk_size = 8192) {
  3545. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3546. }
  3547. template <typename ClientType>
  3548. inline Result Options(ClientType &cli, const std::string &path,
  3549. const Params &params, const Headers &headers,
  3550. size_t chunk_size = 8192) {
  3551. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3552. }
  3553. } // namespace stream
  3554. namespace sse {
  3555. struct SSEMessage {
  3556. std::string event; // Event type (default: "message")
  3557. std::string data; // Event payload
  3558. std::string id; // Event ID for Last-Event-ID header
  3559. SSEMessage();
  3560. void clear();
  3561. };
  3562. class SSEClient {
  3563. public:
  3564. using MessageHandler = std::function<void(const SSEMessage &)>;
  3565. using ErrorHandler = std::function<void(Error)>;
  3566. using OpenHandler = std::function<void()>;
  3567. SSEClient(Client &client, const std::string &path);
  3568. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3569. ~SSEClient();
  3570. SSEClient(const SSEClient &) = delete;
  3571. SSEClient &operator=(const SSEClient &) = delete;
  3572. // Event handlers
  3573. SSEClient &on_message(MessageHandler handler);
  3574. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3575. SSEClient &on_open(OpenHandler handler);
  3576. SSEClient &on_error(ErrorHandler handler);
  3577. SSEClient &set_reconnect_interval(int ms);
  3578. SSEClient &set_max_reconnect_attempts(int n);
  3579. // Update headers (thread-safe)
  3580. SSEClient &set_headers(const Headers &headers);
  3581. // State accessors
  3582. bool is_connected() const;
  3583. const std::string &last_event_id() const;
  3584. // Blocking start - runs event loop with auto-reconnect
  3585. void start();
  3586. // Non-blocking start - runs in background thread
  3587. void start_async();
  3588. // Stop the client (thread-safe)
  3589. void stop();
  3590. private:
  3591. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3592. void run_event_loop();
  3593. void dispatch_event(const SSEMessage &msg);
  3594. bool should_reconnect(int count) const;
  3595. void wait_for_reconnect();
  3596. // Client and path
  3597. Client &client_;
  3598. std::string path_;
  3599. Headers headers_;
  3600. mutable std::mutex headers_mutex_;
  3601. // Callbacks
  3602. MessageHandler on_message_;
  3603. std::map<std::string, MessageHandler> event_handlers_;
  3604. OpenHandler on_open_;
  3605. ErrorHandler on_error_;
  3606. // Configuration
  3607. int reconnect_interval_ms_ = 3000;
  3608. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3609. // State
  3610. std::atomic<bool> running_{false};
  3611. std::atomic<bool> connected_{false};
  3612. std::string last_event_id_;
  3613. // Async support
  3614. std::thread async_thread_;
  3615. };
  3616. } // namespace sse
  3617. namespace ws {
  3618. enum class Opcode : uint8_t {
  3619. Continuation = 0x0,
  3620. Text = 0x1,
  3621. Binary = 0x2,
  3622. Close = 0x8,
  3623. Ping = 0x9,
  3624. Pong = 0xA,
  3625. };
  3626. enum class CloseStatus : uint16_t {
  3627. Normal = 1000,
  3628. GoingAway = 1001,
  3629. ProtocolError = 1002,
  3630. UnsupportedData = 1003,
  3631. NoStatus = 1005,
  3632. Abnormal = 1006,
  3633. InvalidPayload = 1007,
  3634. PolicyViolation = 1008,
  3635. MessageTooBig = 1009,
  3636. MandatoryExtension = 1010,
  3637. InternalError = 1011,
  3638. };
  3639. // Timeout is returned only when a read timeout was set and it elapsed before
  3640. // any byte of a frame arrived: nothing was consumed and the connection is
  3641. // still open, so the caller can send on it and read again. `msg` is left
  3642. // untouched, so a `while (ws.read(msg))` loop must not treat it as a message.
  3643. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2, Timeout = 3 };
  3644. // Result of WebSocketClient::connect(). Truthy only when the WebSocket
  3645. // upgrade handshake fully succeeded. On failure error() identifies the
  3646. // failing layer; status()/headers() expose the server's upgrade response
  3647. // when one was received (status() is -1 otherwise).
  3648. class Result {
  3649. public:
  3650. Result() = default;
  3651. Result(Error err, int status, Headers &&headers)
  3652. : err_(err), status_(status), headers_(std::move(headers)) {}
  3653. explicit operator bool() const { return err_ == Error::Success; }
  3654. Error error() const { return err_; }
  3655. // Upgrade response info
  3656. int status() const { return status_; }
  3657. const Headers &headers() const { return headers_; }
  3658. std::string get_header_value(const std::string &key,
  3659. const char *def = "") const {
  3660. return detail::get_header_value(headers_, key, def, 0);
  3661. }
  3662. bool has_header(const std::string &key) const {
  3663. return headers_.find(key) != headers_.end();
  3664. }
  3665. #ifdef CPPHTTPLIB_SSL_ENABLED
  3666. Result(Error err, int status, Headers &&headers, int ssl_error,
  3667. uint64_t ssl_backend_error)
  3668. : err_(err), status_(status), headers_(std::move(headers)),
  3669. ssl_error_(ssl_error), ssl_backend_error_(ssl_backend_error) {}
  3670. int ssl_error() const { return ssl_error_; }
  3671. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  3672. #endif
  3673. private:
  3674. Error err_ = Error::Unknown; // a default-constructed Result is falsy
  3675. int status_ = -1;
  3676. Headers headers_;
  3677. #ifdef CPPHTTPLIB_SSL_ENABLED
  3678. int ssl_error_ = 0;
  3679. uint64_t ssl_backend_error_ = 0;
  3680. #endif
  3681. };
  3682. class WebSocket {
  3683. public:
  3684. WebSocket(const WebSocket &) = delete;
  3685. WebSocket &operator=(const WebSocket &) = delete;
  3686. ~WebSocket();
  3687. ReadResult read(std::string &msg);
  3688. bool send(const std::string &data);
  3689. bool send(const char *data, size_t len);
  3690. void close(CloseStatus status = CloseStatus::Normal,
  3691. const std::string &reason = "");
  3692. const Request &request() const;
  3693. bool is_open() const;
  3694. // Bound how long read() waits before returning Timeout. 0 waits forever.
  3695. // A server handler owns its connection's timeout this way; a client sets it
  3696. // through WebSocketClient. Safe to call while another thread is in read().
  3697. //
  3698. // Only a timeout set here is reported as Timeout. The compile-time default
  3699. // (CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND) is a backstop rather
  3700. // than a request for control, so when it elapses read() returns Fail and
  3701. // closes the connection, and `while (ws.read(msg))` ends as it always has.
  3702. void set_read_timeout(time_t sec, time_t usec = 0);
  3703. template <class Rep, class Period>
  3704. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  3705. private:
  3706. friend class httplib::Server;
  3707. friend class WebSocketClient;
  3708. WebSocket(
  3709. Stream &strm, const Request &req, bool is_server,
  3710. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3711. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3712. : strm_(strm), req_(req), is_server_(is_server),
  3713. ping_interval_sec_(ping_interval_sec),
  3714. max_missed_pongs_(max_missed_pongs) {
  3715. start_heartbeat();
  3716. }
  3717. WebSocket(
  3718. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3719. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3720. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3721. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3722. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3723. max_missed_pongs_(max_missed_pongs) {
  3724. start_heartbeat();
  3725. }
  3726. void start_heartbeat();
  3727. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3728. Stream &strm_;
  3729. std::unique_ptr<Stream> owned_strm_;
  3730. Request req_;
  3731. bool is_server_;
  3732. time_t ping_interval_sec_;
  3733. int max_missed_pongs_;
  3734. int unacked_pings_ = 0;
  3735. std::atomic<bool> closed_{false};
  3736. // Set once the caller has bounded read() through set_read_timeout(). Until
  3737. // then the timeout in effect is the compile-time default, and elapsing it
  3738. // is a failure that closes the connection, not a Timeout.
  3739. std::atomic<bool> read_timeout_set_{false};
  3740. std::mutex write_mutex_;
  3741. // Owned by whichever thread is parsing frames off strm_. Only one thread
  3742. // may do so: read_websocket_frame() reads a payload until it has the whole
  3743. // declared length, so a second parser stealing bytes silently corrupts the
  3744. // message the first one is assembling.
  3745. std::mutex read_mutex_;
  3746. std::thread ping_thread_;
  3747. std::mutex ping_mutex_;
  3748. std::condition_variable ping_cv_;
  3749. };
  3750. class WebSocketClient {
  3751. public:
  3752. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3753. const Headers &headers = {});
  3754. ~WebSocketClient();
  3755. WebSocketClient(const WebSocketClient &) = delete;
  3756. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3757. bool is_valid() const;
  3758. Result connect();
  3759. ReadResult read(std::string &msg);
  3760. bool send(const std::string &data);
  3761. bool send(const char *data, size_t len);
  3762. void close(CloseStatus status = CloseStatus::Normal,
  3763. const std::string &reason = "");
  3764. bool is_open() const;
  3765. const std::string &subprotocol() const;
  3766. void set_read_timeout(time_t sec, time_t usec = 0);
  3767. template <class Rep, class Period>
  3768. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  3769. void set_write_timeout(time_t sec, time_t usec = 0);
  3770. template <class Rep, class Period>
  3771. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  3772. void set_websocket_ping_interval(time_t sec);
  3773. void set_websocket_max_missed_pongs(int count);
  3774. void set_tcp_nodelay(bool on);
  3775. void set_address_family(int family);
  3776. void set_ipv6_v6only(bool on);
  3777. void set_socket_options(SocketOptions socket_options);
  3778. void set_connection_timeout(time_t sec, time_t usec = 0);
  3779. template <class Rep, class Period>
  3780. void
  3781. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  3782. void set_interface(const std::string &intf);
  3783. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3784. #ifdef CPPHTTPLIB_SSL_ENABLED
  3785. struct PemMemory {
  3786. const char *cert_pem;
  3787. size_t cert_pem_len;
  3788. const char *key_pem;
  3789. size_t key_pem_len;
  3790. const char *private_key_password;
  3791. };
  3792. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3793. const PemMemory &pem, const Headers &headers = {});
  3794. void set_ca_cert_path(const std::string &ca_cert_file_path,
  3795. const std::string &ca_cert_dir_path = std::string());
  3796. void set_ca_cert_store(tls::ca_store_t store);
  3797. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3798. void enable_server_certificate_verification(bool enabled);
  3799. void enable_server_hostname_verification(bool enabled);
  3800. void enable_system_ca(bool enabled);
  3801. #endif
  3802. private:
  3803. void shutdown_and_close();
  3804. bool create_stream(std::unique_ptr<Stream> &strm, Error &error,
  3805. int &ssl_error, uint64_t &ssl_backend_error);
  3806. void prepare_default_headers(Request &req);
  3807. std::string host_;
  3808. int port_;
  3809. std::string path_;
  3810. Headers headers_;
  3811. std::string subprotocol_;
  3812. bool is_valid_ = false;
  3813. socket_t sock_ = INVALID_SOCKET;
  3814. std::unique_ptr<WebSocket> ws_;
  3815. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND;
  3816. time_t read_timeout_usec_ = 0;
  3817. bool read_timeout_set_ = false; // see WebSocket::read_timeout_set_
  3818. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3819. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3820. time_t websocket_ping_interval_sec_ =
  3821. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3822. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3823. int address_family_ = AF_UNSPEC;
  3824. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3825. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3826. SocketOptions socket_options_ = nullptr;
  3827. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3828. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3829. std::string interface_;
  3830. // Hostname to connection target map. The value is an IP literal or another
  3831. // hostname; only the connection target changes, never the identity.
  3832. std::map<std::string, std::string> addr_map_;
  3833. #ifdef CPPHTTPLIB_SSL_ENABLED
  3834. bool is_ssl_ = false;
  3835. tls::ctx_t tls_ctx_ = nullptr;
  3836. tls::session_t tls_session_ = nullptr;
  3837. std::string ca_cert_file_path_;
  3838. std::string ca_cert_dir_path_;
  3839. bool custom_ca_loaded_ = false;
  3840. bool certs_loaded_ = false;
  3841. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3842. bool server_certificate_verification_ = true;
  3843. bool server_hostname_verification_ = true;
  3844. #endif
  3845. };
  3846. template <class Rep, class Period>
  3847. inline void WebSocket::set_read_timeout(
  3848. const std::chrono::duration<Rep, Period> &duration) {
  3849. detail::duration_to_sec_and_usec(
  3850. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3851. }
  3852. template <class Rep, class Period>
  3853. inline void WebSocketClient::set_read_timeout(
  3854. const std::chrono::duration<Rep, Period> &duration) {
  3855. detail::duration_to_sec_and_usec(
  3856. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  3857. }
  3858. template <class Rep, class Period>
  3859. inline void WebSocketClient::set_write_timeout(
  3860. const std::chrono::duration<Rep, Period> &duration) {
  3861. detail::duration_to_sec_and_usec(
  3862. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  3863. }
  3864. template <class Rep, class Period>
  3865. inline void WebSocketClient::set_connection_timeout(
  3866. const std::chrono::duration<Rep, Period> &duration) {
  3867. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  3868. set_connection_timeout(sec, usec);
  3869. });
  3870. }
  3871. namespace impl {
  3872. bool is_valid_utf8(const std::string &s);
  3873. // Three states, because a failure that consumed bytes and one that consumed
  3874. // none are not the same thing: the first has left the stream in the middle of
  3875. // a frame and the connection cannot be reused, the second can just be retried.
  3876. enum class FrameRead { Ok, Fail, Timeout };
  3877. FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  3878. std::string &payload, bool &fin,
  3879. bool expect_masked, size_t max_len);
  3880. } // namespace impl
  3881. } // namespace ws
  3882. // ----------------------------------------------------------------------------
  3883. /*
  3884. * Implementation that will be part of the .cc file if split into .h + .cc.
  3885. */
  3886. namespace stream {
  3887. // stream::Result implementations
  3888. inline Result::Result() : chunk_size_(8192) {}
  3889. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3890. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3891. inline Result::Result(Result &&other) noexcept
  3892. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3893. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3894. finished_(other.finished_) {
  3895. other.current_size_ = 0;
  3896. other.finished_ = true;
  3897. }
  3898. inline Result &Result::operator=(Result &&other) noexcept {
  3899. if (this != &other) {
  3900. handle_ = std::move(other.handle_);
  3901. buffer_ = std::move(other.buffer_);
  3902. current_size_ = other.current_size_;
  3903. chunk_size_ = other.chunk_size_;
  3904. finished_ = other.finished_;
  3905. other.current_size_ = 0;
  3906. other.finished_ = true;
  3907. }
  3908. return *this;
  3909. }
  3910. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3911. inline Result::operator bool() const { return is_valid(); }
  3912. inline int Result::status() const {
  3913. return handle_.response ? handle_.response->status : -1;
  3914. }
  3915. inline const Headers &Result::headers() const {
  3916. static const Headers empty_headers;
  3917. return handle_.response ? handle_.response->headers : empty_headers;
  3918. }
  3919. inline std::string Result::get_header_value(const std::string &key,
  3920. const char *def) const {
  3921. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3922. }
  3923. inline bool Result::has_header(const std::string &key) const {
  3924. return handle_.response ? handle_.response->has_header(key) : false;
  3925. }
  3926. inline Error Result::error() const { return handle_.error; }
  3927. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3928. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3929. inline bool Result::next() {
  3930. if (!handle_.is_valid() || finished_) { return false; }
  3931. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3932. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3933. if (n > 0) {
  3934. current_size_ = static_cast<size_t>(n);
  3935. return true;
  3936. }
  3937. current_size_ = 0;
  3938. finished_ = true;
  3939. return false;
  3940. }
  3941. inline const char *Result::data() const { return buffer_.data(); }
  3942. inline size_t Result::size() const { return current_size_; }
  3943. inline std::string Result::read_all() {
  3944. std::string result;
  3945. while (next()) {
  3946. result.append(data(), size());
  3947. }
  3948. return result;
  3949. }
  3950. } // namespace stream
  3951. namespace sse {
  3952. // SSEMessage implementations
  3953. inline SSEMessage::SSEMessage() : event("message") {}
  3954. inline void SSEMessage::clear() {
  3955. event = "message";
  3956. data.clear();
  3957. id.clear();
  3958. }
  3959. // SSEClient implementations
  3960. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3961. : client_(client), path_(path) {}
  3962. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3963. const Headers &headers)
  3964. : client_(client), path_(path), headers_(headers) {}
  3965. inline SSEClient::~SSEClient() { stop(); }
  3966. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3967. on_message_ = std::move(handler);
  3968. return *this;
  3969. }
  3970. inline SSEClient &SSEClient::on_event(const std::string &type,
  3971. MessageHandler handler) {
  3972. event_handlers_[type] = std::move(handler);
  3973. return *this;
  3974. }
  3975. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3976. on_open_ = std::move(handler);
  3977. return *this;
  3978. }
  3979. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3980. on_error_ = std::move(handler);
  3981. return *this;
  3982. }
  3983. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3984. reconnect_interval_ms_ = ms;
  3985. return *this;
  3986. }
  3987. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3988. max_reconnect_attempts_ = n;
  3989. return *this;
  3990. }
  3991. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3992. std::lock_guard<std::mutex> lock(headers_mutex_);
  3993. headers_ = headers;
  3994. return *this;
  3995. }
  3996. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3997. inline const std::string &SSEClient::last_event_id() const {
  3998. return last_event_id_;
  3999. }
  4000. inline void SSEClient::start() {
  4001. running_.store(true);
  4002. run_event_loop();
  4003. }
  4004. inline void SSEClient::start_async() {
  4005. running_.store(true);
  4006. async_thread_ = std::thread([this]() { run_event_loop(); });
  4007. }
  4008. inline void SSEClient::stop() {
  4009. running_.store(false);
  4010. client_.stop(); // Cancel any pending operations
  4011. if (async_thread_.joinable()) { async_thread_.join(); }
  4012. }
  4013. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  4014. int &retry_ms) {
  4015. // Blank line signals end of event
  4016. if (line.empty() || line == "\r") { return true; }
  4017. // Lines starting with ':' are comments (ignored)
  4018. if (!line.empty() && line[0] == ':') { return false; }
  4019. // Find the colon separator
  4020. auto colon_pos = line.find(':');
  4021. if (colon_pos == std::string::npos) {
  4022. // Line with no colon is treated as field name with empty value
  4023. return false;
  4024. }
  4025. auto field = line.substr(0, colon_pos);
  4026. std::string value;
  4027. // Value starts after colon, skip optional single space
  4028. if (colon_pos + 1 < line.size()) {
  4029. auto value_start = colon_pos + 1;
  4030. if (line[value_start] == ' ') { value_start++; }
  4031. value = line.substr(value_start);
  4032. // Remove trailing \r if present
  4033. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  4034. }
  4035. // Handle known fields
  4036. if (field == "event") {
  4037. msg.event = value;
  4038. } else if (field == "data") {
  4039. // Multiple data lines are concatenated with newlines
  4040. if (!msg.data.empty()) { msg.data += "\n"; }
  4041. msg.data += value;
  4042. } else if (field == "id") {
  4043. // Empty id is valid (clears the last event ID)
  4044. msg.id = value;
  4045. } else if (field == "retry") {
  4046. // Parse retry interval in milliseconds
  4047. {
  4048. int v = 0;
  4049. auto res =
  4050. detail::from_chars(value.data(), value.data() + value.size(), v);
  4051. if (res.ec == std::errc{}) { retry_ms = v; }
  4052. }
  4053. }
  4054. // Unknown fields are ignored per SSE spec
  4055. return false;
  4056. }
  4057. inline void SSEClient::run_event_loop() {
  4058. auto reconnect_count = 0;
  4059. while (running_.load()) {
  4060. // Build headers, including Last-Event-ID if we have one
  4061. Headers request_headers;
  4062. {
  4063. std::lock_guard<std::mutex> lock(headers_mutex_);
  4064. request_headers = headers_;
  4065. }
  4066. if (!last_event_id_.empty()) {
  4067. request_headers.emplace("Last-Event-ID", last_event_id_);
  4068. }
  4069. // Open streaming connection
  4070. auto result = stream::Get(client_, path_, request_headers);
  4071. // Connection error handling
  4072. if (!result) {
  4073. connected_.store(false);
  4074. if (on_error_) { on_error_(result.error()); }
  4075. if (!should_reconnect(reconnect_count)) { break; }
  4076. wait_for_reconnect();
  4077. reconnect_count++;
  4078. continue;
  4079. }
  4080. if (result.status() != StatusCode::OK_200) {
  4081. connected_.store(false);
  4082. if (on_error_) { on_error_(Error::Connection); }
  4083. // For certain errors, don't reconnect.
  4084. // Note: 401 is intentionally absent so that handlers can refresh
  4085. // credentials via set_headers() and let the client reconnect.
  4086. if (result.status() == StatusCode::NoContent_204 ||
  4087. result.status() == StatusCode::NotFound_404 ||
  4088. result.status() == StatusCode::Forbidden_403) {
  4089. break;
  4090. }
  4091. if (!should_reconnect(reconnect_count)) { break; }
  4092. wait_for_reconnect();
  4093. reconnect_count++;
  4094. continue;
  4095. }
  4096. // Connection successful
  4097. connected_.store(true);
  4098. reconnect_count = 0;
  4099. if (on_open_) { on_open_(); }
  4100. // Event receiving loop
  4101. std::string buffer;
  4102. SSEMessage current_msg;
  4103. while (running_.load() && result.next()) {
  4104. buffer.append(result.data(), result.size());
  4105. // Process complete lines in the buffer
  4106. size_t line_start = 0;
  4107. size_t newline_pos;
  4108. while ((newline_pos = buffer.find('\n', line_start)) !=
  4109. std::string::npos) {
  4110. auto line = buffer.substr(line_start, newline_pos - line_start);
  4111. line_start = newline_pos + 1;
  4112. // Parse the line and check if event is complete
  4113. auto event_complete =
  4114. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  4115. if (event_complete && !current_msg.data.empty()) {
  4116. // Update last_event_id for reconnection
  4117. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  4118. // Dispatch event to appropriate handler
  4119. dispatch_event(current_msg);
  4120. current_msg.clear();
  4121. }
  4122. }
  4123. // Keep unprocessed data in buffer
  4124. buffer.erase(0, line_start);
  4125. }
  4126. // Connection ended
  4127. connected_.store(false);
  4128. if (!running_.load()) { break; }
  4129. // Check for read errors
  4130. if (result.has_read_error()) {
  4131. if (on_error_) { on_error_(result.read_error()); }
  4132. }
  4133. if (!should_reconnect(reconnect_count)) { break; }
  4134. wait_for_reconnect();
  4135. reconnect_count++;
  4136. }
  4137. connected_.store(false);
  4138. }
  4139. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  4140. // Check for specific event type handler first
  4141. auto it = event_handlers_.find(msg.event);
  4142. if (it != event_handlers_.end()) {
  4143. it->second(msg);
  4144. return;
  4145. }
  4146. // Fall back to generic message handler
  4147. if (on_message_) { on_message_(msg); }
  4148. }
  4149. inline bool SSEClient::should_reconnect(int count) const {
  4150. if (!running_.load()) { return false; }
  4151. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  4152. return count < max_reconnect_attempts_;
  4153. }
  4154. inline void SSEClient::wait_for_reconnect() {
  4155. // Use small increments to check running_ flag frequently
  4156. auto waited = 0;
  4157. while (running_.load() && waited < reconnect_interval_ms_) {
  4158. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4159. waited += 100;
  4160. }
  4161. }
  4162. } // namespace sse
  4163. #ifdef CPPHTTPLIB_SSL_ENABLED
  4164. /*
  4165. * TLS abstraction layer - internal function declarations
  4166. * These are implementation details and not part of the public API.
  4167. */
  4168. namespace tls {
  4169. // Client context
  4170. ctx_t create_client_context();
  4171. void free_context(ctx_t ctx);
  4172. bool set_min_version(ctx_t ctx, Version version);
  4173. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  4174. bool load_ca_file(ctx_t ctx, const char *file_path);
  4175. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  4176. bool load_system_certs(ctx_t ctx);
  4177. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4178. const char *password);
  4179. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  4180. const char *key_path, const char *password);
  4181. // Server context
  4182. ctx_t create_server_context();
  4183. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  4184. const char *password);
  4185. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  4186. const char *key_path, const char *password);
  4187. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  4188. void set_verify_client(ctx_t ctx, bool require);
  4189. // Session management
  4190. session_t create_session(ctx_t ctx, socket_t sock);
  4191. void free_session(session_t session);
  4192. bool set_sni(session_t session, const char *hostname, bool verify_hostname);
  4193. // Handshake (non-blocking capable)
  4194. TlsError connect(session_t session);
  4195. TlsError accept(session_t session);
  4196. // Handshake with timeout (blocking until timeout)
  4197. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4198. time_t timeout_usec, TlsError *err);
  4199. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  4200. time_t timeout_usec, TlsError *err);
  4201. // I/O (non-blocking capable)
  4202. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  4203. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  4204. int pending(const_session_t session);
  4205. void shutdown(session_t session, bool graceful);
  4206. // Connection state
  4207. bool is_peer_closed(session_t session, socket_t sock);
  4208. // Certificate verification
  4209. cert_t get_peer_cert(const_session_t session);
  4210. void free_cert(cert_t cert);
  4211. bool verify_hostname(cert_t cert, const char *hostname);
  4212. uint64_t hostname_mismatch_code();
  4213. long get_verify_result(const_session_t session);
  4214. // Certificate introspection
  4215. std::string get_cert_subject_cn(cert_t cert);
  4216. std::string get_cert_issuer_name(cert_t cert);
  4217. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  4218. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  4219. std::string get_cert_serial(cert_t cert);
  4220. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  4221. const char *get_sni(const_session_t session);
  4222. // CA store management
  4223. ca_store_t create_ca_store(const char *pem, size_t len);
  4224. void free_ca_store(ca_store_t store);
  4225. bool set_ca_store(ctx_t ctx, ca_store_t store);
  4226. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  4227. std::vector<std::string> get_ca_names(ctx_t ctx);
  4228. // Dynamic certificate update (for servers)
  4229. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  4230. const char *password);
  4231. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  4232. // Certificate verification callback
  4233. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  4234. long get_verify_error(const_session_t session);
  4235. std::string verify_error_string(long error_code);
  4236. // TlsError information
  4237. uint64_t peek_error();
  4238. uint64_t get_error();
  4239. std::string error_string(uint64_t code);
  4240. } // namespace tls
  4241. #endif // CPPHTTPLIB_SSL_ENABLED
  4242. /*
  4243. * Group 1: detail namespace - Non-SSL utilities
  4244. */
  4245. namespace detail {
  4246. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  4247. const void *optval, socklen_t optlen) {
  4248. return setsockopt(sock, level, optname,
  4249. #ifdef _WIN32
  4250. reinterpret_cast<const char *>(optval),
  4251. #else
  4252. optval,
  4253. #endif
  4254. optlen) == 0;
  4255. }
  4256. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  4257. time_t sec, time_t usec) {
  4258. #ifdef _WIN32
  4259. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  4260. #else
  4261. timeval timeout;
  4262. timeout.tv_sec = static_cast<long>(sec);
  4263. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  4264. #endif
  4265. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  4266. }
  4267. inline bool is_hex(char c, int &v) {
  4268. if (is_ascii_digit(c)) {
  4269. v = c - '0';
  4270. return true;
  4271. } else if ('A' <= c && c <= 'F') {
  4272. v = c - 'A' + 10;
  4273. return true;
  4274. } else if ('a' <= c && c <= 'f') {
  4275. v = c - 'a' + 10;
  4276. return true;
  4277. }
  4278. return false;
  4279. }
  4280. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  4281. int &val) {
  4282. if (i >= s.size()) { return false; }
  4283. val = 0;
  4284. for (; cnt; i++, cnt--) {
  4285. if (!s[i]) { return false; }
  4286. auto v = 0;
  4287. if (is_hex(s[i], v)) {
  4288. val = val * 16 + v;
  4289. } else {
  4290. return false;
  4291. }
  4292. }
  4293. return true;
  4294. }
  4295. inline std::string from_i_to_hex(size_t n) {
  4296. static const auto charset = "0123456789abcdef";
  4297. std::string ret;
  4298. do {
  4299. ret = charset[n & 15] + ret;
  4300. n >>= 4;
  4301. } while (n > 0);
  4302. return ret;
  4303. }
  4304. inline std::string compute_etag(const FileStat &fs,
  4305. const std::string &suffix = std::string()) {
  4306. if (!fs.is_file()) { return std::string(); }
  4307. // If mtime cannot be determined (negative value indicates an error
  4308. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  4309. // value like 0 could collide with a real file that legitimately has
  4310. // mtime == 0 (epoch) and lead to misleading validators.
  4311. auto mtime_raw = fs.mtime();
  4312. if (mtime_raw < 0) { return std::string(); }
  4313. auto mtime = static_cast<size_t>(mtime_raw);
  4314. auto size = fs.size();
  4315. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  4316. from_i_to_hex(size) + suffix + "\"";
  4317. }
  4318. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  4319. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  4320. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  4321. inline std::string file_mtime_to_http_date(time_t mtime) {
  4322. if (mtime < 0) { return std::string(); }
  4323. struct tm tm_buf;
  4324. #ifdef _WIN32
  4325. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  4326. #else
  4327. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  4328. #endif
  4329. char buf[64];
  4330. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  4331. return std::string();
  4332. }
  4333. return std::string(buf);
  4334. }
  4335. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  4336. inline time_t parse_http_date(const std::string &date_str) {
  4337. struct tm tm_buf;
  4338. // Create a classic locale object once for all parsing attempts
  4339. const std::locale classic_locale = std::locale::classic();
  4340. // Try to parse using std::get_time (C++11, cross-platform)
  4341. auto try_parse = [&](const char *fmt) -> bool {
  4342. std::istringstream ss(date_str);
  4343. ss.imbue(classic_locale);
  4344. memset(&tm_buf, 0, sizeof(tm_buf));
  4345. ss >> std::get_time(&tm_buf, fmt);
  4346. return !ss.fail();
  4347. };
  4348. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  4349. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  4350. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  4351. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  4352. // asctime format: "Sun Nov 6 08:49:37 1994"
  4353. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  4354. return static_cast<time_t>(-1);
  4355. }
  4356. }
  4357. }
  4358. #ifdef _WIN32
  4359. return _mkgmtime(&tm_buf);
  4360. #elif defined _AIX
  4361. return mktime(&tm_buf);
  4362. #else
  4363. return timegm(&tm_buf);
  4364. #endif
  4365. }
  4366. inline bool is_weak_etag(const std::string &s) {
  4367. // Check if the string is a weak ETag (starts with 'W/"')
  4368. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  4369. }
  4370. inline bool is_strong_etag(const std::string &s) {
  4371. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  4372. // chars)
  4373. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  4374. }
  4375. inline size_t to_utf8(int code, char *buff) {
  4376. if (code < 0x0080) {
  4377. buff[0] = static_cast<char>(code & 0x7F);
  4378. return 1;
  4379. } else if (code < 0x0800) {
  4380. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  4381. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  4382. return 2;
  4383. } else if (code < 0xD800) {
  4384. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4385. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4386. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4387. return 3;
  4388. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  4389. return 0;
  4390. } else if (code < 0x10000) {
  4391. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  4392. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4393. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  4394. return 3;
  4395. } else if (code < 0x110000) {
  4396. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  4397. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  4398. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  4399. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  4400. return 4;
  4401. }
  4402. // NOTREACHED
  4403. return 0;
  4404. }
  4405. } // namespace detail
  4406. namespace ws {
  4407. namespace impl {
  4408. inline bool is_valid_utf8(const std::string &s) {
  4409. size_t i = 0;
  4410. auto n = s.size();
  4411. while (i < n) {
  4412. auto c = static_cast<unsigned char>(s[i]);
  4413. size_t len;
  4414. uint32_t cp;
  4415. if (c < 0x80) {
  4416. i++;
  4417. continue;
  4418. } else if ((c & 0xE0) == 0xC0) {
  4419. len = 2;
  4420. cp = c & 0x1F;
  4421. } else if ((c & 0xF0) == 0xE0) {
  4422. len = 3;
  4423. cp = c & 0x0F;
  4424. } else if ((c & 0xF8) == 0xF0) {
  4425. len = 4;
  4426. cp = c & 0x07;
  4427. } else {
  4428. return false;
  4429. }
  4430. if (i + len > n) { return false; }
  4431. for (size_t j = 1; j < len; j++) {
  4432. auto b = static_cast<unsigned char>(s[i + j]);
  4433. if ((b & 0xC0) != 0x80) { return false; }
  4434. cp = (cp << 6) | (b & 0x3F);
  4435. }
  4436. // Overlong encoding check
  4437. if (len == 2 && cp < 0x80) { return false; }
  4438. if (len == 3 && cp < 0x800) { return false; }
  4439. if (len == 4 && cp < 0x10000) { return false; }
  4440. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  4441. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  4442. if (cp > 0x10FFFF) { return false; }
  4443. i += len;
  4444. }
  4445. return true;
  4446. }
  4447. } // namespace impl
  4448. } // namespace ws
  4449. namespace detail {
  4450. // NOTE: This code came up with the following stackoverflow post:
  4451. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  4452. inline std::string base64_encode(const std::string &in) {
  4453. static const auto lookup =
  4454. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4455. std::string out;
  4456. out.reserve(in.size());
  4457. // Unsigned: the accumulator is never masked, so with a signed int the
  4458. // `val << 8` below overflows once enough bytes are folded in (undefined
  4459. // behaviour before C++20). Only the low bits are ever emitted, so the
  4460. // wrap-around of an unsigned accumulator does not affect the output.
  4461. uint32_t val = 0;
  4462. auto valb = -6;
  4463. for (auto c : in) {
  4464. val = (val << 8) + static_cast<uint8_t>(c);
  4465. valb += 8;
  4466. while (valb >= 0) {
  4467. out.push_back(lookup[(val >> valb) & 0x3F]);
  4468. valb -= 6;
  4469. }
  4470. }
  4471. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  4472. while (out.size() % 4) {
  4473. out.push_back('=');
  4474. }
  4475. return out;
  4476. }
  4477. inline std::string sha1(const std::string &input) {
  4478. // RFC 3174 SHA-1 implementation
  4479. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  4480. return (x << n) | (x >> (32 - n));
  4481. };
  4482. uint32_t h0 = 0x67452301;
  4483. uint32_t h1 = 0xEFCDAB89;
  4484. uint32_t h2 = 0x98BADCFE;
  4485. uint32_t h3 = 0x10325476;
  4486. uint32_t h4 = 0xC3D2E1F0;
  4487. // Pre-processing: adding padding bits
  4488. std::string msg = input;
  4489. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  4490. msg.push_back(static_cast<char>(0x80u));
  4491. while (msg.size() % 64 != 56) {
  4492. msg.push_back(0);
  4493. }
  4494. // Append original length in bits as 64-bit big-endian
  4495. for (int i = 56; i >= 0; i -= 8) {
  4496. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  4497. }
  4498. // Process each 512-bit chunk
  4499. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  4500. uint32_t w[80];
  4501. for (size_t i = 0; i < 16; i++) {
  4502. w[i] =
  4503. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  4504. << 24) |
  4505. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  4506. << 16) |
  4507. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  4508. << 8) |
  4509. (static_cast<uint32_t>(
  4510. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  4511. }
  4512. for (int i = 16; i < 80; i++) {
  4513. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  4514. }
  4515. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  4516. for (int i = 0; i < 80; i++) {
  4517. uint32_t f, k;
  4518. if (i < 20) {
  4519. f = (b & c) | ((~b) & d);
  4520. k = 0x5A827999;
  4521. } else if (i < 40) {
  4522. f = b ^ c ^ d;
  4523. k = 0x6ED9EBA1;
  4524. } else if (i < 60) {
  4525. f = (b & c) | (b & d) | (c & d);
  4526. k = 0x8F1BBCDC;
  4527. } else {
  4528. f = b ^ c ^ d;
  4529. k = 0xCA62C1D6;
  4530. }
  4531. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  4532. e = d;
  4533. d = c;
  4534. c = left_rotate(b, 30);
  4535. b = a;
  4536. a = temp;
  4537. }
  4538. h0 += a;
  4539. h1 += b;
  4540. h2 += c;
  4541. h3 += d;
  4542. h4 += e;
  4543. }
  4544. // Produce the final hash as a 20-byte binary string
  4545. std::string hash(20, '\0');
  4546. for (size_t i = 0; i < 4; i++) {
  4547. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  4548. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  4549. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  4550. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  4551. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  4552. }
  4553. return hash;
  4554. }
  4555. inline std::string websocket_accept_key(const std::string &client_key) {
  4556. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  4557. return base64_encode(sha1(client_key + magic));
  4558. }
  4559. inline bool is_websocket_upgrade(const Request &req) {
  4560. if (req.method != "GET") { return false; }
  4561. // Check Upgrade: websocket. RFC 9110 7.8 defines Upgrade as a comma-separated
  4562. // list of protocols and asks recipients to match each name
  4563. // case-insensitively, so look for the token rather than compare the whole
  4564. // field value.
  4565. if (!has_header_token(req.headers, "Upgrade", "websocket")) { return false; }
  4566. // Check Connection: Upgrade
  4567. if (!has_header_token(req.headers, "Connection", "upgrade")) { return false; }
  4568. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  4569. // RFC 6455 Section 4.2.1
  4570. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  4571. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  4572. return false;
  4573. }
  4574. static const std::string b64chars =
  4575. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4576. for (size_t i = 0; i < 22; i++) {
  4577. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  4578. }
  4579. // Check Sec-WebSocket-Version: 13
  4580. auto version = req.get_header_value("Sec-WebSocket-Version");
  4581. if (version != "13") { return false; }
  4582. return true;
  4583. }
  4584. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  4585. const char *data, size_t len, bool fin,
  4586. bool mask) {
  4587. // First byte: FIN + opcode
  4588. uint8_t header[2];
  4589. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  4590. (static_cast<uint8_t>(opcode) & 0x0F));
  4591. // Second byte: MASK + payload length
  4592. if (len < 126) {
  4593. header[1] = static_cast<uint8_t>(len);
  4594. if (mask) { header[1] |= 0x80; }
  4595. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4596. } else if (len <= 0xFFFF) {
  4597. header[1] = 126;
  4598. if (mask) { header[1] |= 0x80; }
  4599. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4600. uint8_t ext[2];
  4601. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4602. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4603. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4604. } else {
  4605. header[1] = 127;
  4606. if (mask) { header[1] |= 0x80; }
  4607. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4608. uint8_t ext[8];
  4609. for (int i = 7; i >= 0; i--) {
  4610. ext[7 - i] =
  4611. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4612. }
  4613. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4614. }
  4615. if (mask) {
  4616. // Generate random mask key
  4617. thread_local std::mt19937 rng(std::random_device{}());
  4618. uint8_t mask_key[4];
  4619. auto r = rng();
  4620. std::memcpy(mask_key, &r, 4);
  4621. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4622. // Write masked payload in chunks
  4623. const size_t chunk_size = 4096;
  4624. std::vector<char> buf((std::min)(len, chunk_size));
  4625. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4626. size_t n = (std::min)(chunk_size, len - offset);
  4627. for (size_t i = 0; i < n; i++) {
  4628. buf[i] =
  4629. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4630. }
  4631. if (strm.write(buf.data(), n) < 0) { return false; }
  4632. }
  4633. } else {
  4634. if (len > 0) {
  4635. if (strm.write(data, len) < 0) { return false; }
  4636. }
  4637. }
  4638. return true;
  4639. }
  4640. } // namespace detail
  4641. namespace ws {
  4642. namespace impl {
  4643. // Read exactly `size` bytes. Stream::read may return less than asked for -- it
  4644. // hands back whatever its buffer already holds -- so every multi-byte field has
  4645. // to loop. Reading a 2-byte header with a single read() fails whenever the
  4646. // header straddles the read buffer's boundary.
  4647. //
  4648. // Timeout is reported only when nothing at all was consumed. Once a byte has
  4649. // been taken the stream sits mid-field and cannot be resumed, so a timeout
  4650. // there is a failure like any other. (When read() fails it always records why,
  4651. // so the error belongs to this call and not to an earlier one.)
  4652. inline FrameRead read_exact(Stream &strm, void *buf, size_t size) {
  4653. auto p = static_cast<char *>(buf);
  4654. size_t total = 0;
  4655. while (total < size) {
  4656. auto n = strm.read(p + total, size - total);
  4657. if (n <= 0) {
  4658. auto timed_out = total == 0 && strm.get_error() == Error::Timeout;
  4659. return timed_out ? FrameRead::Timeout : FrameRead::Fail;
  4660. }
  4661. total += static_cast<size_t>(n);
  4662. }
  4663. return FrameRead::Ok;
  4664. }
  4665. inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
  4666. std::string &payload, bool &fin,
  4667. bool expect_masked, size_t max_len) {
  4668. // Read first 2 bytes. This is the only read that may report a timeout: it
  4669. // sits on a frame boundary, where nothing has been consumed yet.
  4670. uint8_t header[2];
  4671. FrameRead first = read_exact(strm, header, 2);
  4672. if (first != FrameRead::Ok) { return first; }
  4673. fin = (header[0] & 0x80) != 0;
  4674. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4675. if (header[0] & 0x70) { return FrameRead::Fail; }
  4676. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4677. bool masked = (header[1] & 0x80) != 0;
  4678. uint64_t payload_len = header[1] & 0x7F;
  4679. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4680. // MUST have a payload length of 125 bytes or less
  4681. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4682. if (is_control) {
  4683. if (!fin) { return FrameRead::Fail; }
  4684. if (payload_len > 125) { return FrameRead::Fail; }
  4685. }
  4686. if (masked != expect_masked) { return FrameRead::Fail; }
  4687. // Extended payload length
  4688. if (payload_len == 126) {
  4689. uint8_t ext[2];
  4690. if (read_exact(strm, ext, 2) != FrameRead::Ok) { return FrameRead::Fail; }
  4691. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4692. } else if (payload_len == 127) {
  4693. uint8_t ext[8];
  4694. if (read_exact(strm, ext, 8) != FrameRead::Ok) { return FrameRead::Fail; }
  4695. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4696. if (ext[0] & 0x80) { return FrameRead::Fail; }
  4697. payload_len = 0;
  4698. for (int i = 0; i < 8; i++) {
  4699. payload_len = (payload_len << 8) | ext[i];
  4700. }
  4701. }
  4702. if (payload_len > max_len) { return FrameRead::Fail; }
  4703. // Read mask key if present
  4704. uint8_t mask_key[4] = {0};
  4705. if (masked) {
  4706. if (read_exact(strm, mask_key, 4) != FrameRead::Ok) {
  4707. return FrameRead::Fail;
  4708. }
  4709. }
  4710. // Read payload
  4711. payload.resize(static_cast<size_t>(payload_len));
  4712. if (payload_len > 0 &&
  4713. read_exact(strm, &payload[0], static_cast<size_t>(payload_len)) !=
  4714. FrameRead::Ok) {
  4715. return FrameRead::Fail;
  4716. }
  4717. // Unmask if needed
  4718. if (masked) {
  4719. for (size_t i = 0; i < payload.size(); i++) {
  4720. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4721. }
  4722. }
  4723. return FrameRead::Ok;
  4724. }
  4725. } // namespace impl
  4726. } // namespace ws
  4727. namespace detail {
  4728. inline bool is_valid_path(const std::string &path) {
  4729. size_t level = 0;
  4730. size_t i = 0;
  4731. // Skip slash
  4732. while (i < path.size() && path[i] == '/') {
  4733. i++;
  4734. }
  4735. while (i < path.size()) {
  4736. // Read component
  4737. auto beg = i;
  4738. while (i < path.size() && path[i] != '/') {
  4739. if (path[i] == '\0') {
  4740. return false;
  4741. } else if (path[i] == '\\') {
  4742. return false;
  4743. }
  4744. i++;
  4745. }
  4746. auto len = i - beg;
  4747. assert(len > 0);
  4748. if (!path.compare(beg, len, ".")) {
  4749. ;
  4750. } else if (!path.compare(beg, len, "..")) {
  4751. if (level == 0) { return false; }
  4752. level--;
  4753. } else {
  4754. level++;
  4755. }
  4756. // Skip slash
  4757. while (i < path.size() && path[i] == '/') {
  4758. i++;
  4759. }
  4760. }
  4761. return true;
  4762. }
  4763. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4764. #if defined(_WIN32)
  4765. char buf[_MAX_PATH];
  4766. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4767. resolved = buf;
  4768. #elif defined(PATH_MAX)
  4769. char buf[PATH_MAX];
  4770. if (realpath(path, buf) == nullptr) { return false; }
  4771. resolved = buf;
  4772. #else
  4773. auto buf = realpath(path, nullptr);
  4774. auto guard = scope_exit([&]() { std::free(buf); });
  4775. if (buf == nullptr) { return false; }
  4776. resolved = buf;
  4777. #endif
  4778. return true;
  4779. }
  4780. inline bool is_path_within_base(const std::string &resolved_path,
  4781. const std::string &resolved_base) {
  4782. #if defined(_WIN32)
  4783. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4784. resolved_base.size()) == 0;
  4785. #else
  4786. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4787. resolved_base.size()) == 0;
  4788. #endif
  4789. }
  4790. inline FileStat::FileStat(const std::string &path) {
  4791. #if defined(_WIN32)
  4792. auto wpath = u8string_to_wstring(path.c_str());
  4793. ret_ = _wstat(wpath.c_str(), &st_);
  4794. #else
  4795. ret_ = stat(path.c_str(), &st_);
  4796. #endif
  4797. }
  4798. inline bool FileStat::is_file() const {
  4799. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4800. }
  4801. inline bool FileStat::is_dir() const {
  4802. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4803. }
  4804. inline time_t FileStat::mtime() const {
  4805. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4806. : static_cast<time_t>(-1);
  4807. }
  4808. inline size_t FileStat::size() const {
  4809. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4810. }
  4811. inline std::string encode_path(const std::string &s) {
  4812. std::string result;
  4813. result.reserve(s.size());
  4814. for (size_t i = 0; s[i]; i++) {
  4815. switch (s[i]) {
  4816. case ' ': result += "%20"; break;
  4817. case '+': result += "%2B"; break;
  4818. case '\'': result += "%27"; break;
  4819. case ',': result += "%2C"; break;
  4820. // case ':': result += "%3A"; break; // ok? probably...
  4821. case ';': result += "%3B"; break;
  4822. default:
  4823. auto c = static_cast<uint8_t>(s[i]);
  4824. // Control characters (incl. CR/LF) and non-ASCII bytes are not allowed
  4825. // in a request-target as-is.
  4826. if (c < 0x20 || c == 0x7f || c >= 0x80) {
  4827. result += '%';
  4828. char hex[4];
  4829. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4830. assert(len == 2);
  4831. result.append(hex, static_cast<size_t>(len));
  4832. } else {
  4833. result += s[i];
  4834. }
  4835. break;
  4836. }
  4837. }
  4838. return result;
  4839. }
  4840. inline std::string file_extension(const std::string &path) {
  4841. std::smatch m;
  4842. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4843. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4844. return std::string();
  4845. }
  4846. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4847. template <typename T>
  4848. inline bool parse_header(const char *beg, const char *end, T fn);
  4849. template <typename T>
  4850. inline bool parse_header(const char *beg, const char *end, T fn) {
  4851. // Skip trailing spaces and tabs.
  4852. while (beg < end && is_space_or_tab(end[-1])) {
  4853. end--;
  4854. }
  4855. auto p = beg;
  4856. while (p < end && *p != ':') {
  4857. p++;
  4858. }
  4859. auto name = std::string(beg, p);
  4860. if (!detail::fields::is_field_name(name)) { return false; }
  4861. if (p == end) { return false; }
  4862. auto key_end = p;
  4863. if (*p++ != ':') { return false; }
  4864. while (p < end && is_space_or_tab(*p)) {
  4865. p++;
  4866. }
  4867. if (p <= end) {
  4868. auto key_len = key_end - beg;
  4869. if (!key_len) { return false; }
  4870. auto key = std::string(beg, key_end);
  4871. auto val = std::string(p, end);
  4872. if (!detail::fields::is_field_value(val)) { return false; }
  4873. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4874. // percent-decoded by the recipient. Applications that need to interpret a
  4875. // value as a URI component should call httplib::decode_uri_component()
  4876. // (or decode_path_component()) explicitly.
  4877. fn(key, val);
  4878. return true;
  4879. }
  4880. return false;
  4881. }
  4882. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4883. const Headers &src_headers) {
  4884. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4885. // transfer coding is complete when a chunk with a chunk-size of zero is
  4886. // received, possibly followed by a trailer section, and finally terminated by
  4887. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4888. //
  4889. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4890. // doesn't care for the existence of the final CRLF. In other words, it seems
  4891. // to be ok whether the final CRLF exists or not in the chunked data.
  4892. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4893. //
  4894. // According to the reference code in RFC 9112, cpp-httplib now allows
  4895. // chunked transfer coding data without the final CRLF.
  4896. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4897. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4898. "transfer-encoding",
  4899. "content-length",
  4900. "host",
  4901. "authorization",
  4902. "www-authenticate",
  4903. "proxy-authenticate",
  4904. "proxy-authorization",
  4905. "cookie",
  4906. "set-cookie",
  4907. "cache-control",
  4908. "expect",
  4909. "max-forwards",
  4910. "pragma",
  4911. "range",
  4912. "te",
  4913. "age",
  4914. "expires",
  4915. "date",
  4916. "location",
  4917. "retry-after",
  4918. "vary",
  4919. "warning",
  4920. "content-encoding",
  4921. "content-type",
  4922. "content-range",
  4923. "trailer"};
  4924. case_ignore::unordered_set<std::string> declared_trailers;
  4925. auto trailer_header = get_combined_header_value(src_headers, "Trailer");
  4926. if (!trailer_header.empty()) {
  4927. // split() trims each token and skips empty ones, so the name arrives ready
  4928. // to look up.
  4929. split(trailer_header.data(), trailer_header.data() + trailer_header.size(),
  4930. ',', [&](const char *b, const char *e) {
  4931. // A legitimate message declares only a handful of trailers. Cap the
  4932. // set so a peer cannot grow it without bound: an oversized set only
  4933. // arises from an attempt to force many colliding names into
  4934. // quadratic lookups (case_ignore::hash is unkeyed).
  4935. if (declared_trailers.size() >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  4936. return;
  4937. }
  4938. std::string key(b, e);
  4939. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4940. declared_trailers.insert(key);
  4941. }
  4942. });
  4943. }
  4944. size_t trailer_header_count = 0;
  4945. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4946. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4947. // Count every received trailer field, not only the declared ones stored in
  4948. // dest, so undeclared fields cannot keep this loop running past the limit.
  4949. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4950. constexpr auto line_terminator_len = 2;
  4951. auto line_beg = line_reader.ptr();
  4952. auto line_end =
  4953. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4954. if (!parse_header(line_beg, line_end,
  4955. [&](const std::string &key, const std::string &val) {
  4956. if (declared_trailers.find(key) !=
  4957. declared_trailers.end()) {
  4958. dest.emplace(key, val);
  4959. }
  4960. })) {
  4961. return false;
  4962. }
  4963. trailer_header_count++;
  4964. if (!line_reader.getline()) { return false; }
  4965. }
  4966. return true;
  4967. }
  4968. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4969. size_t right) {
  4970. while (b + left < e && is_space_or_tab(b[left])) {
  4971. left++;
  4972. }
  4973. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4974. right--;
  4975. }
  4976. return std::make_pair(left, right);
  4977. }
  4978. inline std::string trim_copy(const std::string &s) {
  4979. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4980. return s.substr(r.first, r.second - r.first);
  4981. }
  4982. inline std::string trim_double_quotes_copy(const std::string &s) {
  4983. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4984. return s.substr(1, s.size() - 2);
  4985. }
  4986. return s;
  4987. }
  4988. inline void
  4989. divide(const char *data, std::size_t size, char d,
  4990. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4991. fn) {
  4992. const auto it = std::find(data, data + size, d);
  4993. const auto found = static_cast<std::size_t>(it != data + size);
  4994. const auto lhs_data = data;
  4995. const auto lhs_size = static_cast<std::size_t>(it - data);
  4996. const auto rhs_data = it + found;
  4997. const auto rhs_size = size - lhs_size - found;
  4998. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4999. }
  5000. inline void
  5001. divide(const std::string &str, char d,
  5002. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  5003. fn) {
  5004. divide(str.data(), str.size(), d, std::move(fn));
  5005. }
  5006. inline void split(const char *b, const char *e, char d,
  5007. std::function<void(const char *, const char *)> fn) {
  5008. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  5009. }
  5010. inline void split(const char *b, const char *e, char d, size_t m,
  5011. std::function<void(const char *, const char *)> fn) {
  5012. size_t i = 0;
  5013. size_t beg = 0;
  5014. size_t count = 1;
  5015. while (e ? (b + i < e) : (b[i] != '\0')) {
  5016. if (b[i] == d && count < m) {
  5017. auto r = trim(b, e, beg, i);
  5018. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5019. beg = i + 1;
  5020. count++;
  5021. }
  5022. i++;
  5023. }
  5024. if (i) {
  5025. auto r = trim(b, e, beg, i);
  5026. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5027. }
  5028. }
  5029. // Same contract as split(), except that a delimiter inside a quoted-string is
  5030. // not a delimiter. RFC 9110 Section 5.6.6 lets a parameter value be a
  5031. // quoted-string, and ';' and '=' are legal characters inside one.
  5032. inline void split_unquoted(const char *b, const char *e, char d, size_t m,
  5033. std::function<void(const char *, const char *)> fn) {
  5034. size_t i = 0;
  5035. size_t beg = 0;
  5036. size_t count = 1;
  5037. auto in_quotes = false;
  5038. while (e ? (b + i < e) : (b[i] != '\0')) {
  5039. if (b[i] == '"') {
  5040. in_quotes = !in_quotes;
  5041. } else if (b[i] == d && !in_quotes && count < m) {
  5042. auto r = trim(b, e, beg, i);
  5043. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5044. beg = i + 1;
  5045. count++;
  5046. }
  5047. i++;
  5048. }
  5049. if (i) {
  5050. auto r = trim(b, e, beg, i);
  5051. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  5052. }
  5053. }
  5054. inline void split_unquoted(const char *b, const char *e, char d,
  5055. std::function<void(const char *, const char *)> fn) {
  5056. return split_unquoted(b, e, d, (std::numeric_limits<size_t>::max)(),
  5057. std::move(fn));
  5058. }
  5059. // Divide a header parameter at its first '='. RFC 9110 Section 5.6.6 makes the
  5060. // key a token, so the first '=' is the separator even when the value is a
  5061. // quoted-string carrying more of them.
  5062. inline void divide_param_pair(const char *b, const char *e, std::string &key,
  5063. std::string &val) {
  5064. divide(
  5065. b, static_cast<std::size_t>(e - b), '=',
  5066. [&](const char *kb, std::size_t klen, const char *vb, std::size_t vlen) {
  5067. const auto kr = trim(kb, kb + klen, 0, klen);
  5068. key.assign(kb + kr.first, kb + kr.second);
  5069. const auto vr = trim(vb, vb + vlen, 0, vlen);
  5070. val.assign(vb + vr.first, vb + vr.second);
  5071. });
  5072. }
  5073. inline bool split_find(const char *b, const char *e, char d, size_t m,
  5074. std::function<bool(const char *, const char *)> fn) {
  5075. size_t i = 0;
  5076. size_t beg = 0;
  5077. size_t count = 1;
  5078. while (e ? (b + i < e) : (b[i] != '\0')) {
  5079. if (b[i] == d && count < m) {
  5080. auto r = trim(b, e, beg, i);
  5081. if (r.first < r.second) {
  5082. auto found = fn(&b[r.first], &b[r.second]);
  5083. if (found) { return true; }
  5084. }
  5085. beg = i + 1;
  5086. count++;
  5087. }
  5088. i++;
  5089. }
  5090. if (i) {
  5091. auto r = trim(b, e, beg, i);
  5092. if (r.first < r.second) {
  5093. auto found = fn(&b[r.first], &b[r.second]);
  5094. if (found) { return true; }
  5095. }
  5096. }
  5097. return false;
  5098. }
  5099. inline bool split_find(const char *b, const char *e, char d,
  5100. std::function<bool(const char *, const char *)> fn) {
  5101. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  5102. std::move(fn));
  5103. }
  5104. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  5105. size_t fixed_buffer_size)
  5106. : strm_(strm), fixed_buffer_(fixed_buffer),
  5107. fixed_buffer_size_(fixed_buffer_size) {}
  5108. inline const char *stream_line_reader::ptr() const {
  5109. if (growable_buffer_.empty()) {
  5110. return fixed_buffer_;
  5111. } else {
  5112. return growable_buffer_.data();
  5113. }
  5114. }
  5115. inline size_t stream_line_reader::size() const {
  5116. if (growable_buffer_.empty()) {
  5117. return fixed_buffer_used_size_;
  5118. } else {
  5119. return growable_buffer_.size();
  5120. }
  5121. }
  5122. inline bool stream_line_reader::end_with_crlf() const {
  5123. auto end = ptr() + size();
  5124. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  5125. }
  5126. inline bool stream_line_reader::getline() {
  5127. fixed_buffer_used_size_ = 0;
  5128. growable_buffer_.clear();
  5129. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5130. char prev_byte = 0;
  5131. #endif
  5132. for (size_t i = 0;; i++) {
  5133. // Fast path: whatever the stream has already buffered can be scanned for
  5134. // the terminator in one pass. Asking for a byte at a time costs a virtual
  5135. // call, a bounds check and a one-byte copy per character of the request.
  5136. size_t buffered_size = 0;
  5137. if (auto buffered = strm_.buffered_data(buffered_size)) {
  5138. auto take = buffered_size;
  5139. auto terminated = false;
  5140. for (size_t at = 0; at < buffered_size;) {
  5141. auto nl = static_cast<const char *>(
  5142. memchr(buffered + at, '\n', buffered_size - at));
  5143. if (!nl) { break; }
  5144. auto pos = static_cast<size_t>(nl - buffered);
  5145. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5146. take = pos + 1;
  5147. terminated = true;
  5148. break;
  5149. #else
  5150. // A bare LF does not end the line; keep looking for CRLF. The CR may
  5151. // be the last byte of an earlier chunk, hence prev_byte.
  5152. if ((pos > 0 ? buffered[pos - 1] : prev_byte) == '\r') {
  5153. take = pos + 1;
  5154. terminated = true;
  5155. break;
  5156. }
  5157. at = pos + 1;
  5158. #endif
  5159. }
  5160. if (size() + take > CPPHTTPLIB_MAX_LINE_LENGTH) { return false; }
  5161. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5162. prev_byte = buffered[take - 1];
  5163. #endif
  5164. append(buffered, take);
  5165. strm_.consume_buffered(take);
  5166. i += take;
  5167. if (terminated) { return true; }
  5168. continue;
  5169. }
  5170. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  5171. // Treat exceptionally long lines as an error to
  5172. // prevent infinite loops/memory exhaustion
  5173. return false;
  5174. }
  5175. char byte;
  5176. auto n = strm_.read(&byte, 1);
  5177. if (n < 0) {
  5178. return false;
  5179. } else if (n == 0) {
  5180. if (i == 0) {
  5181. return false;
  5182. } else {
  5183. break;
  5184. }
  5185. }
  5186. append(byte);
  5187. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5188. if (byte == '\n') { break; }
  5189. #else
  5190. if (prev_byte == '\r' && byte == '\n') { break; }
  5191. prev_byte = byte;
  5192. #endif
  5193. }
  5194. return true;
  5195. }
  5196. inline void stream_line_reader::append(char c) { append(&c, 1); }
  5197. inline void stream_line_reader::append(const char *data, size_t size) {
  5198. // Once the line has outgrown the fixed buffer everything must keep going to
  5199. // the growable one, even if a later chunk would have fit. Without the
  5200. // emptiness check a short append after a long one would land in the fixed
  5201. // buffer, which ptr() and size() no longer look at, and be lost.
  5202. if (growable_buffer_.empty() &&
  5203. fixed_buffer_used_size_ + size < fixed_buffer_size_) {
  5204. memcpy(fixed_buffer_ + fixed_buffer_used_size_, data, size);
  5205. fixed_buffer_used_size_ += size;
  5206. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  5207. } else {
  5208. // Unlike the per-character overload, this can be the very first append of
  5209. // the line, so the fixed buffer may hold nothing and carry no terminator
  5210. // yet. assign() takes an explicit length and does not need one.
  5211. if (growable_buffer_.empty()) {
  5212. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  5213. }
  5214. growable_buffer_.append(data, size);
  5215. }
  5216. }
  5217. inline mmap::mmap(const char *path) { open(path); }
  5218. inline mmap::~mmap() { close(); }
  5219. inline bool mmap::open(const char *path) {
  5220. close();
  5221. #if defined(_WIN32)
  5222. auto wpath = u8string_to_wstring(path);
  5223. if (wpath.empty()) { return false; }
  5224. hFile_ =
  5225. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  5226. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  5227. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  5228. LARGE_INTEGER size{};
  5229. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  5230. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  5231. // See:
  5232. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  5233. if (static_cast<ULONGLONG>(size.QuadPart) >
  5234. (std::numeric_limits<decltype(size_)>::max)()) {
  5235. // `size_t` might be 32-bits, on 32-bits Windows.
  5236. return false;
  5237. }
  5238. size_ = static_cast<size_t>(size.QuadPart);
  5239. hMapping_ =
  5240. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  5241. // Special treatment for an empty file...
  5242. if (hMapping_ == NULL && size_ == 0) {
  5243. close();
  5244. is_open_empty_file = true;
  5245. return true;
  5246. }
  5247. if (hMapping_ == NULL) {
  5248. close();
  5249. return false;
  5250. }
  5251. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  5252. if (addr_ == nullptr) {
  5253. close();
  5254. return false;
  5255. }
  5256. #else
  5257. fd_ = ::open(path, O_RDONLY);
  5258. if (fd_ == -1) { return false; }
  5259. struct stat sb;
  5260. if (fstat(fd_, &sb) == -1) {
  5261. close();
  5262. return false;
  5263. }
  5264. size_ = static_cast<size_t>(sb.st_size);
  5265. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  5266. // Special treatment for an empty file...
  5267. if (addr_ == MAP_FAILED && size_ == 0) {
  5268. close();
  5269. is_open_empty_file = true;
  5270. return false;
  5271. }
  5272. if (addr_ == MAP_FAILED) {
  5273. // Clear the sentinel before `close()`, since `is_open()` only checks
  5274. // `addr_` against nullptr and `munmap()` must not be called with it.
  5275. addr_ = nullptr;
  5276. close();
  5277. return false;
  5278. }
  5279. #endif
  5280. return true;
  5281. }
  5282. inline bool mmap::is_open() const {
  5283. return is_open_empty_file ? true : addr_ != nullptr;
  5284. }
  5285. inline size_t mmap::size() const { return size_; }
  5286. inline const char *mmap::data() const {
  5287. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  5288. }
  5289. inline void mmap::close() {
  5290. #if defined(_WIN32)
  5291. if (addr_) {
  5292. ::UnmapViewOfFile(addr_);
  5293. addr_ = nullptr;
  5294. }
  5295. if (hMapping_) {
  5296. ::CloseHandle(hMapping_);
  5297. hMapping_ = NULL;
  5298. }
  5299. if (hFile_ != INVALID_HANDLE_VALUE) {
  5300. ::CloseHandle(hFile_);
  5301. hFile_ = INVALID_HANDLE_VALUE;
  5302. }
  5303. is_open_empty_file = false;
  5304. #else
  5305. if (addr_ != nullptr) {
  5306. munmap(addr_, size_);
  5307. addr_ = nullptr;
  5308. }
  5309. if (fd_ != -1) {
  5310. ::close(fd_);
  5311. fd_ = -1;
  5312. }
  5313. #endif
  5314. size_ = 0;
  5315. }
  5316. inline int close_socket(socket_t sock) noexcept {
  5317. #ifdef _WIN32
  5318. return closesocket(sock);
  5319. #else
  5320. return close(sock);
  5321. #endif
  5322. }
  5323. template <typename T> inline ssize_t handle_EINTR(T fn) {
  5324. ssize_t res = 0;
  5325. while (true) {
  5326. res = fn();
  5327. if (res < 0 && errno == EINTR) {
  5328. std::this_thread::sleep_for(std::chrono::microseconds{1});
  5329. continue;
  5330. }
  5331. break;
  5332. }
  5333. return res;
  5334. }
  5335. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  5336. return handle_EINTR([&]() {
  5337. return recv(sock,
  5338. #ifdef _WIN32
  5339. static_cast<char *>(ptr), static_cast<int>(size),
  5340. #else
  5341. ptr, size,
  5342. #endif
  5343. flags);
  5344. });
  5345. }
  5346. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  5347. int flags) {
  5348. return handle_EINTR([&]() {
  5349. return send(sock,
  5350. #ifdef _WIN32
  5351. static_cast<const char *>(ptr), static_cast<int>(size),
  5352. #else
  5353. ptr, size,
  5354. #endif
  5355. flags);
  5356. });
  5357. }
  5358. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  5359. #ifdef _WIN32
  5360. return ::WSAPoll(fds, nfds, timeout);
  5361. #else
  5362. return ::poll(fds, nfds, timeout);
  5363. #endif
  5364. }
  5365. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  5366. time_t usec) {
  5367. struct pollfd pfd;
  5368. pfd.fd = sock;
  5369. pfd.events = events;
  5370. pfd.revents = 0;
  5371. // A negative timeout waits forever, poll's own convention. 0 keeps meaning
  5372. // "return immediately", which callers here rely on to probe a socket.
  5373. auto timeout = sec < 0 ? -1 : static_cast<int>(sec * 1000 + usec / 1000);
  5374. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  5375. }
  5376. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  5377. return select_impl(sock, POLLIN, sec, usec);
  5378. }
  5379. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  5380. return select_impl(sock, POLLOUT, sec, usec);
  5381. }
  5382. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  5383. time_t usec) {
  5384. struct pollfd pfd_read;
  5385. pfd_read.fd = sock;
  5386. pfd_read.events = POLLIN | POLLOUT;
  5387. pfd_read.revents = 0;
  5388. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  5389. auto poll_res =
  5390. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  5391. if (poll_res == 0) { return Error::ConnectionTimeout; }
  5392. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  5393. auto error = 0;
  5394. socklen_t len = sizeof(error);
  5395. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  5396. reinterpret_cast<char *>(&error), &len);
  5397. auto successful = res >= 0 && !error;
  5398. return successful ? Error::Success : Error::Connection;
  5399. }
  5400. return Error::Connection;
  5401. }
  5402. inline bool is_socket_alive(socket_t sock) {
  5403. const auto val = detail::select_read(sock, 0, 0);
  5404. if (val == 0) {
  5405. return true;
  5406. } else if (val < 0 && errno == EBADF) {
  5407. return false;
  5408. }
  5409. char buf[1];
  5410. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  5411. }
  5412. class SocketStream final : public Stream {
  5413. public:
  5414. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5415. time_t write_timeout_sec, time_t write_timeout_usec,
  5416. time_t max_timeout_msec = 0,
  5417. std::chrono::time_point<std::chrono::steady_clock> start_time =
  5418. (std::chrono::steady_clock::time_point::min)());
  5419. ~SocketStream() override;
  5420. bool is_readable() const override;
  5421. bool wait_readable() const override;
  5422. bool wait_writable() const override;
  5423. bool is_peer_alive() const override;
  5424. ssize_t read(char *ptr, size_t size) override;
  5425. ssize_t write(const char *ptr, size_t size) override;
  5426. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  5427. void get_local_ip_and_port(std::string &ip, int &port) const override;
  5428. socket_t socket() const override;
  5429. time_t duration() const override;
  5430. void set_read_timeout(time_t sec, time_t usec = 0) override;
  5431. const char *buffered_data(size_t &size) const override;
  5432. void consume_buffered(size_t size) override;
  5433. // The caller has just seen this socket become readable. Lets the next read
  5434. // skip its own readiness wait, which would otherwise ask the kernel a
  5435. // question that was answered a moment ago. Consumed by that read.
  5436. void set_readable_hint() { readable_hint_ = true; }
  5437. private:
  5438. bool ensure_readable();
  5439. socket_t sock_;
  5440. // Atomic because ws::WebSocket::set_read_timeout() reaches this from another
  5441. // thread while a read is in flight -- that is the point of it, for a caller
  5442. // holding one connection and wanting control back to send on it.
  5443. std::atomic<time_t> read_timeout_sec_;
  5444. std::atomic<time_t> read_timeout_usec_;
  5445. time_t write_timeout_sec_;
  5446. time_t write_timeout_usec_;
  5447. time_t max_timeout_msec_;
  5448. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  5449. std::vector<char> read_buff_;
  5450. size_t read_buff_off_ = 0;
  5451. size_t read_buff_content_size_ = 0;
  5452. bool readable_hint_ = false;
  5453. static const size_t read_buff_size_ = 1024l * 4;
  5454. };
  5455. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5456. time_t keep_alive_timeout_sec) {
  5457. using namespace std::chrono;
  5458. const auto interval_usec =
  5459. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  5460. // Avoid expensive `steady_clock::now()` call for the first time
  5461. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  5462. const auto start = steady_clock::now() - microseconds{interval_usec};
  5463. const auto timeout = seconds{keep_alive_timeout_sec};
  5464. while (true) {
  5465. if (svr_sock == INVALID_SOCKET) {
  5466. break; // Server socket is closed
  5467. }
  5468. auto val = select_read(sock, 0, interval_usec);
  5469. if (val < 0) {
  5470. break; // Ssocket error
  5471. } else if (val == 0) {
  5472. if (steady_clock::now() - start > timeout) {
  5473. break; // Timeout
  5474. }
  5475. } else {
  5476. return true; // Ready for read
  5477. }
  5478. }
  5479. return false;
  5480. }
  5481. template <typename T>
  5482. inline bool
  5483. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5484. size_t keep_alive_max_count,
  5485. time_t keep_alive_timeout_sec, T callback) {
  5486. assert(keep_alive_max_count > 0);
  5487. auto ret = false;
  5488. auto count = keep_alive_max_count;
  5489. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  5490. auto close_connection = count == 1;
  5491. auto connection_closed = false;
  5492. ret = callback(close_connection, connection_closed);
  5493. if (!ret || connection_closed) { break; }
  5494. count--;
  5495. }
  5496. return ret;
  5497. }
  5498. template <typename T>
  5499. inline bool
  5500. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  5501. size_t keep_alive_max_count,
  5502. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  5503. time_t read_timeout_usec, time_t write_timeout_sec,
  5504. time_t write_timeout_usec, T callback) {
  5505. return process_server_socket_core(
  5506. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  5507. [&](bool close_connection, bool &connection_closed) {
  5508. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5509. write_timeout_sec, write_timeout_usec);
  5510. // process_server_socket_core() only gets here once keep_alive() has
  5511. // seen the socket go readable.
  5512. strm.set_readable_hint();
  5513. return callback(strm, close_connection, connection_closed);
  5514. });
  5515. }
  5516. inline bool process_client_socket(
  5517. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5518. time_t write_timeout_sec, time_t write_timeout_usec,
  5519. time_t max_timeout_msec,
  5520. std::chrono::time_point<std::chrono::steady_clock> start_time,
  5521. std::function<bool(Stream &)> callback) {
  5522. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  5523. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  5524. start_time);
  5525. return callback(strm);
  5526. }
  5527. inline int shutdown_socket(socket_t sock) noexcept {
  5528. #ifdef _WIN32
  5529. return shutdown(sock, SD_BOTH);
  5530. #else
  5531. return shutdown(sock, SHUT_RDWR);
  5532. #endif
  5533. }
  5534. // Half-closes the write side and drains any in-flight/queued bytes before
  5535. // the final shutdown+close. Closing with unread data in the receive queue
  5536. // (or bytes arriving after the receive side is closed) makes the stack send
  5537. // an abortive RST instead of a graceful FIN, which can make the peer see the
  5538. // response as a failed read even though it was fully written.
  5539. inline void drain_and_close_socket(socket_t sock) noexcept {
  5540. #ifdef _WIN32
  5541. shutdown(sock, SD_SEND);
  5542. #else
  5543. shutdown(sock, SHUT_WR);
  5544. #endif
  5545. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5546. size_t total = 0;
  5547. const auto deadline = std::chrono::steady_clock::now() +
  5548. std::chrono::milliseconds(100); // bound #1
  5549. while (total < size_t(1024u * 1024u)) { // bound #2
  5550. const auto remaining =
  5551. std::chrono::duration_cast<std::chrono::microseconds>(
  5552. deadline - std::chrono::steady_clock::now())
  5553. .count();
  5554. if (remaining <= 0) { break; }
  5555. if (select_read(sock, 0, static_cast<time_t>(remaining)) <= 0) { break; }
  5556. const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
  5557. if (n <= 0) { break; }
  5558. total += static_cast<size_t>(n);
  5559. }
  5560. shutdown_socket(sock);
  5561. close_socket(sock);
  5562. }
  5563. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  5564. if (s.size() > 1 && s[0] == '\0') {
  5565. auto ret = s;
  5566. ret[0] = '@';
  5567. return ret;
  5568. }
  5569. return s;
  5570. }
  5571. inline std::string
  5572. unescape_abstract_namespace_unix_domain(const std::string &s) {
  5573. if (s.size() > 1 && s[0] == '@') {
  5574. auto ret = s;
  5575. ret[0] = '\0';
  5576. return ret;
  5577. }
  5578. return s;
  5579. }
  5580. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  5581. const struct addrinfo *hints,
  5582. struct addrinfo **res, time_t timeout_sec) {
  5583. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  5584. if (timeout_sec <= 0) {
  5585. // No timeout specified, use standard getaddrinfo
  5586. return getaddrinfo(node, service, hints, res);
  5587. }
  5588. #ifdef _WIN32
  5589. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  5590. OVERLAPPED overlapped = {};
  5591. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  5592. if (!event) { return EAI_FAIL; }
  5593. overlapped.hEvent = event;
  5594. PADDRINFOEXW result_addrinfo = nullptr;
  5595. HANDLE cancel_handle = nullptr;
  5596. ADDRINFOEXW hints_ex = {};
  5597. if (hints) {
  5598. hints_ex.ai_flags = hints->ai_flags;
  5599. hints_ex.ai_family = hints->ai_family;
  5600. hints_ex.ai_socktype = hints->ai_socktype;
  5601. hints_ex.ai_protocol = hints->ai_protocol;
  5602. }
  5603. auto wnode = u8string_to_wstring(node);
  5604. auto wservice = u8string_to_wstring(service);
  5605. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  5606. hints ? &hints_ex : nullptr, &result_addrinfo,
  5607. nullptr, &overlapped, nullptr, &cancel_handle);
  5608. if (ret == WSA_IO_PENDING) {
  5609. auto wait_result =
  5610. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  5611. if (wait_result == WAIT_TIMEOUT) {
  5612. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  5613. ::CloseHandle(event);
  5614. return EAI_AGAIN;
  5615. }
  5616. DWORD bytes_returned;
  5617. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  5618. &bytes_returned, FALSE)) {
  5619. ::CloseHandle(event);
  5620. return ::WSAGetLastError();
  5621. }
  5622. }
  5623. ::CloseHandle(event);
  5624. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  5625. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  5626. return 0;
  5627. }
  5628. return ret;
  5629. #elif TARGET_OS_MAC && defined(__clang__)
  5630. if (!node) { return EAI_NONAME; }
  5631. // macOS implementation using CFHost API for asynchronous DNS resolution
  5632. CFStringRef hostname_ref = CFStringCreateWithCString(
  5633. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  5634. if (!hostname_ref) { return EAI_MEMORY; }
  5635. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  5636. CFRelease(hostname_ref);
  5637. if (!host_ref) { return EAI_MEMORY; }
  5638. // Set up context for callback
  5639. struct CFHostContext {
  5640. bool completed = false;
  5641. bool success = false;
  5642. CFArrayRef addresses = nullptr;
  5643. std::mutex mutex;
  5644. std::condition_variable cv;
  5645. } context;
  5646. CFHostClientContext client_context;
  5647. memset(&client_context, 0, sizeof(client_context));
  5648. client_context.info = &context;
  5649. // Set callback
  5650. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  5651. const CFStreamError *error, void *info) {
  5652. auto ctx = static_cast<CFHostContext *>(info);
  5653. std::lock_guard<std::mutex> lock(ctx->mutex);
  5654. if (error && error->error != 0) {
  5655. ctx->success = false;
  5656. } else {
  5657. Boolean hasBeenResolved;
  5658. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  5659. if (ctx->addresses && hasBeenResolved) {
  5660. CFRetain(ctx->addresses);
  5661. ctx->success = true;
  5662. } else {
  5663. ctx->success = false;
  5664. }
  5665. }
  5666. ctx->completed = true;
  5667. ctx->cv.notify_one();
  5668. };
  5669. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  5670. CFRelease(host_ref);
  5671. return EAI_SYSTEM;
  5672. }
  5673. // Schedule on run loop
  5674. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  5675. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5676. // Start resolution
  5677. CFStreamError stream_error;
  5678. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  5679. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5680. CFRelease(host_ref);
  5681. return EAI_FAIL;
  5682. }
  5683. // Wait for completion with timeout
  5684. auto timeout_time =
  5685. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  5686. bool timed_out = false;
  5687. {
  5688. std::unique_lock<std::mutex> lock(context.mutex);
  5689. while (!context.completed) {
  5690. auto now = std::chrono::steady_clock::now();
  5691. if (now >= timeout_time) {
  5692. timed_out = true;
  5693. break;
  5694. }
  5695. // Run the runloop for a short time
  5696. lock.unlock();
  5697. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  5698. lock.lock();
  5699. }
  5700. }
  5701. // Clean up
  5702. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  5703. CFHostSetClient(host_ref, nullptr, nullptr);
  5704. if (timed_out || !context.completed) {
  5705. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  5706. CFRelease(host_ref);
  5707. return EAI_AGAIN;
  5708. }
  5709. if (!context.success || !context.addresses) {
  5710. CFRelease(host_ref);
  5711. return EAI_NODATA;
  5712. }
  5713. // Convert CFArray to addrinfo
  5714. CFIndex count = CFArrayGetCount(context.addresses);
  5715. if (count == 0) {
  5716. CFRelease(context.addresses);
  5717. CFRelease(host_ref);
  5718. return EAI_NODATA;
  5719. }
  5720. struct addrinfo *result_addrinfo = nullptr;
  5721. struct addrinfo **current = &result_addrinfo;
  5722. for (CFIndex i = 0; i < count; i++) {
  5723. CFDataRef addr_data =
  5724. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  5725. if (!addr_data) continue;
  5726. const struct sockaddr *sockaddr_ptr =
  5727. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  5728. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  5729. // Allocate addrinfo structure
  5730. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  5731. if (!*current) {
  5732. freeaddrinfo(result_addrinfo);
  5733. CFRelease(context.addresses);
  5734. CFRelease(host_ref);
  5735. return EAI_MEMORY;
  5736. }
  5737. memset(*current, 0, sizeof(struct addrinfo));
  5738. // Set up addrinfo fields
  5739. (*current)->ai_family = sockaddr_ptr->sa_family;
  5740. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  5741. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  5742. (*current)->ai_addrlen = sockaddr_len;
  5743. // Copy sockaddr
  5744. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  5745. if (!(*current)->ai_addr) {
  5746. freeaddrinfo(result_addrinfo);
  5747. CFRelease(context.addresses);
  5748. CFRelease(host_ref);
  5749. return EAI_MEMORY;
  5750. }
  5751. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  5752. // Set port if service is specified
  5753. if (service && *service) {
  5754. int port = 0;
  5755. if (parse_port(service, strlen(service), port)) {
  5756. if (sockaddr_ptr->sa_family == AF_INET) {
  5757. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5758. ->sin_port = htons(static_cast<uint16_t>(port));
  5759. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5760. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5761. ->sin6_port = htons(static_cast<uint16_t>(port));
  5762. }
  5763. }
  5764. }
  5765. current = &((*current)->ai_next);
  5766. }
  5767. CFRelease(context.addresses);
  5768. CFRelease(host_ref);
  5769. *res = result_addrinfo;
  5770. return 0;
  5771. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5772. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5773. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5774. // the resolver worker still references the stack-local gaicb. The cancel
  5775. // path therefore waits (gai_suspend with no timeout) for the worker to
  5776. // actually finish before letting the stack frame go. The trade-off is that
  5777. // a wedged DNS server can hold this thread for the system resolver timeout
  5778. // (~30s by default) past the caller's connection timeout.
  5779. struct gaicb request{};
  5780. struct gaicb *requests[1] = {&request};
  5781. struct sigevent sevp{};
  5782. struct timespec timeout{timeout_sec, 0};
  5783. request.ar_name = node;
  5784. request.ar_service = service;
  5785. request.ar_request = hints;
  5786. sevp.sigev_notify = SIGEV_NONE;
  5787. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5788. if (rc != 0) { return rc; }
  5789. auto cleanup = scope_exit([&] {
  5790. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5791. });
  5792. int wait_result = gai_suspend(requests, 1, &timeout);
  5793. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5794. int gai_result = gai_error(&request);
  5795. if (gai_result == 0) {
  5796. *res = request.ar_result;
  5797. request.ar_result = nullptr;
  5798. return 0;
  5799. }
  5800. return gai_result;
  5801. }
  5802. gai_cancel(&request);
  5803. while (gai_error(&request) == EAI_INPROGRESS) {
  5804. gai_suspend(requests, 1, nullptr);
  5805. }
  5806. return wait_result;
  5807. #else
  5808. // Fallback implementation using thread-based timeout for other Unix systems.
  5809. struct GetAddrInfoState {
  5810. ~GetAddrInfoState() {
  5811. if (info) { freeaddrinfo(info); }
  5812. }
  5813. std::mutex mutex;
  5814. std::condition_variable result_cv;
  5815. bool completed = false;
  5816. int result = EAI_SYSTEM;
  5817. std::string node;
  5818. std::string service;
  5819. struct addrinfo hints;
  5820. struct addrinfo *info = nullptr;
  5821. };
  5822. // Allocate on the heap, so the resolver thread can keep using the data.
  5823. auto state = std::make_shared<GetAddrInfoState>();
  5824. if (node) { state->node = node; }
  5825. state->service = service;
  5826. state->hints = *hints;
  5827. std::thread resolve_thread([state]() {
  5828. auto thread_result =
  5829. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5830. &state->info);
  5831. std::lock_guard<std::mutex> lock(state->mutex);
  5832. state->result = thread_result;
  5833. state->completed = true;
  5834. state->result_cv.notify_one();
  5835. });
  5836. // Wait for completion or timeout
  5837. std::unique_lock<std::mutex> lock(state->mutex);
  5838. auto finished =
  5839. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5840. [&] { return state->completed; });
  5841. if (finished) {
  5842. // Operation completed within timeout
  5843. resolve_thread.join();
  5844. *res = state->info;
  5845. state->info = nullptr; // Pass ownership to caller
  5846. return state->result;
  5847. } else {
  5848. // Timeout occurred
  5849. resolve_thread.detach(); // Let the thread finish in background
  5850. return EAI_AGAIN; // Return timeout error
  5851. }
  5852. #endif
  5853. #else
  5854. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5855. return getaddrinfo(node, service, hints, res);
  5856. #endif
  5857. }
  5858. template <typename BindOrConnect>
  5859. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5860. int address_family, int socket_flags, bool tcp_nodelay,
  5861. bool ipv6_v6only, SocketOptions socket_options,
  5862. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5863. // Get address info
  5864. const char *node = nullptr;
  5865. struct addrinfo hints;
  5866. struct addrinfo *result;
  5867. memset(&hints, 0, sizeof(struct addrinfo));
  5868. hints.ai_socktype = SOCK_STREAM;
  5869. hints.ai_protocol = IPPROTO_IP;
  5870. if (!ip.empty()) {
  5871. node = ip.c_str();
  5872. // Ask getaddrinfo to convert IP in c-string to address
  5873. hints.ai_family = AF_UNSPEC;
  5874. hints.ai_flags = AI_NUMERICHOST;
  5875. } else {
  5876. if (!host.empty()) { node = host.c_str(); }
  5877. hints.ai_family = address_family;
  5878. hints.ai_flags = socket_flags;
  5879. }
  5880. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5881. if (hints.ai_family == AF_UNIX) {
  5882. const auto addrlen = host.length();
  5883. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5884. #ifdef SOCK_CLOEXEC
  5885. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5886. hints.ai_protocol);
  5887. #else
  5888. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5889. #endif
  5890. if (sock != INVALID_SOCKET) {
  5891. sockaddr_un addr{};
  5892. addr.sun_family = AF_UNIX;
  5893. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5894. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5895. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5896. hints.ai_addrlen = static_cast<socklen_t>(
  5897. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5898. #ifndef SOCK_CLOEXEC
  5899. #ifndef _WIN32
  5900. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5901. #endif
  5902. #endif
  5903. if (socket_options) { socket_options(sock); }
  5904. #ifdef _WIN32
  5905. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5906. // remove the option.
  5907. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5908. #endif
  5909. bool dummy;
  5910. if (!bind_or_connect(sock, hints, dummy)) {
  5911. close_socket(sock);
  5912. sock = INVALID_SOCKET;
  5913. }
  5914. }
  5915. return sock;
  5916. }
  5917. #endif
  5918. auto service = std::to_string(port);
  5919. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5920. timeout_sec)) {
  5921. #if defined __linux__ && !defined __ANDROID__
  5922. res_init();
  5923. #endif
  5924. return INVALID_SOCKET;
  5925. }
  5926. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5927. for (auto rp = result; rp; rp = rp->ai_next) {
  5928. // Create a socket
  5929. #ifdef _WIN32
  5930. auto sock =
  5931. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5932. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5933. /**
  5934. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5935. * and above the socket creation fails on older Windows Systems.
  5936. *
  5937. * Let's try to create a socket the old way in this case.
  5938. *
  5939. * Reference:
  5940. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5941. *
  5942. * WSA_FLAG_NO_HANDLE_INHERIT:
  5943. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5944. * SP1, and later
  5945. *
  5946. */
  5947. if (sock == INVALID_SOCKET) {
  5948. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5949. }
  5950. #else
  5951. #ifdef SOCK_CLOEXEC
  5952. auto sock =
  5953. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5954. #else
  5955. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5956. #endif
  5957. #endif
  5958. if (sock == INVALID_SOCKET) { continue; }
  5959. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5960. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5961. close_socket(sock);
  5962. continue;
  5963. }
  5964. #endif
  5965. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5966. if (rp->ai_family == AF_INET6) {
  5967. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5968. }
  5969. if (socket_options) { socket_options(sock); }
  5970. // bind or connect
  5971. auto quit = false;
  5972. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5973. close_socket(sock);
  5974. if (quit) { break; }
  5975. }
  5976. return INVALID_SOCKET;
  5977. }
  5978. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5979. #ifdef _WIN32
  5980. auto flags = nonblocking ? 1UL : 0UL;
  5981. ioctlsocket(sock, FIONBIO, &flags);
  5982. #else
  5983. auto flags = fcntl(sock, F_GETFL, 0);
  5984. fcntl(sock, F_SETFL,
  5985. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5986. #endif
  5987. }
  5988. inline bool is_connection_error() {
  5989. #ifdef _WIN32
  5990. return WSAGetLastError() != WSAEWOULDBLOCK;
  5991. #else
  5992. return errno != EINPROGRESS;
  5993. #endif
  5994. }
  5995. // accept() failed because the process or the network stack is temporarily out
  5996. // of resources. The listening socket is still usable, so back off briefly and
  5997. // try again.
  5998. inline bool is_accept_resource_error() {
  5999. #ifdef _WIN32
  6000. auto err = WSAGetLastError();
  6001. return err == WSAEMFILE || err == WSAENOBUFS;
  6002. #else
  6003. auto err = errno;
  6004. return err == EMFILE || err == ENFILE || err == ENOBUFS || err == ENOMEM;
  6005. #endif
  6006. }
  6007. // accept() failed for a reason that says nothing about the listening socket:
  6008. // the pending connection went away before it could be accepted, or the call
  6009. // was interrupted. Retry immediately. WSAAccept()'s own documentation omits
  6010. // WSAECONNRESET, but the accept() it wraps reports an aborted pending
  6011. // connection that way.
  6012. inline bool is_accept_transient_error() {
  6013. #ifdef _WIN32
  6014. auto err = WSAGetLastError();
  6015. return err == WSAEINTR || err == WSAEWOULDBLOCK || err == WSAECONNRESET ||
  6016. err == WSAECONNABORTED;
  6017. #else
  6018. auto err = errno;
  6019. return err == EINTR || err == EAGAIN || err == EWOULDBLOCK ||
  6020. err == ECONNABORTED;
  6021. #endif
  6022. }
  6023. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  6024. struct addrinfo hints;
  6025. struct addrinfo *result;
  6026. memset(&hints, 0, sizeof(struct addrinfo));
  6027. hints.ai_family = AF_UNSPEC;
  6028. hints.ai_socktype = SOCK_STREAM;
  6029. hints.ai_protocol = 0;
  6030. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  6031. return false;
  6032. }
  6033. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6034. auto ret = false;
  6035. for (auto rp = result; rp; rp = rp->ai_next) {
  6036. const auto &ai = *rp;
  6037. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6038. ret = true;
  6039. break;
  6040. }
  6041. }
  6042. return ret;
  6043. }
  6044. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  6045. #define USE_IF2IP
  6046. #endif
  6047. #ifdef USE_IF2IP
  6048. inline std::string if2ip(int address_family, const std::string &ifn) {
  6049. struct ifaddrs *ifap;
  6050. getifaddrs(&ifap);
  6051. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  6052. std::string addr_candidate;
  6053. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  6054. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  6055. (AF_UNSPEC == address_family ||
  6056. ifa->ifa_addr->sa_family == address_family)) {
  6057. if (ifa->ifa_addr->sa_family == AF_INET) {
  6058. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  6059. char buf[INET_ADDRSTRLEN];
  6060. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  6061. return std::string(buf, INET_ADDRSTRLEN);
  6062. }
  6063. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  6064. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  6065. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  6066. char buf[INET6_ADDRSTRLEN] = {};
  6067. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  6068. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  6069. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  6070. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  6071. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  6072. } else {
  6073. return std::string(buf, INET6_ADDRSTRLEN);
  6074. }
  6075. }
  6076. }
  6077. }
  6078. }
  6079. }
  6080. return addr_candidate;
  6081. }
  6082. #endif
  6083. inline socket_t create_client_socket(
  6084. const std::string &host, const std::string &ip, int port,
  6085. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  6086. SocketOptions socket_options, time_t connection_timeout_sec,
  6087. time_t connection_timeout_usec, time_t read_timeout_sec,
  6088. time_t read_timeout_usec, time_t write_timeout_sec,
  6089. time_t write_timeout_usec, const std::string &intf, Error &error) {
  6090. auto sock = create_socket(
  6091. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  6092. std::move(socket_options),
  6093. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  6094. if (!intf.empty()) {
  6095. #ifdef USE_IF2IP
  6096. auto ip_from_if = if2ip(address_family, intf);
  6097. if (ip_from_if.empty()) { ip_from_if = intf; }
  6098. if (!bind_ip_address(sock2, ip_from_if)) {
  6099. error = Error::BindIPAddress;
  6100. return false;
  6101. }
  6102. #endif
  6103. }
  6104. set_nonblocking(sock2, true);
  6105. auto ret =
  6106. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  6107. if (ret < 0) {
  6108. if (is_connection_error()) {
  6109. error = Error::Connection;
  6110. return false;
  6111. }
  6112. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  6113. connection_timeout_usec);
  6114. if (error != Error::Success) {
  6115. if (error == Error::ConnectionTimeout) { quit = true; }
  6116. return false;
  6117. }
  6118. }
  6119. set_nonblocking(sock2, false);
  6120. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  6121. read_timeout_usec);
  6122. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  6123. write_timeout_usec);
  6124. error = Error::Success;
  6125. return true;
  6126. },
  6127. connection_timeout_sec); // Pass DNS timeout
  6128. if (sock != INVALID_SOCKET) {
  6129. error = Error::Success;
  6130. } else {
  6131. if (error == Error::Success) { error = Error::Connection; }
  6132. }
  6133. return sock;
  6134. }
  6135. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  6136. socklen_t addr_len, std::string &ip, int &port) {
  6137. if (addr.ss_family == AF_INET) {
  6138. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  6139. } else if (addr.ss_family == AF_INET6) {
  6140. port =
  6141. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  6142. } else {
  6143. return false;
  6144. }
  6145. std::array<char, NI_MAXHOST> ipstr{};
  6146. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  6147. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  6148. 0, NI_NUMERICHOST)) {
  6149. return false;
  6150. }
  6151. ip = ipstr.data();
  6152. return true;
  6153. }
  6154. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  6155. struct sockaddr_storage addr;
  6156. socklen_t addr_len = sizeof(addr);
  6157. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  6158. &addr_len)) {
  6159. get_ip_and_port(addr, addr_len, ip, port);
  6160. }
  6161. }
  6162. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  6163. struct sockaddr_storage addr;
  6164. socklen_t addr_len = sizeof(addr);
  6165. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  6166. &addr_len)) {
  6167. #ifndef _WIN32
  6168. if (addr.ss_family == AF_UNIX) {
  6169. #if defined(__linux__)
  6170. struct ucred ucred;
  6171. socklen_t len = sizeof(ucred);
  6172. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  6173. port = ucred.pid;
  6174. }
  6175. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  6176. pid_t pid;
  6177. socklen_t len = sizeof(pid);
  6178. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  6179. port = pid;
  6180. }
  6181. #endif
  6182. return;
  6183. }
  6184. #endif
  6185. get_ip_and_port(addr, addr_len, ip, port);
  6186. }
  6187. }
  6188. // Recursive form retained so operator""_t below can compute hashes for
  6189. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  6190. // call from runtime paths with arbitrary-length inputs — use str2tag()
  6191. // instead, which is iterative and stack-safe.
  6192. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  6193. unsigned int h) {
  6194. return (l == 0)
  6195. ? h
  6196. : str2tag_core(
  6197. s + 1, l - 1,
  6198. // Unsets the 6 high bits of h, therefore no overflow happens
  6199. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  6200. h * 33) ^
  6201. static_cast<unsigned char>(*s));
  6202. }
  6203. inline unsigned int str2tag(const std::string &s) {
  6204. // Iterative form of str2tag_core: the recursive constexpr version is kept
  6205. // for compile-time UDL evaluation of short string literals, but at runtime
  6206. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  6207. // would blow the stack with one frame per character.
  6208. unsigned int h = 0;
  6209. for (auto c : s) {
  6210. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  6211. static_cast<unsigned char>(c);
  6212. }
  6213. return h;
  6214. }
  6215. namespace udl {
  6216. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  6217. return str2tag_core(s, l, 0);
  6218. }
  6219. } // namespace udl
  6220. inline std::string
  6221. find_content_type(const std::string &path,
  6222. const std::map<std::string, std::string> &user_data,
  6223. const std::string &default_content_type) {
  6224. auto ext = file_extension(path);
  6225. auto it = user_data.find(ext);
  6226. if (it != user_data.end()) { return it->second; }
  6227. using udl::operator""_t;
  6228. switch (str2tag(ext)) {
  6229. default: return default_content_type;
  6230. case "css"_t: return "text/css";
  6231. case "csv"_t: return "text/csv";
  6232. case "htm"_t:
  6233. case "html"_t: return "text/html";
  6234. case "js"_t:
  6235. case "mjs"_t: return "text/javascript";
  6236. case "txt"_t: return "text/plain";
  6237. case "vtt"_t: return "text/vtt";
  6238. case "apng"_t: return "image/apng";
  6239. case "avif"_t: return "image/avif";
  6240. case "bmp"_t: return "image/bmp";
  6241. case "gif"_t: return "image/gif";
  6242. case "png"_t: return "image/png";
  6243. case "svg"_t: return "image/svg+xml";
  6244. case "webp"_t: return "image/webp";
  6245. case "ico"_t: return "image/x-icon";
  6246. case "tif"_t: return "image/tiff";
  6247. case "tiff"_t: return "image/tiff";
  6248. case "jpg"_t:
  6249. case "jpeg"_t: return "image/jpeg";
  6250. case "mp4"_t: return "video/mp4";
  6251. case "mpeg"_t: return "video/mpeg";
  6252. case "webm"_t: return "video/webm";
  6253. case "mp3"_t: return "audio/mp3";
  6254. case "mpga"_t: return "audio/mpeg";
  6255. case "weba"_t: return "audio/webm";
  6256. case "wav"_t: return "audio/wave";
  6257. case "otf"_t: return "font/otf";
  6258. case "ttf"_t: return "font/ttf";
  6259. case "woff"_t: return "font/woff";
  6260. case "woff2"_t: return "font/woff2";
  6261. case "7z"_t: return "application/x-7z-compressed";
  6262. case "atom"_t: return "application/atom+xml";
  6263. case "pdf"_t: return "application/pdf";
  6264. case "json"_t: return "application/json";
  6265. case "rss"_t: return "application/rss+xml";
  6266. case "tar"_t: return "application/x-tar";
  6267. case "xht"_t:
  6268. case "xhtml"_t: return "application/xhtml+xml";
  6269. case "xslt"_t: return "application/xslt+xml";
  6270. case "xml"_t: return "application/xml";
  6271. case "gz"_t: return "application/gzip";
  6272. case "zip"_t: return "application/zip";
  6273. case "wasm"_t: return "application/wasm";
  6274. }
  6275. }
  6276. inline std::string
  6277. extract_media_type(const std::string &content_type,
  6278. std::map<std::string, std::string> *params = nullptr) {
  6279. // Extract type/subtype from Content-Type value (RFC 2045)
  6280. // e.g. "application/json; charset=utf-8" -> "application/json"
  6281. auto media_type = content_type;
  6282. auto semicolon_pos = media_type.find(';');
  6283. if (semicolon_pos != std::string::npos) {
  6284. auto param_str = media_type.substr(semicolon_pos + 1);
  6285. media_type = media_type.substr(0, semicolon_pos);
  6286. if (params) {
  6287. // Parse parameters: key=value pairs separated by ';'
  6288. split_unquoted(param_str.data(), param_str.data() + param_str.size(), ';',
  6289. [&](const char *b, const char *e) {
  6290. std::string key;
  6291. std::string val;
  6292. divide_param_pair(b, e, key, val);
  6293. if (!key.empty()) {
  6294. params->emplace(trim_copy(key),
  6295. trim_double_quotes_copy(val));
  6296. }
  6297. });
  6298. }
  6299. }
  6300. // Trim whitespace from media type
  6301. return trim_copy(media_type);
  6302. }
  6303. inline bool can_compress_content_type(const std::string &content_type) {
  6304. using udl::operator""_t;
  6305. auto mime_type = extract_media_type(content_type);
  6306. auto tag = str2tag(mime_type);
  6307. switch (tag) {
  6308. case "image/svg+xml"_t:
  6309. case "application/javascript"_t:
  6310. case "application/x-javascript"_t:
  6311. case "application/json"_t:
  6312. case "application/ld+json"_t:
  6313. case "application/xml"_t:
  6314. case "application/xhtml+xml"_t:
  6315. case "application/rss+xml"_t:
  6316. case "application/atom+xml"_t:
  6317. case "application/xslt+xml"_t:
  6318. case "application/protobuf"_t: return true;
  6319. case "text/event-stream"_t: return false;
  6320. default: return !mime_type.rfind("text/", 0);
  6321. }
  6322. }
  6323. inline bool parse_quality(const char *b, const char *e, std::string &token,
  6324. double &quality) {
  6325. quality = 1.0;
  6326. token.clear();
  6327. // Split on first ';': left = token name, right = parameters
  6328. const char *params_b = nullptr;
  6329. std::size_t params_len = 0;
  6330. divide(
  6331. b, static_cast<std::size_t>(e - b), ';',
  6332. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  6333. auto r = trim(lb, lb + llen, 0, llen);
  6334. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  6335. params_b = rb;
  6336. params_len = rlen;
  6337. });
  6338. if (token.empty()) { return false; }
  6339. if (params_len == 0) { return true; }
  6340. // Scan parameters for q= (stops on first match)
  6341. bool invalid = false;
  6342. split_find(params_b, params_b + params_len, ';',
  6343. (std::numeric_limits<size_t>::max)(),
  6344. [&](const char *pb, const char *pe) -> bool {
  6345. // Match exactly "q=" or "Q=" (not "query=" etc.)
  6346. auto len = static_cast<size_t>(pe - pb);
  6347. if (len < 2) { return false; }
  6348. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  6349. return false;
  6350. }
  6351. // Trim the value portion
  6352. auto r = trim(pb, pe, 2, len);
  6353. if (r.first >= r.second) {
  6354. invalid = true;
  6355. return true;
  6356. }
  6357. double v = 0.0;
  6358. auto res = from_chars(pb + r.first, pb + r.second, v);
  6359. if (res.ec != std::errc{} || res.ptr != pb + r.second ||
  6360. v < 0.0 || v > 1.0) {
  6361. invalid = true;
  6362. return true;
  6363. }
  6364. quality = v;
  6365. return true;
  6366. });
  6367. return !invalid;
  6368. }
  6369. inline EncodingType encoding_type(const Request &req,
  6370. const std::string &content_type) {
  6371. if (!can_compress_content_type(content_type)) { return EncodingType::None; }
  6372. auto s = get_combined_header_value(req.headers, "Accept-Encoding");
  6373. if (s.empty()) { return EncodingType::None; }
  6374. // Single-pass: iterate tokens and track the best supported encoding.
  6375. // Server preference breaks ties (br > gzip > zstd).
  6376. EncodingType best = EncodingType::None;
  6377. double best_q = 0.0; // q=0 means "not acceptable"
  6378. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  6379. auto priority = [](EncodingType t) -> int {
  6380. switch (t) {
  6381. case EncodingType::Brotli: return 0;
  6382. case EncodingType::Gzip: return 1;
  6383. case EncodingType::Zstd: return 2;
  6384. default: return 3;
  6385. }
  6386. };
  6387. std::string name;
  6388. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6389. double quality = 1.0;
  6390. if (!parse_quality(b, e, name, quality)) { return; }
  6391. if (quality <= 0.0) { return; }
  6392. EncodingType type = EncodingType::None;
  6393. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6394. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  6395. #endif
  6396. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6397. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  6398. type = EncodingType::Gzip;
  6399. }
  6400. #endif
  6401. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6402. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  6403. type = EncodingType::Zstd;
  6404. }
  6405. #endif
  6406. if (type == EncodingType::None) { return; }
  6407. // Higher q-value wins; for equal q, server preference breaks ties
  6408. if (quality > best_q ||
  6409. (quality == best_q && priority(type) < priority(best))) {
  6410. best_q = quality;
  6411. best = type;
  6412. }
  6413. });
  6414. return best;
  6415. }
  6416. // `content_type` is taken separately because a file-backed response has not
  6417. // been given one yet when its coding has to be decided.
  6418. inline EncodingType encoding_type(const Request &req, const Response &res,
  6419. const std::string &content_type) {
  6420. // The response already names a content coding of its own: a handler serving
  6421. // a body it encoded itself (pre-compressed static assets, say), or a mount
  6422. // point whose headers name the coding its files are stored in. Applying one
  6423. // on top of that would double-encode the body and append a second
  6424. // `Content-Encoding` field line.
  6425. if (res.has_header("Content-Encoding")) { return EncodingType::None; }
  6426. return encoding_type(req, content_type);
  6427. }
  6428. inline EncodingType encoding_type(const Request &req, const Response &res) {
  6429. return encoding_type(req, res, res.get_header_value("Content-Type"));
  6430. }
  6431. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  6432. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6433. if (type == EncodingType::Gzip) {
  6434. return detail::make_unique<gzip_compressor>();
  6435. }
  6436. #endif
  6437. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6438. if (type == EncodingType::Brotli) {
  6439. return detail::make_unique<brotli_compressor>();
  6440. }
  6441. #endif
  6442. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6443. if (type == EncodingType::Zstd) {
  6444. return detail::make_unique<zstd_compressor>();
  6445. }
  6446. #endif
  6447. (void)type;
  6448. return nullptr;
  6449. }
  6450. inline const char *encoding_name(EncodingType type) {
  6451. switch (type) {
  6452. case EncodingType::Gzip: return "gzip";
  6453. case EncodingType::Brotli: return "br";
  6454. case EncodingType::Zstd: return "zstd";
  6455. default: return "";
  6456. }
  6457. }
  6458. inline bool nocompressor::compress(const char *data, size_t data_length,
  6459. bool /*last*/, Callback callback) {
  6460. if (!data_length) { return true; }
  6461. return callback(data, data_length);
  6462. }
  6463. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6464. inline gzip_compressor::gzip_compressor() {
  6465. std::memset(&strm_, 0, sizeof(strm_));
  6466. strm_.zalloc = Z_NULL;
  6467. strm_.zfree = Z_NULL;
  6468. strm_.opaque = Z_NULL;
  6469. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  6470. Z_DEFAULT_STRATEGY) == Z_OK;
  6471. }
  6472. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  6473. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  6474. bool last, Callback callback) {
  6475. assert(is_valid_);
  6476. do {
  6477. constexpr size_t max_avail_in =
  6478. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6479. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6480. (std::min)(data_length, max_avail_in));
  6481. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6482. data_length -= strm_.avail_in;
  6483. data += strm_.avail_in;
  6484. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  6485. auto ret = Z_OK;
  6486. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6487. do {
  6488. strm_.avail_out = static_cast<uInt>(buff.size());
  6489. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6490. ret = deflate(&strm_, flush);
  6491. if (ret == Z_STREAM_ERROR) { return false; }
  6492. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6493. return false;
  6494. }
  6495. } while (strm_.avail_out == 0);
  6496. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  6497. (flush == Z_NO_FLUSH && ret == Z_OK));
  6498. assert(strm_.avail_in == 0);
  6499. } while (data_length > 0);
  6500. return true;
  6501. }
  6502. inline gzip_decompressor::gzip_decompressor() {
  6503. std::memset(&strm_, 0, sizeof(strm_));
  6504. strm_.zalloc = Z_NULL;
  6505. strm_.zfree = Z_NULL;
  6506. strm_.opaque = Z_NULL;
  6507. // 15 is the value of wbits, which should be at the maximum possible value
  6508. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  6509. // that the stream type should be automatically detected either gzip or
  6510. // deflate.
  6511. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  6512. }
  6513. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  6514. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  6515. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  6516. Callback callback) {
  6517. assert(is_valid_);
  6518. auto ret = Z_OK;
  6519. do {
  6520. constexpr size_t max_avail_in =
  6521. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  6522. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  6523. (std::min)(data_length, max_avail_in));
  6524. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  6525. data_length -= strm_.avail_in;
  6526. data += strm_.avail_in;
  6527. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6528. while (strm_.avail_in > 0 && ret == Z_OK) {
  6529. strm_.avail_out = static_cast<uInt>(buff.size());
  6530. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  6531. ret = inflate(&strm_, Z_NO_FLUSH);
  6532. assert(ret != Z_STREAM_ERROR);
  6533. switch (ret) {
  6534. case Z_NEED_DICT:
  6535. case Z_DATA_ERROR:
  6536. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  6537. }
  6538. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  6539. return false;
  6540. }
  6541. }
  6542. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  6543. } while (data_length > 0);
  6544. return true;
  6545. }
  6546. #endif
  6547. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6548. inline brotli_compressor::brotli_compressor() {
  6549. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  6550. }
  6551. inline brotli_compressor::~brotli_compressor() {
  6552. BrotliEncoderDestroyInstance(state_);
  6553. }
  6554. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  6555. bool last, Callback callback) {
  6556. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6557. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  6558. auto available_in = data_length;
  6559. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6560. for (;;) {
  6561. if (last) {
  6562. if (BrotliEncoderIsFinished(state_)) { break; }
  6563. } else {
  6564. if (!available_in) { break; }
  6565. }
  6566. auto available_out = buff.size();
  6567. auto next_out = buff.data();
  6568. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  6569. &available_out, &next_out, nullptr)) {
  6570. return false;
  6571. }
  6572. auto output_bytes = buff.size() - available_out;
  6573. if (output_bytes) {
  6574. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  6575. }
  6576. }
  6577. return true;
  6578. }
  6579. inline brotli_decompressor::brotli_decompressor() {
  6580. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  6581. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  6582. : BROTLI_DECODER_RESULT_ERROR;
  6583. }
  6584. inline brotli_decompressor::~brotli_decompressor() {
  6585. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  6586. }
  6587. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  6588. inline bool brotli_decompressor::decompress(const char *data,
  6589. size_t data_length,
  6590. Callback callback) {
  6591. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6592. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  6593. return 0;
  6594. }
  6595. auto next_in = reinterpret_cast<const uint8_t *>(data);
  6596. size_t avail_in = data_length;
  6597. size_t total_out;
  6598. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  6599. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6600. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  6601. char *next_out = buff.data();
  6602. size_t avail_out = buff.size();
  6603. decoder_r = BrotliDecoderDecompressStream(
  6604. decoder_s, &avail_in, &next_in, &avail_out,
  6605. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  6606. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  6607. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  6608. }
  6609. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  6610. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  6611. }
  6612. #endif
  6613. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6614. inline zstd_compressor::zstd_compressor() {
  6615. ctx_ = ZSTD_createCCtx();
  6616. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  6617. }
  6618. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  6619. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  6620. bool last, Callback callback) {
  6621. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6622. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  6623. ZSTD_inBuffer input = {data, data_length, 0};
  6624. bool finished;
  6625. do {
  6626. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6627. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  6628. if (ZSTD_isError(remaining)) { return false; }
  6629. if (!callback(buff.data(), output.pos)) { return false; }
  6630. finished = last ? (remaining == 0) : (input.pos == input.size);
  6631. } while (!finished);
  6632. return true;
  6633. }
  6634. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  6635. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  6636. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  6637. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  6638. Callback callback) {
  6639. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  6640. ZSTD_inBuffer input = {data, data_length, 0};
  6641. while (input.pos < input.size) {
  6642. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  6643. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  6644. if (ZSTD_isError(remaining)) { return false; }
  6645. if (!callback(buff.data(), output.pos)) { return false; }
  6646. }
  6647. return true;
  6648. }
  6649. #endif
  6650. // Content codings are case-insensitive (RFC 9110 8.4.1). Matching them
  6651. // case-sensitively would make a response labeled e.g. "GZIP" look like an
  6652. // unknown coding, and its payload would be handed back still compressed.
  6653. inline bool is_zlib_encoding(const std::string &encoding) {
  6654. return case_ignore::equal(encoding, "gzip") ||
  6655. case_ignore::equal(encoding, "deflate");
  6656. }
  6657. inline bool is_brotli_encoding(const std::string &encoding) {
  6658. return case_ignore::equal(encoding, "br");
  6659. }
  6660. inline bool is_zstd_encoding(const std::string &encoding) {
  6661. return case_ignore::equal(encoding, "zstd");
  6662. }
  6663. // Returns true if the content coding is one cpp-httplib is able to decompress
  6664. // when the corresponding support is compiled in.
  6665. inline bool is_known_content_encoding(const std::string &encoding) {
  6666. return is_zlib_encoding(encoding) || is_brotli_encoding(encoding) ||
  6667. is_zstd_encoding(encoding);
  6668. }
  6669. inline std::unique_ptr<decompressor>
  6670. create_decompressor(const std::string &encoding) {
  6671. std::unique_ptr<decompressor> decompressor;
  6672. if (is_zlib_encoding(encoding)) {
  6673. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6674. decompressor = detail::make_unique<gzip_decompressor>();
  6675. #endif
  6676. } else if (is_brotli_encoding(encoding)) {
  6677. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6678. decompressor = detail::make_unique<brotli_decompressor>();
  6679. #endif
  6680. } else if (is_zstd_encoding(encoding)) {
  6681. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6682. decompressor = detail::make_unique<zstd_decompressor>();
  6683. #endif
  6684. }
  6685. return decompressor;
  6686. }
  6687. // Returns the best available compressor and its Content-Encoding name.
  6688. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  6689. inline std::pair<std::unique_ptr<compressor>, const char *>
  6690. create_compressor() {
  6691. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6692. return {detail::make_unique<brotli_compressor>(), "br"};
  6693. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6694. return {detail::make_unique<gzip_compressor>(), "gzip"};
  6695. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6696. return {detail::make_unique<zstd_compressor>(), "zstd"};
  6697. #else
  6698. return {nullptr, nullptr};
  6699. #endif
  6700. }
  6701. inline bool is_prohibited_header_name(const std::string &name) {
  6702. using udl::operator""_t;
  6703. switch (str2tag(name)) {
  6704. case "REMOTE_ADDR"_t:
  6705. case "REMOTE_PORT"_t:
  6706. case "LOCAL_ADDR"_t:
  6707. case "LOCAL_PORT"_t: return true;
  6708. default: return false;
  6709. }
  6710. }
  6711. inline bool has_header(const Headers &headers, const std::string &key) {
  6712. if (is_prohibited_header_name(key)) { return false; }
  6713. return headers.find(key) != headers.end();
  6714. }
  6715. inline const char *get_header_value(const Headers &headers,
  6716. const std::string &key, const char *def,
  6717. size_t id) {
  6718. if (is_prohibited_header_name(key)) {
  6719. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6720. std::string msg = "Prohibited header name '" + key + "' is specified.";
  6721. throw std::invalid_argument(msg);
  6722. #else
  6723. return "";
  6724. #endif
  6725. }
  6726. auto rng = headers.equal_range(key);
  6727. auto it = rng.first;
  6728. std::advance(it, static_cast<ssize_t>(id));
  6729. if (it != rng.second) { return it->second.c_str(); }
  6730. return def;
  6731. }
  6732. inline size_t get_header_value_count(const Headers &headers,
  6733. const std::string &key) {
  6734. return headers.count(key);
  6735. }
  6736. // RFC 9110 Section 5.2 and 5.3: a field that is defined as a comma-separated
  6737. // list may be sent as several field lines, and the combined field value is
  6738. // those values joined by commas in the order they were received. Callers that
  6739. // parse such a list must work on the combined value; reading only the first
  6740. // occurrence silently drops whatever the later field lines carry.
  6741. inline std::string get_combined_header_value(const Headers &headers,
  6742. const std::string &key) {
  6743. std::string combined;
  6744. auto rng = headers.equal_range(key);
  6745. for (auto it = rng.first; it != rng.second; ++it) {
  6746. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  6747. // elements, so an empty field line must not contribute a bare comma to the
  6748. // combined value.
  6749. if (it->second.empty()) { continue; }
  6750. if (!combined.empty()) { combined += ", "; }
  6751. combined += it->second;
  6752. }
  6753. return combined;
  6754. }
  6755. inline bool has_header_token(const Headers &headers, const std::string &key,
  6756. const std::string &token) {
  6757. // RFC 9110 7.6.1: a comma-separated token list field such as Connection may
  6758. // carry several tokens, and RFC 9110 5.3 lets that list be split across
  6759. // several lines. Match complete tokens rather than searching the raw value,
  6760. // so that a value such as "notupgrade" is not read as the token "upgrade".
  6761. auto rng = headers.equal_range(key);
  6762. for (auto it = rng.first; it != rng.second; ++it) {
  6763. const auto &value = it->second;
  6764. if (split_find(value.data(), value.data() + value.size(), ',',
  6765. [&](const char *b, const char *e) {
  6766. return case_ignore::equal(std::string(b, e), token);
  6767. })) {
  6768. return true;
  6769. }
  6770. }
  6771. return false;
  6772. }
  6773. template <typename Map>
  6774. inline typename Map::mapped_type
  6775. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  6776. auto rng = m.equal_range(key);
  6777. auto it = rng.first;
  6778. std::advance(it, static_cast<ssize_t>(id));
  6779. if (it != rng.second) { return it->second; }
  6780. return typename Map::mapped_type();
  6781. }
  6782. inline void set_header(Headers &headers, const std::string &key,
  6783. const std::string &val) {
  6784. if (fields::is_field_valid(key, val)) { headers.emplace(key, val); }
  6785. }
  6786. inline bool read_headers(Stream &strm, Headers &headers) {
  6787. const auto bufsiz = 2048;
  6788. char buf[bufsiz];
  6789. stream_line_reader line_reader(strm, buf, bufsiz);
  6790. size_t header_count = 0;
  6791. for (;;) {
  6792. if (!line_reader.getline()) { return false; }
  6793. // Check if the line ends with CRLF.
  6794. auto line_terminator_len = 2;
  6795. if (line_reader.end_with_crlf()) {
  6796. // Blank line indicates end of headers.
  6797. if (line_reader.size() == 2) { break; }
  6798. } else {
  6799. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6800. // Blank line indicates end of headers.
  6801. if (line_reader.size() == 1) { break; }
  6802. line_terminator_len = 1;
  6803. #else
  6804. continue; // Skip invalid line.
  6805. #endif
  6806. }
  6807. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6808. // Check header count limit
  6809. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  6810. // Exclude line terminator
  6811. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  6812. if (!parse_header(line_reader.ptr(), end,
  6813. [&](const std::string &key, const std::string &val) {
  6814. headers.emplace(key, val);
  6815. })) {
  6816. return false;
  6817. }
  6818. header_count++;
  6819. }
  6820. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  6821. // headers that have different values to prevent request smuggling.
  6822. auto cl_range = headers.equal_range("Content-Length");
  6823. if (cl_range.first != cl_range.second) {
  6824. const auto &first_val = cl_range.first->second;
  6825. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  6826. if (it->second != first_val) { return false; }
  6827. }
  6828. }
  6829. return true;
  6830. }
  6831. inline bool parse_status_line(const char *line, std::string &version,
  6832. int &status, std::string &reason) {
  6833. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6834. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  6835. #else
  6836. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  6837. #endif
  6838. std::cmatch m;
  6839. if (!std::regex_match(line, m, re)) { return false; }
  6840. version = std::string(m[1]);
  6841. status = std::stoi(std::string(m[2]));
  6842. reason = std::string(m[3]);
  6843. return true;
  6844. }
  6845. // Everything WebSocketClient::connect() reports about the upgrade exchange.
  6846. // status stays -1 until a status line is parsed, mirroring stream::Result.
  6847. struct WebSocketUpgradeResponse {
  6848. Error error = Error::Success;
  6849. int status = -1;
  6850. Headers headers;
  6851. std::string selected_subprotocol;
  6852. };
  6853. inline bool read_websocket_upgrade_response(Stream &strm,
  6854. const std::string &expected_accept,
  6855. WebSocketUpgradeResponse &upgrade) {
  6856. // Read status line
  6857. const auto bufsiz = 2048;
  6858. char buf[bufsiz];
  6859. stream_line_reader line_reader(strm, buf, bufsiz);
  6860. if (!line_reader.getline()) {
  6861. upgrade.error = Error::Read;
  6862. return false;
  6863. }
  6864. std::string version;
  6865. std::string reason;
  6866. if (!parse_status_line(line_reader.ptr(), version, upgrade.status, reason)) {
  6867. upgrade.error = Error::WebSocketHandshake;
  6868. return false;
  6869. }
  6870. // Read the headers even for a rejection so the caller can see why the
  6871. // server refused the upgrade. A non-101 response may carry a body; it is
  6872. // deliberately left unread since the caller closes the socket right away.
  6873. if (!read_headers(strm, upgrade.headers)) {
  6874. upgrade.error = Error::Read;
  6875. return false;
  6876. }
  6877. const auto &headers = upgrade.headers;
  6878. if (upgrade.status != StatusCode::SwitchingProtocol_101) {
  6879. upgrade.error = Error::WebSocketHandshake;
  6880. return false;
  6881. }
  6882. // Verify Upgrade: websocket (a comma-separated list, matched per token)
  6883. if (!has_header_token(headers, "Upgrade", "websocket")) {
  6884. upgrade.error = Error::WebSocketHandshake;
  6885. return false;
  6886. }
  6887. // Verify Connection: Upgrade
  6888. if (!has_header_token(headers, "Connection", "upgrade")) {
  6889. upgrade.error = Error::WebSocketHandshake;
  6890. return false;
  6891. }
  6892. // Verify Sec-WebSocket-Accept header value
  6893. auto it = headers.find("Sec-WebSocket-Accept");
  6894. if (it == headers.end() || it->second != expected_accept) {
  6895. upgrade.error = Error::WebSocketHandshake;
  6896. return false;
  6897. }
  6898. // Extract negotiated subprotocol
  6899. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6900. if (proto_it != headers.end()) {
  6901. upgrade.selected_subprotocol = proto_it->second;
  6902. }
  6903. return true;
  6904. }
  6905. enum class ReadContentResult {
  6906. Success, // Successfully read the content
  6907. PayloadTooLarge, // The content exceeds the specified payload limit
  6908. Error // An error occurred while reading the content
  6909. };
  6910. inline ReadContentResult read_content_with_length(
  6911. Stream &strm, size_t len, DownloadProgress progress,
  6912. ContentReceiverWithProgress out,
  6913. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6914. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6915. detail::BodyReader br;
  6916. br.stream = &strm;
  6917. br.has_content_length = true;
  6918. br.content_length = len;
  6919. br.payload_max_length = payload_max_length;
  6920. br.chunked = false;
  6921. br.bytes_read = 0;
  6922. br.last_error = Error::Success;
  6923. size_t r = 0;
  6924. while (r < len) {
  6925. auto read_len = static_cast<size_t>(len - r);
  6926. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6927. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6928. if (n <= 0) {
  6929. // Check if it was a payload size error
  6930. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6931. return ReadContentResult::PayloadTooLarge;
  6932. }
  6933. return ReadContentResult::Error;
  6934. }
  6935. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6936. return ReadContentResult::Error;
  6937. }
  6938. r += static_cast<size_t>(n);
  6939. if (progress) {
  6940. if (!progress(r, len)) { return ReadContentResult::Error; }
  6941. }
  6942. }
  6943. return ReadContentResult::Success;
  6944. }
  6945. inline ReadContentResult
  6946. read_content_without_length(Stream &strm, size_t payload_max_length,
  6947. ContentReceiverWithProgress out) {
  6948. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6949. size_t r = 0;
  6950. for (;;) {
  6951. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6952. if (n == 0) { return ReadContentResult::Success; }
  6953. if (n < 0) { return ReadContentResult::Error; }
  6954. // Check if adding this data would exceed the payload limit
  6955. if (r > payload_max_length ||
  6956. payload_max_length - r < static_cast<size_t>(n)) {
  6957. return ReadContentResult::PayloadTooLarge;
  6958. }
  6959. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6960. return ReadContentResult::Error;
  6961. }
  6962. r += static_cast<size_t>(n);
  6963. }
  6964. return ReadContentResult::Success;
  6965. }
  6966. template <typename T>
  6967. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6968. size_t payload_max_length,
  6969. ContentReceiverWithProgress out) {
  6970. detail::ChunkedDecoder dec(strm);
  6971. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6972. size_t total_len = 0;
  6973. for (;;) {
  6974. size_t chunk_offset = 0;
  6975. size_t chunk_total = 0;
  6976. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6977. if (n < 0) { return ReadContentResult::Error; }
  6978. if (n == 0) {
  6979. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6980. return ReadContentResult::Error;
  6981. }
  6982. return ReadContentResult::Success;
  6983. }
  6984. if (total_len > payload_max_length ||
  6985. payload_max_length - total_len < static_cast<size_t>(n)) {
  6986. return ReadContentResult::PayloadTooLarge;
  6987. }
  6988. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6989. return ReadContentResult::Error;
  6990. }
  6991. total_len += static_cast<size_t>(n);
  6992. }
  6993. }
  6994. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6995. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  6996. // is the final transfer coding. A single field value may list several
  6997. // codings ("gzip, chunked"), and RFC 9110 5.3 lets that list be split across
  6998. // several Transfer-Encoding lines, which combine into one comma-separated
  6999. // list in the order the lines were received. Headers preserves that order,
  7000. // so the final coding is the last token of the last line. Match it
  7001. // case-insensitively rather than comparing the whole value against
  7002. // "chunked".
  7003. //
  7004. // Security: reading a chunked message as unframed leaves its body in the
  7005. // socket, where a keep-alive connection parses it as a smuggled request.
  7006. // Server::process_request() answers 400 and closes when the final coding is
  7007. // not chunked, so a request whose framing cannot be determined never
  7008. // reaches the "no body" path.
  7009. auto rng = headers.equal_range("Transfer-Encoding");
  7010. if (rng.first == rng.second) { return false; }
  7011. // Cleared per line, so a trailing line carrying no coding at all leaves the
  7012. // combined list ending in nothing rather than inheriting the line before it.
  7013. std::string last_coding;
  7014. for (auto it = rng.first; it != rng.second; ++it) {
  7015. const auto &value = it->second;
  7016. last_coding.clear();
  7017. split(value.data(), value.data() + value.size(), ',',
  7018. [&](const char *b, const char *e) { last_coding.assign(b, e); });
  7019. }
  7020. return case_ignore::equal(last_coding, "chunked");
  7021. }
  7022. inline bool has_conflicting_content_length(const Headers &headers) {
  7023. // RFC 9112 §6.3: a message carrying both Transfer-Encoding and a non-zero
  7024. // Content-Length is framed ambiguously. The body readers here delimit it by
  7025. // the transfer coding and drop Content-Length, while an intermediary may do
  7026. // the reverse, so the two disagree on where the body ends and a reused
  7027. // connection is desynchronised (request/response smuggling). Content-Length:
  7028. // 0 is tolerated for compatibility with existing peers.
  7029. return has_header(headers, "Transfer-Encoding") &&
  7030. get_header_value_u64(headers, "Content-Length", 0, 0) > 0;
  7031. }
  7032. template <typename T, typename U>
  7033. bool prepare_content_receiver(T &x, int &status,
  7034. ContentReceiverWithProgress receiver,
  7035. bool decompress, size_t payload_max_length,
  7036. bool &exceed_payload_max_length, U callback) {
  7037. if (decompress) {
  7038. auto encoding = get_combined_header_value(x.headers, "Content-Encoding");
  7039. std::unique_ptr<decompressor> decompressor;
  7040. if (!encoding.empty()) {
  7041. // A coding we know about but were not built with is an error. An
  7042. // unrecognized coding (including "identity") is left alone and the
  7043. // payload is passed through as-is, since some servers misuse the header,
  7044. // e.g. by sending a character set such as "Content-Encoding: UTF-8".
  7045. decompressor = detail::create_decompressor(encoding);
  7046. if (!decompressor && detail::is_known_content_encoding(encoding)) {
  7047. status = StatusCode::UnsupportedMediaType_415;
  7048. return false;
  7049. }
  7050. }
  7051. if (decompressor) {
  7052. if (decompressor->is_valid()) {
  7053. size_t decompressed_size = 0;
  7054. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  7055. size_t off, size_t len) {
  7056. return decompressor->decompress(
  7057. buf, n, [&](const char *buf2, size_t n2) {
  7058. // Guard against zip-bomb: check
  7059. // decompressed size against limit.
  7060. if (payload_max_length > 0 &&
  7061. (decompressed_size >= payload_max_length ||
  7062. n2 > payload_max_length - decompressed_size)) {
  7063. exceed_payload_max_length = true;
  7064. return false;
  7065. }
  7066. decompressed_size += n2;
  7067. return receiver(buf2, n2, off, len);
  7068. });
  7069. };
  7070. return callback(std::move(out));
  7071. } else {
  7072. status = StatusCode::InternalServerError_500;
  7073. return false;
  7074. }
  7075. }
  7076. }
  7077. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  7078. size_t len) {
  7079. return receiver(buf, n, off, len);
  7080. };
  7081. return callback(std::move(out));
  7082. }
  7083. template <typename T>
  7084. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  7085. DownloadProgress progress,
  7086. ContentReceiverWithProgress receiver, bool decompress) {
  7087. bool exceed_payload_max_length = false;
  7088. return prepare_content_receiver(
  7089. x, status, std::move(receiver), decompress, payload_max_length,
  7090. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  7091. auto ret = true;
  7092. // Note: exceed_payload_max_length may also be set by the decompressor
  7093. // wrapper in prepare_content_receiver when the decompressed payload
  7094. // size exceeds the limit.
  7095. if (is_chunked_transfer_encoding(x.headers)) {
  7096. auto result = read_content_chunked(strm, x, payload_max_length, out);
  7097. if (result == ReadContentResult::Success) {
  7098. ret = true;
  7099. } else if (result == ReadContentResult::PayloadTooLarge) {
  7100. exceed_payload_max_length = true;
  7101. ret = false;
  7102. } else {
  7103. ret = false;
  7104. }
  7105. } else if (!has_header(x.headers, "Content-Length")) {
  7106. auto result =
  7107. read_content_without_length(strm, payload_max_length, out);
  7108. if (result == ReadContentResult::Success) {
  7109. ret = true;
  7110. } else if (result == ReadContentResult::PayloadTooLarge) {
  7111. exceed_payload_max_length = true;
  7112. ret = false;
  7113. } else {
  7114. ret = false;
  7115. }
  7116. } else {
  7117. auto is_invalid_value = false;
  7118. auto len = get_header_value_u64(x.headers, "Content-Length",
  7119. (std::numeric_limits<size_t>::max)(),
  7120. 0, is_invalid_value);
  7121. if (is_invalid_value) {
  7122. ret = false;
  7123. } else if (len > 0) {
  7124. auto result = read_content_with_length(
  7125. strm, len, std::move(progress), out, payload_max_length);
  7126. ret = (result == ReadContentResult::Success);
  7127. if (result == ReadContentResult::PayloadTooLarge) {
  7128. exceed_payload_max_length = true;
  7129. }
  7130. }
  7131. }
  7132. if (!ret) {
  7133. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  7134. : StatusCode::BadRequest_400;
  7135. }
  7136. return ret;
  7137. });
  7138. }
  7139. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  7140. const std::string &path) {
  7141. // Neither the method nor the request target may carry CR/LF, SP or other
  7142. // control octets; otherwise a value smuggled into either splits the request
  7143. // line and injects headers or a whole request.
  7144. if (!fields::is_token(method)) { return -1; }
  7145. if (!fields::is_request_target(path)) { return -1; }
  7146. std::string s = method;
  7147. s += ' ';
  7148. s += path;
  7149. s += " HTTP/1.1\r\n";
  7150. return strm.write(s.data(), s.size());
  7151. }
  7152. inline ssize_t write_response_line(Stream &strm, int status) {
  7153. std::string s = "HTTP/1.1 ";
  7154. s += std::to_string(status);
  7155. s += ' ';
  7156. s += httplib::status_message(status);
  7157. s += "\r\n";
  7158. return strm.write(s.data(), s.size());
  7159. }
  7160. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  7161. ssize_t write_len = 0;
  7162. for (const auto &x : headers) {
  7163. // Skip fields with invalid names or values to prevent response splitting
  7164. // via CR/LF injection, matching set_header(). The client validates request
  7165. // headers up front in check_and_write_headers, but the server passes
  7166. // res.headers straight to this writer, and res.headers is a public field
  7167. // an application can populate directly with request-derived values.
  7168. if (!fields::is_field_valid(x.first, x.second)) { continue; }
  7169. std::string s;
  7170. s = x.first;
  7171. s += ": ";
  7172. s += x.second;
  7173. s += "\r\n";
  7174. auto len = strm.write(s.data(), s.size());
  7175. if (len < 0) { return len; }
  7176. write_len += len;
  7177. }
  7178. auto len = strm.write("\r\n");
  7179. if (len < 0) { return len; }
  7180. write_len += len;
  7181. return write_len;
  7182. }
  7183. inline bool write_data(Stream &strm, const char *d, size_t l) {
  7184. size_t offset = 0;
  7185. while (offset < l) {
  7186. auto length = strm.write(d + offset, l - offset);
  7187. if (length < 0) { return false; }
  7188. offset += static_cast<size_t>(length);
  7189. }
  7190. return true;
  7191. }
  7192. template <typename T>
  7193. inline bool write_content_with_progress(Stream &strm,
  7194. const ContentProvider &content_provider,
  7195. size_t offset, size_t length,
  7196. T is_shutting_down,
  7197. const UploadProgress &upload_progress,
  7198. Error &error) {
  7199. size_t end_offset = offset + length;
  7200. size_t start_offset = offset;
  7201. auto ok = true;
  7202. auto finished = false;
  7203. DataSink data_sink;
  7204. data_sink.write = [&](const char *d, size_t l) -> bool {
  7205. if (ok) {
  7206. if (write_data(strm, d, l)) {
  7207. offset += l;
  7208. if (upload_progress && length > 0) {
  7209. size_t current_written = offset - start_offset;
  7210. if (!upload_progress(current_written, length)) {
  7211. ok = false;
  7212. return false;
  7213. }
  7214. }
  7215. } else {
  7216. ok = false;
  7217. }
  7218. }
  7219. return ok;
  7220. };
  7221. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7222. // The body is framed by `length`, so a provider that reports itself done
  7223. // early has truncated it. Record that and let the short-body check below
  7224. // fail the write, rather than calling the provider again forever.
  7225. data_sink.done = [&]() { finished = true; };
  7226. while (offset < end_offset && !finished && !is_shutting_down()) {
  7227. auto last_offset = offset;
  7228. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7229. error = Error::Write;
  7230. return false;
  7231. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  7232. error = Error::Canceled;
  7233. return false;
  7234. } else if (!ok) {
  7235. error = Error::Write;
  7236. return false;
  7237. }
  7238. // A provider that reports success without writing anything and without
  7239. // reporting itself done gets handed the same offset and length again on
  7240. // the next pass, so it would spin here for as long as the peer stays
  7241. // connected. Treat making no progress as a short body, like done() early.
  7242. if (!finished && offset == last_offset) {
  7243. error = Error::Write;
  7244. return false;
  7245. }
  7246. }
  7247. if (offset < end_offset) { // done() called early, or is_shutting_down()
  7248. error = Error::Write;
  7249. return false;
  7250. }
  7251. error = Error::Success;
  7252. return true;
  7253. }
  7254. template <typename T>
  7255. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  7256. size_t offset, size_t length, T is_shutting_down,
  7257. Error &error) {
  7258. return write_content_with_progress<T>(strm, content_provider, offset, length,
  7259. is_shutting_down, nullptr, error);
  7260. }
  7261. template <typename T>
  7262. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  7263. size_t offset, size_t length,
  7264. const T &is_shutting_down) {
  7265. auto error = Error::Success;
  7266. return write_content(strm, content_provider, offset, length, is_shutting_down,
  7267. error);
  7268. }
  7269. template <typename T>
  7270. inline bool
  7271. write_content_without_length(Stream &strm,
  7272. const ContentProvider &content_provider,
  7273. const T &is_shutting_down) {
  7274. size_t offset = 0;
  7275. auto data_available = true;
  7276. auto ok = true;
  7277. DataSink data_sink;
  7278. data_sink.write = [&](const char *d, size_t l) -> bool {
  7279. if (ok) {
  7280. offset += l;
  7281. if (!write_data(strm, d, l)) { ok = false; }
  7282. }
  7283. return ok;
  7284. };
  7285. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7286. data_sink.done = [&](void) { data_available = false; };
  7287. while (data_available && !is_shutting_down()) {
  7288. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7289. return false;
  7290. } else if (!content_provider(offset, 0, data_sink)) {
  7291. return false;
  7292. } else if (!ok) {
  7293. return false;
  7294. }
  7295. }
  7296. return !data_available; // true only if done() was called, false if shutting
  7297. // down
  7298. }
  7299. // Runs a known-length content provider to completion and compresses what it
  7300. // writes into `out`. Nothing is buffered in identity form: a provider backed
  7301. // by an mmap hands the compressor a pointer straight into the mapping.
  7302. inline bool compress_content_provider(const ContentProvider &content_provider,
  7303. size_t length, compressor &cmp,
  7304. std::string &out) {
  7305. size_t offset = 0;
  7306. auto ok = true;
  7307. auto finished = false;
  7308. DataSink data_sink;
  7309. auto append = [&](const char *data, size_t data_len) {
  7310. out.append(data, data_len);
  7311. return true;
  7312. };
  7313. data_sink.write = [&](const char *d, size_t l) -> bool {
  7314. if (!ok) { return false; }
  7315. offset += l;
  7316. if (l > 0 && !cmp.compress(d, l, false, append)) { ok = false; }
  7317. return ok;
  7318. };
  7319. // The body is framed by `length`, so a provider that reports itself done
  7320. // early has truncated it; the short-body check below turns that into a
  7321. // failure rather than calling the provider again forever.
  7322. data_sink.done = [&]() { finished = true; };
  7323. while (offset < length && !finished) {
  7324. auto prev_offset = offset;
  7325. if (!content_provider(offset, length - offset, data_sink) || !ok) {
  7326. return false;
  7327. }
  7328. // No Stream to block on here, so a provider that keeps returning true
  7329. // without writing would spin. Treat a pass that made no progress as a
  7330. // failure.
  7331. if (offset == prev_offset) { return false; }
  7332. }
  7333. if (offset != length) { return false; }
  7334. return cmp.compress(nullptr, 0, true, append);
  7335. }
  7336. // Serves `m` as the response body. `set_content_provider()` clears the coding
  7337. // and the file flag, so recording them has to come after; keeping all of it
  7338. // here means a third file-serving path cannot get that order wrong.
  7339. inline void set_file_content_provider(Response &res,
  7340. const std::shared_ptr<mmap> &m,
  7341. const std::string &content_type,
  7342. EncodingType encoding) {
  7343. res.set_content_provider(
  7344. m->size(), content_type,
  7345. [m](size_t offset, size_t length, DataSink &sink) -> bool {
  7346. sink.write(m->data() + offset, length);
  7347. return true;
  7348. });
  7349. res.is_file_content_provider_ = true;
  7350. res.content_coding_ = encoding;
  7351. }
  7352. template <typename T, typename U>
  7353. inline bool
  7354. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  7355. const T &is_shutting_down, U &compressor, Error &error) {
  7356. size_t offset = 0;
  7357. auto data_available = true;
  7358. auto ok = true;
  7359. DataSink data_sink;
  7360. data_sink.write = [&](const char *d, size_t l) -> bool {
  7361. // Only done()/done_with_trailer() end a chunked body. A pass with nothing
  7362. // to hand over is ordinary (an empty buffer popped off a queue), and a
  7363. // zero-length chunk is the terminator, so it must not be emitted here.
  7364. if (ok && l > 0) {
  7365. offset += l;
  7366. std::string payload;
  7367. if (compressor.compress(d, l, false,
  7368. [&](const char *data, size_t data_len) {
  7369. payload.append(data, data_len);
  7370. return true;
  7371. })) {
  7372. if (!payload.empty()) {
  7373. // Emit chunked response header and footer for each chunk
  7374. auto chunk =
  7375. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7376. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  7377. }
  7378. } else {
  7379. ok = false;
  7380. }
  7381. }
  7382. return ok;
  7383. };
  7384. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  7385. auto done_with_trailer = [&](const Headers *trailer) {
  7386. if (!ok) { return; }
  7387. data_available = false;
  7388. std::string payload;
  7389. if (!compressor.compress(nullptr, 0, true,
  7390. [&](const char *data, size_t data_len) {
  7391. payload.append(data, data_len);
  7392. return true;
  7393. })) {
  7394. ok = false;
  7395. return;
  7396. }
  7397. if (!payload.empty()) {
  7398. // Emit chunked response header and footer for each chunk
  7399. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  7400. if (!write_data(strm, chunk.data(), chunk.size())) {
  7401. ok = false;
  7402. return;
  7403. }
  7404. }
  7405. constexpr const char done_marker[] = "0\r\n";
  7406. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  7407. // Trailer
  7408. if (trailer) {
  7409. for (const auto &kv : *trailer) {
  7410. // Skip fields with invalid names or values to prevent response
  7411. // splitting via CR/LF injection, matching set_header().
  7412. if (!fields::is_field_valid(kv.first, kv.second)) { continue; }
  7413. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  7414. if (!write_data(strm, field_line.data(), field_line.size())) {
  7415. ok = false;
  7416. }
  7417. }
  7418. }
  7419. constexpr const char crlf[] = "\r\n";
  7420. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  7421. };
  7422. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  7423. data_sink.done_with_trailer = [&](const Headers &trailer) {
  7424. done_with_trailer(&trailer);
  7425. };
  7426. while (data_available && !is_shutting_down()) {
  7427. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  7428. error = Error::Write;
  7429. return false;
  7430. } else if (!content_provider(offset, 0, data_sink)) {
  7431. error = Error::Canceled;
  7432. return false;
  7433. } else if (!ok) {
  7434. error = Error::Write;
  7435. return false;
  7436. }
  7437. }
  7438. if (data_available) { // exited due to is_shutting_down(), not done()
  7439. error = Error::Write;
  7440. return false;
  7441. }
  7442. error = Error::Success;
  7443. return true;
  7444. }
  7445. template <typename T, typename U>
  7446. inline bool write_content_chunked(Stream &strm,
  7447. const ContentProvider &content_provider,
  7448. const T &is_shutting_down, U &compressor) {
  7449. auto error = Error::Success;
  7450. return write_content_chunked(strm, content_provider, is_shutting_down,
  7451. compressor, error);
  7452. }
  7453. template <typename T>
  7454. inline bool redirect(T &cli, Request &req, Response &res,
  7455. const std::string &path, const std::string &location,
  7456. Error &error) {
  7457. Request new_req = req;
  7458. new_req.path = path;
  7459. new_req.redirect_count_ -= 1;
  7460. if (res.status == StatusCode::SeeOther_303 &&
  7461. (req.method != "GET" && req.method != "HEAD")) {
  7462. new_req.method = "GET";
  7463. new_req.body.clear();
  7464. new_req.headers.clear();
  7465. }
  7466. Response new_res;
  7467. auto ret = cli.send(new_req, new_res, error);
  7468. if (ret) {
  7469. req = std::move(new_req);
  7470. res = std::move(new_res);
  7471. if (res.location.empty()) { res.location = location; }
  7472. }
  7473. return ret;
  7474. }
  7475. inline std::string params_to_query_str(const Params &params) {
  7476. std::string query;
  7477. for (auto it = params.begin(); it != params.end(); ++it) {
  7478. if (it != params.begin()) { query += '&'; }
  7479. query += encode_query_component(it->first);
  7480. query += '=';
  7481. query += encode_query_component(it->second);
  7482. }
  7483. return query;
  7484. }
  7485. // Splits one "key=value" span of a query string at its first '='. A span with
  7486. // no '=' at all lands entirely in key, leaving val empty, which is how a bare
  7487. // "?flag" keeps its name.
  7488. inline void divide_query_pair(const char *b, const char *e, std::string &key,
  7489. std::string &val) {
  7490. divide(b, static_cast<std::size_t>(e - b), '=',
  7491. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  7492. std::size_t rhs_size) {
  7493. key.assign(lhs_data, lhs_size);
  7494. val.assign(rhs_data, rhs_size);
  7495. });
  7496. }
  7497. inline void parse_query_text(const char *data, std::size_t size,
  7498. Params &params) {
  7499. std::set<std::string> cache;
  7500. split(data, data + size, '&', [&](const char *b, const char *e) {
  7501. std::string kv(b, e);
  7502. if (cache.find(kv) != cache.end()) { return; }
  7503. cache.insert(std::move(kv));
  7504. std::string key;
  7505. std::string val;
  7506. divide_query_pair(b, e, key, val);
  7507. if (!key.empty()) {
  7508. params.emplace(decode_query_component(key), decode_query_component(val));
  7509. }
  7510. });
  7511. }
  7512. inline void parse_query_text(const std::string &s, Params &params) {
  7513. parse_query_text(s.data(), s.size(), params);
  7514. }
  7515. // Normalize a query string by decoding and re-encoding each key/value pair
  7516. // while preserving the original parameter order. This avoids double-encoding
  7517. // and ensures consistent encoding. It works on the raw string rather than
  7518. // parsing into Params and re-serializing, because that round trip cannot
  7519. // reproduce the input: params_to_query_str() always emits '=', so a bare
  7520. // "flag" would come back as "flag=", and parse_query_text() drops exactly
  7521. // duplicated pairs.
  7522. inline std::string normalize_query_string(const std::string &query) {
  7523. std::string result;
  7524. split(query.data(), query.data() + query.size(), '&',
  7525. [&](const char *b, const char *e) {
  7526. std::string key;
  7527. std::string val;
  7528. divide_query_pair(b, e, key, val);
  7529. if (!key.empty()) {
  7530. auto dec_key = decode_query_component(key);
  7531. auto dec_val = decode_query_component(val);
  7532. if (!result.empty()) { result += '&'; }
  7533. result += encode_query_component(dec_key);
  7534. if (!val.empty() || std::find(b, e, '=') != e) {
  7535. result += '=';
  7536. result += encode_query_component(dec_val);
  7537. }
  7538. }
  7539. });
  7540. return result;
  7541. }
  7542. // Build the request target that goes on the wire from a caller-supplied path.
  7543. // Shared by the buffered send path and the streaming API so that both put the
  7544. // same bytes in the request line for the same input.
  7545. inline std::string encode_request_target(const std::string &target,
  7546. bool path_encode) {
  7547. // `substr(0, npos)` yields the whole string, which is what the no-query
  7548. // case needs.
  7549. auto query_pos = target.find('?');
  7550. auto path_part = target.substr(0, query_pos);
  7551. std::string query_part;
  7552. if (query_pos != std::string::npos) {
  7553. query_part = target.substr(query_pos + 1);
  7554. }
  7555. auto result = path_encode ? encode_path(path_part) : std::move(path_part);
  7556. if (!query_part.empty()) {
  7557. // When path encoding is disabled the caller has supplied an already-encoded
  7558. // target and expects the exact bytes to be sent on the wire, so skip
  7559. // normalization for the query too. Normalizing would decode-then-re-encode
  7560. // it and corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  7561. // which a strict RFC 3986 server decodes back as `+`, not a space).
  7562. if (path_encode) {
  7563. auto normalized = normalize_query_string(query_part);
  7564. if (!normalized.empty()) {
  7565. result += '?';
  7566. result += normalized;
  7567. }
  7568. } else {
  7569. result += '?';
  7570. result += query_part;
  7571. }
  7572. }
  7573. return result;
  7574. }
  7575. inline bool parse_multipart_boundary(const std::string &content_type,
  7576. std::string &boundary) {
  7577. std::map<std::string, std::string> params;
  7578. extract_media_type(content_type, &params);
  7579. auto it = params.find("boundary");
  7580. if (it == params.end()) { return false; }
  7581. boundary = it->second;
  7582. // RFC 2046 5.1.1 caps a boundary at 70 characters. The parser scans the body
  7583. // for "--" + boundary, so a body crafted to repeat that delimiter's leading
  7584. // bytes costs a nearly full comparison at nearly every position: the
  7585. // boundary's length multiplies the worst-case cost of scanning a body.
  7586. return !boundary.empty() && boundary.size() <= 70;
  7587. }
  7588. inline void parse_disposition_params(const std::string &s, Params &params) {
  7589. std::set<std::string> cache;
  7590. split_unquoted(s.data(), s.data() + s.size(), ';',
  7591. [&](const char *b, const char *e) {
  7592. std::string kv(b, e);
  7593. if (cache.find(kv) != cache.end()) { return; }
  7594. cache.insert(kv);
  7595. std::string key;
  7596. std::string val;
  7597. divide_param_pair(b, e, key, val);
  7598. if (!key.empty()) {
  7599. params.emplace(trim_double_quotes_copy(key),
  7600. trim_double_quotes_copy(val));
  7601. }
  7602. });
  7603. }
  7604. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7605. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  7606. #else
  7607. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  7608. #endif
  7609. auto is_valid = [](const std::string &str) {
  7610. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  7611. };
  7612. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  7613. const auto pos = static_cast<size_t>(6);
  7614. const auto len = static_cast<size_t>(s.size() - 6);
  7615. auto all_valid_ranges = true;
  7616. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  7617. if (!all_valid_ranges) { return; }
  7618. const auto it = std::find(b, e, '-');
  7619. if (it == e) {
  7620. all_valid_ranges = false;
  7621. return;
  7622. }
  7623. const auto lhs = std::string(b, it);
  7624. const auto rhs = std::string(it + 1, e);
  7625. if (!is_valid(lhs) || !is_valid(rhs)) {
  7626. all_valid_ranges = false;
  7627. return;
  7628. }
  7629. ssize_t first = -1;
  7630. if (!lhs.empty()) {
  7631. // Reject an overflowing first-byte-pos; treating it as absent (-1)
  7632. // would turn the range into a suffix range.
  7633. auto res =
  7634. detail::from_chars(lhs.data(), lhs.data() + lhs.size(), first);
  7635. if (res.ec != std::errc{}) {
  7636. all_valid_ranges = false;
  7637. return;
  7638. }
  7639. }
  7640. ssize_t last = -1;
  7641. if (!rhs.empty()) {
  7642. // An overflowing last-byte-pos is past any content length, so keeping
  7643. // -1 ("remainder", RFC 9110 14.1.2) is correct here.
  7644. ssize_t v;
  7645. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  7646. if (res.ec == std::errc{}) { last = v; }
  7647. }
  7648. if ((first == -1 && last == -1) ||
  7649. (first != -1 && last != -1 && first > last)) {
  7650. all_valid_ranges = false;
  7651. return;
  7652. }
  7653. ranges.emplace_back(first, last);
  7654. });
  7655. return all_valid_ranges && !ranges.empty();
  7656. }
  7657. return false;
  7658. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7659. }
  7660. #else
  7661. } catch (...) { return false; }
  7662. #endif
  7663. inline bool parse_accept_header(const std::string &s,
  7664. std::vector<std::string> &content_types) {
  7665. content_types.clear();
  7666. // Empty string is considered valid (no preference)
  7667. if (s.empty()) { return true; }
  7668. struct AcceptEntry {
  7669. std::string media_type;
  7670. double quality;
  7671. int order;
  7672. };
  7673. std::vector<AcceptEntry> entries;
  7674. int order = 0;
  7675. bool has_invalid_entry = false;
  7676. // Split by comma and parse each entry. RFC 9110 Section 5.6.1.2: a recipient
  7677. // has to parse and ignore empty list elements, so a leading, trailing or
  7678. // doubled comma must not turn a legal Accept value into 400 Bad Request.
  7679. // split() skips them, and the header length limit bounds how many a sender
  7680. // can send, so ignoring all of them cannot be used as a denial-of-service
  7681. // vector.
  7682. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  7683. std::string entry(b, e);
  7684. entry = trim_copy(entry);
  7685. AcceptEntry accept_entry;
  7686. accept_entry.order = order++;
  7687. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  7688. accept_entry.media_type, accept_entry.quality)) {
  7689. has_invalid_entry = true;
  7690. return;
  7691. }
  7692. // Remove additional parameters from media type
  7693. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  7694. // Basic validation of media type format
  7695. if (accept_entry.media_type.empty()) {
  7696. has_invalid_entry = true;
  7697. return;
  7698. }
  7699. // Check for basic media type format (should contain '/' or be '*')
  7700. if (accept_entry.media_type != "*" &&
  7701. accept_entry.media_type.find('/') == std::string::npos) {
  7702. has_invalid_entry = true;
  7703. return;
  7704. }
  7705. entries.push_back(std::move(accept_entry));
  7706. });
  7707. // Return false if any invalid entry was found
  7708. if (has_invalid_entry) { return false; }
  7709. // Sort by quality (descending), then by original order (ascending)
  7710. std::sort(entries.begin(), entries.end(),
  7711. [](const AcceptEntry &a, const AcceptEntry &b) {
  7712. if (a.quality != b.quality) {
  7713. return a.quality > b.quality; // Higher quality first
  7714. }
  7715. return a.order < b.order; // Earlier order first for same quality
  7716. });
  7717. // Extract sorted media types
  7718. content_types.reserve(entries.size());
  7719. for (auto &entry : entries) {
  7720. content_types.push_back(std::move(entry.media_type));
  7721. }
  7722. return true;
  7723. }
  7724. class FormDataParser {
  7725. public:
  7726. FormDataParser() = default;
  7727. void set_boundary(std::string &&boundary) {
  7728. boundary_ = std::move(boundary);
  7729. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  7730. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  7731. }
  7732. bool is_valid() const { return is_valid_; }
  7733. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  7734. const ContentReceiver &content_callback) {
  7735. // Once the close delimiter has been seen the rest of the body is epilogue
  7736. // to be discarded (RFC 2046). Drop it without buffering so a large epilogue
  7737. // spread across reads is not copied in only to be erased right away.
  7738. if (state_ == 5) { return true; }
  7739. buf_append(buf, n);
  7740. while (buf_size() > 0) {
  7741. switch (state_) {
  7742. case 0: { // Initial boundary
  7743. auto pos = buf_find(dash_boundary_crlf_);
  7744. if (pos == buf_size()) {
  7745. // Not found yet: keep only a possible partial boundary at the tail so
  7746. // that a body which never contains the boundary cannot grow the
  7747. // buffer (and get rescanned from the start) without bound.
  7748. auto keep = dash_boundary_crlf_.size() - 1;
  7749. if (buf_size() > keep) { buf_erase(buf_size() - keep); }
  7750. return true;
  7751. }
  7752. buf_erase(pos + dash_boundary_crlf_.size());
  7753. state_ = 1;
  7754. break;
  7755. }
  7756. case 1: { // New entry
  7757. clear_file_info();
  7758. state_ = 2;
  7759. break;
  7760. }
  7761. case 2: { // Headers
  7762. auto pos = buf_find(crlf_);
  7763. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  7764. while (pos < buf_size()) {
  7765. // Empty line
  7766. if (pos == 0) {
  7767. if (!header_callback(file_)) {
  7768. is_valid_ = false;
  7769. return false;
  7770. }
  7771. buf_erase(crlf_.size());
  7772. state_ = 3;
  7773. break;
  7774. }
  7775. // Check header count limit
  7776. if (header_count_ >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  7777. is_valid_ = false;
  7778. return false;
  7779. }
  7780. header_count_++;
  7781. const auto header = buf_head(pos);
  7782. if (!parse_header(header.data(), header.data() + header.size(),
  7783. [&](const std::string &, const std::string &) {})) {
  7784. is_valid_ = false;
  7785. return false;
  7786. }
  7787. // Parse and emplace space trimmed headers into a map
  7788. if (!parse_header(
  7789. header.data(), header.data() + header.size(),
  7790. [&](const std::string &key, const std::string &val) {
  7791. file_.headers.emplace(key, val);
  7792. })) {
  7793. is_valid_ = false;
  7794. return false;
  7795. }
  7796. constexpr const char header_content_type[] = "Content-Type:";
  7797. if (start_with_case_ignore(header, header_content_type)) {
  7798. file_.content_type =
  7799. trim_copy(header.substr(str_len(header_content_type)));
  7800. } else {
  7801. std::string disposition_params;
  7802. if (parse_content_disposition(header, disposition_params)) {
  7803. Params params;
  7804. parse_disposition_params(disposition_params, params);
  7805. auto it = params.find("name");
  7806. if (it != params.end()) {
  7807. file_.name = it->second;
  7808. } else {
  7809. is_valid_ = false;
  7810. return false;
  7811. }
  7812. it = params.find("filename");
  7813. if (it != params.end()) { file_.filename = it->second; }
  7814. it = params.find("filename*");
  7815. if (it != params.end()) {
  7816. // RFC 5987: only UTF-8 encoding is allowed
  7817. const auto &val = it->second;
  7818. constexpr const char utf8_prefix[] = "UTF-8''";
  7819. constexpr size_t prefix_len = str_len(utf8_prefix);
  7820. if (val.size() > prefix_len &&
  7821. start_with_case_ignore(val, utf8_prefix)) {
  7822. file_.filename = decode_path_component(
  7823. val.substr(prefix_len)); // override...
  7824. } else {
  7825. is_valid_ = false;
  7826. return false;
  7827. }
  7828. }
  7829. }
  7830. }
  7831. buf_erase(pos + crlf_.size());
  7832. pos = buf_find(crlf_);
  7833. }
  7834. if (state_ != 3) { return true; }
  7835. break;
  7836. }
  7837. case 3: { // Body
  7838. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  7839. auto pos = buf_find(crlf_dash_boundary_);
  7840. if (pos < buf_size()) {
  7841. if (!content_callback(buf_data(), pos)) {
  7842. is_valid_ = false;
  7843. return false;
  7844. }
  7845. buf_erase(pos + crlf_dash_boundary_.size());
  7846. state_ = 4;
  7847. } else {
  7848. auto len = buf_size() - crlf_dash_boundary_.size();
  7849. if (len > 0) {
  7850. if (!content_callback(buf_data(), len)) {
  7851. is_valid_ = false;
  7852. return false;
  7853. }
  7854. buf_erase(len);
  7855. }
  7856. return true;
  7857. }
  7858. break;
  7859. }
  7860. case 4: { // Boundary
  7861. if (crlf_.size() > buf_size()) { return true; }
  7862. if (buf_start_with(crlf_)) {
  7863. buf_erase(crlf_.size());
  7864. state_ = 1;
  7865. } else if (buf_start_with(dash_)) {
  7866. buf_erase(dash_.size());
  7867. is_valid_ = true;
  7868. state_ = 5;
  7869. } else {
  7870. // Only CRLF (another part follows) and "--" (close-delimiter) are
  7871. // accepted after a boundary; RFC 2046 allows transport-padding in
  7872. // between, but this parser has never supported it. Either way the
  7873. // body is already destined to be rejected, so fail now instead of
  7874. // buffering the rest of it. Both are two bytes, so the check above
  7875. // already guarantees enough buffered data to decide.
  7876. is_valid_ = false;
  7877. return false;
  7878. }
  7879. break;
  7880. }
  7881. case 5: { // Epilogue
  7882. buf_erase(buf_size());
  7883. break;
  7884. }
  7885. }
  7886. }
  7887. return true;
  7888. }
  7889. private:
  7890. void clear_file_info() {
  7891. file_.name.clear();
  7892. file_.filename.clear();
  7893. file_.content_type.clear();
  7894. file_.headers.clear();
  7895. header_count_ = 0;
  7896. }
  7897. bool start_with_case_ignore(const std::string &a, const char *b,
  7898. size_t offset = 0) const {
  7899. const auto b_len = strlen(b);
  7900. if (a.size() < offset + b_len) { return false; }
  7901. for (size_t i = 0; i < b_len; i++) {
  7902. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  7903. return false;
  7904. }
  7905. }
  7906. return true;
  7907. }
  7908. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  7909. // Returns true if header matches, with the params portion in `params_out`.
  7910. bool parse_content_disposition(const std::string &header,
  7911. std::string &params_out) const {
  7912. constexpr const char prefix[] = "Content-Disposition:";
  7913. constexpr size_t prefix_len = str_len(prefix);
  7914. if (!start_with_case_ignore(header, prefix)) { return false; }
  7915. // Skip whitespace after "Content-Disposition:"
  7916. auto pos = prefix_len;
  7917. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  7918. pos++;
  7919. }
  7920. // Match "form-data;" (case-insensitive)
  7921. constexpr const char form_data[] = "form-data;";
  7922. constexpr size_t form_data_len = str_len(form_data);
  7923. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  7924. pos += form_data_len;
  7925. // Skip whitespace after "form-data;"
  7926. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  7927. pos++;
  7928. }
  7929. params_out = header.substr(pos);
  7930. return true;
  7931. }
  7932. const std::string dash_ = "--";
  7933. const std::string crlf_ = "\r\n";
  7934. std::string boundary_;
  7935. std::string dash_boundary_crlf_;
  7936. std::string crlf_dash_boundary_;
  7937. size_t state_ = 0;
  7938. bool is_valid_ = false;
  7939. FormData file_;
  7940. size_t header_count_ = 0;
  7941. // Buffer
  7942. bool start_with(const std::string &a, size_t spos, size_t epos,
  7943. const std::string &b) const {
  7944. if (epos - spos < b.size()) { return false; }
  7945. for (size_t i = 0; i < b.size(); i++) {
  7946. if (a[i + spos] != b[i]) { return false; }
  7947. }
  7948. return true;
  7949. }
  7950. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  7951. const char *buf_data() const { return &buf_[buf_spos_]; }
  7952. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  7953. bool buf_start_with(const std::string &s) const {
  7954. return start_with(buf_, buf_spos_, buf_epos_, s);
  7955. }
  7956. size_t buf_find(const std::string &s) const {
  7957. auto c = s.front();
  7958. size_t off = buf_spos_;
  7959. while (off < buf_epos_) {
  7960. auto pos = off;
  7961. while (true) {
  7962. if (pos == buf_epos_) { return buf_size(); }
  7963. if (buf_[pos] == c) { break; }
  7964. pos++;
  7965. }
  7966. auto remaining_size = buf_epos_ - pos;
  7967. if (s.size() > remaining_size) { return buf_size(); }
  7968. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  7969. off = pos + 1;
  7970. }
  7971. return buf_size();
  7972. }
  7973. void buf_append(const char *data, size_t n) {
  7974. auto remaining_size = buf_size();
  7975. if (remaining_size > 0 && buf_spos_ > 0) {
  7976. for (size_t i = 0; i < remaining_size; i++) {
  7977. buf_[i] = buf_[buf_spos_ + i];
  7978. }
  7979. }
  7980. buf_spos_ = 0;
  7981. buf_epos_ = remaining_size;
  7982. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  7983. for (size_t i = 0; i < n; i++) {
  7984. buf_[buf_epos_ + i] = data[i];
  7985. }
  7986. buf_epos_ += n;
  7987. }
  7988. void buf_erase(size_t size) { buf_spos_ += size; }
  7989. std::string buf_;
  7990. size_t buf_spos_ = 0;
  7991. size_t buf_epos_ = 0;
  7992. };
  7993. inline std::string random_string(size_t length) {
  7994. constexpr const char data[] =
  7995. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  7996. thread_local auto engine([]() {
  7997. // std::random_device might actually be deterministic on some
  7998. // platforms, but due to lack of support in the c++ standard library,
  7999. // doing better requires either some ugly hacks or breaking portability.
  8000. std::random_device seed_gen;
  8001. // Request 128 bits of entropy for initialization
  8002. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  8003. return std::mt19937(seed_sequence);
  8004. }());
  8005. std::string result;
  8006. for (size_t i = 0; i < length; i++) {
  8007. result += data[engine() % (sizeof(data) - 1)];
  8008. }
  8009. return result;
  8010. }
  8011. inline std::string make_multipart_data_boundary() {
  8012. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  8013. }
  8014. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  8015. auto valid = true;
  8016. for (size_t i = 0; i < boundary.size(); i++) {
  8017. auto c = boundary[i];
  8018. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  8019. valid = false;
  8020. break;
  8021. }
  8022. }
  8023. return valid;
  8024. }
  8025. // Escape a multipart field name/filename following the WHATWG HTML standard
  8026. // ("escape a multipart form-data name"), which is what browsers send:
  8027. // '"' -> %22, CR -> %0D, LF -> %0A
  8028. // With escape_quote = false, only CR and LF are escaped; this is for header
  8029. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  8030. inline std::string escape_multipart_field(const std::string &s,
  8031. bool escape_quote = true) {
  8032. std::string result;
  8033. result.reserve(s.size());
  8034. for (auto c : s) {
  8035. switch (c) {
  8036. case '"':
  8037. if (escape_quote) {
  8038. result += "%22";
  8039. } else {
  8040. result += c;
  8041. }
  8042. break;
  8043. case '\r': result += "%0D"; break;
  8044. case '\n': result += "%0A"; break;
  8045. default: result += c; break;
  8046. }
  8047. }
  8048. return result;
  8049. }
  8050. template <typename T>
  8051. inline std::string
  8052. serialize_multipart_formdata_item_begin(const T &item,
  8053. const std::string &boundary) {
  8054. std::string body = "--" + boundary + "\r\n";
  8055. body += "Content-Disposition: form-data; name=\"" +
  8056. escape_multipart_field(item.name) + "\"";
  8057. if (!item.filename.empty()) {
  8058. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  8059. }
  8060. body += "\r\n";
  8061. if (!item.content_type.empty()) {
  8062. body +=
  8063. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  8064. "\r\n";
  8065. }
  8066. body += "\r\n";
  8067. return body;
  8068. }
  8069. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  8070. inline std::string
  8071. serialize_multipart_formdata_finish(const std::string &boundary) {
  8072. return "--" + boundary + "--\r\n";
  8073. }
  8074. inline std::string
  8075. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  8076. return "multipart/form-data; boundary=" + boundary;
  8077. }
  8078. inline std::string
  8079. serialize_multipart_formdata(const UploadFormDataItems &items,
  8080. const std::string &boundary, bool finish = true) {
  8081. std::string body;
  8082. for (const auto &item : items) {
  8083. body += serialize_multipart_formdata_item_begin(item, boundary);
  8084. body += item.content + serialize_multipart_formdata_item_end();
  8085. }
  8086. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  8087. return body;
  8088. }
  8089. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  8090. const std::string &boundary) {
  8091. size_t total = 0;
  8092. for (const auto &item : items) {
  8093. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  8094. total += item.content.size();
  8095. total += serialize_multipart_formdata_item_end().size();
  8096. }
  8097. total += serialize_multipart_formdata_finish(boundary).size();
  8098. return total;
  8099. }
  8100. struct MultipartSegment {
  8101. const char *data;
  8102. size_t size;
  8103. };
  8104. // NOTE: items must outlive the returned ContentProvider
  8105. // (safe for synchronous use inside Post/Put/Patch)
  8106. inline ContentProvider
  8107. make_multipart_content_provider(const UploadFormDataItems &items,
  8108. const std::string &boundary) {
  8109. // Own the per-item header strings and the finish string
  8110. std::vector<std::string> owned;
  8111. owned.reserve(items.size() + 1);
  8112. for (const auto &item : items)
  8113. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  8114. owned.push_back(serialize_multipart_formdata_finish(boundary));
  8115. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  8116. std::vector<MultipartSegment> segs;
  8117. segs.reserve(items.size() * 3 + 1);
  8118. static const char crlf[] = "\r\n";
  8119. for (size_t i = 0; i < items.size(); i++) {
  8120. segs.push_back({owned[i].data(), owned[i].size()});
  8121. segs.push_back({items[i].content.data(), items[i].content.size()});
  8122. segs.push_back({crlf, 2});
  8123. }
  8124. segs.push_back({owned.back().data(), owned.back().size()});
  8125. struct MultipartState {
  8126. std::vector<std::string> owned;
  8127. std::vector<MultipartSegment> segs;
  8128. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  8129. };
  8130. auto state = std::make_shared<MultipartState>();
  8131. state->owned = std::move(owned);
  8132. // `segs` holds raw pointers into owned strings; std::string move preserves
  8133. // the data pointer, so these pointers remain valid after the move above.
  8134. state->segs = std::move(segs);
  8135. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  8136. // Buffer multiple small segments into fewer, larger writes to avoid
  8137. // excessive TCP packets when there are many form data items (#2410)
  8138. auto &buf = state->buf;
  8139. auto buf_size = buf.size();
  8140. size_t buf_len = 0;
  8141. size_t remaining = length;
  8142. // Find the first segment containing 'offset'
  8143. size_t pos = 0;
  8144. size_t seg_idx = 0;
  8145. for (; seg_idx < state->segs.size(); seg_idx++) {
  8146. const auto &seg = state->segs[seg_idx];
  8147. if (seg.size > 0 && offset - pos < seg.size) { break; }
  8148. pos += seg.size;
  8149. }
  8150. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  8151. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  8152. const auto &seg = state->segs[seg_idx];
  8153. size_t available = seg.size - seg_offset;
  8154. size_t to_copy = (std::min)(available, remaining);
  8155. const char *src = seg.data + seg_offset;
  8156. seg_offset = 0; // only the first segment has a non-zero offset
  8157. while (to_copy > 0) {
  8158. size_t space = buf_size - buf_len;
  8159. size_t chunk = (std::min)(to_copy, space);
  8160. std::memcpy(buf.data() + buf_len, src, chunk);
  8161. buf_len += chunk;
  8162. src += chunk;
  8163. to_copy -= chunk;
  8164. remaining -= chunk;
  8165. if (buf_len == buf_size) {
  8166. if (!sink.write(buf.data(), buf_len)) { return false; }
  8167. buf_len = 0;
  8168. }
  8169. }
  8170. }
  8171. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  8172. return true;
  8173. };
  8174. }
  8175. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  8176. if (ranges.size() <= 1) return;
  8177. // Sort ranges by start position
  8178. std::sort(ranges.begin(), ranges.end(),
  8179. [](const Range &a, const Range &b) { return a.first < b.first; });
  8180. Ranges coalesced;
  8181. coalesced.reserve(ranges.size());
  8182. for (auto &r : ranges) {
  8183. auto first_pos = r.first;
  8184. auto last_pos = r.second;
  8185. // Handle special cases like in range_error
  8186. if (first_pos == -1 && last_pos == -1) {
  8187. first_pos = 0;
  8188. last_pos = static_cast<ssize_t>(content_length);
  8189. }
  8190. if (first_pos == -1) {
  8191. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  8192. last_pos = static_cast<ssize_t>(content_length) - 1;
  8193. }
  8194. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  8195. last_pos = static_cast<ssize_t>(content_length) - 1;
  8196. }
  8197. // Skip invalid ranges
  8198. if (!(0 <= first_pos && first_pos <= last_pos &&
  8199. last_pos < static_cast<ssize_t>(content_length))) {
  8200. continue;
  8201. }
  8202. // Coalesce with previous range if overlapping or adjacent (but not
  8203. // identical)
  8204. if (!coalesced.empty()) {
  8205. auto &prev = coalesced.back();
  8206. // Check if current range overlaps or is adjacent to previous range
  8207. // but don't coalesce identical ranges (allow duplicates)
  8208. if (first_pos <= prev.second + 1 &&
  8209. !(first_pos == prev.first && last_pos == prev.second)) {
  8210. // Extend the previous range
  8211. prev.second = (std::max)(prev.second, last_pos);
  8212. continue;
  8213. }
  8214. }
  8215. // Add new range
  8216. coalesced.emplace_back(first_pos, last_pos);
  8217. }
  8218. ranges = std::move(coalesced);
  8219. }
  8220. inline bool range_error(Request &req, Response &res) {
  8221. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  8222. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  8223. req.ranges.clear();
  8224. if (res.status == StatusCode::PartialContent_206) {
  8225. res.status = StatusCode::OK_200;
  8226. }
  8227. return false;
  8228. }
  8229. ssize_t content_len = static_cast<ssize_t>(
  8230. res.content_length_ ? res.content_length_ : res.body.size());
  8231. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  8232. size_t overwrapping_count = 0;
  8233. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  8234. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  8235. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  8236. // Too many ranges
  8237. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  8238. for (auto &r : req.ranges) {
  8239. auto &first_pos = r.first;
  8240. auto &last_pos = r.second;
  8241. if (first_pos == -1 && last_pos == -1) {
  8242. first_pos = 0;
  8243. last_pos = content_len;
  8244. }
  8245. if (first_pos == -1) {
  8246. first_pos = content_len - last_pos;
  8247. last_pos = content_len - 1;
  8248. }
  8249. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  8250. // A client can limit the number of bytes requested without knowing the
  8251. // size of the selected representation. If the last-pos value is absent,
  8252. // or if the value is greater than or equal to the current length of the
  8253. // representation data, the byte range is interpreted as the remainder of
  8254. // the representation (i.e., the server replaces the value of last-pos
  8255. // with a value that is one less than the current length of the selected
  8256. // representation).
  8257. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  8258. if (last_pos == -1 || last_pos >= content_len) {
  8259. last_pos = content_len - 1;
  8260. }
  8261. // Range must be within content length
  8262. if (!(0 <= first_pos && first_pos <= last_pos &&
  8263. last_pos <= content_len - 1)) {
  8264. return true;
  8265. }
  8266. // Request must not have more than two overlapping ranges
  8267. for (const auto &processed_range : processed_ranges) {
  8268. if (!(last_pos < processed_range.first ||
  8269. first_pos > processed_range.second)) {
  8270. overwrapping_count++;
  8271. if (overwrapping_count > 2) { return true; }
  8272. break; // Only count once per range
  8273. }
  8274. }
  8275. processed_ranges.emplace_back(first_pos, last_pos);
  8276. }
  8277. // After validation, coalesce overlapping ranges as per RFC 9110
  8278. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  8279. }
  8280. return false;
  8281. }
  8282. inline std::pair<size_t, size_t>
  8283. get_range_offset_and_length(Range r, size_t content_length) {
  8284. assert(r.first != -1 && r.second != -1);
  8285. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  8286. assert(r.first <= r.second &&
  8287. r.second < static_cast<ssize_t>(content_length));
  8288. (void)(content_length);
  8289. return std::make_pair(static_cast<size_t>(r.first),
  8290. static_cast<size_t>(r.second - r.first) + 1);
  8291. }
  8292. inline std::string make_content_range_header_field(
  8293. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  8294. auto st = offset_and_length.first;
  8295. auto ed = st + offset_and_length.second - 1;
  8296. std::string field = "bytes ";
  8297. field += std::to_string(st);
  8298. field += '-';
  8299. field += std::to_string(ed);
  8300. field += '/';
  8301. field += std::to_string(content_length);
  8302. return field;
  8303. }
  8304. template <typename SToken, typename CToken, typename Content>
  8305. bool process_multipart_ranges_data(const Request &req,
  8306. const std::string &boundary,
  8307. const std::string &content_type,
  8308. size_t content_length, SToken stoken,
  8309. CToken ctoken, Content content) {
  8310. for (size_t i = 0; i < req.ranges.size(); i++) {
  8311. ctoken("--");
  8312. stoken(boundary);
  8313. ctoken("\r\n");
  8314. if (!content_type.empty()) {
  8315. ctoken("Content-Type: ");
  8316. stoken(content_type);
  8317. ctoken("\r\n");
  8318. }
  8319. auto offset_and_length =
  8320. get_range_offset_and_length(req.ranges[i], content_length);
  8321. ctoken("Content-Range: ");
  8322. stoken(make_content_range_header_field(offset_and_length, content_length));
  8323. ctoken("\r\n");
  8324. ctoken("\r\n");
  8325. if (!content(offset_and_length.first, offset_and_length.second)) {
  8326. return false;
  8327. }
  8328. ctoken("\r\n");
  8329. }
  8330. ctoken("--");
  8331. stoken(boundary);
  8332. ctoken("--");
  8333. return true;
  8334. }
  8335. inline void make_multipart_ranges_data(const Request &req, Response &res,
  8336. const std::string &boundary,
  8337. const std::string &content_type,
  8338. size_t content_length,
  8339. std::string &data) {
  8340. process_multipart_ranges_data(
  8341. req, boundary, content_type, content_length,
  8342. [&](const std::string &token) { data += token; },
  8343. [&](const std::string &token) { data += token; },
  8344. [&](size_t offset, size_t length) {
  8345. assert(offset + length <= content_length);
  8346. data += res.body.substr(offset, length);
  8347. return true;
  8348. });
  8349. }
  8350. inline size_t get_multipart_ranges_data_length(const Request &req,
  8351. const std::string &boundary,
  8352. const std::string &content_type,
  8353. size_t content_length) {
  8354. size_t data_length = 0;
  8355. process_multipart_ranges_data(
  8356. req, boundary, content_type, content_length,
  8357. [&](const std::string &token) { data_length += token.size(); },
  8358. [&](const std::string &token) { data_length += token.size(); },
  8359. [&](size_t /*offset*/, size_t length) {
  8360. data_length += length;
  8361. return true;
  8362. });
  8363. return data_length;
  8364. }
  8365. template <typename T>
  8366. inline bool
  8367. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  8368. const std::string &boundary,
  8369. const std::string &content_type,
  8370. size_t content_length, const T &is_shutting_down) {
  8371. return process_multipart_ranges_data(
  8372. req, boundary, content_type, content_length,
  8373. [&](const std::string &token) { strm.write(token); },
  8374. [&](const std::string &token) { strm.write(token); },
  8375. [&](size_t offset, size_t length) {
  8376. return write_content(strm, res.content_provider_, offset, length,
  8377. is_shutting_down);
  8378. });
  8379. }
  8380. inline bool has_framed_body(const Request &req) {
  8381. return is_chunked_transfer_encoding(req.headers) ||
  8382. req.get_header_value_u64("Content-Length") > 0;
  8383. }
  8384. inline bool is_connection_persistent(const Request &req) {
  8385. if (has_header_token(req.headers, "Connection", "close")) { return false; }
  8386. if (req.version == "HTTP/1.0" &&
  8387. !has_header_token(req.headers, "Connection", "keep-alive")) {
  8388. return false;
  8389. }
  8390. return true;
  8391. }
  8392. inline bool expect_content(const Request &req) {
  8393. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  8394. req.method == "DELETE") {
  8395. return true;
  8396. }
  8397. return has_framed_body(req);
  8398. }
  8399. #ifdef _WIN32
  8400. class WSInit {
  8401. public:
  8402. WSInit() {
  8403. WSADATA wsaData;
  8404. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  8405. }
  8406. ~WSInit() {
  8407. if (is_valid_) WSACleanup();
  8408. }
  8409. bool is_valid_ = false;
  8410. };
  8411. static WSInit wsinit_;
  8412. #endif
  8413. // RFC 9110 Section 11.6.1 defines a challenge list as
  8414. // WWW-Authenticate = #challenge
  8415. // challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
  8416. // auth-param = token BWS "=" BWS ( token / quoted-string )
  8417. // so a server may offer several schemes, each with its own comma-separated
  8418. // auth-param list, in either order and either as separate field lines or
  8419. // packed into one. Splitting on every comma would break apart a challenge's
  8420. // own param list; splitting only on the first space would miss a Digest
  8421. // challenge that isn't first. Split on commas that aren't inside a
  8422. // quoted-string instead, then track which scheme each resulting segment
  8423. // belongs to: a segment whose text before "=" contains whitespace (or that
  8424. // has no "=" at all) starts a new challenge named by its leading token.
  8425. inline std::vector<std::string> split_challenge_segments(const std::string &s) {
  8426. std::vector<std::string> segments;
  8427. size_t start = 0;
  8428. auto in_quotes = false;
  8429. for (size_t i = 0; i < s.size(); i++) {
  8430. auto c = s[i];
  8431. if (in_quotes) {
  8432. if (c == '\\' && i + 1 < s.size()) {
  8433. i++;
  8434. } else if (c == '"') {
  8435. in_quotes = false;
  8436. }
  8437. } else if (c == '"') {
  8438. in_quotes = true;
  8439. } else if (c == ',') {
  8440. segments.push_back(s.substr(start, i - start));
  8441. start = i + 1;
  8442. }
  8443. }
  8444. segments.push_back(s.substr(start));
  8445. return segments;
  8446. }
  8447. inline std::string unescape_quoted_pairs(const std::string &s) {
  8448. std::string out;
  8449. out.reserve(s.size());
  8450. for (size_t i = 0; i < s.size(); i++) {
  8451. if (s[i] == '\\' && i + 1 < s.size()) {
  8452. out += s[++i];
  8453. } else {
  8454. out += s[i];
  8455. }
  8456. }
  8457. return out;
  8458. }
  8459. inline bool parse_www_authenticate(const Response &res,
  8460. std::map<std::string, std::string> &auth,
  8461. bool is_proxy) {
  8462. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  8463. auto combined = get_combined_header_value(res.headers, auth_key);
  8464. if (combined.empty()) { return false; }
  8465. auto found_digest = false;
  8466. auto in_digest_challenge = false;
  8467. for (const auto &raw_segment : split_challenge_segments(combined)) {
  8468. auto segment = trim_copy(raw_segment);
  8469. if (segment.empty()) { continue; }
  8470. auto eq_pos = segment.find('=');
  8471. // BWS is allowed on both sides of "=", so the text naming the key (or,
  8472. // for the first segment of a challenge, "<scheme> <key>") must be
  8473. // trimmed before its boundaries are inspected.
  8474. auto key_part = trim_copy(
  8475. eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
  8476. auto space_pos = key_part.find_last_of(" \t");
  8477. if (space_pos != std::string::npos || eq_pos == std::string::npos) {
  8478. // "<scheme>[ <key>]" starts a new challenge.
  8479. auto scheme_end =
  8480. space_pos == std::string::npos ? key_part.size() : space_pos;
  8481. // RFC 7616 Section 3.7: a server may offer more than one Digest
  8482. // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
  8483. // from one challenge is never paired with another's algorithm.
  8484. in_digest_challenge =
  8485. !found_digest &&
  8486. case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
  8487. if (in_digest_challenge) { found_digest = true; }
  8488. if (space_pos == std::string::npos) {
  8489. // Bare scheme (or a token68), no auth-param on this segment.
  8490. continue;
  8491. }
  8492. key_part = key_part.substr(space_pos + 1);
  8493. }
  8494. if (!in_digest_challenge) { continue; }
  8495. auto val = trim_copy(segment.substr(eq_pos + 1));
  8496. auto unquoted = trim_double_quotes_copy(val);
  8497. if (unquoted.size() != val.size()) {
  8498. unquoted = unescape_quoted_pairs(unquoted);
  8499. }
  8500. auth[std::move(key_part)] = std::move(unquoted);
  8501. }
  8502. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
  8503. // make_digest_authentication_header() dereferences both unconditionally, so
  8504. // a challenge missing either can't produce a usable Authorization header.
  8505. // Treat it the same as no Digest challenge at all.
  8506. return found_digest && auth.find("realm") != auth.end() &&
  8507. auth.find("nonce") != auth.end();
  8508. }
  8509. class ContentProviderAdapter {
  8510. public:
  8511. explicit ContentProviderAdapter(
  8512. ContentProviderWithoutLength &&content_provider)
  8513. : content_provider_(std::move(content_provider)) {}
  8514. bool operator()(size_t offset, size_t, DataSink &sink) {
  8515. return content_provider_(offset, sink);
  8516. }
  8517. private:
  8518. ContentProviderWithoutLength content_provider_;
  8519. };
  8520. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  8521. namespace fields {
  8522. inline bool is_token_char(char c) {
  8523. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  8524. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  8525. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  8526. }
  8527. inline bool is_token(const std::string &s) {
  8528. if (s.empty()) { return false; }
  8529. for (auto c : s) {
  8530. if (!is_token_char(c)) { return false; }
  8531. }
  8532. return true;
  8533. }
  8534. inline bool is_field_name(const std::string &s) { return is_token(s); }
  8535. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  8536. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  8537. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  8538. inline bool is_field_content(const std::string &s) {
  8539. if (s.empty()) { return true; }
  8540. if (s.size() == 1) {
  8541. return is_field_vchar(s[0]);
  8542. } else if (s.size() == 2) {
  8543. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  8544. } else {
  8545. size_t i = 0;
  8546. if (!is_field_vchar(s[i])) { return false; }
  8547. i++;
  8548. while (i < s.size() - 1) {
  8549. auto c = s[i++];
  8550. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  8551. } else {
  8552. return false;
  8553. }
  8554. }
  8555. return is_field_vchar(s[i]);
  8556. }
  8557. }
  8558. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  8559. inline bool is_field_valid(const std::string &name, const std::string &value) {
  8560. return is_field_name(name) && is_field_value(value);
  8561. }
  8562. // RFC 9112 §2.2/§3.2: the request-target has no SP, HTAB or other control
  8563. // characters (incl. bare CR). obs-text (raw UTF-8) is allowed.
  8564. inline bool is_request_target(const std::string &s) {
  8565. return std::all_of(s.begin(), s.end(), is_field_vchar);
  8566. }
  8567. } // namespace fields
  8568. inline bool perform_websocket_handshake(Stream &strm, Request &req,
  8569. WebSocketUpgradeResponse &upgrade) {
  8570. // Generate random Sec-WebSocket-Key
  8571. thread_local std::mt19937 rng(std::random_device{}());
  8572. std::string key_bytes(16, '\0');
  8573. for (size_t i = 0; i < 16; i += 4) {
  8574. auto r = rng();
  8575. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  8576. }
  8577. auto client_key = base64_encode(key_bytes);
  8578. req.headers.erase("Upgrade");
  8579. req.headers.erase("Connection");
  8580. req.headers.erase("Sec-WebSocket-Key");
  8581. req.headers.erase("Sec-WebSocket-Version");
  8582. req.headers.emplace("Upgrade", "websocket");
  8583. req.headers.emplace("Connection", "Upgrade");
  8584. req.headers.emplace("Sec-WebSocket-Key", client_key);
  8585. req.headers.emplace("Sec-WebSocket-Version", "13");
  8586. // Build the request in memory first, like ClientImpl::write_request does.
  8587. // Writing straight to the socket would leak a request line onto the wire
  8588. // before check_and_write_headers gets a chance to reject an invalid header,
  8589. // and would emit one small write per header.
  8590. BufferStream bstrm;
  8591. if (write_request_line(bstrm, req.method, req.path) < 0) {
  8592. upgrade.error = Error::Write;
  8593. return false;
  8594. }
  8595. auto error = Error::Success;
  8596. if (!check_and_write_headers(bstrm, req.headers, write_headers, error)) {
  8597. upgrade.error = error;
  8598. return false;
  8599. }
  8600. const auto &data = bstrm.get_buffer();
  8601. if (!write_data(strm, data.data(), data.size())) {
  8602. upgrade.error = Error::Write;
  8603. return false;
  8604. }
  8605. // Verify 101 response and Sec-WebSocket-Accept header
  8606. auto expected_accept = websocket_accept_key(client_key);
  8607. return read_websocket_upgrade_response(strm, expected_accept, upgrade);
  8608. }
  8609. inline bool is_ip_address(const std::string &host) {
  8610. struct in_addr addr4;
  8611. struct in6_addr addr6;
  8612. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  8613. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  8614. }
  8615. // Resolve where a client should connect for `host`, honoring a user-supplied
  8616. // hostname-to-address map. `host` itself is never rewritten, so it keeps
  8617. // supplying the Host header and SNI; only the connection target changes.
  8618. //
  8619. // A mapped IP literal goes to `ip`, which keeps create_socket's AI_NUMERICHOST
  8620. // path. Anything else goes to `connect_host`, which create_socket resolves as
  8621. // a name, or uses as the socket path when the address family is AF_UNIX. An
  8622. // absent or empty mapping leaves `host` as the connection target; without the
  8623. // empty check the value would reach getaddrinfo as a null node and silently
  8624. // resolve to loopback.
  8625. inline void apply_addr_map(const std::map<std::string, std::string> &addr_map,
  8626. const std::string &host, std::string &connect_host,
  8627. std::string &ip) {
  8628. connect_host = host;
  8629. ip.clear();
  8630. auto it = addr_map.find(host);
  8631. if (it == addr_map.end() || it->second.empty()) { return; }
  8632. if (is_ip_address(it->second)) {
  8633. ip = it->second;
  8634. } else {
  8635. connect_host = it->second;
  8636. }
  8637. }
  8638. } // namespace detail
  8639. /*
  8640. * Group 2: detail namespace - SSL common utilities
  8641. */
  8642. #ifdef CPPHTTPLIB_SSL_ENABLED
  8643. namespace detail {
  8644. class SSLSocketStream final : public Stream {
  8645. public:
  8646. SSLSocketStream(
  8647. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8648. time_t read_timeout_usec, time_t write_timeout_sec,
  8649. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  8650. std::chrono::time_point<std::chrono::steady_clock> start_time =
  8651. (std::chrono::steady_clock::time_point::min)());
  8652. ~SSLSocketStream() override;
  8653. bool is_readable() const override;
  8654. bool wait_readable() const override;
  8655. bool wait_writable() const override;
  8656. bool is_peer_alive() const override;
  8657. ssize_t read(char *ptr, size_t size) override;
  8658. ssize_t write(const char *ptr, size_t size) override;
  8659. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8660. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8661. socket_t socket() const override;
  8662. time_t duration() const override;
  8663. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8664. // See SocketStream::set_readable_hint().
  8665. void set_readable_hint() { readable_hint_ = true; }
  8666. private:
  8667. bool ensure_readable();
  8668. socket_t sock_;
  8669. tls::session_t session_;
  8670. time_t read_timeout_sec_;
  8671. time_t read_timeout_usec_;
  8672. time_t write_timeout_sec_;
  8673. time_t write_timeout_usec_;
  8674. time_t max_timeout_msec_;
  8675. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8676. bool readable_hint_ = false;
  8677. };
  8678. // A TLS stream for WebSocket connections, where the receive path and the
  8679. // send path (application send() plus the heartbeat ping thread) run on
  8680. // different threads. A single TLS session must never be entered
  8681. // concurrently, so every call into the session is serialized by one mutex.
  8682. //
  8683. // Unlike SSLSocketStream, the socket is kept non-blocking for the stream's
  8684. // whole lifetime and each read()/write() performs a single non-blocking TLS
  8685. // call under the lock, then waits for readiness with select() outside the
  8686. // lock. The lock is therefore held only for CPU-bound work, so a reader
  8687. // blocked waiting for data never stalls a concurrent sender.
  8688. //
  8689. // This stream is used only for wss:// connections. Plain ws:// and ordinary
  8690. // HTTP/HTTPS keep using SocketStream/SSLSocketStream unchanged.
  8691. class WebSocketSSLStream final : public Stream {
  8692. public:
  8693. WebSocketSSLStream(socket_t sock, tls::session_t session,
  8694. time_t read_timeout_sec, time_t read_timeout_usec,
  8695. time_t write_timeout_sec, time_t write_timeout_usec);
  8696. ~WebSocketSSLStream() override;
  8697. bool is_readable() const override;
  8698. bool wait_readable() const override;
  8699. bool wait_writable() const override;
  8700. ssize_t read(char *ptr, size_t size) override;
  8701. ssize_t write(const char *ptr, size_t size) override;
  8702. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  8703. void get_local_ip_and_port(std::string &ip, int &port) const override;
  8704. socket_t socket() const override;
  8705. time_t duration() const override;
  8706. void set_read_timeout(time_t sec, time_t usec = 0) override;
  8707. private:
  8708. mutable std::mutex session_mutex_;
  8709. socket_t sock_;
  8710. tls::session_t session_;
  8711. // WebSocket::close() shortens the read timeout from the closing thread
  8712. // while the receive thread is inside wait_readable(), so these two are read
  8713. // and written concurrently. The write timeouts are never mutated.
  8714. std::atomic<time_t> read_timeout_sec_;
  8715. std::atomic<time_t> read_timeout_usec_;
  8716. time_t write_timeout_sec_;
  8717. time_t write_timeout_usec_;
  8718. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  8719. };
  8720. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8721. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  8722. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  8723. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  8724. unsigned int hash_length = 0;
  8725. unsigned char hash[EVP_MAX_MD_SIZE];
  8726. EVP_DigestInit_ex(context.get(), algo, nullptr);
  8727. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  8728. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  8729. std::stringstream ss;
  8730. for (auto i = 0u; i < hash_length; ++i) {
  8731. ss << std::hex << std::setw(2) << std::setfill('0')
  8732. << static_cast<unsigned int>(hash[i]);
  8733. }
  8734. return ss.str();
  8735. }
  8736. inline std::string MD5(const std::string &s) {
  8737. return message_digest(s, EVP_md5());
  8738. }
  8739. inline std::string SHA_256(const std::string &s) {
  8740. return message_digest(s, EVP_sha256());
  8741. }
  8742. inline std::string SHA_512(const std::string &s) {
  8743. return message_digest(s, EVP_sha512());
  8744. }
  8745. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  8746. namespace {
  8747. template <size_t N>
  8748. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8749. std::stringstream ss;
  8750. for (size_t i = 0; i < N; ++i) {
  8751. ss << std::hex << std::setw(2) << std::setfill('0')
  8752. << static_cast<unsigned int>(hash[i]);
  8753. }
  8754. return ss.str();
  8755. }
  8756. } // namespace
  8757. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8758. // Mbed TLS 4.x provides hashing (and TLS RNG) via PSA Crypto, which must be
  8759. // initialized once. PSA state is process-global; do not free it.
  8760. inline bool ensure_mbedtls_psa_crypto() {
  8761. static std::once_flag once;
  8762. static bool ok = false;
  8763. std::call_once(once, []() { ok = (psa_crypto_init() == PSA_SUCCESS); });
  8764. return ok;
  8765. }
  8766. inline bool psa_hash(psa_algorithm_t alg, const std::string &s,
  8767. unsigned char *out, size_t out_size) {
  8768. if (!ensure_mbedtls_psa_crypto()) { return false; }
  8769. size_t olen = 0;
  8770. return psa_hash_compute(alg, reinterpret_cast<const uint8_t *>(s.data()),
  8771. s.size(), out, out_size, &olen) == PSA_SUCCESS &&
  8772. olen == out_size;
  8773. }
  8774. #endif
  8775. inline std::string MD5(const std::string &s) {
  8776. unsigned char hash[16];
  8777. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8778. if (!psa_hash(PSA_ALG_MD5, s, hash, sizeof(hash))) { return {}; }
  8779. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8780. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8781. hash);
  8782. #else
  8783. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8784. hash);
  8785. #endif
  8786. return hash_to_hex(hash);
  8787. }
  8788. inline std::string SHA_256(const std::string &s) {
  8789. unsigned char hash[32];
  8790. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8791. if (!psa_hash(PSA_ALG_SHA_256, s, hash, sizeof(hash))) { return {}; }
  8792. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8793. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8794. hash, 0);
  8795. #else
  8796. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8797. s.size(), hash, 0);
  8798. #endif
  8799. return hash_to_hex(hash);
  8800. }
  8801. inline std::string SHA_512(const std::string &s) {
  8802. unsigned char hash[64];
  8803. #ifdef CPPHTTPLIB_MBEDTLS_V4
  8804. if (!psa_hash(PSA_ALG_SHA_512, s, hash, sizeof(hash))) { return {}; }
  8805. #elif defined(CPPHTTPLIB_MBEDTLS_V3)
  8806. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  8807. hash, 0);
  8808. #else
  8809. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  8810. s.size(), hash, 0);
  8811. #endif
  8812. return hash_to_hex(hash);
  8813. }
  8814. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  8815. namespace {
  8816. template <size_t N>
  8817. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  8818. std::stringstream ss;
  8819. for (size_t i = 0; i < N; ++i) {
  8820. ss << std::hex << std::setw(2) << std::setfill('0')
  8821. << static_cast<unsigned int>(hash[i]);
  8822. }
  8823. return ss.str();
  8824. }
  8825. } // namespace
  8826. inline std::string MD5(const std::string &s) {
  8827. unsigned char hash[WC_MD5_DIGEST_SIZE];
  8828. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8829. static_cast<word32>(s.size()), hash);
  8830. return hash_to_hex(hash);
  8831. }
  8832. inline std::string SHA_256(const std::string &s) {
  8833. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  8834. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8835. static_cast<word32>(s.size()), hash);
  8836. return hash_to_hex(hash);
  8837. }
  8838. inline std::string SHA_512(const std::string &s) {
  8839. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  8840. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  8841. static_cast<word32>(s.size()), hash);
  8842. return hash_to_hex(hash);
  8843. }
  8844. #endif
  8845. template <typename T>
  8846. inline bool process_server_socket_ssl(
  8847. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  8848. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8849. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8850. time_t write_timeout_usec, T callback) {
  8851. return process_server_socket_core(
  8852. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8853. [&](bool close_connection, bool &connection_closed) {
  8854. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  8855. write_timeout_sec, write_timeout_usec);
  8856. // See the non-TLS path in process_server_socket().
  8857. strm.set_readable_hint();
  8858. return callback(strm, close_connection, connection_closed);
  8859. });
  8860. }
  8861. template <typename T>
  8862. inline bool process_client_socket_ssl(
  8863. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  8864. time_t read_timeout_usec, time_t write_timeout_sec,
  8865. time_t write_timeout_usec, time_t max_timeout_msec,
  8866. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  8867. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  8868. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  8869. start_time);
  8870. return callback(strm);
  8871. }
  8872. inline std::pair<std::string, std::string> make_digest_authentication_header(
  8873. const Request &req, const std::map<std::string, std::string> &auth,
  8874. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  8875. const std::string &password, bool is_proxy = false) {
  8876. std::string nc;
  8877. {
  8878. std::stringstream ss;
  8879. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  8880. nc = ss.str();
  8881. }
  8882. std::string qop;
  8883. if (auth.find("qop") != auth.end()) {
  8884. qop = auth.at("qop");
  8885. if (qop.find("auth-int") != std::string::npos) {
  8886. qop = "auth-int";
  8887. } else if (qop.find("auth") != std::string::npos) {
  8888. qop = "auth";
  8889. } else {
  8890. qop.clear();
  8891. }
  8892. }
  8893. std::string algo = "MD5";
  8894. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  8895. std::string response;
  8896. {
  8897. auto H = algo == "SHA-256" ? detail::SHA_256
  8898. : algo == "SHA-512" ? detail::SHA_512
  8899. : detail::MD5;
  8900. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  8901. auto A2 = req.method + ":" + req.path;
  8902. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  8903. if (qop.empty()) {
  8904. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  8905. } else {
  8906. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  8907. ":" + qop + ":" + H(A2));
  8908. }
  8909. }
  8910. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  8911. auto field = "Digest username=\"" + username + "\", realm=\"" +
  8912. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  8913. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  8914. (qop.empty() ? ", response=\""
  8915. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  8916. cnonce + "\", response=\"") +
  8917. response + "\"" +
  8918. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  8919. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8920. return std::make_pair(key, field);
  8921. }
  8922. inline bool match_hostname(const std::string &pattern,
  8923. const std::string &hostname) {
  8924. // Exact match (case-insensitive)
  8925. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  8926. // Split both pattern and hostname into components by '.'
  8927. std::vector<std::string> pattern_components;
  8928. if (!pattern.empty()) {
  8929. split(pattern.data(), pattern.data() + pattern.size(), '.',
  8930. [&](const char *b, const char *e) {
  8931. pattern_components.emplace_back(b, e);
  8932. });
  8933. }
  8934. std::vector<std::string> host_components;
  8935. if (!hostname.empty()) {
  8936. split(hostname.data(), hostname.data() + hostname.size(), '.',
  8937. [&](const char *b, const char *e) {
  8938. host_components.emplace_back(b, e);
  8939. });
  8940. }
  8941. // Component count must match
  8942. if (host_components.size() != pattern_components.size()) { return false; }
  8943. // Compare each component with wildcard support
  8944. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  8945. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  8946. auto itr = pattern_components.begin();
  8947. for (const auto &h : host_components) {
  8948. auto &p = *itr;
  8949. if (!detail::case_ignore::equal(p, h) && p != "*") {
  8950. bool partial_match = false;
  8951. if (!p.empty() && p[p.size() - 1] == '*') {
  8952. const auto prefix_length = p.size() - 1;
  8953. if (prefix_length == 0) {
  8954. partial_match = true;
  8955. } else if (h.size() >= prefix_length) {
  8956. partial_match =
  8957. std::equal(p.begin(),
  8958. p.begin() + static_cast<std::string::difference_type>(
  8959. prefix_length),
  8960. h.begin(), [](const char ca, const char cb) {
  8961. return detail::case_ignore::to_lower(ca) ==
  8962. detail::case_ignore::to_lower(cb);
  8963. });
  8964. }
  8965. }
  8966. if (!partial_match) { return false; }
  8967. }
  8968. ++itr;
  8969. }
  8970. return true;
  8971. }
  8972. #ifdef _WIN32
  8973. // Verify certificate using Windows CertGetCertificateChain API.
  8974. // This provides real-time certificate validation with Windows Update
  8975. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  8976. inline bool
  8977. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  8978. const std::string &hostname,
  8979. bool verify_hostname, uint64_t &out_error) {
  8980. if (der_cert.empty()) { return false; }
  8981. out_error = 0;
  8982. // Create Windows certificate context from DER data
  8983. auto cert_context = CertCreateCertificateContext(
  8984. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  8985. static_cast<DWORD>(der_cert.size()));
  8986. if (!cert_context) {
  8987. out_error = GetLastError();
  8988. return false;
  8989. }
  8990. auto cert_guard =
  8991. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  8992. // Setup chain parameters
  8993. CERT_CHAIN_PARA chain_para = {};
  8994. chain_para.cbSize = sizeof(chain_para);
  8995. // Build certificate chain with revocation checking
  8996. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  8997. auto chain_result = CertGetCertificateChain(
  8998. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  8999. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  9000. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  9001. nullptr, &chain_context);
  9002. if (!chain_result || !chain_context) {
  9003. out_error = GetLastError();
  9004. return false;
  9005. }
  9006. auto chain_guard =
  9007. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  9008. // Check if chain has errors
  9009. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  9010. out_error = chain_context->TrustStatus.dwErrorStatus;
  9011. return false;
  9012. }
  9013. // Verify SSL policy
  9014. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  9015. extra_policy_para.cbSize = sizeof(extra_policy_para);
  9016. #ifdef AUTHTYPE_SERVER
  9017. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  9018. #endif
  9019. std::wstring whost;
  9020. if (verify_hostname) {
  9021. whost = u8string_to_wstring(hostname.c_str());
  9022. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  9023. }
  9024. CERT_CHAIN_POLICY_PARA policy_para = {};
  9025. policy_para.cbSize = sizeof(policy_para);
  9026. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  9027. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  9028. #else
  9029. policy_para.dwFlags = 0;
  9030. #endif
  9031. policy_para.pvExtraPolicyPara = &extra_policy_para;
  9032. CERT_CHAIN_POLICY_STATUS policy_status = {};
  9033. policy_status.cbSize = sizeof(policy_status);
  9034. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  9035. &policy_para, &policy_status)) {
  9036. out_error = GetLastError();
  9037. return false;
  9038. }
  9039. if (policy_status.dwError != 0) {
  9040. out_error = policy_status.dwError;
  9041. return false;
  9042. }
  9043. return true;
  9044. }
  9045. #endif // _WIN32
  9046. // Loads CA file/dir configuration and applies the system CA policy to a
  9047. // client TLS context. PEM data and native stores are applied to the context
  9048. // directly at set time; has_custom_store reflects them for the Auto policy
  9049. // decision.
  9050. inline bool load_client_ca_config(tls::ctx_t ctx,
  9051. const std::string &ca_cert_file_path,
  9052. const std::string &ca_cert_dir_path,
  9053. bool has_custom_store, SystemCAMode mode,
  9054. uint64_t &backend_error) {
  9055. auto ret = true;
  9056. if (!ca_cert_file_path.empty()) {
  9057. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  9058. backend_error = tls::get_error();
  9059. ret = false;
  9060. }
  9061. } else if (!ca_cert_dir_path.empty()) {
  9062. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  9063. backend_error = tls::get_error();
  9064. ret = false;
  9065. }
  9066. }
  9067. auto has_custom_ca = !ca_cert_file_path.empty() ||
  9068. !ca_cert_dir_path.empty() || has_custom_store;
  9069. if (mode == SystemCAMode::Enabled ||
  9070. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  9071. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  9072. }
  9073. return ret;
  9074. }
  9075. // The parts of session setup that only SSLClient needs, plus the handful
  9076. // WebSocketClient also exposes; everything else takes the defaults, which is
  9077. // what keeps the two clients on one implementation.
  9078. struct ClientTlsSessionOptions {
  9079. // Both SSLClient and WebSocketClient expose this independently of
  9080. // certificate verification.
  9081. bool server_hostname_verification = true;
  9082. std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
  9083. // When non-null, guards session creation against concurrent use of the
  9084. // context. A WebSocketClient is not safe to use from several threads to
  9085. // begin with, so it passes nothing.
  9086. std::mutex *ctx_mutex = nullptr;
  9087. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  9088. // The caller decides whether Schannel has anything to say about this
  9089. // connection; see SSLClient::initialize_ssl().
  9090. bool windows_cert_verification = false;
  9091. #endif
  9092. };
  9093. // Filled in on failure for callers that report error details.
  9094. struct ClientTlsSessionError {
  9095. Error error = Error::Success;
  9096. int ssl_error = 0;
  9097. uint64_t backend_error = 0;
  9098. };
  9099. // Establishes a client TLS session on an already connected socket. On failure
  9100. // the session is left for the caller to free: SSLClient frees it right away,
  9101. // WebSocketClient keeps it in a member that shutdown_and_close() cleans up.
  9102. inline bool setup_client_tls_session(
  9103. const std::string &host, tls::ctx_t ctx, tls::session_t &session,
  9104. socket_t sock, bool server_certificate_verification, time_t timeout_sec,
  9105. time_t timeout_usec, ClientTlsSessionError *out_error = nullptr,
  9106. const ClientTlsSessionOptions &options = ClientTlsSessionOptions()) {
  9107. using namespace tls;
  9108. auto fail = [&](Error error, int ssl_error, uint64_t backend_error) {
  9109. if (out_error) {
  9110. out_error->error = error;
  9111. out_error->ssl_error = ssl_error;
  9112. out_error->backend_error = backend_error;
  9113. }
  9114. return false;
  9115. };
  9116. if (!ctx) {
  9117. session = nullptr;
  9118. return fail(Error::SSLConnection, 0, 0);
  9119. }
  9120. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  9121. // Mbed TLS and wolfSSL need the verification mode set explicitly; OpenSSL
  9122. // uses SSL_VERIFY_NONE and does all verification post-handshake. Chain
  9123. // verification happens during the handshake even for IP hosts; the
  9124. // certificate identity is verified post-handshake via verify_hostname().
  9125. set_verify_client(ctx, server_certificate_verification);
  9126. #endif
  9127. {
  9128. std::unique_lock<std::mutex> guard;
  9129. if (options.ctx_mutex) {
  9130. guard = std::unique_lock<std::mutex>(*options.ctx_mutex);
  9131. }
  9132. session = create_session(ctx, sock);
  9133. }
  9134. if (!session) { return fail(Error::SSLConnection, 0, get_error()); }
  9135. // RFC 6066: SNI must not be set for IP addresses; skip it for IP hosts, so
  9136. // their identity is checked post-handshake below instead. On Mbed TLS and
  9137. // wolfSSL, set_sni also drives handshake-time hostname verification, so
  9138. // options.server_hostname_verification is threaded through here.
  9139. if (!is_ip_address(host)) {
  9140. if (!set_sni(session, host.c_str(), options.server_hostname_verification)) {
  9141. return fail(Error::SSLConnection, 0, get_error());
  9142. }
  9143. }
  9144. TlsError tls_err;
  9145. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec,
  9146. &tls_err)) {
  9147. auto error = Error::SSLConnection;
  9148. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  9149. error = Error::SSLServerVerification;
  9150. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  9151. error = Error::SSLServerHostnameVerification;
  9152. }
  9153. return fail(error, static_cast<int>(tls_err.code), tls_err.backend_code);
  9154. }
  9155. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  9156. if (options.session_verifier) {
  9157. verification_status = options.session_verifier(session);
  9158. }
  9159. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  9160. return fail(Error::SSLServerVerification, 0, get_error());
  9161. }
  9162. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  9163. server_certificate_verification) {
  9164. auto verify_result = get_verify_result(session);
  9165. if (verify_result != 0) {
  9166. return fail(Error::SSLServerVerification, 0,
  9167. static_cast<uint64_t>(verify_result));
  9168. }
  9169. auto server_cert = get_peer_cert(session);
  9170. if (!server_cert) {
  9171. return fail(Error::SSLServerVerification, 0, get_error());
  9172. }
  9173. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  9174. // Identity check against the peer certificate, post-handshake for all
  9175. // backends. For IP hosts this is the only identity verification, since no
  9176. // hostname is bound during the handshake.
  9177. if (options.server_hostname_verification) {
  9178. if (!verify_hostname(server_cert, host.c_str())) {
  9179. return fail(Error::SSLServerHostnameVerification, 0,
  9180. hostname_mismatch_code());
  9181. }
  9182. }
  9183. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  9184. // Additional Windows Schannel verification.
  9185. // This provides real-time certificate validation with Windows Update
  9186. // integration, working with both OpenSSL and MbedTLS backends.
  9187. if (options.windows_cert_verification) {
  9188. std::vector<unsigned char> der;
  9189. if (get_cert_der(server_cert, der)) {
  9190. uint64_t wincrypt_error = 0;
  9191. if (!verify_cert_with_windows_schannel(
  9192. der, host, options.server_hostname_verification,
  9193. wincrypt_error)) {
  9194. return fail(Error::SSLServerVerification, 0, wincrypt_error);
  9195. }
  9196. }
  9197. }
  9198. #endif
  9199. }
  9200. return true;
  9201. }
  9202. } // namespace detail
  9203. #endif // CPPHTTPLIB_SSL_ENABLED
  9204. /*
  9205. * Group 3: httplib namespace - Non-SSL public API implementations
  9206. */
  9207. inline void default_socket_options(socket_t sock) {
  9208. set_socket_opt(sock, SOL_SOCKET,
  9209. #ifdef SO_REUSEPORT
  9210. SO_REUSEPORT,
  9211. #else
  9212. SO_REUSEADDR,
  9213. #endif
  9214. 1);
  9215. }
  9216. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  9217. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  9218. sizeof(optval));
  9219. }
  9220. inline std::string get_bearer_token_auth(const Request &req) {
  9221. // The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
  9222. // than the prefix carries no token.
  9223. constexpr const char bearer_prefix[] = "Bearer ";
  9224. constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
  9225. auto value = req.get_header_value("Authorization");
  9226. if (value.size() >= bearer_prefix_len &&
  9227. detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
  9228. bearer_prefix)) {
  9229. return value.substr(bearer_prefix_len);
  9230. }
  9231. return "";
  9232. }
  9233. inline const char *status_message(int status) {
  9234. switch (status) {
  9235. case StatusCode::Continue_100: return "Continue";
  9236. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  9237. case StatusCode::Processing_102: return "Processing";
  9238. case StatusCode::EarlyHints_103: return "Early Hints";
  9239. case StatusCode::OK_200: return "OK";
  9240. case StatusCode::Created_201: return "Created";
  9241. case StatusCode::Accepted_202: return "Accepted";
  9242. case StatusCode::NonAuthoritativeInformation_203:
  9243. return "Non-Authoritative Information";
  9244. case StatusCode::NoContent_204: return "No Content";
  9245. case StatusCode::ResetContent_205: return "Reset Content";
  9246. case StatusCode::PartialContent_206: return "Partial Content";
  9247. case StatusCode::MultiStatus_207: return "Multi-Status";
  9248. case StatusCode::AlreadyReported_208: return "Already Reported";
  9249. case StatusCode::IMUsed_226: return "IM Used";
  9250. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  9251. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  9252. case StatusCode::Found_302: return "Found";
  9253. case StatusCode::SeeOther_303: return "See Other";
  9254. case StatusCode::NotModified_304: return "Not Modified";
  9255. case StatusCode::UseProxy_305: return "Use Proxy";
  9256. case StatusCode::unused_306: return "unused";
  9257. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  9258. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  9259. case StatusCode::BadRequest_400: return "Bad Request";
  9260. case StatusCode::Unauthorized_401: return "Unauthorized";
  9261. case StatusCode::PaymentRequired_402: return "Payment Required";
  9262. case StatusCode::Forbidden_403: return "Forbidden";
  9263. case StatusCode::NotFound_404: return "Not Found";
  9264. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  9265. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  9266. case StatusCode::ProxyAuthenticationRequired_407:
  9267. return "Proxy Authentication Required";
  9268. case StatusCode::RequestTimeout_408: return "Request Timeout";
  9269. case StatusCode::Conflict_409: return "Conflict";
  9270. case StatusCode::Gone_410: return "Gone";
  9271. case StatusCode::LengthRequired_411: return "Length Required";
  9272. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  9273. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  9274. case StatusCode::UriTooLong_414: return "URI Too Long";
  9275. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  9276. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  9277. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  9278. case StatusCode::ImATeapot_418: return "I'm a teapot";
  9279. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  9280. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  9281. case StatusCode::Locked_423: return "Locked";
  9282. case StatusCode::FailedDependency_424: return "Failed Dependency";
  9283. case StatusCode::TooEarly_425: return "Too Early";
  9284. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  9285. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  9286. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  9287. case StatusCode::RequestHeaderFieldsTooLarge_431:
  9288. return "Request Header Fields Too Large";
  9289. case StatusCode::UnavailableForLegalReasons_451:
  9290. return "Unavailable For Legal Reasons";
  9291. case StatusCode::NotImplemented_501: return "Not Implemented";
  9292. case StatusCode::BadGateway_502: return "Bad Gateway";
  9293. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  9294. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  9295. case StatusCode::HttpVersionNotSupported_505:
  9296. return "HTTP Version Not Supported";
  9297. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  9298. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  9299. case StatusCode::LoopDetected_508: return "Loop Detected";
  9300. case StatusCode::NotExtended_510: return "Not Extended";
  9301. case StatusCode::NetworkAuthenticationRequired_511:
  9302. return "Network Authentication Required";
  9303. default:
  9304. case StatusCode::InternalServerError_500: return "Internal Server Error";
  9305. }
  9306. }
  9307. inline std::string to_string(const Error error) {
  9308. switch (error) {
  9309. case Error::Success: return "Success (no error)";
  9310. case Error::Unknown: return "Unknown";
  9311. case Error::Connection: return "Could not establish connection";
  9312. case Error::BindIPAddress: return "Failed to bind IP address";
  9313. case Error::Read: return "Failed to read connection";
  9314. case Error::Write: return "Failed to write connection";
  9315. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  9316. case Error::Canceled: return "Connection handling canceled";
  9317. case Error::SSLConnection: return "SSL connection failed";
  9318. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  9319. case Error::SSLServerVerification: return "SSL server verification failed";
  9320. case Error::SSLServerHostnameVerification:
  9321. return "SSL server hostname verification failed";
  9322. case Error::UnsupportedMultipartBoundaryChars:
  9323. return "Unsupported HTTP multipart boundary characters";
  9324. case Error::Compression: return "Compression failed";
  9325. case Error::ConnectionTimeout: return "Connection timed out";
  9326. case Error::ProxyConnection: return "Proxy connection failed";
  9327. case Error::ConnectionClosed: return "Connection closed by server";
  9328. case Error::Timeout: return "Read timeout";
  9329. case Error::ResourceExhaustion: return "Resource exhaustion";
  9330. case Error::TooManyFormDataFiles: return "Too many form data files";
  9331. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  9332. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  9333. case Error::ExceedMaxSocketDescriptorCount:
  9334. return "Exceeded maximum socket descriptor count";
  9335. case Error::InvalidRequestLine: return "Invalid request line";
  9336. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  9337. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  9338. case Error::InvalidHeaders: return "Invalid headers";
  9339. case Error::MultipartParsing: return "Multipart parsing failed";
  9340. case Error::OpenFile: return "Failed to open file";
  9341. case Error::Listen: return "Failed to listen on socket";
  9342. case Error::GetSockName: return "Failed to get socket name";
  9343. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  9344. case Error::HTTPParsing: return "HTTP parsing failed";
  9345. case Error::InvalidRangeHeader: return "Invalid Range header";
  9346. case Error::UnsupportedContentEncoding: return "Unsupported Content-Encoding";
  9347. case Error::WebSocketHandshake: return "WebSocket handshake failed";
  9348. case Error::UserCallbackException: return "User callback threw an exception";
  9349. default: break;
  9350. }
  9351. return "Invalid";
  9352. }
  9353. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  9354. os << to_string(obj);
  9355. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  9356. return os;
  9357. }
  9358. inline std::string hosted_at(const std::string &hostname) {
  9359. std::vector<std::string> addrs;
  9360. hosted_at(hostname, addrs);
  9361. if (addrs.empty()) { return std::string(); }
  9362. return addrs[0];
  9363. }
  9364. inline void hosted_at(const std::string &hostname,
  9365. std::vector<std::string> &addrs) {
  9366. struct addrinfo hints;
  9367. struct addrinfo *result;
  9368. memset(&hints, 0, sizeof(struct addrinfo));
  9369. hints.ai_family = AF_UNSPEC;
  9370. hints.ai_socktype = SOCK_STREAM;
  9371. hints.ai_protocol = 0;
  9372. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  9373. &result, 0)) {
  9374. #if defined __linux__ && !defined __ANDROID__
  9375. res_init();
  9376. #endif
  9377. return;
  9378. }
  9379. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  9380. for (auto rp = result; rp; rp = rp->ai_next) {
  9381. const auto &addr =
  9382. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  9383. std::string ip;
  9384. auto dummy = -1;
  9385. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  9386. dummy)) {
  9387. addrs.emplace_back(std::move(ip));
  9388. }
  9389. }
  9390. }
  9391. inline std::string encode_uri_component(const std::string &value) {
  9392. std::ostringstream escaped;
  9393. escaped.fill('0');
  9394. escaped << std::hex;
  9395. for (auto c : value) {
  9396. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9397. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  9398. escaped << c;
  9399. } else {
  9400. escaped << std::uppercase;
  9401. escaped << '%' << std::setw(2)
  9402. << static_cast<int>(static_cast<unsigned char>(c));
  9403. escaped << std::nouppercase;
  9404. }
  9405. }
  9406. return escaped.str();
  9407. }
  9408. inline std::string encode_uri(const std::string &value) {
  9409. std::ostringstream escaped;
  9410. escaped.fill('0');
  9411. escaped << std::hex;
  9412. for (auto c : value) {
  9413. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  9414. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  9415. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  9416. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  9417. escaped << c;
  9418. } else {
  9419. escaped << std::uppercase;
  9420. escaped << '%' << std::setw(2)
  9421. << static_cast<int>(static_cast<unsigned char>(c));
  9422. escaped << std::nouppercase;
  9423. }
  9424. }
  9425. return escaped.str();
  9426. }
  9427. inline std::string decode_uri_component(const std::string &value) {
  9428. std::string result;
  9429. for (size_t i = 0; i < value.size(); i++) {
  9430. if (value[i] == '%' && i + 2 < value.size()) {
  9431. auto val = 0;
  9432. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9433. result += static_cast<char>(val);
  9434. i += 2;
  9435. } else {
  9436. result += value[i];
  9437. }
  9438. } else {
  9439. result += value[i];
  9440. }
  9441. }
  9442. return result;
  9443. }
  9444. inline std::string decode_uri(const std::string &value) {
  9445. std::string result;
  9446. for (size_t i = 0; i < value.size(); i++) {
  9447. if (value[i] == '%' && i + 2 < value.size()) {
  9448. auto val = 0;
  9449. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  9450. auto c = static_cast<char>(val);
  9451. // Keep escapes of the reserved characters that encode_uri leaves
  9452. // literal, so decode_uri is the inverse of encode_uri and an escaped
  9453. // delimiter is not promoted into a real one (as with JS decodeURI).
  9454. if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  9455. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' ||
  9456. c == '#') {
  9457. result += value[i];
  9458. result += value[i + 1];
  9459. result += value[i + 2];
  9460. } else {
  9461. result += c;
  9462. }
  9463. i += 2;
  9464. } else {
  9465. result += value[i];
  9466. }
  9467. } else {
  9468. result += value[i];
  9469. }
  9470. }
  9471. return result;
  9472. }
  9473. inline std::string encode_path_component(const std::string &component) {
  9474. std::string result;
  9475. result.reserve(component.size() * 3);
  9476. for (size_t i = 0; i < component.size(); i++) {
  9477. auto c = static_cast<unsigned char>(component[i]);
  9478. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  9479. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9480. c == '_' || c == '~') {
  9481. result += static_cast<char>(c);
  9482. }
  9483. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  9484. // "," / ";" / "="
  9485. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  9486. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  9487. c == '=') {
  9488. result += static_cast<char>(c);
  9489. }
  9490. // Colon is allowed in path segments except first segment
  9491. else if (c == ':') {
  9492. result += static_cast<char>(c);
  9493. }
  9494. // @ is allowed in path
  9495. else if (c == '@') {
  9496. result += static_cast<char>(c);
  9497. } else {
  9498. result += '%';
  9499. char hex[3];
  9500. snprintf(hex, sizeof(hex), "%02X", c);
  9501. result.append(hex, 2);
  9502. }
  9503. }
  9504. return result;
  9505. }
  9506. inline std::string decode_path_component(const std::string &component) {
  9507. std::string result;
  9508. result.reserve(component.size());
  9509. for (size_t i = 0; i < component.size(); i++) {
  9510. if (component[i] == '%' && i + 1 < component.size()) {
  9511. if (component[i + 1] == 'u') {
  9512. // Unicode %uXXXX encoding
  9513. auto val = 0;
  9514. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  9515. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  9516. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  9517. char buff[4];
  9518. size_t len = detail::to_utf8(val, buff);
  9519. if (len > 0) { result.append(buff, len); }
  9520. i += 5; // 'u0000'
  9521. } else {
  9522. result += component[i];
  9523. }
  9524. } else {
  9525. // Standard %XX encoding
  9526. auto val = 0;
  9527. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9528. // 2 digits hex codes
  9529. result += static_cast<char>(val);
  9530. i += 2; // 'XX'
  9531. } else {
  9532. result += component[i];
  9533. }
  9534. }
  9535. } else {
  9536. result += component[i];
  9537. }
  9538. }
  9539. return result;
  9540. }
  9541. inline std::string encode_query_component(const std::string &component,
  9542. bool space_as_plus) {
  9543. std::string result;
  9544. result.reserve(component.size() * 3);
  9545. for (size_t i = 0; i < component.size(); i++) {
  9546. auto c = static_cast<unsigned char>(component[i]);
  9547. // Unreserved characters per RFC 3986
  9548. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  9549. c == '_' || c == '~') {
  9550. result += static_cast<char>(c);
  9551. }
  9552. // Space handling
  9553. else if (c == ' ') {
  9554. if (space_as_plus) {
  9555. result += '+';
  9556. } else {
  9557. result += "%20";
  9558. }
  9559. }
  9560. // Plus sign handling
  9561. else if (c == '+') {
  9562. if (space_as_plus) {
  9563. result += "%2B";
  9564. } else {
  9565. result += static_cast<char>(c);
  9566. }
  9567. }
  9568. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  9569. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  9570. c == '*' || c == ',' || c == ';') {
  9571. result += static_cast<char>(c);
  9572. }
  9573. // Colon and @ are allowed in query
  9574. else if (c == ':' || c == '@') {
  9575. result += static_cast<char>(c);
  9576. }
  9577. // Forward slash is allowed in query values
  9578. else if (c == '/') {
  9579. result += static_cast<char>(c);
  9580. }
  9581. // Question mark is allowed in query values (after first ?)
  9582. else if (c == '?') {
  9583. result += static_cast<char>(c);
  9584. } else {
  9585. result += '%';
  9586. char hex[3];
  9587. snprintf(hex, sizeof(hex), "%02X", c);
  9588. result.append(hex, 2);
  9589. }
  9590. }
  9591. return result;
  9592. }
  9593. inline std::string decode_query_component(const std::string &component,
  9594. bool plus_as_space) {
  9595. std::string result;
  9596. result.reserve(component.size());
  9597. for (size_t i = 0; i < component.size(); i++) {
  9598. if (component[i] == '%' && i + 2 < component.size()) {
  9599. auto val = 0;
  9600. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  9601. result += static_cast<char>(val);
  9602. i += 2;
  9603. } else {
  9604. result += component[i];
  9605. }
  9606. } else if (component[i] == '+' && plus_as_space) {
  9607. result += ' '; // + becomes space in form-urlencoded
  9608. } else {
  9609. result += component[i];
  9610. }
  9611. }
  9612. return result;
  9613. }
  9614. inline std::string sanitize_filename(const std::string &filename) {
  9615. // Extract basename: find the last path separator (/ or \)
  9616. auto pos = filename.find_last_of("/\\");
  9617. auto result =
  9618. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  9619. // Strip null bytes
  9620. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  9621. // Trim whitespace
  9622. {
  9623. auto start = result.find_first_not_of(" \t");
  9624. auto end = result.find_last_not_of(" \t");
  9625. result = (start == std::string::npos)
  9626. ? ""
  9627. : result.substr(start, end - start + 1);
  9628. }
  9629. // Reject . and ..
  9630. if (result == "." || result == "..") { return ""; }
  9631. return result;
  9632. }
  9633. inline std::string append_query_params(const std::string &path,
  9634. const Params &params) {
  9635. std::string path_with_query = path;
  9636. thread_local const std::regex re("[^?]+\\?.*");
  9637. auto delm = std::regex_match(path, re) ? '&' : '?';
  9638. path_with_query += delm + detail::params_to_query_str(params);
  9639. return path_with_query;
  9640. }
  9641. // Header utilities
  9642. inline std::pair<std::string, std::string>
  9643. make_range_header(const Ranges &ranges) {
  9644. std::string field = "bytes=";
  9645. auto i = 0;
  9646. for (const auto &r : ranges) {
  9647. if (i != 0) { field += ", "; }
  9648. if (r.first != -1) { field += std::to_string(r.first); }
  9649. field += '-';
  9650. if (r.second != -1) { field += std::to_string(r.second); }
  9651. i++;
  9652. }
  9653. return std::make_pair("Range", std::move(field));
  9654. }
  9655. inline std::pair<std::string, std::string>
  9656. make_basic_authentication_header(const std::string &username,
  9657. const std::string &password, bool is_proxy) {
  9658. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  9659. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9660. return std::make_pair(key, std::move(field));
  9661. }
  9662. inline std::pair<std::string, std::string>
  9663. make_bearer_token_authentication_header(const std::string &token,
  9664. bool is_proxy = false) {
  9665. auto field = "Bearer " + token;
  9666. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  9667. return std::make_pair(key, std::move(field));
  9668. }
  9669. // Request implementation
  9670. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  9671. size_t id) const {
  9672. return detail::get_header_value_u64(headers, key, def, id);
  9673. }
  9674. inline bool Request::has_header(const std::string &key) const {
  9675. return detail::has_header(headers, key);
  9676. }
  9677. inline std::string Request::get_header_value(const std::string &key,
  9678. const char *def, size_t id) const {
  9679. return detail::get_header_value(headers, key, def, id);
  9680. }
  9681. inline size_t Request::get_header_value_count(const std::string &key) const {
  9682. return detail::get_header_value_count(headers, key);
  9683. }
  9684. inline void Request::set_header(const std::string &key,
  9685. const std::string &val) {
  9686. detail::set_header(headers, key, val);
  9687. }
  9688. inline bool Request::has_trailer(const std::string &key) const {
  9689. return trailers.find(key) != trailers.end();
  9690. }
  9691. inline std::string Request::get_trailer_value(const std::string &key,
  9692. size_t id) const {
  9693. return detail::get_multimap_value(trailers, key, id);
  9694. }
  9695. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  9696. return trailers.count(key);
  9697. }
  9698. inline bool Request::has_param(const std::string &key) const {
  9699. return params.find(key) != params.end();
  9700. }
  9701. inline std::string Request::get_param_value(const std::string &key,
  9702. size_t id) const {
  9703. return detail::get_multimap_value(params, key, id);
  9704. }
  9705. inline std::vector<std::string>
  9706. Request::get_param_values(const std::string &key) const {
  9707. auto rng = params.equal_range(key);
  9708. std::vector<std::string> values;
  9709. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  9710. for (auto it = rng.first; it != rng.second; ++it) {
  9711. values.push_back(it->second);
  9712. }
  9713. return values;
  9714. }
  9715. inline size_t Request::get_param_value_count(const std::string &key) const {
  9716. return params.count(key);
  9717. }
  9718. inline bool Request::is_multipart_form_data() const {
  9719. const auto &content_type = get_header_value("Content-Type");
  9720. return detail::extract_media_type(content_type) == "multipart/form-data";
  9721. }
  9722. // Multipart FormData implementation
  9723. inline std::string MultipartFormData::get_field(const std::string &key,
  9724. size_t id) const {
  9725. auto rng = fields.equal_range(key);
  9726. auto it = rng.first;
  9727. std::advance(it, static_cast<ssize_t>(id));
  9728. if (it != rng.second) { return it->second.content; }
  9729. return std::string();
  9730. }
  9731. inline std::vector<std::string>
  9732. MultipartFormData::get_fields(const std::string &key) const {
  9733. std::vector<std::string> values;
  9734. auto rng = fields.equal_range(key);
  9735. for (auto it = rng.first; it != rng.second; it++) {
  9736. values.push_back(it->second.content);
  9737. }
  9738. return values;
  9739. }
  9740. inline bool MultipartFormData::has_field(const std::string &key) const {
  9741. return fields.find(key) != fields.end();
  9742. }
  9743. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  9744. return fields.count(key);
  9745. }
  9746. inline FormData MultipartFormData::get_file(const std::string &key,
  9747. size_t id) const {
  9748. return detail::get_multimap_value(files, key, id);
  9749. }
  9750. inline std::vector<FormData>
  9751. MultipartFormData::get_files(const std::string &key) const {
  9752. std::vector<FormData> values;
  9753. auto rng = files.equal_range(key);
  9754. for (auto it = rng.first; it != rng.second; it++) {
  9755. values.push_back(it->second);
  9756. }
  9757. return values;
  9758. }
  9759. inline bool MultipartFormData::has_file(const std::string &key) const {
  9760. return files.find(key) != files.end();
  9761. }
  9762. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  9763. return files.count(key);
  9764. }
  9765. // Multipart FormData writer implementation
  9766. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  9767. return detail::is_multipart_boundary_chars_valid(boundary);
  9768. }
  9769. inline MultipartFormDataWriter::MultipartFormDataWriter()
  9770. : boundary_(detail::make_multipart_data_boundary()) {}
  9771. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  9772. : boundary_(std::move(boundary)) {}
  9773. inline const std::string &MultipartFormDataWriter::boundary() const {
  9774. return boundary_;
  9775. }
  9776. inline std::string MultipartFormDataWriter::content_type() const {
  9777. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  9778. }
  9779. inline std::string
  9780. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  9781. return detail::serialize_multipart_formdata(items, boundary_);
  9782. }
  9783. inline size_t MultipartFormDataWriter::content_length(
  9784. const UploadFormDataItems &items) const {
  9785. return detail::get_multipart_content_length(items, boundary_);
  9786. }
  9787. inline std::string
  9788. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  9789. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  9790. }
  9791. inline std::string MultipartFormDataWriter::item_end() {
  9792. return detail::serialize_multipart_formdata_item_end();
  9793. }
  9794. inline std::string MultipartFormDataWriter::finish() const {
  9795. return detail::serialize_multipart_formdata_finish(boundary_);
  9796. }
  9797. // Response implementation
  9798. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  9799. size_t id) const {
  9800. return detail::get_header_value_u64(headers, key, def, id);
  9801. }
  9802. inline bool Response::has_header(const std::string &key) const {
  9803. return headers.find(key) != headers.end();
  9804. }
  9805. inline std::string Response::get_header_value(const std::string &key,
  9806. const char *def,
  9807. size_t id) const {
  9808. return detail::get_header_value(headers, key, def, id);
  9809. }
  9810. inline size_t Response::get_header_value_count(const std::string &key) const {
  9811. return detail::get_header_value_count(headers, key);
  9812. }
  9813. inline void Response::set_header(const std::string &key,
  9814. const std::string &val) {
  9815. detail::set_header(headers, key, val);
  9816. }
  9817. inline bool Response::has_trailer(const std::string &key) const {
  9818. return trailers.find(key) != trailers.end();
  9819. }
  9820. inline std::string Response::get_trailer_value(const std::string &key,
  9821. size_t id) const {
  9822. return detail::get_multimap_value(trailers, key, id);
  9823. }
  9824. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  9825. return trailers.count(key);
  9826. }
  9827. inline void Response::set_redirect(const std::string &url, int stat) {
  9828. if (detail::fields::is_field_value(url)) {
  9829. set_header("Location", url);
  9830. if (300 <= stat && stat < 400) {
  9831. this->status = stat;
  9832. } else {
  9833. this->status = StatusCode::Found_302;
  9834. }
  9835. }
  9836. }
  9837. inline void Response::set_content(const char *s, size_t n,
  9838. const std::string &content_type) {
  9839. body.assign(s, n);
  9840. auto rng = headers.equal_range("Content-Type");
  9841. headers.erase(rng.first, rng.second);
  9842. set_header("Content-Type", content_type);
  9843. content_coding_ = detail::EncodingType::None;
  9844. }
  9845. inline void Response::set_content(const std::string &s,
  9846. const std::string &content_type) {
  9847. set_content(s.data(), s.size(), content_type);
  9848. }
  9849. inline void Response::set_content(std::string &&s,
  9850. const std::string &content_type) {
  9851. body = std::move(s);
  9852. auto rng = headers.equal_range("Content-Type");
  9853. headers.erase(rng.first, rng.second);
  9854. set_header("Content-Type", content_type);
  9855. content_coding_ = detail::EncodingType::None;
  9856. }
  9857. inline void Response::set_content_provider(
  9858. size_t in_length, const std::string &content_type, ContentProvider provider,
  9859. ContentProviderResourceReleaser resource_releaser) {
  9860. set_header("Content-Type", content_type);
  9861. content_length_ = in_length;
  9862. if (in_length > 0) { content_provider_ = std::move(provider); }
  9863. content_provider_resource_releaser_ = std::move(resource_releaser);
  9864. is_chunked_content_provider_ = false;
  9865. is_file_content_provider_ = false;
  9866. content_coding_ = detail::EncodingType::None;
  9867. }
  9868. inline void Response::set_content_provider(
  9869. const std::string &content_type, ContentProviderWithoutLength provider,
  9870. ContentProviderResourceReleaser resource_releaser) {
  9871. set_header("Content-Type", content_type);
  9872. content_length_ = 0;
  9873. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  9874. content_provider_resource_releaser_ = std::move(resource_releaser);
  9875. is_chunked_content_provider_ = false;
  9876. is_file_content_provider_ = false;
  9877. content_coding_ = detail::EncodingType::None;
  9878. }
  9879. inline void Response::set_chunked_content_provider(
  9880. const std::string &content_type, ContentProviderWithoutLength provider,
  9881. ContentProviderResourceReleaser resource_releaser) {
  9882. set_header("Content-Type", content_type);
  9883. content_length_ = 0;
  9884. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  9885. content_provider_resource_releaser_ = std::move(resource_releaser);
  9886. is_chunked_content_provider_ = true;
  9887. is_file_content_provider_ = false;
  9888. content_coding_ = detail::EncodingType::None;
  9889. }
  9890. inline void Response::set_file_content(const std::string &path,
  9891. const std::string &content_type) {
  9892. file_content_path_ = path;
  9893. file_content_content_type_ = content_type;
  9894. }
  9895. inline void Response::set_file_content(const std::string &path) {
  9896. file_content_path_ = path;
  9897. }
  9898. // Result implementation
  9899. inline size_t Result::get_request_header_value_u64(const std::string &key,
  9900. size_t def,
  9901. size_t id) const {
  9902. return detail::get_header_value_u64(request_headers_, key, def, id);
  9903. }
  9904. inline bool Result::has_request_header(const std::string &key) const {
  9905. return request_headers_.find(key) != request_headers_.end();
  9906. }
  9907. inline std::string Result::get_request_header_value(const std::string &key,
  9908. const char *def,
  9909. size_t id) const {
  9910. return detail::get_header_value(request_headers_, key, def, id);
  9911. }
  9912. inline size_t
  9913. Result::get_request_header_value_count(const std::string &key) const {
  9914. return request_headers_.count(key);
  9915. }
  9916. // Stream implementation
  9917. inline ssize_t Stream::write(const char *ptr) {
  9918. return write(ptr, strlen(ptr));
  9919. }
  9920. inline ssize_t Stream::write(const std::string &s) {
  9921. return write(s.data(), s.size());
  9922. }
  9923. // BodyReader implementation
  9924. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  9925. if (!stream) {
  9926. last_error = Error::Connection;
  9927. return -1;
  9928. }
  9929. if (eof) { return 0; }
  9930. if (!chunked) {
  9931. // Content-Length based reading
  9932. if (has_content_length && bytes_read >= content_length) {
  9933. eof = true;
  9934. return 0;
  9935. }
  9936. auto to_read = len;
  9937. if (has_content_length) {
  9938. auto remaining = content_length - bytes_read;
  9939. to_read = (std::min)(len, remaining);
  9940. }
  9941. auto n = stream->read(buf, to_read);
  9942. if (n < 0) {
  9943. last_error = stream->get_error();
  9944. if (last_error == Error::Success) { last_error = Error::Read; }
  9945. eof = true;
  9946. return n;
  9947. }
  9948. if (n == 0) {
  9949. // Unexpected EOF before content_length
  9950. last_error = stream->get_error();
  9951. if (last_error == Error::Success) { last_error = Error::Read; }
  9952. eof = true;
  9953. return 0;
  9954. }
  9955. bytes_read += static_cast<size_t>(n);
  9956. if (has_content_length && bytes_read >= content_length) { eof = true; }
  9957. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  9958. last_error = Error::ExceedMaxPayloadSize;
  9959. eof = true;
  9960. return -1;
  9961. }
  9962. return n;
  9963. }
  9964. // Chunked transfer encoding: delegate to shared decoder instance.
  9965. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  9966. size_t chunk_offset = 0;
  9967. size_t chunk_total = 0;
  9968. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  9969. if (n < 0) {
  9970. last_error = stream->get_error();
  9971. if (last_error == Error::Success) { last_error = Error::Read; }
  9972. eof = true;
  9973. return n;
  9974. }
  9975. if (n == 0) {
  9976. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  9977. eof = true;
  9978. return 0;
  9979. }
  9980. bytes_read += static_cast<size_t>(n);
  9981. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  9982. last_error = Error::ExceedMaxPayloadSize;
  9983. eof = true;
  9984. return -1;
  9985. }
  9986. return n;
  9987. }
  9988. // ThreadPool implementation
  9989. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  9990. time_t idle_timeout_sec)
  9991. : base_thread_count_(n), max_queued_requests_(mqr),
  9992. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  9993. shutdown_(false) {
  9994. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9995. if (max_n != 0 && max_n < n) {
  9996. std::string msg = "max_threads must be >= base_threads";
  9997. throw std::invalid_argument(msg);
  9998. }
  9999. #endif
  10000. max_thread_count_ = max_n == 0 ? n : max_n;
  10001. threads_.reserve(base_thread_count_);
  10002. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10003. try {
  10004. #endif
  10005. for (size_t i = 0; i < base_thread_count_; i++) {
  10006. threads_.emplace_back(std::thread([this]() { worker(false); }));
  10007. }
  10008. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10009. } catch (...) {
  10010. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  10011. // signal the workers we already spawned to exit and join them so the
  10012. // vector destructor does not see joinable threads (which would call
  10013. // std::terminate). Then rethrow so the caller learns of the failure.
  10014. {
  10015. std::unique_lock<std::mutex> lock(mutex_);
  10016. shutdown_ = true;
  10017. }
  10018. cond_.notify_all();
  10019. for (auto &t : threads_) {
  10020. if (t.joinable()) { t.join(); }
  10021. }
  10022. throw;
  10023. }
  10024. #endif
  10025. }
  10026. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  10027. {
  10028. std::unique_lock<std::mutex> lock(mutex_);
  10029. if (shutdown_) { return false; }
  10030. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  10031. return false;
  10032. }
  10033. jobs_.push_back(std::move(fn));
  10034. // Spawn a dynamic thread if no idle threads and under max
  10035. if (idle_thread_count_ == 0 &&
  10036. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  10037. cleanup_finished_threads();
  10038. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  10039. }
  10040. }
  10041. cond_.notify_one();
  10042. return true;
  10043. }
  10044. inline void ThreadPool::shutdown() {
  10045. {
  10046. std::unique_lock<std::mutex> lock(mutex_);
  10047. shutdown_ = true;
  10048. }
  10049. cond_.notify_all();
  10050. for (auto &t : threads_) {
  10051. if (t.joinable()) { t.join(); }
  10052. }
  10053. // Move dynamic_threads_ to a local list under the lock to avoid racing
  10054. // with worker threads that call move_to_finished() concurrently.
  10055. std::list<std::thread> remaining_dynamic;
  10056. {
  10057. std::unique_lock<std::mutex> lock(mutex_);
  10058. remaining_dynamic = std::move(dynamic_threads_);
  10059. }
  10060. for (auto &t : remaining_dynamic) {
  10061. if (t.joinable()) { t.join(); }
  10062. }
  10063. std::unique_lock<std::mutex> lock(mutex_);
  10064. cleanup_finished_threads();
  10065. }
  10066. inline void ThreadPool::move_to_finished(std::thread::id id) {
  10067. // Must be called with mutex_ held
  10068. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  10069. if (it->get_id() == id) {
  10070. finished_threads_.push_back(std::move(*it));
  10071. dynamic_threads_.erase(it);
  10072. return;
  10073. }
  10074. }
  10075. }
  10076. inline void ThreadPool::cleanup_finished_threads() {
  10077. // Must be called with mutex_ held
  10078. for (auto &t : finished_threads_) {
  10079. if (t.joinable()) { t.join(); }
  10080. }
  10081. finished_threads_.clear();
  10082. }
  10083. inline void ThreadPool::worker(bool is_dynamic) {
  10084. for (;;) {
  10085. std::function<void()> fn;
  10086. {
  10087. std::unique_lock<std::mutex> lock(mutex_);
  10088. idle_thread_count_++;
  10089. if (is_dynamic) {
  10090. auto has_work =
  10091. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  10092. [&] { return !jobs_.empty() || shutdown_; });
  10093. if (!has_work) {
  10094. // Timed out with no work - exit this dynamic thread
  10095. idle_thread_count_--;
  10096. move_to_finished(std::this_thread::get_id());
  10097. break;
  10098. }
  10099. } else {
  10100. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  10101. }
  10102. idle_thread_count_--;
  10103. if (shutdown_ && jobs_.empty()) { break; }
  10104. fn = std::move(jobs_.front());
  10105. jobs_.pop_front();
  10106. }
  10107. assert(true == static_cast<bool>(fn));
  10108. fn();
  10109. }
  10110. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  10111. !defined(LIBRESSL_VERSION_NUMBER)
  10112. OPENSSL_thread_stop();
  10113. #endif
  10114. }
  10115. /*
  10116. * Group 1 (continued): detail namespace - Stream implementations
  10117. */
  10118. namespace detail {
  10119. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  10120. time_t timeout_sec, time_t timeout_usec,
  10121. time_t &actual_timeout_sec,
  10122. time_t &actual_timeout_usec) {
  10123. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  10124. auto actual_timeout_msec =
  10125. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  10126. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  10127. actual_timeout_sec = actual_timeout_msec / 1000;
  10128. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  10129. }
  10130. // Socket stream implementation
  10131. inline SocketStream::SocketStream(
  10132. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  10133. time_t write_timeout_sec, time_t write_timeout_usec,
  10134. time_t max_timeout_msec,
  10135. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10136. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  10137. read_timeout_usec_(read_timeout_usec),
  10138. write_timeout_sec_(write_timeout_sec),
  10139. write_timeout_usec_(write_timeout_usec),
  10140. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  10141. read_buff_(read_buff_size_, 0) {}
  10142. inline SocketStream::~SocketStream() = default;
  10143. inline bool SocketStream::is_readable() const {
  10144. return read_buff_off_ < read_buff_content_size_;
  10145. }
  10146. inline bool SocketStream::wait_readable() const {
  10147. if (max_timeout_msec_ <= 0) {
  10148. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10149. }
  10150. time_t read_timeout_sec;
  10151. time_t read_timeout_usec;
  10152. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10153. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10154. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10155. }
  10156. inline bool SocketStream::wait_writable() const {
  10157. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  10158. }
  10159. inline bool SocketStream::ensure_readable() {
  10160. if (readable_hint_) {
  10161. readable_hint_ = false;
  10162. return true;
  10163. }
  10164. return wait_readable();
  10165. }
  10166. inline const char *SocketStream::buffered_data(size_t &size) const {
  10167. size = read_buff_content_size_ - read_buff_off_;
  10168. return size ? read_buff_.data() + read_buff_off_ : nullptr;
  10169. }
  10170. inline void SocketStream::consume_buffered(size_t size) {
  10171. assert(size <= read_buff_content_size_ - read_buff_off_);
  10172. read_buff_off_ += size;
  10173. }
  10174. inline bool SocketStream::is_peer_alive() const {
  10175. return detail::is_socket_alive(sock_);
  10176. }
  10177. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  10178. #ifdef _WIN32
  10179. size =
  10180. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  10181. #else
  10182. size = (std::min)(size,
  10183. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  10184. #endif
  10185. if (read_buff_off_ < read_buff_content_size_) {
  10186. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  10187. if (size <= remaining_size) {
  10188. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  10189. read_buff_off_ += size;
  10190. return static_cast<ssize_t>(size);
  10191. } else {
  10192. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  10193. read_buff_off_ += remaining_size;
  10194. return static_cast<ssize_t>(remaining_size);
  10195. }
  10196. }
  10197. if (!ensure_readable()) {
  10198. error_ = Error::Timeout;
  10199. return -1;
  10200. }
  10201. read_buff_off_ = 0;
  10202. read_buff_content_size_ = 0;
  10203. if (size < read_buff_size_) {
  10204. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  10205. CPPHTTPLIB_RECV_FLAGS);
  10206. if (n <= 0) {
  10207. if (n == 0) {
  10208. error_ = Error::ConnectionClosed;
  10209. } else {
  10210. error_ = Error::Read;
  10211. }
  10212. return n;
  10213. } else if (n <= static_cast<ssize_t>(size)) {
  10214. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  10215. return n;
  10216. } else {
  10217. memcpy(ptr, read_buff_.data(), size);
  10218. read_buff_off_ = size;
  10219. read_buff_content_size_ = static_cast<size_t>(n);
  10220. return static_cast<ssize_t>(size);
  10221. }
  10222. } else {
  10223. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  10224. if (n <= 0) {
  10225. if (n == 0) {
  10226. error_ = Error::ConnectionClosed;
  10227. } else {
  10228. error_ = Error::Read;
  10229. }
  10230. }
  10231. return n;
  10232. }
  10233. }
  10234. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  10235. if (!wait_writable()) { return -1; }
  10236. #if defined(_WIN32) && !defined(_WIN64)
  10237. size =
  10238. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  10239. #endif
  10240. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  10241. }
  10242. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  10243. int &port) const {
  10244. return detail::get_remote_ip_and_port(sock_, ip, port);
  10245. }
  10246. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  10247. int &port) const {
  10248. return detail::get_local_ip_and_port(sock_, ip, port);
  10249. }
  10250. inline socket_t SocketStream::socket() const { return sock_; }
  10251. inline time_t SocketStream::duration() const {
  10252. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10253. std::chrono::steady_clock::now() - start_time_)
  10254. .count();
  10255. }
  10256. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  10257. read_timeout_sec_ = sec;
  10258. read_timeout_usec_ = usec;
  10259. }
  10260. // Buffer stream implementation
  10261. inline bool BufferStream::is_readable() const { return true; }
  10262. inline bool BufferStream::wait_readable() const { return true; }
  10263. inline bool BufferStream::wait_writable() const { return true; }
  10264. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  10265. #if defined(_MSC_VER) && _MSC_VER < 1910
  10266. auto len_read = buffer._Copy_s(ptr, size, size, position);
  10267. #else
  10268. auto len_read = buffer.copy(ptr, size, position);
  10269. #endif
  10270. position += static_cast<size_t>(len_read);
  10271. return static_cast<ssize_t>(len_read);
  10272. }
  10273. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  10274. buffer.append(ptr, size);
  10275. return static_cast<ssize_t>(size);
  10276. }
  10277. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  10278. int & /*port*/) const {}
  10279. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  10280. int & /*port*/) const {}
  10281. inline socket_t BufferStream::socket() const { return 0; }
  10282. inline time_t BufferStream::duration() const { return 0; }
  10283. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  10284. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  10285. : MatcherBase(pattern) {
  10286. constexpr const char marker[] = "/:";
  10287. // One past the last ending position of a path param substring
  10288. std::size_t last_param_end = 0;
  10289. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10290. // Needed to ensure that parameter names are unique during matcher
  10291. // construction
  10292. // If exceptions are disabled, only last duplicate path
  10293. // parameter will be set
  10294. std::unordered_set<std::string> param_name_set;
  10295. #endif
  10296. while (true) {
  10297. const auto marker_pos = pattern.find(
  10298. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  10299. if (marker_pos == std::string::npos) { break; }
  10300. static_fragments_.push_back(
  10301. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  10302. const auto param_name_start = marker_pos + str_len(marker);
  10303. auto sep_pos = pattern.find(separator, param_name_start);
  10304. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  10305. auto param_name =
  10306. pattern.substr(param_name_start, sep_pos - param_name_start);
  10307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10308. if (param_name_set.find(param_name) != param_name_set.cend()) {
  10309. std::string msg = "Encountered path parameter '" + param_name +
  10310. "' multiple times in route pattern '" + pattern + "'.";
  10311. throw std::invalid_argument(msg);
  10312. }
  10313. #endif
  10314. param_names_.push_back(std::move(param_name));
  10315. last_param_end = sep_pos + 1;
  10316. }
  10317. if (last_param_end < pattern.length()) {
  10318. static_fragments_.push_back(pattern.substr(last_param_end));
  10319. }
  10320. }
  10321. inline bool PathParamsMatcher::match(Request &request) const {
  10322. request.matches = std::smatch();
  10323. request.path_params.clear();
  10324. // A pattern without parameters is just a literal path to compare against
  10325. if (param_names_.empty()) { return request.path == pattern(); }
  10326. request.path_params.reserve(param_names_.size());
  10327. // One past the position at which the path matched the pattern last time
  10328. std::size_t starting_pos = 0;
  10329. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  10330. const auto &fragment = static_fragments_[i];
  10331. if (starting_pos + fragment.length() > request.path.length()) {
  10332. return false;
  10333. }
  10334. // Avoid unnecessary allocation by using strncmp instead of substr +
  10335. // comparison
  10336. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  10337. fragment.length()) != 0) {
  10338. return false;
  10339. }
  10340. starting_pos += fragment.length();
  10341. // Should only happen when we have a static fragment after a param
  10342. // Example: '/users/:id/subscriptions'
  10343. // The 'subscriptions' fragment here does not have a corresponding param
  10344. if (i >= param_names_.size()) { continue; }
  10345. auto sep_pos = request.path.find(separator, starting_pos);
  10346. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  10347. const auto &param_name = param_names_[i];
  10348. request.path_params.emplace(
  10349. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  10350. // Mark everything up to '/' as matched
  10351. starting_pos = sep_pos + 1;
  10352. }
  10353. // Returns false if the path is longer than the pattern
  10354. return starting_pos >= request.path.length();
  10355. }
  10356. inline bool RegexMatcher::match(Request &request) const {
  10357. request.path_params.clear();
  10358. // See CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH: an overlong path is treated as
  10359. // a non-match rather than risking a stack overflow in std::regex_match.
  10360. if (request.path.length() > CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH) {
  10361. return false;
  10362. }
  10363. return std::regex_match(request.path, request.matches, regex_);
  10364. }
  10365. // Enclose IPv6 address in brackets if needed
  10366. inline std::string prepare_host_string(const std::string &host) {
  10367. // Enclose IPv6 address in brackets (but not if already enclosed)
  10368. if (host.find(':') == std::string::npos ||
  10369. (!host.empty() && host[0] == '[')) {
  10370. // IPv4, hostname, or already bracketed IPv6
  10371. return host;
  10372. } else {
  10373. // IPv6 address without brackets
  10374. return "[" + host + "]";
  10375. }
  10376. }
  10377. inline std::string make_host_and_port_string(const std::string &host, int port,
  10378. bool is_ssl) {
  10379. auto result = prepare_host_string(host);
  10380. // Append port if not default
  10381. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  10382. ; // do nothing
  10383. } else {
  10384. result += ":" + std::to_string(port);
  10385. }
  10386. return result;
  10387. }
  10388. // Create "host:port" string always including port number (for CONNECT method)
  10389. inline std::string
  10390. make_host_and_port_string_always_port(const std::string &host, int port) {
  10391. return prepare_host_string(host) + ":" + std::to_string(port);
  10392. }
  10393. // Value for the Host header a client sends when the caller supplied none.
  10394. // Only the value: callers decide where in their header list it goes.
  10395. inline std::string make_default_host_header_value(const std::string &host,
  10396. int port, bool is_ssl,
  10397. int address_family) {
  10398. if (address_family == AF_UNIX) { return "localhost"; }
  10399. return make_host_and_port_string(host, port, is_ssl);
  10400. }
  10401. inline void add_default_user_agent_header(Request &req) {
  10402. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10403. if (!req.has_header("User-Agent")) {
  10404. req.set_header("User-Agent",
  10405. std::string("cpp-httplib/") + CPPHTTPLIB_VERSION);
  10406. }
  10407. #else
  10408. (void)req;
  10409. #endif
  10410. }
  10411. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  10412. NormalizedTarget normalize_target(const std::string &host);
  10413. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  10414. bool host_matches_no_proxy(const NormalizedTarget &target,
  10415. const std::vector<NoProxyEntry> &entries);
  10416. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  10417. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  10418. if (prefix_bits == 0) { return true; }
  10419. int full_bytes = prefix_bits / 8;
  10420. int rem_bits = prefix_bits % 8;
  10421. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  10422. static_cast<size_t>(full_bytes)) != 0) {
  10423. return false;
  10424. }
  10425. if (rem_bits == 0) { return true; }
  10426. auto i = static_cast<size_t>(full_bytes);
  10427. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  10428. return (ip[i] & mask) == (net[i] & mask);
  10429. }
  10430. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  10431. if (token.empty()) { return false; }
  10432. if (token == "*") {
  10433. out.kind = NoProxyKind::Wildcard;
  10434. return true;
  10435. }
  10436. auto slash = token.find('/');
  10437. std::string addr_part =
  10438. (slash == std::string::npos) ? token : token.substr(0, slash);
  10439. std::string prefix_part =
  10440. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  10441. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  10442. // don't silently treat it as a /32 (or /128).
  10443. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  10444. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  10445. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  10446. // when brackets are present.
  10447. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  10448. addr_part.back() == ']';
  10449. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  10450. if (!bracketed) {
  10451. struct in_addr v4;
  10452. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  10453. int prefix = 32;
  10454. if (!prefix_part.empty()) {
  10455. auto r = from_chars(prefix_part.data(),
  10456. prefix_part.data() + prefix_part.size(), prefix);
  10457. if (r.ec != std::errc{} ||
  10458. r.ptr != prefix_part.data() + prefix_part.size()) {
  10459. return false;
  10460. }
  10461. if (prefix < 0 || prefix > 32) { return false; }
  10462. }
  10463. out.kind = NoProxyKind::IPv4Cidr;
  10464. std::memcpy(out.net.data(), &v4, sizeof(v4));
  10465. out.prefix_bits = prefix;
  10466. return true;
  10467. }
  10468. }
  10469. struct in6_addr v6;
  10470. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  10471. int prefix = 128;
  10472. if (!prefix_part.empty()) {
  10473. auto r = from_chars(prefix_part.data(),
  10474. prefix_part.data() + prefix_part.size(), prefix);
  10475. if (r.ec != std::errc{} ||
  10476. r.ptr != prefix_part.data() + prefix_part.size()) {
  10477. return false;
  10478. }
  10479. if (prefix < 0 || prefix > 128) { return false; }
  10480. }
  10481. out.kind = NoProxyKind::IPv6Cidr;
  10482. std::memcpy(out.net.data(), &v6, sizeof(v6));
  10483. out.prefix_bits = prefix;
  10484. return true;
  10485. }
  10486. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  10487. // the entry is malformed — don't fall through to the hostname branch.
  10488. if (bracketed) { return false; }
  10489. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  10490. if (slash != std::string::npos) { return false; }
  10491. // Port-specific entries (host:port) are not supported.
  10492. if (token.find(':') != std::string::npos) { return false; }
  10493. std::string hostname = case_ignore::to_lower(token);
  10494. while (!hostname.empty() && hostname.front() == '.') {
  10495. hostname.erase(hostname.begin());
  10496. }
  10497. while (!hostname.empty() && hostname.back() == '.') {
  10498. hostname.pop_back();
  10499. }
  10500. if (hostname.empty()) { return false; }
  10501. out.kind = NoProxyKind::HostnameSuffix;
  10502. out.hostname_pattern = std::move(hostname);
  10503. return true;
  10504. }
  10505. inline NormalizedTarget normalize_target(const std::string &host) {
  10506. NormalizedTarget t;
  10507. std::string h = host;
  10508. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  10509. h = h.substr(1, h.size() - 2);
  10510. }
  10511. // Strip a single trailing dot so "example.com." canonicalizes to
  10512. // "example.com".
  10513. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  10514. t.hostname = case_ignore::to_lower(h);
  10515. if (!t.hostname.empty()) {
  10516. struct in_addr v4;
  10517. struct in6_addr v6;
  10518. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  10519. t.is_ipv4 = true;
  10520. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  10521. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  10522. t.is_ipv6 = true;
  10523. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  10524. }
  10525. }
  10526. return t;
  10527. }
  10528. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  10529. const std::vector<NoProxyEntry> &entries) {
  10530. if (target.hostname.empty()) { return false; }
  10531. for (const auto &e : entries) {
  10532. switch (e.kind) {
  10533. case NoProxyKind::Wildcard: return true;
  10534. case NoProxyKind::IPv4Cidr:
  10535. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10536. return true;
  10537. }
  10538. break;
  10539. case NoProxyKind::IPv6Cidr:
  10540. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  10541. return true;
  10542. }
  10543. break;
  10544. case NoProxyKind::HostnameSuffix:
  10545. if (target.is_ipv4 || target.is_ipv6) { break; }
  10546. if (target.hostname == e.hostname_pattern) { return true; }
  10547. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  10548. // an entry of "example.com".
  10549. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  10550. auto offset = target.hostname.size() - e.hostname_pattern.size();
  10551. if (target.hostname[offset - 1] == '.' &&
  10552. target.hostname.compare(offset, e.hostname_pattern.size(),
  10553. e.hostname_pattern) == 0) {
  10554. return true;
  10555. }
  10556. }
  10557. break;
  10558. }
  10559. }
  10560. return false;
  10561. }
  10562. template <typename T>
  10563. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  10564. T header_writer, Error &error) {
  10565. for (const auto &h : headers) {
  10566. if (!detail::fields::is_field_valid(h.first, h.second)) {
  10567. error = Error::InvalidHeaders;
  10568. return false;
  10569. }
  10570. }
  10571. if (header_writer(strm, headers) <= 0) {
  10572. error = Error::Write;
  10573. return false;
  10574. }
  10575. return true;
  10576. }
  10577. } // namespace detail
  10578. /*
  10579. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  10580. */
  10581. #ifdef CPPHTTPLIB_SSL_ENABLED
  10582. namespace detail {
  10583. // SSL socket stream implementation
  10584. inline SSLSocketStream::SSLSocketStream(
  10585. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  10586. time_t read_timeout_usec, time_t write_timeout_sec,
  10587. time_t write_timeout_usec, time_t max_timeout_msec,
  10588. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10589. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10590. read_timeout_usec_(read_timeout_usec),
  10591. write_timeout_sec_(write_timeout_sec),
  10592. write_timeout_usec_(write_timeout_usec),
  10593. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  10594. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10595. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  10596. // Note: create_session() also clears this, but SSLClient currently
  10597. // uses ssl_new() which does not. Until full TLS API migration is complete,
  10598. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  10599. // SSL session was created.
  10600. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  10601. #endif
  10602. }
  10603. inline SSLSocketStream::~SSLSocketStream() = default;
  10604. inline bool SSLSocketStream::is_readable() const {
  10605. return tls::pending(session_) > 0;
  10606. }
  10607. inline bool SSLSocketStream::wait_readable() const {
  10608. if (max_timeout_msec_ <= 0) {
  10609. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10610. }
  10611. time_t read_timeout_sec;
  10612. time_t read_timeout_usec;
  10613. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10614. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10615. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10616. }
  10617. inline bool SSLSocketStream::wait_writable() const {
  10618. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  10619. !tls::is_peer_closed(session_, sock_);
  10620. }
  10621. inline bool SSLSocketStream::ensure_readable() {
  10622. if (readable_hint_) {
  10623. readable_hint_ = false;
  10624. return true;
  10625. }
  10626. return wait_readable();
  10627. }
  10628. inline bool SSLSocketStream::is_peer_alive() const {
  10629. return !tls::is_peer_closed(session_, sock_);
  10630. }
  10631. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  10632. if (tls::pending(session_) > 0) {
  10633. tls::TlsError err;
  10634. auto ret = tls::read(session_, ptr, size, err);
  10635. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10636. error_ = Error::ConnectionClosed;
  10637. }
  10638. return ret;
  10639. } else if (ensure_readable()) {
  10640. tls::TlsError err;
  10641. auto ret = tls::read(session_, ptr, size, err);
  10642. if (ret < 0) {
  10643. auto n = 1000;
  10644. #ifdef _WIN32
  10645. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  10646. (err.code == tls::ErrorCode::SyscallError &&
  10647. WSAGetLastError() == WSAETIMEDOUT))) {
  10648. #else
  10649. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  10650. #endif
  10651. if (tls::pending(session_) > 0) {
  10652. return tls::read(session_, ptr, size, err);
  10653. } else if (wait_readable()) {
  10654. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10655. ret = tls::read(session_, ptr, size, err);
  10656. if (ret >= 0) { return ret; }
  10657. } else {
  10658. break;
  10659. }
  10660. }
  10661. assert(ret < 0);
  10662. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10663. error_ = Error::ConnectionClosed;
  10664. }
  10665. return ret;
  10666. } else {
  10667. error_ = Error::Timeout;
  10668. return -1;
  10669. }
  10670. }
  10671. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  10672. if (wait_writable()) {
  10673. auto handle_size =
  10674. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10675. tls::TlsError err;
  10676. auto ret = tls::write(session_, ptr, handle_size, err);
  10677. if (ret < 0) {
  10678. auto n = 1000;
  10679. #ifdef _WIN32
  10680. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  10681. (err.code == tls::ErrorCode::SyscallError &&
  10682. WSAGetLastError() == WSAETIMEDOUT))) {
  10683. #else
  10684. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  10685. #endif
  10686. if (wait_writable()) {
  10687. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10688. ret = tls::write(session_, ptr, handle_size, err);
  10689. if (ret >= 0) { return ret; }
  10690. } else {
  10691. break;
  10692. }
  10693. }
  10694. assert(ret < 0);
  10695. }
  10696. return ret;
  10697. }
  10698. return -1;
  10699. }
  10700. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  10701. int &port) const {
  10702. detail::get_remote_ip_and_port(sock_, ip, port);
  10703. }
  10704. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  10705. int &port) const {
  10706. detail::get_local_ip_and_port(sock_, ip, port);
  10707. }
  10708. inline socket_t SSLSocketStream::socket() const { return sock_; }
  10709. inline time_t SSLSocketStream::duration() const {
  10710. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10711. std::chrono::steady_clock::now() - start_time_)
  10712. .count();
  10713. }
  10714. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  10715. read_timeout_sec_ = sec;
  10716. read_timeout_usec_ = usec;
  10717. }
  10718. inline WebSocketSSLStream::WebSocketSSLStream(socket_t sock,
  10719. tls::session_t session,
  10720. time_t read_timeout_sec,
  10721. time_t read_timeout_usec,
  10722. time_t write_timeout_sec,
  10723. time_t write_timeout_usec)
  10724. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  10725. read_timeout_usec_(read_timeout_usec),
  10726. write_timeout_sec_(write_timeout_sec),
  10727. write_timeout_usec_(write_timeout_usec),
  10728. start_time_(std::chrono::steady_clock::now()) {
  10729. // The receive and send paths run on different threads, so each TLS call is
  10730. // driven in non-blocking mode and readiness is awaited with select()
  10731. // outside the session lock. Set the socket non-blocking once here; it is
  10732. // never flipped back, so no thread races on the flag.
  10733. detail::set_nonblocking(sock_, true);
  10734. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10735. SSL_clear_mode(static_cast<SSL *>(session_), SSL_MODE_AUTO_RETRY);
  10736. #endif
  10737. }
  10738. inline WebSocketSSLStream::~WebSocketSSLStream() = default;
  10739. inline bool WebSocketSSLStream::is_readable() const {
  10740. std::lock_guard<std::mutex> guard(session_mutex_);
  10741. return tls::pending(session_) > 0;
  10742. }
  10743. inline bool WebSocketSSLStream::wait_readable() const {
  10744. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10745. }
  10746. inline bool WebSocketSSLStream::wait_writable() const {
  10747. // Unlike SSLSocketStream, this deliberately does not call is_peer_closed():
  10748. // that probe toggles the socket's blocking flag, which would race with the
  10749. // concurrent reader on a permanently non-blocking socket.
  10750. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  10751. }
  10752. inline ssize_t WebSocketSSLStream::read(char *ptr, size_t size) {
  10753. tls::TlsError err;
  10754. auto n = 1000;
  10755. while (--n >= 0) {
  10756. {
  10757. std::lock_guard<std::mutex> guard(session_mutex_);
  10758. auto ret = tls::read(session_, ptr, size, err);
  10759. if (ret > 0) { return ret; }
  10760. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  10761. error_ = Error::ConnectionClosed;
  10762. return ret;
  10763. }
  10764. }
  10765. // ret < 0. On a non-blocking socket a TLS read can stop needing either
  10766. // direction: the send path shares this session, so output it left pending
  10767. // has to be flushed before more input can be decrypted. Anything else is
  10768. // a hard error.
  10769. auto needs_readable = err.code == tls::ErrorCode::WantRead;
  10770. #ifdef _WIN32
  10771. // On Windows a socket timeout surfaces as a syscall error, not WantRead.
  10772. needs_readable =
  10773. needs_readable || (err.code == tls::ErrorCode::SyscallError &&
  10774. WSAGetLastError() == WSAETIMEDOUT);
  10775. #endif
  10776. if (!needs_readable && err.code != tls::ErrorCode::WantWrite) {
  10777. error_ = Error::Read;
  10778. return -1;
  10779. }
  10780. if (!(needs_readable ? wait_readable() : wait_writable())) {
  10781. error_ = Error::Timeout;
  10782. return -1;
  10783. }
  10784. }
  10785. // Out of retries. Recording a reason matters: a caller that reads get_error()
  10786. // to tell a timeout from a close would otherwise see whatever the previous
  10787. // failure left behind (error_ is never cleared on success).
  10788. error_ = Error::Read;
  10789. return -1;
  10790. }
  10791. inline ssize_t WebSocketSSLStream::write(const char *ptr, size_t size) {
  10792. auto handle_size = std::min<size_t>(size, (std::numeric_limits<int>::max)());
  10793. tls::TlsError err;
  10794. auto n = 1000;
  10795. while (--n >= 0) {
  10796. {
  10797. std::lock_guard<std::mutex> guard(session_mutex_);
  10798. auto ret = tls::write(session_, ptr, handle_size, err);
  10799. if (ret >= 0) { return ret; }
  10800. }
  10801. // ret < 0. As in read(), either direction can be needed: a renegotiation
  10802. // or a post-handshake message must be consumed before the record goes
  10803. // out. Anything else is a hard error.
  10804. auto needs_writable = err.code == tls::ErrorCode::WantWrite;
  10805. #ifdef _WIN32
  10806. // On Windows a socket timeout surfaces as a syscall error, not WantWrite.
  10807. needs_writable =
  10808. needs_writable || (err.code == tls::ErrorCode::SyscallError &&
  10809. WSAGetLastError() == WSAETIMEDOUT);
  10810. #endif
  10811. if (!needs_writable && err.code != tls::ErrorCode::WantRead) { return -1; }
  10812. if (!(needs_writable ? wait_writable() : wait_readable())) { return -1; }
  10813. }
  10814. return -1;
  10815. }
  10816. inline void WebSocketSSLStream::get_remote_ip_and_port(std::string &ip,
  10817. int &port) const {
  10818. detail::get_remote_ip_and_port(sock_, ip, port);
  10819. }
  10820. inline void WebSocketSSLStream::get_local_ip_and_port(std::string &ip,
  10821. int &port) const {
  10822. detail::get_local_ip_and_port(sock_, ip, port);
  10823. }
  10824. inline socket_t WebSocketSSLStream::socket() const { return sock_; }
  10825. inline time_t WebSocketSSLStream::duration() const {
  10826. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10827. std::chrono::steady_clock::now() - start_time_)
  10828. .count();
  10829. }
  10830. inline void WebSocketSSLStream::set_read_timeout(time_t sec, time_t usec) {
  10831. read_timeout_sec_ = sec;
  10832. read_timeout_usec_ = usec;
  10833. }
  10834. } // namespace detail
  10835. #endif // CPPHTTPLIB_SSL_ENABLED
  10836. /*
  10837. * Group 4: Server implementation
  10838. */
  10839. // HTTP server implementation
  10840. inline Server::Server()
  10841. : new_task_queue([] {
  10842. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  10843. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  10844. }) {
  10845. #ifndef _WIN32
  10846. signal(SIGPIPE, SIG_IGN);
  10847. #endif
  10848. }
  10849. inline Server::~Server() = default;
  10850. inline std::unique_ptr<detail::MatcherBase>
  10851. Server::make_matcher(const std::string &pattern) {
  10852. // Path params take precedence, so "/users/:id/(.*)" keeps being matched as
  10853. // a path params pattern
  10854. if (pattern.find("/:") != std::string::npos) {
  10855. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  10856. }
  10857. // A pattern with no regex metacharacter only has to be compared literally,
  10858. // which is what PathParamsMatcher already does when it captures no
  10859. // parameter, so std::regex is only worth building for the patterns that
  10860. // actually need it
  10861. if (pattern.find_first_of(".^$|()[]{}*+?\\") == std::string::npos) {
  10862. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  10863. }
  10864. return detail::make_unique<detail::RegexMatcher>(pattern);
  10865. }
  10866. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  10867. return add_handler(get_handlers_, pattern, std::move(handler));
  10868. }
  10869. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  10870. return add_handler(post_handlers_, pattern, std::move(handler));
  10871. }
  10872. inline Server &Server::Post(const std::string &pattern,
  10873. HandlerWithContentReader handler) {
  10874. return add_handler(post_handlers_for_content_reader_, pattern,
  10875. std::move(handler));
  10876. }
  10877. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  10878. return add_handler(put_handlers_, pattern, std::move(handler));
  10879. }
  10880. inline Server &Server::Put(const std::string &pattern,
  10881. HandlerWithContentReader handler) {
  10882. return add_handler(put_handlers_for_content_reader_, pattern,
  10883. std::move(handler));
  10884. }
  10885. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  10886. return add_handler(patch_handlers_, pattern, std::move(handler));
  10887. }
  10888. inline Server &Server::Patch(const std::string &pattern,
  10889. HandlerWithContentReader handler) {
  10890. return add_handler(patch_handlers_for_content_reader_, pattern,
  10891. std::move(handler));
  10892. }
  10893. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  10894. return add_handler(delete_handlers_, pattern, std::move(handler));
  10895. }
  10896. inline Server &Server::Delete(const std::string &pattern,
  10897. HandlerWithContentReader handler) {
  10898. return add_handler(delete_handlers_for_content_reader_, pattern,
  10899. std::move(handler));
  10900. }
  10901. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  10902. return add_handler(options_handlers_, pattern, std::move(handler));
  10903. }
  10904. inline const std::set<std::string> &Server::builtin_methods() {
  10905. thread_local const std::set<std::string> methods{
  10906. "GET", "HEAD", "POST", "PUT", "DELETE",
  10907. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10908. return methods;
  10909. }
  10910. inline Server::CustomHandlerEntry *
  10911. Server::custom_entry_for_registration(const std::string &method) {
  10912. // Built-in methods are refused for two different reasons. GET, HEAD, POST,
  10913. // PUT, DELETE, OPTIONS and PATCH are dispatched by the if/else chain in
  10914. // routing() before the custom tables are consulted, so a route registered
  10915. // for one of them could never fire. CONNECT, TRACE and PRI have no branch
  10916. // there and would be reachable, but they carry protocol-level meaning
  10917. // (tunnel setup, request echo, the HTTP/2 connection preface) that this
  10918. // library does not route.
  10919. if (!detail::fields::is_token(method) || builtin_methods().count(method)) {
  10920. output_error_log(Error::InvalidHTTPMethod, nullptr);
  10921. has_invalid_registration_ = true;
  10922. return nullptr;
  10923. }
  10924. return &custom_handlers_[method];
  10925. }
  10926. inline Server &Server::CustomRoute(const std::string &method,
  10927. const std::string &pattern,
  10928. Handler handler) {
  10929. auto *entry = custom_entry_for_registration(method);
  10930. if (!entry) { return *this; }
  10931. return add_handler(entry->handlers, pattern, std::move(handler));
  10932. }
  10933. inline Server &Server::CustomRoute(const std::string &method,
  10934. const std::string &pattern,
  10935. HandlerWithContentReader handler) {
  10936. auto *entry = custom_entry_for_registration(method);
  10937. if (!entry) { return *this; }
  10938. return add_handler(entry->handlers_for_content_reader, pattern,
  10939. std::move(handler));
  10940. }
  10941. inline const Server::CustomHandlerEntry *
  10942. Server::find_custom_entry(const std::string &method) const {
  10943. // find() alone would be correct here. The empty() check is what keeps the
  10944. // per-request cost off servers that never call CustomRoute(), which is the
  10945. // overwhelmingly common case; keep it rather than walking into the tree.
  10946. if (custom_handlers_.empty()) { return nullptr; }
  10947. auto it = custom_handlers_.find(method);
  10948. return it == custom_handlers_.end() ? nullptr : &it->second;
  10949. }
  10950. inline Server &Server::WebSocket(const std::string &pattern,
  10951. WebSocketHandler handler) {
  10952. websocket_handlers_.push_back(
  10953. {make_matcher(pattern), std::move(handler), nullptr});
  10954. return *this;
  10955. }
  10956. inline Server &Server::WebSocket(const std::string &pattern,
  10957. WebSocketHandler handler,
  10958. SubProtocolSelector sub_protocol_selector) {
  10959. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  10960. std::move(sub_protocol_selector)});
  10961. return *this;
  10962. }
  10963. inline bool Server::set_base_dir(const std::string &dir,
  10964. const std::string &mount_point) {
  10965. return set_mount_point(mount_point, dir);
  10966. }
  10967. inline bool Server::set_mount_point(const std::string &mount_point,
  10968. const std::string &dir, Headers headers) {
  10969. detail::FileStat stat(dir);
  10970. if (stat.is_dir()) {
  10971. std::string mnt = !mount_point.empty() ? mount_point : "/";
  10972. if (!mnt.empty() && mnt[0] == '/') {
  10973. std::string resolved_base;
  10974. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  10975. #if defined(_WIN32)
  10976. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  10977. resolved_base += '\\';
  10978. }
  10979. #else
  10980. if (resolved_base.back() != '/') { resolved_base += '/'; }
  10981. #endif
  10982. }
  10983. base_dirs_.push_back(
  10984. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  10985. return true;
  10986. }
  10987. }
  10988. return false;
  10989. }
  10990. inline bool Server::remove_mount_point(const std::string &mount_point) {
  10991. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  10992. if (it->mount_point == mount_point) {
  10993. base_dirs_.erase(it);
  10994. return true;
  10995. }
  10996. }
  10997. return false;
  10998. }
  10999. inline Server &
  11000. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  11001. const std::string &mime) {
  11002. file_extension_and_mimetype_map_[ext] = mime;
  11003. return *this;
  11004. }
  11005. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  11006. default_file_mimetype_ = mime;
  11007. return *this;
  11008. }
  11009. inline Server &Server::set_file_request_handler(Handler handler) {
  11010. file_request_handler_ = std::move(handler);
  11011. return *this;
  11012. }
  11013. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  11014. std::true_type) {
  11015. error_handler_ = std::move(handler);
  11016. return *this;
  11017. }
  11018. inline Server &Server::set_error_handler_core(Handler handler,
  11019. std::false_type) {
  11020. error_handler_ = [handler](const Request &req, Response &res) {
  11021. handler(req, res);
  11022. return HandlerResponse::Handled;
  11023. };
  11024. return *this;
  11025. }
  11026. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  11027. exception_handler_ = std::move(handler);
  11028. return *this;
  11029. }
  11030. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  11031. pre_routing_handler_ = std::move(handler);
  11032. return *this;
  11033. }
  11034. inline Server &Server::set_post_routing_handler(Handler handler) {
  11035. post_routing_handler_ = std::move(handler);
  11036. return *this;
  11037. }
  11038. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  11039. pre_request_handler_ = std::move(handler);
  11040. return *this;
  11041. }
  11042. inline Server &Server::set_logger(Logger logger) {
  11043. logger_ = std::move(logger);
  11044. return *this;
  11045. }
  11046. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  11047. error_logger_ = std::move(error_logger);
  11048. return *this;
  11049. }
  11050. inline Server &Server::set_pre_compression_logger(Logger logger) {
  11051. pre_compression_logger_ = std::move(logger);
  11052. return *this;
  11053. }
  11054. inline Server &
  11055. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  11056. expect_100_continue_handler_ = std::move(handler);
  11057. return *this;
  11058. }
  11059. inline Server &Server::set_start_handler(StartHandler handler) {
  11060. start_handler_ = std::move(handler);
  11061. return *this;
  11062. }
  11063. inline Server &Server::set_address_family(int family) {
  11064. address_family_ = family;
  11065. return *this;
  11066. }
  11067. inline Server &Server::set_tcp_nodelay(bool on) {
  11068. tcp_nodelay_ = on;
  11069. return *this;
  11070. }
  11071. inline Server &Server::set_ipv6_v6only(bool on) {
  11072. ipv6_v6only_ = on;
  11073. return *this;
  11074. }
  11075. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  11076. socket_options_ = std::move(socket_options);
  11077. return *this;
  11078. }
  11079. inline Server &Server::set_default_headers(Headers headers) {
  11080. default_headers_ = std::move(headers);
  11081. return *this;
  11082. }
  11083. inline Server &Server::set_header_writer(
  11084. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11085. header_writer_ = writer;
  11086. return *this;
  11087. }
  11088. inline Server &
  11089. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  11090. trusted_proxies_ = proxies;
  11091. return *this;
  11092. }
  11093. inline Server &Server::set_keep_alive_max_count(size_t count) {
  11094. keep_alive_max_count_ = count;
  11095. return *this;
  11096. }
  11097. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  11098. keep_alive_timeout_sec_ = sec;
  11099. return *this;
  11100. }
  11101. template <class Rep, class Period>
  11102. inline Server &Server::set_keep_alive_timeout(
  11103. const std::chrono::duration<Rep, Period> &duration) {
  11104. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  11105. set_keep_alive_timeout(sec);
  11106. });
  11107. return *this;
  11108. }
  11109. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  11110. read_timeout_sec_ = sec;
  11111. read_timeout_usec_ = usec;
  11112. return *this;
  11113. }
  11114. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  11115. write_timeout_sec_ = sec;
  11116. write_timeout_usec_ = usec;
  11117. return *this;
  11118. }
  11119. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  11120. idle_interval_sec_ = sec;
  11121. idle_interval_usec_ = usec;
  11122. return *this;
  11123. }
  11124. inline Server &Server::set_payload_max_length(size_t length) {
  11125. payload_max_length_ = length;
  11126. return *this;
  11127. }
  11128. inline Server &Server::set_static_file_compression(bool on) {
  11129. static_file_compression_ = on;
  11130. return *this;
  11131. }
  11132. inline Server &Server::set_static_file_compression_min_length(size_t length) {
  11133. static_file_compression_min_length_ = length;
  11134. return *this;
  11135. }
  11136. inline Server &Server::set_static_file_compression_max_length(size_t length) {
  11137. static_file_compression_max_length_ = length;
  11138. return *this;
  11139. }
  11140. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  11141. websocket_max_missed_pongs_ = count;
  11142. return *this;
  11143. }
  11144. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  11145. websocket_ping_interval_sec_ = sec;
  11146. return *this;
  11147. }
  11148. template <class Rep, class Period>
  11149. inline Server &Server::set_websocket_ping_interval(
  11150. const std::chrono::duration<Rep, Period> &duration) {
  11151. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  11152. set_websocket_ping_interval(sec);
  11153. });
  11154. return *this;
  11155. }
  11156. inline bool Server::bind_to_port(const std::string &host, int port,
  11157. int socket_flags) {
  11158. auto ret = bind_internal(host, port, socket_flags);
  11159. if (ret == -1) { is_decommissioned = true; }
  11160. return ret >= 0;
  11161. }
  11162. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  11163. auto ret = bind_internal(host, 0, socket_flags);
  11164. if (ret == -1) { is_decommissioned = true; }
  11165. return ret;
  11166. }
  11167. inline bool Server::listen_after_bind() { return listen_internal(); }
  11168. inline bool Server::listen(const std::string &host, int port,
  11169. int socket_flags) {
  11170. return bind_to_port(host, port, socket_flags) && listen_internal();
  11171. }
  11172. inline bool Server::is_running() const { return is_running_; }
  11173. inline void Server::wait_until_ready() const {
  11174. while (!is_running_ && !is_decommissioned) {
  11175. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  11176. }
  11177. }
  11178. inline void Server::stop() noexcept {
  11179. // Release the listening socket whether or not the accept loop is running:
  11180. // bind_to_port() without listen_after_bind() still owns the descriptor. The
  11181. // exchange is what makes this safe to call concurrently with the accept loop.
  11182. socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
  11183. if (sock != INVALID_SOCKET) {
  11184. detail::shutdown_socket(sock);
  11185. detail::close_socket(sock);
  11186. }
  11187. is_decommissioned = false;
  11188. }
  11189. inline void Server::decommission() { is_decommissioned = true; }
  11190. inline bool Server::parse_request_line(const char *s, Request &req) const {
  11191. auto len = strlen(s);
  11192. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  11193. len -= 2;
  11194. {
  11195. size_t count = 0;
  11196. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  11197. switch (count) {
  11198. case 0: req.method = std::string(b, e); break;
  11199. case 1: req.target = std::string(b, e); break;
  11200. case 2: req.version = std::string(b, e); break;
  11201. default: break;
  11202. }
  11203. count++;
  11204. });
  11205. if (count != 3) { return false; }
  11206. }
  11207. // A method outside the built-in set is accepted only when a handler has been
  11208. // registered for it with CustomRoute().
  11209. const auto &methods = builtin_methods();
  11210. if (methods.find(req.method) == methods.end() &&
  11211. !find_custom_entry(req.method)) {
  11212. output_error_log(Error::InvalidHTTPMethod, &req);
  11213. return false;
  11214. }
  11215. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  11216. output_error_log(Error::InvalidHTTPVersion, &req);
  11217. return false;
  11218. }
  11219. if (!detail::fields::is_request_target(req.target)) { return false; }
  11220. {
  11221. // Skip URL fragment
  11222. for (size_t i = 0; i < req.target.size(); i++) {
  11223. if (req.target[i] == '#') {
  11224. req.target.erase(i);
  11225. break;
  11226. }
  11227. }
  11228. detail::divide(req.target, '?',
  11229. [&](const char *lhs_data, std::size_t lhs_size,
  11230. const char *rhs_data, std::size_t rhs_size) {
  11231. req.path =
  11232. decode_path_component(std::string(lhs_data, lhs_size));
  11233. detail::parse_query_text(rhs_data, rhs_size, req.params);
  11234. });
  11235. }
  11236. return true;
  11237. }
  11238. inline bool Server::write_response(Stream &strm, bool close_connection,
  11239. Request &req, Response &res) {
  11240. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  11241. // incorrectly to the error content.
  11242. req.ranges.clear();
  11243. return write_response_core(strm, close_connection, req, res, false);
  11244. }
  11245. inline bool Server::write_response_with_content(Stream &strm,
  11246. bool close_connection,
  11247. const Request &req,
  11248. Response &res) {
  11249. return write_response_core(strm, close_connection, req, res, true);
  11250. }
  11251. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  11252. const Request &req, Response &res,
  11253. bool need_apply_ranges) {
  11254. assert(res.status != -1);
  11255. if (400 <= res.status && error_handler_ &&
  11256. error_handler_(req, res) == HandlerResponse::Handled) {
  11257. need_apply_ranges = true;
  11258. }
  11259. std::string content_type;
  11260. std::string boundary;
  11261. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  11262. // Prepare additional headers
  11263. if (close_connection ||
  11264. detail::has_header_token(req.headers, "Connection", "close") ||
  11265. 400 <= res.status || // Don't leave connections open after errors
  11266. // The client withholds the body until `100 Continue`, which was never
  11267. // sent, so whether and when the body follows is unknown.
  11268. (req.expect_100_continue_pending_ && detail::has_framed_body(req))) {
  11269. res.set_header("Connection", "close");
  11270. } else {
  11271. std::string s = "timeout=";
  11272. s += std::to_string(keep_alive_timeout_sec_);
  11273. s += ", max=";
  11274. s += std::to_string(keep_alive_max_count_);
  11275. res.set_header("Keep-Alive", s);
  11276. }
  11277. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  11278. !res.has_header("Content-Type")) {
  11279. res.set_header("Content-Type", "text/plain");
  11280. }
  11281. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  11282. !res.has_header("Content-Length")) {
  11283. res.set_header("Content-Length", "0");
  11284. }
  11285. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  11286. res.set_header("Accept-Ranges", "bytes");
  11287. }
  11288. if (post_routing_handler_) { post_routing_handler_(req, res); }
  11289. // Response line and headers
  11290. detail::BufferStream bstrm;
  11291. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  11292. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  11293. // Combine a small body with the headers so the whole response leaves in a
  11294. // single write. A large body is written on its own instead: a copy of it
  11295. // costs more than the extra write saves.
  11296. auto send_body = req.method != "HEAD";
  11297. auto body_is_separate = false;
  11298. auto provider_done = false;
  11299. if (send_body && !res.body.empty() && !res.content_provider_) {
  11300. if (res.body.size() < CPPHTTPLIB_SEND_BUFSIZ) {
  11301. bstrm.write(res.body.data(), res.body.size());
  11302. } else {
  11303. body_is_separate = true;
  11304. }
  11305. } else if (send_body && res.content_provider_ &&
  11306. res.is_file_content_provider_ &&
  11307. res.content_length_ < CPPHTTPLIB_SEND_BUFSIZ) {
  11308. // A small file is read into the same buffer. Other providers may produce
  11309. // their data over time, so they are never held back.
  11310. if (!write_content_with_provider(bstrm, req, res, boundary, content_type)) {
  11311. return false;
  11312. }
  11313. provider_done = true;
  11314. }
  11315. // Log before writing to avoid race condition with client-side code that
  11316. // accesses logger-captured data immediately after receiving the response.
  11317. output_log(req, res);
  11318. // Flush buffer
  11319. auto &data = bstrm.get_buffer();
  11320. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  11321. if (body_is_separate) {
  11322. return detail::write_data(strm, res.body.data(), res.body.size());
  11323. }
  11324. // Streaming body
  11325. if (send_body && res.content_provider_) {
  11326. if (!provider_done &&
  11327. !write_content_with_provider(strm, req, res, boundary, content_type)) {
  11328. return false;
  11329. }
  11330. res.content_provider_success_ = true;
  11331. }
  11332. return true;
  11333. }
  11334. inline bool
  11335. Server::write_content_with_provider(Stream &strm, const Request &req,
  11336. Response &res, const std::string &boundary,
  11337. const std::string &content_type) {
  11338. auto is_shutting_down = [this]() {
  11339. return this->svr_sock_ == INVALID_SOCKET;
  11340. };
  11341. if (res.content_length_ > 0) {
  11342. // Only a 206 response is served as a partial representation, matching the
  11343. // condition `apply_ranges()` used to decide the Content-Length and the
  11344. // multipart boundary. Since `detail::range_error()` validates `req.ranges`
  11345. // only for a 2xx status, slicing under any other status would write a body
  11346. // that disagrees with the header already sent, from an unchecked offset.
  11347. auto is_partial =
  11348. !req.ranges.empty() && res.status == StatusCode::PartialContent_206;
  11349. if (!is_partial) {
  11350. return detail::write_content(strm, res.content_provider_, 0,
  11351. res.content_length_, is_shutting_down);
  11352. } else if (req.ranges.size() == 1) {
  11353. auto offset_and_length = detail::get_range_offset_and_length(
  11354. req.ranges[0], res.content_length_);
  11355. return detail::write_content(strm, res.content_provider_,
  11356. offset_and_length.first,
  11357. offset_and_length.second, is_shutting_down);
  11358. } else {
  11359. return detail::write_multipart_ranges_data(
  11360. strm, req, res, boundary, content_type, res.content_length_,
  11361. is_shutting_down);
  11362. }
  11363. } else {
  11364. if (res.is_chunked_content_provider_) {
  11365. // Use the coding `apply_ranges()` chose when it wrote the headers;
  11366. // re-negotiating here would disagree with them, e.g. once a handler's
  11367. // own Content-Encoding header suppresses the negotiation.
  11368. auto compressor = detail::make_compressor(res.content_coding_);
  11369. if (!compressor) {
  11370. compressor = detail::make_unique<detail::nocompressor>();
  11371. }
  11372. return detail::write_content_chunked(strm, res.content_provider_,
  11373. is_shutting_down, *compressor);
  11374. } else {
  11375. return detail::write_content_without_length(strm, res.content_provider_,
  11376. is_shutting_down);
  11377. }
  11378. }
  11379. }
  11380. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  11381. FormFields::iterator cur_field;
  11382. FormFiles::iterator cur_file;
  11383. auto is_text_field = false;
  11384. size_t count = 0;
  11385. if (read_content_core(
  11386. strm, req, res,
  11387. // Regular
  11388. [&](const char *buf, size_t n) {
  11389. // Prevent arithmetic overflow when checking sizes.
  11390. // Avoid computing (req.body.size() + n) directly because
  11391. // adding two unsigned `size_t` values can wrap around and
  11392. // produce a small result instead of indicating overflow.
  11393. // Instead, check using subtraction: ensure `n` does not
  11394. // exceed the remaining capacity `max_size() - size()`.
  11395. if (req.body.size() >= req.body.max_size() ||
  11396. n > req.body.max_size() - req.body.size()) {
  11397. return false;
  11398. }
  11399. // Limit decompressed body size to payload_max_length_ to protect
  11400. // against "zip bomb" attacks where a small compressed payload
  11401. // decompresses to a massive size.
  11402. if (payload_max_length_ > 0 &&
  11403. (req.body.size() >= payload_max_length_ ||
  11404. n > payload_max_length_ - req.body.size())) {
  11405. return false;
  11406. }
  11407. req.body.append(buf, n);
  11408. return true;
  11409. },
  11410. // Multipart FormData
  11411. [&](const FormData &file) {
  11412. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  11413. output_error_log(Error::TooManyFormDataFiles, &req);
  11414. return false;
  11415. }
  11416. if (file.filename.empty()) {
  11417. cur_field = req.form.fields.emplace(
  11418. file.name, FormField{file.name, file.content, file.headers});
  11419. is_text_field = true;
  11420. } else {
  11421. cur_file = req.form.files.emplace(file.name, file);
  11422. is_text_field = false;
  11423. }
  11424. return true;
  11425. },
  11426. [&](const char *buf, size_t n) {
  11427. if (is_text_field) {
  11428. auto &content = cur_field->second.content;
  11429. if (content.size() + n > content.max_size()) { return false; }
  11430. content.append(buf, n);
  11431. } else {
  11432. auto &content = cur_file->second.content;
  11433. if (content.size() + n > content.max_size()) { return false; }
  11434. content.append(buf, n);
  11435. }
  11436. return true;
  11437. })) {
  11438. const auto &content_type = req.get_header_value("Content-Type");
  11439. if (detail::extract_media_type(content_type) ==
  11440. "application/x-www-form-urlencoded") {
  11441. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  11442. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  11443. output_error_log(Error::ExceedMaxPayloadSize, &req);
  11444. return false;
  11445. }
  11446. detail::parse_query_text(req.body, req.params);
  11447. }
  11448. return true;
  11449. }
  11450. return false;
  11451. }
  11452. inline bool Server::read_content_with_content_receiver(
  11453. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11454. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  11455. return read_content_core(strm, req, res, std::move(receiver),
  11456. std::move(multipart_header),
  11457. std::move(multipart_receiver));
  11458. }
  11459. inline bool Server::read_content_core(
  11460. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  11461. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  11462. detail::FormDataParser multipart_form_data_parser;
  11463. ContentReceiverWithProgress out;
  11464. if (req.is_multipart_form_data()) {
  11465. const auto &content_type = req.get_header_value("Content-Type");
  11466. std::string boundary;
  11467. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  11468. res.status = StatusCode::BadRequest_400;
  11469. output_error_log(Error::MultipartParsing, &req);
  11470. return false;
  11471. }
  11472. multipart_form_data_parser.set_boundary(std::move(boundary));
  11473. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  11474. return multipart_form_data_parser.parse(buf, n, multipart_header,
  11475. multipart_receiver);
  11476. };
  11477. } else {
  11478. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  11479. size_t /*len*/) { return receiver(buf, n); };
  11480. }
  11481. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  11482. // For non-SSL builds we still scan non-persistent connections for stray
  11483. // body bytes so the payload limit is enforced (413). On keep-alive,
  11484. // pending bytes may be the next request (issue #2450), so skip.
  11485. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  11486. if (!req.has_header("Content-Length") &&
  11487. !detail::is_chunked_transfer_encoding(req.headers)) {
  11488. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  11489. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  11490. auto has_data = strm.is_readable();
  11491. if (!has_data) {
  11492. auto s = strm.socket();
  11493. if (s != INVALID_SOCKET) {
  11494. has_data = detail::select_read(s, 0, 0) > 0;
  11495. }
  11496. }
  11497. if (has_data) {
  11498. // Route through the same decompressing reader used by the
  11499. // length-framed and chunked paths below, so payload_max_length_ is
  11500. // enforced on the decompressed size here too instead of only on the
  11501. // compressed wire bytes.
  11502. return detail::read_content(strm, req, payload_max_length_, res.status,
  11503. nullptr, out, true);
  11504. }
  11505. }
  11506. return true;
  11507. }
  11508. #else
  11509. if (!req.has_header("Content-Length") &&
  11510. !detail::is_chunked_transfer_encoding(req.headers)) {
  11511. return true;
  11512. }
  11513. #endif
  11514. // The client is waiting for this before it sends the body.
  11515. if (req.expect_100_continue_pending_) {
  11516. req.expect_100_continue_pending_ = false;
  11517. detail::write_response_line(strm, StatusCode::Continue_100);
  11518. strm.write("\r\n");
  11519. }
  11520. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  11521. out, true)) {
  11522. return false;
  11523. }
  11524. req.body_consumed_ = true;
  11525. if (req.is_multipart_form_data()) {
  11526. if (!multipart_form_data_parser.is_valid()) {
  11527. res.status = StatusCode::BadRequest_400;
  11528. output_error_log(Error::MultipartParsing, &req);
  11529. return false;
  11530. }
  11531. }
  11532. return true;
  11533. }
  11534. inline bool Server::handle_file_request(Request &req, Response &res) {
  11535. for (const auto &entry : base_dirs_) {
  11536. // Prefix match, on a path segment boundary. A mount point of "/mount"
  11537. // covers "/mount" and "/mount/...", but must not swallow "/mountdir/...".
  11538. // One that already ends in '/' (the root mount among them) carries its own
  11539. // boundary; set_mount_point() guarantees the mount point is not empty.
  11540. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point) &&
  11541. (entry.mount_point.back() == '/' ||
  11542. req.path.size() == entry.mount_point.size() ||
  11543. req.path[entry.mount_point.size()] == '/')) {
  11544. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  11545. if (detail::is_valid_path(sub_path)) {
  11546. auto path = entry.base_dir + sub_path;
  11547. if (path.back() == '/') { path += "index.html"; }
  11548. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  11549. // but symlinks/junctions can still escape the base directory.
  11550. if (!entry.resolved_base_dir.empty()) {
  11551. std::string resolved_path;
  11552. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  11553. !detail::is_path_within_base(resolved_path,
  11554. entry.resolved_base_dir)) {
  11555. res.status = StatusCode::Forbidden_403;
  11556. return true;
  11557. }
  11558. }
  11559. detail::FileStat stat(path);
  11560. if (stat.is_dir()) {
  11561. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  11562. return true;
  11563. }
  11564. if (stat.is_file()) {
  11565. for (const auto &kv : entry.headers) {
  11566. res.set_header(kv.first, kv.second);
  11567. }
  11568. auto content_type_of = [&]() {
  11569. return detail::find_content_type(
  11570. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  11571. };
  11572. // Only the ETag needs the content type this early, and only to name
  11573. // the coding. Deciding it here would otherwise put a regex in front
  11574. // of the 304 below, which serving a file never used to pay for.
  11575. std::string content_type;
  11576. auto encoding = detail::EncodingType::None;
  11577. if (static_file_compression_) {
  11578. content_type = content_type_of();
  11579. encoding =
  11580. static_file_encoding(req, res, content_type, stat.size());
  11581. }
  11582. // The ETag names the representation actually sent, so a client that
  11583. // cached the compressed form revalidates against the compressed ETag
  11584. // and still gets a 304, while one that took identity keeps the plain
  11585. // ETag.
  11586. auto etag = detail::compute_etag(
  11587. stat, encoding == detail::EncodingType::None
  11588. ? std::string()
  11589. : std::string("-") + detail::encoding_name(encoding));
  11590. if (!etag.empty()) { res.set_header("ETag", etag); }
  11591. auto mtime = stat.mtime();
  11592. auto last_modified = detail::file_mtime_to_http_date(mtime);
  11593. if (!last_modified.empty()) {
  11594. res.set_header("Last-Modified", last_modified);
  11595. }
  11596. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  11597. check_if_range(req, etag, mtime);
  11598. auto mm = std::make_shared<detail::mmap>(path.c_str());
  11599. if (!mm->is_open()) {
  11600. output_error_log(Error::OpenFile, &req);
  11601. return false;
  11602. }
  11603. if (!static_file_compression_) { content_type = content_type_of(); }
  11604. detail::set_file_content_provider(res, mm, content_type, encoding);
  11605. if (req.method != "HEAD" && file_request_handler_) {
  11606. file_request_handler_(req, res);
  11607. }
  11608. return true;
  11609. } else {
  11610. output_error_log(Error::OpenFile, &req);
  11611. }
  11612. }
  11613. }
  11614. }
  11615. return false;
  11616. }
  11617. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  11618. const std::string &etag,
  11619. time_t mtime) const {
  11620. // Handle conditional GET:
  11621. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  11622. // 2. If-Modified-Since is checked only when If-None-Match is absent
  11623. if (req.has_header("If-None-Match")) {
  11624. if (!etag.empty()) {
  11625. auto val =
  11626. detail::get_combined_header_value(req.headers, "If-None-Match");
  11627. // NOTE: We use exact string matching here. This works correctly
  11628. // because our server always generates weak ETags (W/"..."), and
  11629. // clients typically send back the same ETag they received.
  11630. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  11631. // If-None-Match, where W/"x" and "x" would match, but this
  11632. // simplified implementation requires exact matches.
  11633. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  11634. [&](const char *b, const char *e) {
  11635. auto seg_len = static_cast<size_t>(e - b);
  11636. return (seg_len == 1 && *b == '*') ||
  11637. (seg_len == etag.size() &&
  11638. std::equal(b, e, etag.begin()));
  11639. });
  11640. if (ret) {
  11641. res.status = StatusCode::NotModified_304;
  11642. return true;
  11643. }
  11644. }
  11645. } else if (req.has_header("If-Modified-Since")) {
  11646. auto val = req.get_header_value("If-Modified-Since");
  11647. auto t = detail::parse_http_date(val);
  11648. if (t != static_cast<time_t>(-1) && mtime <= t) {
  11649. res.status = StatusCode::NotModified_304;
  11650. return true;
  11651. }
  11652. }
  11653. return false;
  11654. }
  11655. inline bool Server::check_if_range(Request &req, const std::string &etag,
  11656. time_t mtime) const {
  11657. // Handle If-Range for partial content requests (RFC 9110
  11658. // Section 13.1.5). If-Range is only evaluated when Range header is
  11659. // present. If the validator matches, serve partial content; otherwise
  11660. // serve full content.
  11661. if (!req.ranges.empty() && req.has_header("If-Range")) {
  11662. auto val = req.get_header_value("If-Range");
  11663. auto is_valid_range = [&]() {
  11664. if (detail::is_strong_etag(val)) {
  11665. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  11666. // comparison.
  11667. return (!etag.empty() && val == etag);
  11668. } else if (detail::is_weak_etag(val)) {
  11669. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  11670. return false;
  11671. } else {
  11672. // HTTP-date comparison
  11673. auto t = detail::parse_http_date(val);
  11674. return (t != static_cast<time_t>(-1) && mtime <= t);
  11675. }
  11676. };
  11677. if (!is_valid_range()) {
  11678. // Validator doesn't match: ignore Range and serve full content
  11679. req.ranges.clear();
  11680. return false;
  11681. }
  11682. }
  11683. return true;
  11684. }
  11685. inline socket_t
  11686. Server::create_server_socket(const std::string &host, int port,
  11687. int socket_flags,
  11688. SocketOptions socket_options) const {
  11689. return detail::create_socket(
  11690. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  11691. ipv6_v6only_, std::move(socket_options),
  11692. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  11693. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  11694. output_error_log(Error::BindIPAddress, nullptr);
  11695. return false;
  11696. }
  11697. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  11698. output_error_log(Error::Listen, nullptr);
  11699. return false;
  11700. }
  11701. return true;
  11702. });
  11703. }
  11704. inline int Server::bind_internal(const std::string &host, int port,
  11705. int socket_flags) {
  11706. if (is_decommissioned) { return -1; }
  11707. if (!is_valid()) { return -1; }
  11708. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  11709. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  11710. if (port == 0) {
  11711. struct sockaddr_storage addr;
  11712. socklen_t addr_len = sizeof(addr);
  11713. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  11714. &addr_len) == -1) {
  11715. output_error_log(Error::GetSockName, nullptr);
  11716. return -1;
  11717. }
  11718. if (addr.ss_family == AF_INET) {
  11719. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  11720. } else if (addr.ss_family == AF_INET6) {
  11721. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  11722. } else {
  11723. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  11724. return -1;
  11725. }
  11726. } else {
  11727. return port;
  11728. }
  11729. }
  11730. inline bool Server::listen_internal() {
  11731. // A stop() between bind and listen leaves nothing to accept on. Report
  11732. // failure instead of returning success without ever serving, and mark the
  11733. // server decommissioned the way any failed listen does so that a concurrent
  11734. // wait_until_ready() wakes up instead of spinning forever.
  11735. if (is_decommissioned || svr_sock_ == INVALID_SOCKET) {
  11736. is_decommissioned = true;
  11737. return false;
  11738. }
  11739. auto ret = true;
  11740. is_running_ = true;
  11741. auto se = detail::scope_exit([&]() { is_running_ = false; });
  11742. if (start_handler_) { start_handler_(); }
  11743. {
  11744. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  11745. while (svr_sock_ != INVALID_SOCKET) {
  11746. #ifndef _WIN32
  11747. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  11748. #endif
  11749. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  11750. idle_interval_usec_);
  11751. if (val == 0) { // Timeout
  11752. task_queue->on_idle();
  11753. continue;
  11754. }
  11755. #ifndef _WIN32
  11756. }
  11757. #endif
  11758. #if defined _WIN32
  11759. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  11760. // OVERLAPPED
  11761. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  11762. #elif defined SOCK_CLOEXEC
  11763. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  11764. #else
  11765. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  11766. #endif
  11767. if (sock == INVALID_SOCKET) {
  11768. // NOTE: Winsock reports failures through WSAGetLastError() and never
  11769. // touches the CRT errno, so the two have to be asked platform by
  11770. // platform rather than by testing errno here.
  11771. if (detail::is_accept_resource_error()) {
  11772. // The per-process descriptor limit or the network stack's buffer
  11773. // space has been reached. Try to accept new connections after a
  11774. // short sleep.
  11775. std::this_thread::sleep_for(std::chrono::microseconds{1});
  11776. continue;
  11777. } else if (detail::is_accept_transient_error()) {
  11778. continue;
  11779. }
  11780. // Take the descriptor out of svr_sock_ before closing it: a later
  11781. // stop() would otherwise shutdown()/close() a value the OS may have
  11782. // reused, and keep_alive() watches svr_sock_ to notice the server is
  11783. // gone. The exchange also settles the race with a concurrent stop(),
  11784. // since whichever side takes the descriptor closes it exactly once.
  11785. auto listen_sock = svr_sock_.exchange(INVALID_SOCKET);
  11786. if (listen_sock != INVALID_SOCKET) {
  11787. detail::close_socket(listen_sock);
  11788. ret = false;
  11789. output_error_log(Error::Connection, nullptr);
  11790. } else {
  11791. ; // The server socket was closed by user.
  11792. }
  11793. break;
  11794. }
  11795. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  11796. read_timeout_sec_, read_timeout_usec_);
  11797. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  11798. write_timeout_sec_, write_timeout_usec_);
  11799. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  11800. if (!task_queue->enqueue(
  11801. [this, sock]() { process_and_close_socket(sock); })) {
  11802. output_error_log(Error::ResourceExhaustion, nullptr);
  11803. detail::shutdown_socket(sock);
  11804. detail::close_socket(sock);
  11805. }
  11806. }
  11807. task_queue->shutdown();
  11808. }
  11809. is_decommissioned = !ret;
  11810. return ret;
  11811. }
  11812. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  11813. if (pre_routing_handler_ &&
  11814. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  11815. return true;
  11816. }
  11817. // File handler
  11818. if ((req.method == "GET" || req.method == "HEAD") &&
  11819. handle_file_request(req, res)) {
  11820. return true;
  11821. }
  11822. const auto *custom = find_custom_entry(req.method);
  11823. // The second clause mirrors what expect_content() does unconditionally for
  11824. // POST/PUT/PATCH/DELETE: a content reader route fires even when the request
  11825. // carries no body. Without it a body-less PROPFIND (RFC 4918 treats one as
  11826. // `allprop`) would skip its handler and fall through to 404.
  11827. if (detail::expect_content(req) ||
  11828. (custom && !custom->handlers_for_content_reader.empty())) {
  11829. // Content reader handler
  11830. {
  11831. // Track whether the ContentReader was aborted due to the decompressed
  11832. // payload exceeding `payload_max_length_`.
  11833. // The user handler runs after the lambda returns, so we must restore the
  11834. // 413 status if the handler overwrites it.
  11835. bool content_reader_payload_too_large = false;
  11836. ContentReader reader(
  11837. [&](ContentReceiver receiver) {
  11838. auto result = read_content_with_content_receiver(
  11839. strm, req, res, std::move(receiver), nullptr, nullptr);
  11840. if (!result) {
  11841. output_error_log(Error::Read, &req);
  11842. if (res.status == StatusCode::PayloadTooLarge_413) {
  11843. content_reader_payload_too_large = true;
  11844. }
  11845. }
  11846. return result;
  11847. },
  11848. [&](FormDataHeader header, ContentReceiver receiver) {
  11849. auto result = read_content_with_content_receiver(
  11850. strm, req, res, nullptr, std::move(header),
  11851. std::move(receiver));
  11852. if (!result) {
  11853. output_error_log(Error::Read, &req);
  11854. if (res.status == StatusCode::PayloadTooLarge_413) {
  11855. content_reader_payload_too_large = true;
  11856. }
  11857. }
  11858. return result;
  11859. });
  11860. bool dispatched = false;
  11861. if (req.method == "POST") {
  11862. dispatched = dispatch_request_for_content_reader(
  11863. req, res, std::move(reader), post_handlers_for_content_reader_);
  11864. } else if (req.method == "PUT") {
  11865. dispatched = dispatch_request_for_content_reader(
  11866. req, res, std::move(reader), put_handlers_for_content_reader_);
  11867. } else if (req.method == "PATCH") {
  11868. dispatched = dispatch_request_for_content_reader(
  11869. req, res, std::move(reader), patch_handlers_for_content_reader_);
  11870. } else if (req.method == "DELETE") {
  11871. dispatched = dispatch_request_for_content_reader(
  11872. req, res, std::move(reader), delete_handlers_for_content_reader_);
  11873. } else if (custom) {
  11874. dispatched = dispatch_request_for_content_reader(
  11875. req, res, std::move(reader), custom->handlers_for_content_reader);
  11876. }
  11877. if (dispatched) {
  11878. if (content_reader_payload_too_large) {
  11879. // Enforce the limit: override any status the handler may have set
  11880. // and return false so the error path sends a plain 413 response.
  11881. res.status = StatusCode::PayloadTooLarge_413;
  11882. res.body.clear();
  11883. res.content_length_ = 0;
  11884. res.content_provider_ = nullptr;
  11885. return false;
  11886. }
  11887. return true;
  11888. }
  11889. }
  11890. // NOTE: `req.body` is not read here. For a regular handler the body is
  11891. // read inside dispatch_request(), after the route has matched and the
  11892. // pre-request handler has approved the request, so that a rejected
  11893. // request (e.g. failed authentication) never forces us to buffer a
  11894. // potentially large body.
  11895. }
  11896. // Regular handler
  11897. if (req.method == "GET" || req.method == "HEAD") {
  11898. return dispatch_request(req, res, get_handlers_, strm);
  11899. } else if (req.method == "POST") {
  11900. return dispatch_request(req, res, post_handlers_, strm);
  11901. } else if (req.method == "PUT") {
  11902. return dispatch_request(req, res, put_handlers_, strm);
  11903. } else if (req.method == "DELETE") {
  11904. return dispatch_request(req, res, delete_handlers_, strm);
  11905. } else if (req.method == "OPTIONS") {
  11906. return dispatch_request(req, res, options_handlers_, strm);
  11907. } else if (req.method == "PATCH") {
  11908. return dispatch_request(req, res, patch_handlers_, strm);
  11909. } else if (custom) {
  11910. return dispatch_request(req, res, custom->handlers, strm);
  11911. }
  11912. res.status = StatusCode::BadRequest_400;
  11913. return false;
  11914. }
  11915. inline bool Server::dispatch_request(Request &req, Response &res,
  11916. const Handlers &handlers, Stream &strm) {
  11917. for (const auto &x : handlers) {
  11918. const auto &matcher = x.first;
  11919. const auto &handler = x.second;
  11920. if (matcher->match(req)) {
  11921. req.matched_route = matcher->pattern();
  11922. // Run the pre-request handler before reading the body so a rejected
  11923. // request (e.g. failed authentication) never forces us to buffer a
  11924. // potentially large body. `req.matched_route` is available here.
  11925. if (pre_request_handler_ &&
  11926. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  11927. return true;
  11928. }
  11929. // The route matched and the request was approved; read the body now.
  11930. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  11931. output_error_log(Error::Read, &req);
  11932. return false;
  11933. }
  11934. handler(req, res);
  11935. return true;
  11936. }
  11937. }
  11938. return false;
  11939. }
  11940. // Decides the content coding for a response served straight from a file. Both
  11941. // the ETag, which has to name the representation actually sent, and
  11942. // `apply_static_file_compression()` go through this, so the two cannot drift
  11943. // apart.
  11944. inline detail::EncodingType
  11945. Server::static_file_encoding(const Request &req, const Response &res,
  11946. const std::string &content_type,
  11947. size_t length) const {
  11948. if (!static_file_compression_) { return detail::EncodingType::None; }
  11949. // Nothing to compress, and an empty file already answers with
  11950. // `Content-Length: 0`. Checked on its own so that a zero floor still cannot
  11951. // turn an empty body into a 20-byte gzip stream.
  11952. if (length == 0) { return detail::EncodingType::None; }
  11953. // A file that already fits in a single packet gains nothing from being made
  11954. // smaller, since it still travels in that one segment, and a file of a few
  11955. // bytes comes out larger than it went in.
  11956. if (length < static_file_compression_min_length_) {
  11957. return detail::EncodingType::None;
  11958. }
  11959. // RFC 9110 applies Range to the representation after content coding, so a
  11960. // compressed 206 would mean compressing the whole file and then slicing it.
  11961. // Serve ranges from the identity representation instead.
  11962. if (!req.ranges.empty()) { return detail::EncodingType::None; }
  11963. if (static_file_compression_max_length_ > 0 &&
  11964. length > static_file_compression_max_length_) {
  11965. return detail::EncodingType::None;
  11966. }
  11967. return detail::encoding_type(req, res, content_type);
  11968. }
  11969. // Compresses a file-backed content provider into `res.body` and takes over the
  11970. // framing headers. Returns false when the response is left untouched.
  11971. inline bool Server::apply_static_file_compression(const Request &req,
  11972. Response &res) const {
  11973. auto type = res.content_coding_;
  11974. if (type == detail::EncodingType::None || !res.content_provider_) {
  11975. return false;
  11976. }
  11977. auto compressor = detail::make_compressor(type);
  11978. if (!compressor) { return false; }
  11979. output_pre_compression_log(req, res);
  11980. std::string compressed;
  11981. if (!detail::compress_content_provider(res.content_provider_,
  11982. res.content_length_, *compressor,
  11983. compressed)) {
  11984. return false;
  11985. }
  11986. res.body.swap(compressed);
  11987. // The provider was consumed in full, so a resource releaser registered with
  11988. // it should hear about a success when the response goes away.
  11989. res.content_provider_success_ = true;
  11990. res.content_provider_ = nullptr;
  11991. res.content_length_ = 0;
  11992. res.content_coding_ = detail::EncodingType::None;
  11993. res.set_header("Content-Encoding", detail::encoding_name(type));
  11994. res.set_header("Vary", "Accept-Encoding");
  11995. res.set_header("Content-Length", std::to_string(res.body.size()));
  11996. return true;
  11997. }
  11998. inline void Server::apply_ranges(const Request &req, Response &res,
  11999. std::string &content_type,
  12000. std::string &boundary) const {
  12001. // A known-length content provider leaves `res.body` empty, so the compressor
  12002. // at the end of this function never runs for one (issue #2545). A file-backed
  12003. // provider is fully readable right here, so compress it and answer with an
  12004. // ordinary body: `Content-Length` and HEAD keep working, and the response
  12005. // takes the same path as `set_content()` from here on. Range requests never
  12006. // get a content coding, so `Content-Range` still names identity bytes and
  12007. // none of the framing below applies.
  12008. if (apply_static_file_compression(req, res)) { return; }
  12009. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  12010. auto it = res.headers.find("Content-Type");
  12011. if (it != res.headers.end()) {
  12012. content_type = it->second;
  12013. res.headers.erase(it);
  12014. }
  12015. boundary = detail::make_multipart_data_boundary();
  12016. res.set_header("Content-Type",
  12017. "multipart/byteranges; boundary=" + boundary);
  12018. }
  12019. auto type = detail::encoding_type(req, res);
  12020. if (res.body.empty()) {
  12021. if (res.content_length_ > 0) {
  12022. size_t length = 0;
  12023. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  12024. length = res.content_length_;
  12025. } else if (req.ranges.size() == 1) {
  12026. auto offset_and_length = detail::get_range_offset_and_length(
  12027. req.ranges[0], res.content_length_);
  12028. length = offset_and_length.second;
  12029. auto content_range = detail::make_content_range_header_field(
  12030. offset_and_length, res.content_length_);
  12031. res.set_header("Content-Range", content_range);
  12032. } else {
  12033. length = detail::get_multipart_ranges_data_length(
  12034. req, boundary, content_type, res.content_length_);
  12035. }
  12036. res.set_header("Content-Length", std::to_string(length));
  12037. } else {
  12038. if (res.content_provider_) {
  12039. if (res.is_chunked_content_provider_) {
  12040. res.set_header("Transfer-Encoding", "chunked");
  12041. res.content_coding_ = type;
  12042. if (type != detail::EncodingType::None) {
  12043. res.set_header("Content-Encoding", detail::encoding_name(type));
  12044. res.set_header("Vary", "Accept-Encoding");
  12045. }
  12046. }
  12047. }
  12048. }
  12049. } else {
  12050. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  12051. ;
  12052. } else if (req.ranges.size() == 1) {
  12053. auto offset_and_length =
  12054. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  12055. auto offset = offset_and_length.first;
  12056. auto length = offset_and_length.second;
  12057. auto content_range = detail::make_content_range_header_field(
  12058. offset_and_length, res.body.size());
  12059. res.set_header("Content-Range", content_range);
  12060. assert(offset + length <= res.body.size());
  12061. res.body = res.body.substr(offset, length);
  12062. } else {
  12063. std::string data;
  12064. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  12065. res.body.size(), data);
  12066. res.body.swap(data);
  12067. }
  12068. if (type != detail::EncodingType::None) {
  12069. output_pre_compression_log(req, res);
  12070. if (auto compressor = detail::make_compressor(type)) {
  12071. std::string compressed;
  12072. if (compressor->compress(res.body.data(), res.body.size(), true,
  12073. [&](const char *data, size_t data_len) {
  12074. compressed.append(data, data_len);
  12075. return true;
  12076. })) {
  12077. res.body.swap(compressed);
  12078. res.set_header("Content-Encoding", detail::encoding_name(type));
  12079. res.set_header("Vary", "Accept-Encoding");
  12080. }
  12081. }
  12082. }
  12083. res.content_length_ = res.body.size();
  12084. res.set_header("Content-Length", std::to_string(res.content_length_));
  12085. }
  12086. }
  12087. inline bool Server::dispatch_request_for_content_reader(
  12088. Request &req, Response &res, ContentReader content_reader,
  12089. const HandlersForContentReader &handlers) const {
  12090. for (const auto &x : handlers) {
  12091. const auto &matcher = x.first;
  12092. const auto &handler = x.second;
  12093. if (matcher->match(req)) {
  12094. req.matched_route = matcher->pattern();
  12095. if (!pre_request_handler_ ||
  12096. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  12097. handler(req, res, content_reader);
  12098. }
  12099. return true;
  12100. }
  12101. }
  12102. return false;
  12103. }
  12104. inline std::string
  12105. get_client_ip(const std::string &x_forwarded_for,
  12106. const std::vector<std::string> &trusted_proxies) {
  12107. // X-Forwarded-For is a comma-separated list per RFC 7239
  12108. std::vector<std::string> ip_list;
  12109. detail::split(x_forwarded_for.data(),
  12110. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  12111. [&](const char *b, const char *e) {
  12112. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  12113. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  12114. });
  12115. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  12116. // no segments. Signal "no client IP derived" with an empty string so the
  12117. // caller can fall back to the connection-level remote address.
  12118. if (ip_list.empty()) { return std::string(); }
  12119. // Each hop appends the address it received the request from, so the rightmost
  12120. // entries are the ones written by our own infrastructure while the leftmost
  12121. // are whatever the original client chose to send. Walk from the right and
  12122. // skip trusted proxies; the first address that is not a trusted proxy is the
  12123. // furthest point still attributable to a real hop, i.e. the client. Scanning
  12124. // from the left instead lets a client forge an arbitrary address by following
  12125. // it with a trusted proxy's address, which the left-to-right scan then
  12126. // returned as the client.
  12127. for (size_t i = ip_list.size(); i-- > 0;) {
  12128. const auto &ip = ip_list[i];
  12129. auto is_trusted_proxy =
  12130. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  12131. [&](const std::string &proxy) { return ip == proxy; });
  12132. if (!is_trusted_proxy) { return ip; }
  12133. }
  12134. // Every hop was a trusted proxy; fall back to the first entry.
  12135. return ip_list.front();
  12136. }
  12137. inline bool
  12138. Server::process_request(Stream &strm, const std::string &remote_addr,
  12139. int remote_port, const std::string &local_addr,
  12140. int local_port, bool close_connection,
  12141. bool &connection_closed,
  12142. const std::function<void(Request &)> &setup_request,
  12143. bool *websocket_upgraded) {
  12144. std::array<char, 2048> buf{};
  12145. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  12146. // Connection has been closed on client
  12147. if (!line_reader.getline()) { return false; }
  12148. Request req;
  12149. req.start_time_ = std::chrono::steady_clock::now();
  12150. req.remote_addr = remote_addr;
  12151. req.remote_port = remote_port;
  12152. req.local_addr = local_addr;
  12153. req.local_port = local_port;
  12154. Response res;
  12155. res.version = "HTTP/1.1";
  12156. res.headers = default_headers_;
  12157. // Request line and headers
  12158. if (!parse_request_line(line_reader.ptr(), req)) {
  12159. res.status = StatusCode::BadRequest_400;
  12160. output_error_log(Error::InvalidRequestLine, &req);
  12161. return write_response(strm, close_connection, req, res);
  12162. }
  12163. // Request headers
  12164. if (!detail::read_headers(strm, req.headers)) {
  12165. res.status = StatusCode::BadRequest_400;
  12166. output_error_log(Error::InvalidHeaders, &req);
  12167. return write_response(strm, close_connection, req, res);
  12168. }
  12169. // RFC 9112 §6.3: Reject requests whose framing is ambiguous, which would
  12170. // otherwise let an intermediary and this parser disagree on where the body
  12171. // ends and enable request smuggling. Two cases: a non-zero Content-Length
  12172. // alongside any Transfer-Encoding (Content-Length: 0 is tolerated for
  12173. // compatibility with existing clients), and a Transfer-Encoding whose final
  12174. // coding is not chunked, which leaves the body length undeterminable. The
  12175. // latter must not fall through to the "no body" path, or the body bytes are
  12176. // parsed as the next request on a persistent connection.
  12177. if (detail::has_conflicting_content_length(req.headers) ||
  12178. (req.has_header("Transfer-Encoding") &&
  12179. !detail::is_chunked_transfer_encoding(req.headers))) {
  12180. connection_closed = true;
  12181. res.status = StatusCode::BadRequest_400;
  12182. return write_response(strm, close_connection, req, res);
  12183. }
  12184. // Check if the request URI doesn't exceed the limit
  12185. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  12186. connection_closed = true;
  12187. res.status = StatusCode::UriTooLong_414;
  12188. output_error_log(Error::ExceedUriMaxLength, &req);
  12189. return write_response(strm, close_connection, req, res);
  12190. }
  12191. if (detail::has_header_token(req.headers, "Connection", "close")) {
  12192. connection_closed = true;
  12193. }
  12194. if (req.version == "HTTP/1.0" &&
  12195. !detail::has_header_token(req.headers, "Connection", "keep-alive")) {
  12196. connection_closed = true;
  12197. }
  12198. // Only honor X-Forwarded-For if the peer on the actual TCP connection is
  12199. // itself a trusted proxy. Otherwise any direct client could spoof
  12200. // remote_addr simply by sending an arbitrary X-Forwarded-For header.
  12201. auto is_trusted_peer = std::any_of(
  12202. trusted_proxies_.begin(), trusted_proxies_.end(),
  12203. [&](const std::string &proxy) { return proxy == remote_addr; });
  12204. if (is_trusted_peer && req.has_header("X-Forwarded-For")) {
  12205. // Some proxies append the address they observed as a separate
  12206. // X-Forwarded-For field line instead of extending the one the client sent
  12207. // (e.g. HAProxy's "option forwardfor"), so the whole combined value has to
  12208. // be scanned. Reading only the first occurrence would hand back the
  12209. // client-supplied, and therefore forgeable, value.
  12210. auto x_forwarded_for =
  12211. detail::get_combined_header_value(req.headers, "X-Forwarded-For");
  12212. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  12213. req.remote_addr = derived.empty() ? remote_addr : derived;
  12214. } else {
  12215. req.remote_addr = remote_addr;
  12216. }
  12217. req.remote_port = remote_port;
  12218. req.local_addr = local_addr;
  12219. req.local_port = local_port;
  12220. if (req.has_header("Accept")) {
  12221. auto accept_header =
  12222. detail::get_combined_header_value(req.headers, "Accept");
  12223. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  12224. connection_closed = true;
  12225. res.status = StatusCode::BadRequest_400;
  12226. output_error_log(Error::HTTPParsing, &req);
  12227. return write_response(strm, close_connection, req, res);
  12228. }
  12229. }
  12230. if (req.has_header("Range")) {
  12231. const auto &range_header_value = req.get_header_value("Range");
  12232. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  12233. connection_closed = true;
  12234. res.status = StatusCode::RangeNotSatisfiable_416;
  12235. output_error_log(Error::InvalidRangeHeader, &req);
  12236. return write_response(strm, close_connection, req, res);
  12237. }
  12238. }
  12239. if (setup_request) { setup_request(req); }
  12240. // RFC 9110 10.1.1: Expect is a comma-separated list whose value is
  12241. // case-insensitive, and a 100-continue expectation in an HTTP/1.0 request
  12242. // must be ignored. An expectation we do not recognize is left alone; the
  12243. // 417 the section allows for one is a MAY, not a requirement.
  12244. //
  12245. // `100 Continue` itself is deferred until the body is actually read (see
  12246. // read_content_core), so a request rejected by a later handler never
  12247. // invites the client to send a body nobody will read.
  12248. if (req.version != "HTTP/1.0" &&
  12249. detail::has_header_token(req.headers, "Expect", "100-continue")) {
  12250. int status = StatusCode::Continue_100;
  12251. if (expect_100_continue_handler_) {
  12252. status = expect_100_continue_handler_(req, res);
  12253. }
  12254. if (status == StatusCode::Continue_100) {
  12255. req.expect_100_continue_pending_ = true;
  12256. } else {
  12257. if (res.status == -1) { res.status = status; }
  12258. connection_closed = true;
  12259. return write_response(strm, true, req, res);
  12260. }
  12261. }
  12262. // Setup `is_connection_closed` method
  12263. auto sock = strm.socket();
  12264. req.is_connection_closed = [sock]() {
  12265. return !detail::is_socket_alive(sock);
  12266. };
  12267. // WebSocket upgrade
  12268. // Run pre_routing_handler_ and pre_request_handler_ before upgrading so
  12269. // that authentication and other middleware can reject the request with an
  12270. // HTTP response (e.g., 401) before the protocol switches.
  12271. if (detail::is_websocket_upgrade(req)) {
  12272. if (pre_routing_handler_ &&
  12273. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  12274. if (res.status == -1) { res.status = StatusCode::OK_200; }
  12275. return write_response_with_content(strm, close_connection, req, res);
  12276. }
  12277. // Find matching WebSocket handler
  12278. for (const auto &entry : websocket_handlers_) {
  12279. if (entry.matcher->match(req)) {
  12280. req.matched_route = entry.matcher->pattern();
  12281. if (pre_request_handler_ &&
  12282. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  12283. if (res.status == -1) { res.status = StatusCode::OK_200; }
  12284. return write_response_with_content(strm, close_connection, req, res);
  12285. }
  12286. // Compute accept key
  12287. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  12288. auto accept_key = detail::websocket_accept_key(client_key);
  12289. // Negotiate subprotocol
  12290. std::string selected_subprotocol;
  12291. if (entry.sub_protocol_selector) {
  12292. auto protocol_header = detail::get_combined_header_value(
  12293. req.headers, "Sec-WebSocket-Protocol");
  12294. if (!protocol_header.empty()) {
  12295. std::vector<std::string> protocols;
  12296. detail::split(protocol_header.data(),
  12297. protocol_header.data() + protocol_header.size(), ',',
  12298. [&](const char *b, const char *e) {
  12299. protocols.emplace_back(b, e);
  12300. });
  12301. selected_subprotocol = entry.sub_protocol_selector(protocols);
  12302. }
  12303. }
  12304. // Send 101 Switching Protocols
  12305. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  12306. "Upgrade: websocket\r\n"
  12307. "Connection: Upgrade\r\n"
  12308. "Sec-WebSocket-Accept: " +
  12309. accept_key + "\r\n";
  12310. if (!selected_subprotocol.empty()) {
  12311. if (!detail::fields::is_field_value(selected_subprotocol)) {
  12312. return false;
  12313. }
  12314. handshake_response +=
  12315. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  12316. }
  12317. handshake_response += "\r\n";
  12318. if (strm.write(handshake_response.data(), handshake_response.size()) <
  12319. 0) {
  12320. return false;
  12321. }
  12322. connection_closed = true;
  12323. if (websocket_upgraded) { *websocket_upgraded = true; }
  12324. {
  12325. #ifdef CPPHTTPLIB_SSL_ENABLED
  12326. if (req.ssl) {
  12327. // wss: the heartbeat ping thread and the read path enter the same
  12328. // TLS session from different threads. Hand the WebSocket a stream
  12329. // that serializes every TLS call, so the shared SSLSocketStream on
  12330. // the plain HTTP/HTTPS paths stays untouched.
  12331. auto ws_strm =
  12332. std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  12333. strm.socket(), const_cast<tls::session_t>(req.ssl),
  12334. CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
  12335. write_timeout_sec_, write_timeout_usec_));
  12336. ws::WebSocket ws(std::move(ws_strm), req, true,
  12337. websocket_ping_interval_sec_,
  12338. websocket_max_missed_pongs_);
  12339. entry.handler(req, ws);
  12340. return true;
  12341. }
  12342. #endif
  12343. // Use WebSocket-specific read timeout instead of HTTP timeout
  12344. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND,
  12345. 0);
  12346. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  12347. websocket_max_missed_pongs_);
  12348. entry.handler(req, ws);
  12349. }
  12350. return true;
  12351. }
  12352. }
  12353. // No matching handler - fall through to 404
  12354. }
  12355. // Routing
  12356. auto routed = false;
  12357. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12358. routed = routing(req, res, strm);
  12359. #else
  12360. try {
  12361. routed = routing(req, res, strm);
  12362. } catch (std::exception &) {
  12363. if (exception_handler_) {
  12364. auto ep = std::current_exception();
  12365. exception_handler_(req, res, ep);
  12366. routed = true;
  12367. } else {
  12368. res.status = StatusCode::InternalServerError_500;
  12369. }
  12370. } catch (...) {
  12371. if (exception_handler_) {
  12372. auto ep = std::current_exception();
  12373. exception_handler_(req, res, ep);
  12374. routed = true;
  12375. } else {
  12376. res.status = StatusCode::InternalServerError_500;
  12377. }
  12378. }
  12379. #endif
  12380. auto ret = false;
  12381. if (routed) {
  12382. if (res.status == -1) {
  12383. res.status = req.ranges.empty() ? StatusCode::OK_200
  12384. : StatusCode::PartialContent_206;
  12385. }
  12386. // Serve file content by using a content provider
  12387. auto file_open_error = false;
  12388. if (!res.file_content_path_.empty()) {
  12389. const auto &path = res.file_content_path_;
  12390. auto mm = std::make_shared<detail::mmap>(path.c_str());
  12391. if (!mm->is_open()) {
  12392. res.body.clear();
  12393. res.content_length_ = 0;
  12394. res.content_provider_ = nullptr;
  12395. res.status = StatusCode::NotFound_404;
  12396. output_error_log(Error::OpenFile, &req);
  12397. file_open_error = true;
  12398. } else {
  12399. auto content_type = res.file_content_content_type_;
  12400. if (content_type.empty()) {
  12401. content_type = detail::find_content_type(
  12402. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  12403. }
  12404. detail::set_file_content_provider(
  12405. res, mm, content_type,
  12406. static_file_encoding(req, res, content_type, mm->size()));
  12407. }
  12408. }
  12409. if (file_open_error) {
  12410. ret = write_response(strm, close_connection, req, res);
  12411. } else if (detail::range_error(req, res)) {
  12412. res.body.clear();
  12413. res.content_length_ = 0;
  12414. res.content_provider_ = nullptr;
  12415. res.status = StatusCode::RangeNotSatisfiable_416;
  12416. ret = write_response(strm, close_connection, req, res);
  12417. } else {
  12418. ret = write_response_with_content(strm, close_connection, req, res);
  12419. }
  12420. } else {
  12421. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  12422. ret = write_response(strm, close_connection, req, res);
  12423. }
  12424. // Drain any unconsumed framed body to prevent request smuggling on
  12425. // keep-alive. Without framing there is no body to drain — reading would
  12426. // consume the next request (issue #2450). If the response has committed the
  12427. // connection to close, there is no next request to protect.
  12428. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  12429. if (detail::has_header_token(res.headers, "Connection", "close")) {
  12430. connection_closed = true;
  12431. } else {
  12432. int dummy_status;
  12433. if (!detail::read_content(
  12434. strm, req, payload_max_length_, dummy_status, nullptr,
  12435. [](const char *, size_t, size_t, size_t) { return true; },
  12436. false)) {
  12437. connection_closed = true;
  12438. }
  12439. }
  12440. }
  12441. return ret;
  12442. }
  12443. inline bool Server::is_valid() const { return !has_invalid_registration_; }
  12444. inline bool Server::process_and_close_socket(socket_t sock) {
  12445. std::string remote_addr;
  12446. int remote_port = 0;
  12447. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  12448. std::string local_addr;
  12449. int local_port = 0;
  12450. detail::get_local_ip_and_port(sock, local_addr, local_port);
  12451. bool websocket_upgraded = false;
  12452. auto ret = serve_guarded([&]() {
  12453. return detail::process_server_socket(
  12454. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  12455. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12456. write_timeout_usec_,
  12457. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  12458. return process_request(strm, remote_addr, remote_port, local_addr,
  12459. local_port, close_connection,
  12460. connection_closed, nullptr,
  12461. &websocket_upgraded);
  12462. });
  12463. });
  12464. detail::drain_and_close_socket(sock);
  12465. return ret;
  12466. }
  12467. inline void Server::output_log(const Request &req, const Response &res) const {
  12468. if (logger_) {
  12469. std::lock_guard<std::mutex> guard(logger_mutex_);
  12470. logger_(req, res);
  12471. }
  12472. }
  12473. inline void Server::output_pre_compression_log(const Request &req,
  12474. const Response &res) const {
  12475. if (pre_compression_logger_) {
  12476. std::lock_guard<std::mutex> guard(logger_mutex_);
  12477. pre_compression_logger_(req, res);
  12478. }
  12479. }
  12480. inline void Server::output_error_log(const Error &err,
  12481. const Request *req) const {
  12482. if (error_logger_) {
  12483. std::lock_guard<std::mutex> guard(logger_mutex_);
  12484. error_logger_(err, req);
  12485. }
  12486. }
  12487. /*
  12488. * Group 5: ClientImpl and Client (Universal) implementation
  12489. */
  12490. // HTTP client implementation
  12491. inline ClientImpl::ClientImpl(const std::string &host)
  12492. : ClientImpl(host, 80, std::string(), std::string()) {}
  12493. inline ClientImpl::ClientImpl(const std::string &host, int port)
  12494. : ClientImpl(host, port, std::string(), std::string()) {}
  12495. inline ClientImpl::ClientImpl(const std::string &host, int port,
  12496. const std::string &client_cert_path,
  12497. const std::string &client_key_path)
  12498. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  12499. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  12500. inline ClientImpl::~ClientImpl() {
  12501. // Wait until all the requests in flight are handled.
  12502. size_t retry_count = 10;
  12503. while (retry_count-- > 0) {
  12504. {
  12505. std::lock_guard<std::mutex> guard(socket_mutex_);
  12506. if (socket_requests_in_flight_ == 0) { break; }
  12507. }
  12508. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  12509. }
  12510. std::lock_guard<std::mutex> guard(socket_mutex_);
  12511. shutdown_socket(socket_);
  12512. close_socket(socket_);
  12513. }
  12514. inline bool ClientImpl::is_valid() const { return true; }
  12515. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  12516. client_cert_path_ = rhs.client_cert_path_;
  12517. client_key_path_ = rhs.client_key_path_;
  12518. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  12519. read_timeout_sec_ = rhs.read_timeout_sec_;
  12520. read_timeout_usec_ = rhs.read_timeout_usec_;
  12521. write_timeout_sec_ = rhs.write_timeout_sec_;
  12522. write_timeout_usec_ = rhs.write_timeout_usec_;
  12523. max_timeout_msec_ = rhs.max_timeout_msec_;
  12524. basic_auth_username_ = rhs.basic_auth_username_;
  12525. basic_auth_password_ = rhs.basic_auth_password_;
  12526. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  12527. keep_alive_ = rhs.keep_alive_;
  12528. follow_location_ = rhs.follow_location_;
  12529. path_encode_ = rhs.path_encode_;
  12530. address_family_ = rhs.address_family_;
  12531. tcp_nodelay_ = rhs.tcp_nodelay_;
  12532. ipv6_v6only_ = rhs.ipv6_v6only_;
  12533. socket_options_ = rhs.socket_options_;
  12534. compress_ = rhs.compress_;
  12535. decompress_ = rhs.decompress_;
  12536. payload_max_length_ = rhs.payload_max_length_;
  12537. has_payload_max_length_ = rhs.has_payload_max_length_;
  12538. interface_ = rhs.interface_;
  12539. proxy_host_ = rhs.proxy_host_;
  12540. proxy_port_ = rhs.proxy_port_;
  12541. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  12542. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  12543. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  12544. no_proxy_entries_ = rhs.no_proxy_entries_;
  12545. logger_ = rhs.logger_;
  12546. error_logger_ = rhs.error_logger_;
  12547. #ifdef CPPHTTPLIB_SSL_ENABLED
  12548. digest_auth_username_ = rhs.digest_auth_username_;
  12549. digest_auth_password_ = rhs.digest_auth_password_;
  12550. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  12551. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  12552. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  12553. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  12554. server_certificate_verification_ = rhs.server_certificate_verification_;
  12555. server_hostname_verification_ = rhs.server_hostname_verification_;
  12556. system_ca_mode_ = rhs.system_ca_mode_;
  12557. #endif
  12558. }
  12559. inline bool
  12560. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  12561. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  12562. if (no_proxy_entries_.empty()) { return true; }
  12563. // host_ is const so its normalized form is invariant; cache it. The
  12564. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  12565. if (host == host_) {
  12566. if (!host_normalized_valid_) {
  12567. host_normalized_ = detail::normalize_target(host_);
  12568. host_normalized_valid_ = true;
  12569. }
  12570. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  12571. }
  12572. auto target = detail::normalize_target(host);
  12573. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  12574. }
  12575. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  12576. if (is_proxy_enabled_for_host(host_)) {
  12577. return detail::create_client_socket(
  12578. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  12579. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  12580. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  12581. write_timeout_sec_, write_timeout_usec_, interface_, error);
  12582. }
  12583. // Check is custom IP or hostname specified for host_
  12584. std::string connect_host;
  12585. std::string ip;
  12586. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  12587. return detail::create_client_socket(
  12588. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  12589. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  12590. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12591. write_timeout_usec_, interface_, error);
  12592. }
  12593. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  12594. Error &error) {
  12595. auto sock = create_client_socket(error);
  12596. if (sock == INVALID_SOCKET) { return false; }
  12597. socket.sock = sock;
  12598. return true;
  12599. }
  12600. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  12601. return create_and_connect_socket(socket, error);
  12602. }
  12603. inline bool ClientImpl::setup_proxy_connection(
  12604. Socket & /*socket*/,
  12605. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  12606. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  12607. return true;
  12608. }
  12609. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  12610. bool /*shutdown_gracefully*/) {
  12611. // If there are any requests in flight from threads other than us, then it's
  12612. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  12613. assert(socket_requests_in_flight_ == 0 ||
  12614. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12615. }
  12616. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  12617. if (socket.sock == INVALID_SOCKET) { return; }
  12618. detail::shutdown_socket(socket.sock);
  12619. }
  12620. inline void ClientImpl::close_socket(Socket &socket) {
  12621. // If there are requests in flight in another thread, usually closing
  12622. // the socket will be fine and they will simply receive an error when
  12623. // using the closed socket, but it is still a bug since rarely the OS
  12624. // may reassign the socket id to be used for a new socket, and then
  12625. // suddenly they will be operating on a live socket that is different
  12626. // than the one they intended!
  12627. assert(socket_requests_in_flight_ == 0 ||
  12628. socket_requests_are_from_thread_ == std::this_thread::get_id());
  12629. // It is also a bug if this happens while SSL is still active
  12630. #ifdef CPPHTTPLIB_SSL_ENABLED
  12631. assert(socket.ssl == nullptr);
  12632. #endif
  12633. if (socket.sock == INVALID_SOCKET) { return; }
  12634. detail::close_socket(socket.sock);
  12635. socket.sock = INVALID_SOCKET;
  12636. }
  12637. inline void ClientImpl::disconnect(bool gracefully) {
  12638. shutdown_ssl(socket_, gracefully);
  12639. shutdown_socket(socket_);
  12640. close_socket(socket_);
  12641. }
  12642. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  12643. Response &res,
  12644. bool skip_100_continue) const {
  12645. std::array<char, 2048> buf{};
  12646. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  12647. if (!line_reader.getline()) { return false; }
  12648. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12649. res.reason)) {
  12650. return req.method == "CONNECT";
  12651. }
  12652. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  12653. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  12654. if (!line_reader.getline()) { return false; } // CRLF
  12655. if (!line_reader.getline()) { return false; } // next response line
  12656. if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
  12657. res.reason)) {
  12658. return false;
  12659. }
  12660. }
  12661. return true;
  12662. }
  12663. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  12664. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  12665. auto ret = send_(req, res, error);
  12666. if (error == Error::SSLPeerCouldBeClosed_) {
  12667. assert(!ret);
  12668. ret = send_(req, res, error);
  12669. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  12670. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  12671. }
  12672. return ret;
  12673. }
  12674. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  12675. {
  12676. std::lock_guard<std::mutex> guard(socket_mutex_);
  12677. // Set this to false immediately - if it ever gets set to true by the end
  12678. // of the request, we know another thread instructed us to close the
  12679. // socket.
  12680. socket_should_be_closed_when_request_is_done_ = false;
  12681. auto is_alive = false;
  12682. if (socket_.is_open()) {
  12683. is_alive = detail::is_socket_alive(socket_.sock);
  12684. #ifdef CPPHTTPLIB_SSL_ENABLED
  12685. if (is_alive && is_ssl()) {
  12686. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12687. is_alive = false;
  12688. }
  12689. }
  12690. #endif
  12691. if (!is_alive) {
  12692. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  12693. disconnect(/*gracefully=*/false);
  12694. }
  12695. }
  12696. if (!is_alive) {
  12697. if (!ensure_socket_connection(socket_, error)) {
  12698. output_error_log(error, &req);
  12699. return false;
  12700. }
  12701. {
  12702. auto success = true;
  12703. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  12704. error)) {
  12705. if (!success) { output_error_log(error, &req); }
  12706. return success;
  12707. }
  12708. }
  12709. }
  12710. // Mark the current socket as being in use so that it cannot be closed by
  12711. // anyone else while this request is ongoing, even though we will be
  12712. // releasing the mutex.
  12713. if (socket_requests_in_flight_ > 1) {
  12714. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  12715. }
  12716. socket_requests_in_flight_ += 1;
  12717. socket_requests_are_from_thread_ = std::this_thread::get_id();
  12718. }
  12719. for (const auto &header : default_headers_) {
  12720. if (req.headers.find(header.first) == req.headers.end()) {
  12721. req.headers.insert(header);
  12722. }
  12723. }
  12724. auto ret = false;
  12725. auto close_connection = !keep_alive_;
  12726. auto se = detail::scope_exit([&]() {
  12727. // Briefly lock mutex in order to mark that a request is no longer ongoing
  12728. std::lock_guard<std::mutex> guard(socket_mutex_);
  12729. socket_requests_in_flight_ -= 1;
  12730. if (socket_requests_in_flight_ <= 0) {
  12731. assert(socket_requests_in_flight_ == 0);
  12732. socket_requests_are_from_thread_ = std::thread::id();
  12733. }
  12734. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  12735. !ret) {
  12736. disconnect(/*gracefully=*/true);
  12737. }
  12738. });
  12739. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  12740. return handle_request(strm, req, res, close_connection, error);
  12741. });
  12742. if (!ret) {
  12743. if (error == Error::Success) {
  12744. error = Error::Unknown;
  12745. output_error_log(error, &req);
  12746. }
  12747. }
  12748. return ret;
  12749. }
  12750. inline Result ClientImpl::send(const Request &req) {
  12751. auto req2 = req;
  12752. return send_(std::move(req2));
  12753. }
  12754. inline Result ClientImpl::send_(Request &&req) {
  12755. auto res = detail::make_unique<Response>();
  12756. auto error = Error::Success;
  12757. auto ret = send(req, *res, error);
  12758. #ifdef CPPHTTPLIB_SSL_ENABLED
  12759. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  12760. last_ssl_error_, last_backend_error_};
  12761. #else
  12762. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  12763. #endif
  12764. }
  12765. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  12766. const std::string &ct) {
  12767. (void)for_stream;
  12768. // Default headers are meant for the origin and may carry its credentials, so
  12769. // keep them off the CONNECT request the proxy reads.
  12770. if (r.method != "CONNECT") {
  12771. for (const auto &header : default_headers_) {
  12772. if (!r.has_header(header.first)) { r.headers.insert(header); }
  12773. }
  12774. }
  12775. // RFC 9110 5.3 recommends sending control data such as Host first, so
  12776. // prepend it rather than appending it after the caller's own fields.
  12777. if (!r.has_header("Host")) {
  12778. r.headers.emplace_front(
  12779. "Host", detail::make_default_host_header_value(host_, port_, is_ssl(),
  12780. address_family_));
  12781. }
  12782. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  12783. if (!r.content_receiver) {
  12784. if (!r.has_header("Accept-Encoding")) {
  12785. std::string accept_encoding;
  12786. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12787. accept_encoding = "br";
  12788. #endif
  12789. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12790. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  12791. accept_encoding += "gzip, deflate";
  12792. #endif
  12793. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12794. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  12795. accept_encoding += "zstd";
  12796. #endif
  12797. r.set_header("Accept-Encoding", accept_encoding);
  12798. }
  12799. detail::add_default_user_agent_header(r);
  12800. }
  12801. if (!r.body.empty()) {
  12802. if (!ct.empty() && !r.has_header("Content-Type")) {
  12803. r.headers.emplace("Content-Type", ct);
  12804. }
  12805. if (!r.has_header("Content-Length")) {
  12806. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  12807. }
  12808. }
  12809. }
  12810. inline ClientImpl::StreamHandle
  12811. ClientImpl::open_stream(const std::string &method, const std::string &path,
  12812. const Params &params, const Headers &headers,
  12813. const std::string &body,
  12814. const std::string &content_type) {
  12815. StreamHandle handle;
  12816. handle.response = detail::make_unique<Response>();
  12817. handle.error = Error::Success;
  12818. // Encode the target exactly like the buffered send path does, so that the
  12819. // same `path` produces the same request line through either API.
  12820. auto raw_query_path =
  12821. params.empty() ? path : append_query_params(path, params);
  12822. auto query_path = detail::encode_request_target(raw_query_path, path_encode_);
  12823. handle.connection_ = detail::make_unique<ClientConnection>();
  12824. {
  12825. std::lock_guard<std::mutex> guard(socket_mutex_);
  12826. auto is_alive = false;
  12827. if (socket_.is_open()) {
  12828. is_alive = detail::is_socket_alive(socket_.sock);
  12829. #ifdef CPPHTTPLIB_SSL_ENABLED
  12830. if (is_alive && is_ssl()) {
  12831. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  12832. is_alive = false;
  12833. }
  12834. }
  12835. #endif
  12836. if (!is_alive) { disconnect(/*gracefully=*/false); }
  12837. }
  12838. if (!is_alive) {
  12839. if (!ensure_socket_connection(socket_, handle.error)) {
  12840. handle.response.reset();
  12841. return handle;
  12842. }
  12843. {
  12844. auto success = true;
  12845. auto start_time = std::chrono::steady_clock::now();
  12846. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  12847. success, handle.error)) {
  12848. if (!success) { handle.response.reset(); }
  12849. return handle;
  12850. }
  12851. }
  12852. }
  12853. transfer_socket_ownership_to_handle(handle);
  12854. }
  12855. #ifdef CPPHTTPLIB_SSL_ENABLED
  12856. if (is_ssl() && handle.connection_->session) {
  12857. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  12858. handle.connection_->sock, handle.connection_->session,
  12859. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12860. write_timeout_usec_);
  12861. } else {
  12862. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  12863. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  12864. write_timeout_sec_, write_timeout_usec_);
  12865. }
  12866. #else
  12867. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  12868. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  12869. write_timeout_sec_, write_timeout_usec_);
  12870. #endif
  12871. handle.stream_ = handle.socket_stream_.get();
  12872. Request req;
  12873. req.method = method;
  12874. req.path = query_path;
  12875. req.headers = headers;
  12876. req.body = body;
  12877. prepare_default_headers(req, true, content_type);
  12878. auto &strm = *handle.stream_;
  12879. // Build the request line and headers in memory first, like write_request()
  12880. // does, so that a rejected header leaves nothing on the wire.
  12881. {
  12882. detail::BufferStream bstrm;
  12883. if (detail::write_request_line(bstrm, req.method, req.path) < 0) {
  12884. handle.error = Error::Write;
  12885. handle.response.reset();
  12886. return handle;
  12887. }
  12888. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  12889. handle.error)) {
  12890. handle.response.reset();
  12891. return handle;
  12892. }
  12893. const auto &data = bstrm.get_buffer();
  12894. if (!detail::write_data(strm, data.data(), data.size())) {
  12895. handle.error = Error::Write;
  12896. handle.response.reset();
  12897. return handle;
  12898. }
  12899. }
  12900. if (!body.empty()) {
  12901. if (strm.write(body.data(), body.size()) < 0) {
  12902. handle.error = Error::Write;
  12903. handle.response.reset();
  12904. return handle;
  12905. }
  12906. }
  12907. if (!read_response_line(strm, req, *handle.response) ||
  12908. !detail::read_headers(strm, handle.response->headers)) {
  12909. handle.error = Error::Read;
  12910. handle.response.reset();
  12911. return handle;
  12912. }
  12913. // Same framing check as ClientImpl::process_request(). A HEAD or bodyless
  12914. // (204/304) response legitimately carries framing headers with no body.
  12915. if (method != "HEAD" &&
  12916. handle.response->status != StatusCode::NoContent_204 &&
  12917. handle.response->status != StatusCode::NotModified_304 &&
  12918. detail::has_conflicting_content_length(handle.response->headers)) {
  12919. handle.error = Error::Read;
  12920. handle.response.reset();
  12921. return handle;
  12922. }
  12923. handle.body_reader_.stream = handle.stream_;
  12924. handle.body_reader_.payload_max_length = payload_max_length_;
  12925. if (handle.response->has_header("Content-Length")) {
  12926. bool is_invalid = false;
  12927. auto content_length = detail::get_header_value_u64(
  12928. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  12929. if (is_invalid) {
  12930. handle.error = Error::Read;
  12931. handle.response.reset();
  12932. return handle;
  12933. }
  12934. handle.body_reader_.has_content_length = true;
  12935. handle.body_reader_.content_length = content_length;
  12936. }
  12937. handle.body_reader_.chunked =
  12938. detail::is_chunked_transfer_encoding(handle.response->headers);
  12939. auto content_encoding = detail::get_combined_header_value(
  12940. handle.response->headers, "Content-Encoding");
  12941. if (!content_encoding.empty()) {
  12942. // Same policy as prepare_content_receiver(): reject a coding we know about
  12943. // but were not built with, pass an unrecognized one through as-is.
  12944. handle.decompressor_ = detail::create_decompressor(content_encoding);
  12945. if (!handle.decompressor_) {
  12946. if (detail::is_known_content_encoding(content_encoding)) {
  12947. handle.error = Error::UnsupportedContentEncoding;
  12948. handle.response.reset();
  12949. return handle;
  12950. }
  12951. } else if (!handle.decompressor_->is_valid()) {
  12952. handle.error = Error::Compression;
  12953. handle.response.reset();
  12954. return handle;
  12955. }
  12956. }
  12957. return handle;
  12958. }
  12959. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  12960. if (!is_valid() || !response) { return -1; }
  12961. if (decompressor_) { return read_with_decompression(buf, len); }
  12962. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  12963. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  12964. trailers_parsed_ = true;
  12965. if (body_reader_.chunked_decoder) {
  12966. if (!body_reader_.chunked_decoder->parse_trailers_into(
  12967. response->trailers, response->headers)) {
  12968. return n;
  12969. }
  12970. } else {
  12971. detail::ChunkedDecoder dec(*stream_);
  12972. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  12973. return n;
  12974. }
  12975. }
  12976. }
  12977. return n;
  12978. }
  12979. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  12980. size_t len) {
  12981. if (decompress_offset_ < decompress_buffer_.size()) {
  12982. auto available = decompress_buffer_.size() - decompress_offset_;
  12983. auto to_copy = (std::min)(len, available);
  12984. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  12985. decompress_offset_ += to_copy;
  12986. decompressed_bytes_read_ += to_copy;
  12987. return static_cast<ssize_t>(to_copy);
  12988. }
  12989. decompress_buffer_.clear();
  12990. decompress_offset_ = 0;
  12991. constexpr size_t kDecompressionBufferSize = 8192;
  12992. char compressed_buf[kDecompressionBufferSize];
  12993. while (true) {
  12994. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  12995. sizeof(compressed_buf));
  12996. if (n <= 0) { return n; }
  12997. bool decompress_ok = decompressor_->decompress(
  12998. compressed_buf, static_cast<size_t>(n),
  12999. [this](const char *data, size_t data_len) {
  13000. decompress_buffer_.append(data, data_len);
  13001. auto limit = body_reader_.payload_max_length;
  13002. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  13003. return false;
  13004. }
  13005. return true;
  13006. });
  13007. if (!decompress_ok) {
  13008. body_reader_.last_error = Error::Read;
  13009. return -1;
  13010. }
  13011. if (!decompress_buffer_.empty()) { break; }
  13012. }
  13013. auto to_copy = (std::min)(len, decompress_buffer_.size());
  13014. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  13015. decompress_offset_ = to_copy;
  13016. decompressed_bytes_read_ += to_copy;
  13017. return static_cast<ssize_t>(to_copy);
  13018. }
  13019. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  13020. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  13021. return;
  13022. }
  13023. trailers_parsed_ = true;
  13024. const auto bufsiz = 128;
  13025. char line_buf[bufsiz];
  13026. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  13027. if (!line_reader.getline()) { return; }
  13028. if (!detail::parse_trailers(line_reader, response->trailers,
  13029. response->headers)) {
  13030. return;
  13031. }
  13032. }
  13033. namespace detail {
  13034. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  13035. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  13036. size_t &out_chunk_offset,
  13037. size_t &out_chunk_total) {
  13038. if (finished) { return 0; }
  13039. if (chunk_remaining == 0) {
  13040. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  13041. if (!lr.getline()) { return -1; }
  13042. // Everything below is bounded by eol rather than by the buffer's NUL, so
  13043. // the line terminator is never mistaken for line content.
  13044. const char *eol = lr.ptr() + lr.size();
  13045. if (lr.end_with_crlf()) {
  13046. eol -= 2;
  13047. } else if (eol != lr.ptr() && eol[-1] == '\n') {
  13048. // Only reachable under CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR, where
  13049. // getline() ends the line on a bare LF. That LF is the terminator, so it
  13050. // has to come off here or the check below would reject the line.
  13051. eol -= 1;
  13052. }
  13053. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  13054. const char *p = lr.ptr();
  13055. int v = 0;
  13056. if (p == eol || !is_hex(*p, v)) { return -1; }
  13057. size_t chunk_len = 0;
  13058. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  13059. for (; p < eol && is_hex(*p, v); ++p) {
  13060. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  13061. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  13062. }
  13063. while (p < eol && is_space_or_tab(*p)) {
  13064. ++p;
  13065. }
  13066. // RFC 9112 §7.1.1: only a chunk-ext may sit between the size and the line
  13067. // terminator, and it is built from tokens and quoted-strings, so it never
  13068. // holds a CR, LF or any other control character. getline() reads up to the
  13069. // CRLF, so a bare LF left in here would be swallowed as extension text
  13070. // while an intermediary that ends the line on it delimits the chunks
  13071. // differently, and the two disagree on where the body ends (request
  13072. // smuggling).
  13073. if (p < eol && *p != ';') { return -1; }
  13074. for (; p < eol; ++p) {
  13075. if (!is_space_or_tab(*p) && !fields::is_field_vchar(*p)) { return -1; }
  13076. }
  13077. if (chunk_len == 0) {
  13078. chunk_remaining = 0;
  13079. finished = true;
  13080. out_chunk_offset = 0;
  13081. out_chunk_total = 0;
  13082. return 0;
  13083. }
  13084. chunk_remaining = chunk_len;
  13085. last_chunk_total = chunk_remaining;
  13086. last_chunk_offset = 0;
  13087. }
  13088. auto to_read = (std::min)(chunk_remaining, len);
  13089. auto n = strm.read(buf, to_read);
  13090. if (n <= 0) { return -1; }
  13091. auto offset_before = last_chunk_offset;
  13092. last_chunk_offset += static_cast<size_t>(n);
  13093. chunk_remaining -= static_cast<size_t>(n);
  13094. out_chunk_offset = offset_before;
  13095. out_chunk_total = last_chunk_total;
  13096. if (chunk_remaining == 0) {
  13097. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  13098. if (!lr.getline()) { return -1; }
  13099. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  13100. }
  13101. return n;
  13102. }
  13103. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  13104. const Headers &src_headers) {
  13105. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  13106. if (!lr.getline()) { return false; }
  13107. return parse_trailers(lr, dest, src_headers);
  13108. }
  13109. } // namespace detail
  13110. inline void
  13111. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  13112. handle.connection_->sock = socket_.sock;
  13113. #ifdef CPPHTTPLIB_SSL_ENABLED
  13114. handle.connection_->session = socket_.ssl;
  13115. socket_.ssl = nullptr;
  13116. #endif
  13117. socket_.sock = INVALID_SOCKET;
  13118. }
  13119. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  13120. Response &res, bool close_connection,
  13121. Error &error) {
  13122. if (req.path.empty()) {
  13123. error = Error::Connection;
  13124. output_error_log(error, &req);
  13125. return false;
  13126. }
  13127. auto req_save = req;
  13128. bool ret;
  13129. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  13130. auto req2 = req;
  13131. req2.path = "http://" +
  13132. detail::make_host_and_port_string(host_, port_, false) +
  13133. req.path;
  13134. ret = process_request(strm, req2, res, close_connection, error);
  13135. req = std::move(req2);
  13136. req.path = req_save.path;
  13137. } else {
  13138. ret = process_request(strm, req, res, close_connection, error);
  13139. }
  13140. if (!ret) { return false; }
  13141. if (detail::has_header_token(res.headers, "Connection", "close") ||
  13142. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  13143. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  13144. // for this to be safe.
  13145. // This is safe to call because handle_request is only called by send_
  13146. // which locks the request mutex during the process. It would be a bug
  13147. // to call it from a different thread since it's a thread-safety issue
  13148. // to do these things to the socket if another thread is using the socket.
  13149. std::lock_guard<std::mutex> guard(socket_mutex_);
  13150. disconnect(/*gracefully=*/true);
  13151. }
  13152. if (300 < res.status && res.status < 400 && follow_location_) {
  13153. req = std::move(req_save);
  13154. ret = redirect(req, res, error);
  13155. }
  13156. #ifdef CPPHTTPLIB_SSL_ENABLED
  13157. if ((res.status == StatusCode::Unauthorized_401 ||
  13158. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  13159. req.authorization_count_ < 5) {
  13160. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  13161. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  13162. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  13163. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  13164. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  13165. return ret;
  13166. }
  13167. const auto &username =
  13168. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  13169. const auto &password =
  13170. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  13171. if (!username.empty() && !password.empty()) {
  13172. std::map<std::string, std::string> auth;
  13173. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  13174. Request new_req = req;
  13175. new_req.authorization_count_ += 1;
  13176. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  13177. : "Authorization");
  13178. new_req.headers.insert(detail::make_digest_authentication_header(
  13179. req, auth, new_req.authorization_count_, detail::random_string(10),
  13180. username, password, is_proxy));
  13181. Response new_res;
  13182. ret = send(new_req, new_res, error);
  13183. if (ret) { res = std::move(new_res); }
  13184. }
  13185. }
  13186. }
  13187. #endif
  13188. return ret;
  13189. }
  13190. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  13191. if (req.redirect_count_ == 0) {
  13192. error = Error::ExceedRedirectCount;
  13193. output_error_log(error, &req);
  13194. return false;
  13195. }
  13196. auto location = res.get_header_value("location");
  13197. if (location.empty()) { return false; }
  13198. detail::UrlComponents uc;
  13199. if (!detail::parse_url(detail::resolve_relative_location(location, req.path),
  13200. uc)) {
  13201. return false;
  13202. }
  13203. // Only follow http/https redirects
  13204. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  13205. return false;
  13206. }
  13207. auto scheme = is_ssl() ? "https" : "http";
  13208. auto next_scheme = std::move(uc.scheme);
  13209. auto next_host = std::move(uc.host);
  13210. auto port_str = std::move(uc.port);
  13211. auto next_path = std::move(uc.path);
  13212. auto next_query = std::move(uc.query);
  13213. auto next_port = port_;
  13214. if (!port_str.empty()) {
  13215. if (!detail::parse_port(port_str, next_port)) { return false; }
  13216. } else if (!next_scheme.empty()) {
  13217. next_port = next_scheme == "https" ? 443 : 80;
  13218. }
  13219. if (next_scheme.empty()) { next_scheme = scheme; }
  13220. if (next_host.empty()) { next_host = host_; }
  13221. if (next_path.empty()) { next_path = "/"; }
  13222. auto path = decode_path_component(next_path) + next_query;
  13223. // Same host redirect - use current client
  13224. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  13225. return detail::redirect(*this, req, res, path, location, error);
  13226. }
  13227. // Cross-host/scheme redirect - create new client with robust setup
  13228. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  13229. path, location, error);
  13230. }
  13231. // New method for robust redirect client creation
  13232. inline bool ClientImpl::create_redirect_client(
  13233. const std::string &scheme, const std::string &host, int port, Request &req,
  13234. Response &res, const std::string &path, const std::string &location,
  13235. Error &error) {
  13236. // Determine if we need SSL
  13237. auto need_ssl = (scheme == "https");
  13238. // Clean up request headers that are host/client specific
  13239. // Remove headers that should not be carried over to new host
  13240. auto headers_to_remove = std::vector<std::string>{
  13241. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  13242. for (const auto &header_name : headers_to_remove) {
  13243. auto it = req.headers.find(header_name);
  13244. while (it != req.headers.end()) {
  13245. it = req.headers.erase(it);
  13246. it = req.headers.find(header_name);
  13247. }
  13248. }
  13249. // Create appropriate client type and handle redirect
  13250. if (need_ssl) {
  13251. #ifdef CPPHTTPLIB_SSL_ENABLED
  13252. // Create SSL client for HTTPS redirect
  13253. SSLClient redirect_client(host, port);
  13254. // Setup basic client configuration first
  13255. setup_redirect_client(redirect_client);
  13256. redirect_client.enable_server_certificate_verification(
  13257. server_certificate_verification_);
  13258. redirect_client.enable_server_hostname_verification(
  13259. server_hostname_verification_);
  13260. redirect_client.system_ca_mode_ = system_ca_mode_;
  13261. // Transfer CA certificate to redirect client
  13262. if (!ca_cert_pem_.empty()) {
  13263. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  13264. ca_cert_pem_.size());
  13265. }
  13266. if (!ca_cert_file_path_.empty()) {
  13267. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  13268. }
  13269. // Client certificates are set through constructor for SSLClient
  13270. // NOTE: SSLClient constructor already takes client_cert_path and
  13271. // client_key_path so we need to create it properly if client certs are
  13272. // needed
  13273. // Execute the redirect
  13274. return detail::redirect(redirect_client, req, res, path, location, error);
  13275. #else
  13276. // SSL not supported - set appropriate error
  13277. error = Error::SSLConnection;
  13278. output_error_log(error, &req);
  13279. return false;
  13280. #endif
  13281. } else {
  13282. // HTTP redirect
  13283. ClientImpl redirect_client(host, port);
  13284. // Setup client with robust configuration
  13285. setup_redirect_client(redirect_client);
  13286. // Execute the redirect
  13287. return detail::redirect(redirect_client, req, res, path, location, error);
  13288. }
  13289. }
  13290. // New method for robust client setup (based on basic_manual_redirect.cpp
  13291. // logic)
  13292. template <typename ClientType>
  13293. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  13294. // Copy basic settings first
  13295. client.set_connection_timeout(connection_timeout_sec_);
  13296. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  13297. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  13298. client.set_keep_alive(keep_alive_);
  13299. client.set_follow_location(
  13300. true); // Enable redirects to handle multi-step redirects
  13301. client.set_path_encode(path_encode_);
  13302. client.set_compress(compress_);
  13303. client.set_decompress(decompress_);
  13304. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  13305. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  13306. // 15.4, credentials must not be forwarded when redirecting to a different
  13307. // host. This function is only called for cross-host redirects; same-host
  13308. // redirects are handled directly in ClientImpl::redirect().
  13309. // Copy the proxy configuration unconditionally; the per-target bypass is
  13310. // re-evaluated at send time, so a later hop to a non-bypassed host can
  13311. // still use the proxy.
  13312. client.no_proxy_entries_ = no_proxy_entries_;
  13313. if (!proxy_host_.empty() && proxy_port_ != -1) {
  13314. client.set_proxy(proxy_host_, proxy_port_);
  13315. if (!proxy_basic_auth_username_.empty()) {
  13316. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  13317. proxy_basic_auth_password_);
  13318. }
  13319. if (!proxy_bearer_token_auth_token_.empty()) {
  13320. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  13321. }
  13322. #ifdef CPPHTTPLIB_SSL_ENABLED
  13323. if (!proxy_digest_auth_username_.empty()) {
  13324. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  13325. proxy_digest_auth_password_);
  13326. }
  13327. #endif
  13328. }
  13329. // Copy network and socket settings
  13330. client.set_address_family(address_family_);
  13331. client.set_tcp_nodelay(tcp_nodelay_);
  13332. client.set_ipv6_v6only(ipv6_v6only_);
  13333. if (socket_options_) { client.set_socket_options(socket_options_); }
  13334. if (!interface_.empty()) { client.set_interface(interface_); }
  13335. // Copy logging and headers
  13336. if (logger_) { client.set_logger(logger_); }
  13337. if (error_logger_) { client.set_error_logger(error_logger_); }
  13338. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  13339. // Each new client should generate its own headers based on its target host
  13340. }
  13341. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  13342. const Request &req,
  13343. Error &error) const {
  13344. auto is_shutting_down = []() { return false; };
  13345. if (req.is_chunked_content_provider_) {
  13346. auto compressor = compress_ ? detail::create_compressor().first
  13347. : std::unique_ptr<detail::compressor>();
  13348. if (!compressor) {
  13349. compressor = detail::make_unique<detail::nocompressor>();
  13350. }
  13351. return detail::write_content_chunked(strm, req.content_provider_,
  13352. is_shutting_down, *compressor, error);
  13353. } else {
  13354. return detail::write_content_with_progress(
  13355. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  13356. req.upload_progress, error);
  13357. }
  13358. }
  13359. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  13360. bool close_connection, Error &error,
  13361. bool skip_body, bool &rejected_locally) {
  13362. rejected_locally = false;
  13363. // Prepare additional headers
  13364. if (close_connection) {
  13365. if (!req.has_header("Connection")) {
  13366. req.set_header("Connection", "close");
  13367. }
  13368. }
  13369. std::string ct_for_defaults;
  13370. if (!req.has_header("Content-Type") && !req.body.empty()) {
  13371. ct_for_defaults = "text/plain";
  13372. }
  13373. prepare_default_headers(req, false, ct_for_defaults);
  13374. if (req.body.empty()) {
  13375. if (req.content_provider_) {
  13376. if (!req.is_chunked_content_provider_) {
  13377. if (!req.has_header("Content-Length")) {
  13378. auto length = std::to_string(req.content_length_);
  13379. req.set_header("Content-Length", length);
  13380. }
  13381. }
  13382. } else {
  13383. if (req.method == "POST" || req.method == "PUT" ||
  13384. req.method == "PATCH") {
  13385. req.set_header("Content-Length", "0");
  13386. }
  13387. }
  13388. }
  13389. // A CONNECT request is read by the proxy; everything sent through the tunnel
  13390. // it opens is read by the origin. Each credential goes only to its own hop.
  13391. auto is_connect = req.method == "CONNECT";
  13392. if (!is_connect && !req.has_header("Authorization")) {
  13393. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  13394. req.headers.insert(make_basic_authentication_header(
  13395. basic_auth_username_, basic_auth_password_, false));
  13396. } else if (!bearer_token_auth_token_.empty()) {
  13397. req.headers.insert(make_bearer_token_authentication_header(
  13398. bearer_token_auth_token_, false));
  13399. }
  13400. }
  13401. // Proxy-Authorization is only sent when the proxy reads this message —
  13402. // otherwise NO_PROXY-matched requests, and requests inside a TLS tunnel,
  13403. // would leak proxy credentials to the destination server.
  13404. if (is_proxy_enabled_for_host(host_) && (!is_ssl() || is_connect)) {
  13405. if (!proxy_basic_auth_username_.empty() &&
  13406. !proxy_basic_auth_password_.empty() &&
  13407. !req.has_header("Proxy-Authorization")) {
  13408. req.headers.insert(make_basic_authentication_header(
  13409. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  13410. }
  13411. if (!proxy_bearer_token_auth_token_.empty() &&
  13412. !req.has_header("Proxy-Authorization")) {
  13413. req.headers.insert(make_bearer_token_authentication_header(
  13414. proxy_bearer_token_auth_token_, true));
  13415. }
  13416. }
  13417. // Request line and headers
  13418. {
  13419. detail::BufferStream bstrm;
  13420. // Extract the query from req.path. The encoding itself is delegated to
  13421. // `encode_request_target`; the raw query is still needed here to decide
  13422. // between populating `req.params` from it and falling back to building a
  13423. // query out of caller-supplied `req.params`.
  13424. auto query_pos = req.path.find('?');
  13425. auto query_part = query_pos == std::string::npos
  13426. ? std::string()
  13427. : req.path.substr(query_pos + 1);
  13428. auto path_with_query =
  13429. detail::encode_request_target(req.path, path_encode_);
  13430. if (!query_part.empty()) {
  13431. // The query already came in through `req.path`; still populate
  13432. // `req.params` for handlers/users who read them.
  13433. detail::parse_query_text(query_part, req.params);
  13434. } else if (!req.params.empty()) {
  13435. // No query in `req.path`; build one from `req.params` so existing
  13436. // callers that pass `Params` separately continue to work.
  13437. path_with_query = append_query_params(path_with_query, req.params);
  13438. }
  13439. // Write request line and headers
  13440. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  13441. // A rejected method (not a token, e.g. carrying CR/LF) or target (e.g.
  13442. // CR/LF smuggled in via a decoded redirect Location under
  13443. // set_path_encode(false)) must fail the request cleanly instead of
  13444. // emitting a request-line-less, header-injecting request.
  13445. error = Error::Write;
  13446. rejected_locally = true;
  13447. output_error_log(error, &req);
  13448. return false;
  13449. }
  13450. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  13451. error)) {
  13452. rejected_locally = true;
  13453. output_error_log(error, &req);
  13454. return false;
  13455. }
  13456. // Flush buffer
  13457. auto &data = bstrm.get_buffer();
  13458. if (!detail::write_data(strm, data.data(), data.size())) {
  13459. error = Error::Write;
  13460. output_error_log(error, &req);
  13461. return false;
  13462. }
  13463. }
  13464. // After sending request line and headers, wait briefly for an early server
  13465. // response (e.g. 4xx) and avoid sending a potentially large request body
  13466. // unnecessarily. This workaround is only enabled on Windows because Unix
  13467. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  13468. // buffering can accept large writes even when the peer already responded.
  13469. // Check the stream first (which covers SSL via `is_readable()`), then
  13470. // fall back to select on the socket. Only perform the wait for very large
  13471. // request bodies to avoid interfering with normal small requests and
  13472. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  13473. // response. Skip this check when using Expect: 100-continue, as the protocol
  13474. // handles early responses properly.
  13475. #if defined(_WIN32)
  13476. if (!skip_body &&
  13477. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  13478. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  13479. auto start = std::chrono::high_resolution_clock::now();
  13480. for (;;) {
  13481. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  13482. // from SSL internals. If the underlying socket is readable, assume an
  13483. // early response may be present.
  13484. auto sock = strm.socket();
  13485. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  13486. return false;
  13487. }
  13488. // Fallback to stream-level check for non-socket streams or when the
  13489. // socket isn't reporting readable. Avoid using `is_readable()` for
  13490. // SSL, since `SSL_pending()` may report buffered records that do not
  13491. // indicate a complete application-level response yet.
  13492. if (!is_ssl() && strm.is_readable()) { return false; }
  13493. auto now = std::chrono::high_resolution_clock::now();
  13494. auto elapsed =
  13495. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  13496. .count();
  13497. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  13498. break;
  13499. }
  13500. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  13501. }
  13502. }
  13503. #endif
  13504. // Body
  13505. if (skip_body) { return true; }
  13506. return write_request_body(strm, req, error);
  13507. }
  13508. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  13509. Error &error) {
  13510. if (req.body.empty()) {
  13511. return write_content_with_provider(strm, req, error);
  13512. }
  13513. if (req.upload_progress) {
  13514. auto body_size = req.body.size();
  13515. size_t written = 0;
  13516. auto data = req.body.data();
  13517. while (written < body_size) {
  13518. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  13519. if (!detail::write_data(strm, data + written, to_write)) {
  13520. error = Error::Write;
  13521. output_error_log(error, &req);
  13522. return false;
  13523. }
  13524. written += to_write;
  13525. if (!req.upload_progress(written, body_size)) {
  13526. error = Error::Canceled;
  13527. output_error_log(error, &req);
  13528. return false;
  13529. }
  13530. }
  13531. } else {
  13532. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  13533. error = Error::Write;
  13534. output_error_log(error, &req);
  13535. return false;
  13536. }
  13537. }
  13538. return true;
  13539. }
  13540. inline std::unique_ptr<Response>
  13541. ClientImpl::send_with_content_provider_and_receiver(
  13542. Request &req, const char *body, size_t content_length,
  13543. ContentProvider content_provider,
  13544. ContentProviderWithoutLength content_provider_without_length,
  13545. const std::string &content_type, ContentReceiver content_receiver,
  13546. Error &error) {
  13547. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  13548. auto enc = compress_
  13549. ? detail::create_compressor()
  13550. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  13551. nullptr, nullptr);
  13552. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  13553. if (enc.first && !content_provider_without_length) {
  13554. auto &compressor = enc.first;
  13555. if (content_provider) {
  13556. auto ok = true;
  13557. auto finished = false;
  13558. size_t offset = 0;
  13559. DataSink data_sink;
  13560. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  13561. if (ok) {
  13562. auto last = offset + data_len == content_length;
  13563. auto ret = compressor->compress(
  13564. data, data_len, last,
  13565. [&](const char *compressed_data, size_t compressed_data_len) {
  13566. req.body.append(compressed_data, compressed_data_len);
  13567. return true;
  13568. });
  13569. if (ret) {
  13570. offset += data_len;
  13571. } else {
  13572. ok = false;
  13573. }
  13574. }
  13575. return ok;
  13576. };
  13577. // As in detail::write_content_with_progress(): the body is framed by
  13578. // content_length, so a provider that finishes early has truncated it.
  13579. // Stop and report that instead of calling the provider forever.
  13580. data_sink.done = [&]() { finished = true; };
  13581. while (ok && !finished && offset < content_length) {
  13582. if (!content_provider(offset, content_length - offset, data_sink)) {
  13583. error = Error::Canceled;
  13584. output_error_log(error, &req);
  13585. return nullptr;
  13586. }
  13587. }
  13588. // A short body here means either the provider stopped early or the
  13589. // compressor gave up. The branch below reports a failing compressor as
  13590. // Error::Compression, so keep the two distinguishable.
  13591. if (offset < content_length) {
  13592. error = ok ? Error::Write : Error::Compression;
  13593. output_error_log(error, &req);
  13594. return nullptr;
  13595. }
  13596. } else {
  13597. if (!compressor->compress(body, content_length, true,
  13598. [&](const char *data, size_t data_len) {
  13599. req.body.append(data, data_len);
  13600. return true;
  13601. })) {
  13602. error = Error::Compression;
  13603. output_error_log(error, &req);
  13604. return nullptr;
  13605. }
  13606. }
  13607. } else {
  13608. if (content_provider) {
  13609. req.content_length_ = content_length;
  13610. req.content_provider_ = std::move(content_provider);
  13611. req.is_chunked_content_provider_ = false;
  13612. } else if (content_provider_without_length) {
  13613. req.content_length_ = 0;
  13614. req.content_provider_ = detail::ContentProviderAdapter(
  13615. std::move(content_provider_without_length));
  13616. req.is_chunked_content_provider_ = true;
  13617. req.set_header("Transfer-Encoding", "chunked");
  13618. } else {
  13619. req.body.assign(body, content_length);
  13620. }
  13621. }
  13622. if (content_receiver) {
  13623. req.content_receiver =
  13624. [content_receiver](const char *data, size_t data_length,
  13625. size_t /*offset*/, size_t /*total_length*/) {
  13626. return content_receiver(data, data_length);
  13627. };
  13628. }
  13629. auto res = detail::make_unique<Response>();
  13630. return send(req, *res, error) ? std::move(res) : nullptr;
  13631. }
  13632. inline Result ClientImpl::send_with_content_provider_and_receiver(
  13633. const std::string &method, const std::string &path, const Headers &headers,
  13634. const char *body, size_t content_length, ContentProvider content_provider,
  13635. ContentProviderWithoutLength content_provider_without_length,
  13636. const std::string &content_type, ContentReceiver content_receiver,
  13637. UploadProgress progress) {
  13638. Request req;
  13639. req.method = method;
  13640. req.headers = headers;
  13641. req.path = path;
  13642. req.upload_progress = std::move(progress);
  13643. if (max_timeout_msec_ > 0) {
  13644. req.start_time_ = std::chrono::steady_clock::now();
  13645. }
  13646. auto error = Error::Success;
  13647. auto res = send_with_content_provider_and_receiver(
  13648. req, body, content_length, std::move(content_provider),
  13649. std::move(content_provider_without_length), content_type,
  13650. std::move(content_receiver), error);
  13651. #ifdef CPPHTTPLIB_SSL_ENABLED
  13652. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  13653. last_backend_error_};
  13654. #else
  13655. return Result{std::move(res), error, std::move(req.headers)};
  13656. #endif
  13657. }
  13658. inline void ClientImpl::output_log(const Request &req,
  13659. const Response &res) const {
  13660. if (logger_) {
  13661. std::lock_guard<std::mutex> guard(logger_mutex_);
  13662. logger_(req, res);
  13663. }
  13664. }
  13665. inline void ClientImpl::output_error_log(const Error &err,
  13666. const Request *req) const {
  13667. if (error_logger_) {
  13668. std::lock_guard<std::mutex> guard(logger_mutex_);
  13669. error_logger_(err, req);
  13670. }
  13671. }
  13672. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  13673. Response &res, bool close_connection,
  13674. Error &error) {
  13675. // Auto-add Expect: 100-continue for large bodies
  13676. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  13677. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  13678. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  13679. req.set_header("Expect", "100-continue");
  13680. }
  13681. }
  13682. // Check for Expect: 100-continue
  13683. auto expect_100_continue =
  13684. detail::has_header_token(req.headers, "Expect", "100-continue");
  13685. // Send request (skip body if using Expect: 100-continue)
  13686. auto rejected_locally = false;
  13687. auto write_request_success =
  13688. write_request(strm, req, close_connection, error, expect_100_continue,
  13689. rejected_locally);
  13690. // A failed write normally still reads the response below, since the server
  13691. // may have answered early (e.g. 413/414) and closed while the body was being
  13692. // sent. A request rejected before any byte reached the socket gets no such
  13693. // response, and waiting for one would block until the read timeout.
  13694. if (rejected_locally) { return false; }
  13695. #ifdef CPPHTTPLIB_SSL_ENABLED
  13696. if (is_ssl() && !expect_100_continue) {
  13697. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  13698. if (!is_proxy_enabled) {
  13699. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  13700. error = Error::SSLPeerCouldBeClosed_;
  13701. output_error_log(error, &req);
  13702. return false;
  13703. }
  13704. }
  13705. }
  13706. #endif
  13707. // Handle Expect: 100-continue.
  13708. //
  13709. // Wait for an interim/early response by attempting to read the status line
  13710. // under a short timeout, instead of trusting raw socket readability. Over
  13711. // TLS, post-handshake records (e.g. session tickets) make the socket
  13712. // readable without any HTTP response being available; relying on
  13713. // `select_read` there caused the body to be withheld forever and the
  13714. // request to fail with `Read` (#2458). If no status line arrives within the
  13715. // timeout, send the body anyway (matching curl's behavior).
  13716. auto status_line_read = false;
  13717. if (expect_100_continue && write_request_success) {
  13718. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  13719. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  13720. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  13721. strm.set_read_timeout(sec, usec);
  13722. status_line_read = read_response_line(strm, req, res, false);
  13723. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  13724. }
  13725. if (!status_line_read) {
  13726. // No interim response within the timeout: send the body and handle the
  13727. // response as usual.
  13728. if (!write_request_body(strm, req, error)) { return false; }
  13729. expect_100_continue = false; // Switch to normal response handling
  13730. }
  13731. }
  13732. // Receive response and headers
  13733. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  13734. if ((!status_line_read &&
  13735. !read_response_line(strm, req, res, !expect_100_continue)) ||
  13736. !detail::read_headers(strm, res.headers)) {
  13737. if (write_request_success) { error = Error::Read; }
  13738. output_error_log(error, &req);
  13739. return false;
  13740. }
  13741. if (!write_request_success) { return false; }
  13742. // Handle Expect: 100-continue response
  13743. if (expect_100_continue) {
  13744. if (res.status == StatusCode::Continue_100) {
  13745. // Server accepted, send the body
  13746. if (!write_request_body(strm, req, error)) { return false; }
  13747. // Read the actual response
  13748. res.headers.clear();
  13749. res.body.clear();
  13750. if (!read_response_line(strm, req, res) ||
  13751. !detail::read_headers(strm, res.headers)) {
  13752. error = Error::Read;
  13753. output_error_log(error, &req);
  13754. return false;
  13755. }
  13756. }
  13757. // If not 100 Continue, server returned an error; proceed with that response
  13758. }
  13759. // Body
  13760. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  13761. req.method != "CONNECT") {
  13762. // Reject ambiguous framing (RFC 9112 §6.3). Unlike a request, a response
  13763. // whose final transfer coding is not chunked is not ambiguous: its body
  13764. // runs until the server closes the connection, so it is not rejected.
  13765. // HEAD/204 are excluded above and a 304 carries no body.
  13766. if (res.status != StatusCode::NotModified_304 &&
  13767. detail::has_conflicting_content_length(res.headers)) {
  13768. error = Error::Read;
  13769. output_error_log(error, &req);
  13770. return false;
  13771. }
  13772. auto redirect = 300 < res.status && res.status < 400 &&
  13773. res.status != StatusCode::NotModified_304 &&
  13774. follow_location_;
  13775. if (req.response_handler && !redirect) {
  13776. if (!req.response_handler(res)) {
  13777. error = Error::Canceled;
  13778. output_error_log(error, &req);
  13779. return false;
  13780. }
  13781. }
  13782. auto out =
  13783. req.content_receiver
  13784. ? static_cast<ContentReceiverWithProgress>(
  13785. [&](const char *buf, size_t n, size_t off, size_t len) {
  13786. if (redirect) { return true; }
  13787. auto ret = req.content_receiver(buf, n, off, len);
  13788. if (!ret) {
  13789. error = Error::Canceled;
  13790. output_error_log(error, &req);
  13791. }
  13792. return ret;
  13793. })
  13794. : static_cast<ContentReceiverWithProgress>(
  13795. [&](const char *buf, size_t n, size_t /*off*/,
  13796. size_t /*len*/) {
  13797. assert(res.body.size() + n <= res.body.max_size());
  13798. if (payload_max_length_ > 0 &&
  13799. (res.body.size() >= payload_max_length_ ||
  13800. n > payload_max_length_ - res.body.size())) {
  13801. return false;
  13802. }
  13803. res.body.append(buf, n);
  13804. return true;
  13805. });
  13806. auto progress = [&](size_t current, size_t total) {
  13807. if (!req.download_progress || redirect) { return true; }
  13808. auto ret = req.download_progress(current, total);
  13809. if (!ret) {
  13810. error = Error::Canceled;
  13811. output_error_log(error, &req);
  13812. }
  13813. return ret;
  13814. };
  13815. if (res.has_header("Content-Length")) {
  13816. if (!req.content_receiver) {
  13817. auto len = res.get_header_value_u64("Content-Length");
  13818. if (len > res.body.max_size()) {
  13819. error = Error::Read;
  13820. output_error_log(error, &req);
  13821. return false;
  13822. }
  13823. // Cap the reservation by payload_max_length_ to avoid OOM when a
  13824. // hostile or malformed server sends an enormous Content-Length.
  13825. // The actual body read below is bounded by payload_max_length_,
  13826. // so reserving more than that is never useful.
  13827. auto reserve_len = static_cast<size_t>(len);
  13828. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  13829. reserve_len = payload_max_length_;
  13830. }
  13831. res.body.reserve(reserve_len);
  13832. }
  13833. }
  13834. if (res.status != StatusCode::NotModified_304) {
  13835. auto content_status = 0;
  13836. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  13837. ? (std::numeric_limits<size_t>::max)()
  13838. : payload_max_length_;
  13839. if (!detail::read_content(strm, res, max_length, content_status,
  13840. std::move(progress), std::move(out),
  13841. decompress_)) {
  13842. if (error != Error::Canceled) {
  13843. // Tell the caller apart from a plain read failure when the body could
  13844. // not be decoded because of its Content-Encoding.
  13845. switch (content_status) {
  13846. case StatusCode::UnsupportedMediaType_415:
  13847. error = Error::UnsupportedContentEncoding;
  13848. break;
  13849. case StatusCode::InternalServerError_500:
  13850. error = Error::Compression;
  13851. break;
  13852. default: error = Error::Read; break;
  13853. }
  13854. }
  13855. output_error_log(error, &req);
  13856. return false;
  13857. }
  13858. }
  13859. }
  13860. // Log
  13861. output_log(req, res);
  13862. return true;
  13863. }
  13864. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  13865. const std::string &boundary, const UploadFormDataItems &items,
  13866. const FormDataProviderItems &provider_items) const {
  13867. size_t cur_item = 0;
  13868. size_t cur_start = 0;
  13869. // cur_item and cur_start are copied to within the std::function and
  13870. // maintain state between successive calls
  13871. return [&, cur_item, cur_start](size_t offset,
  13872. DataSink &sink) mutable -> bool {
  13873. if (!offset && !items.empty()) {
  13874. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  13875. return true;
  13876. } else if (cur_item < provider_items.size()) {
  13877. if (!cur_start) {
  13878. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  13879. provider_items[cur_item], boundary);
  13880. offset += begin.size();
  13881. cur_start = offset;
  13882. sink.os << begin;
  13883. }
  13884. DataSink cur_sink;
  13885. auto has_data = true;
  13886. cur_sink.write = sink.write;
  13887. // Forward is_writable so a provider item asking whether it may keep
  13888. // going gets the outer sink's answer rather than the default `true`.
  13889. cur_sink.is_writable = sink.is_writable;
  13890. cur_sink.done = [&]() { has_data = false; };
  13891. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  13892. return false;
  13893. }
  13894. if (!has_data) {
  13895. sink.os << detail::serialize_multipart_formdata_item_end();
  13896. cur_item++;
  13897. cur_start = 0;
  13898. }
  13899. return true;
  13900. } else {
  13901. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  13902. sink.done();
  13903. return true;
  13904. }
  13905. };
  13906. }
  13907. inline bool ClientImpl::process_socket(
  13908. const Socket &socket,
  13909. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13910. std::function<bool(Stream &strm)> callback) {
  13911. return detail::process_client_socket(
  13912. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13913. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  13914. }
  13915. inline bool ClientImpl::is_ssl() const { return false; }
  13916. inline Result ClientImpl::Get(const std::string &path,
  13917. DownloadProgress progress) {
  13918. return Get(path, Headers(), std::move(progress));
  13919. }
  13920. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13921. DownloadProgress progress) {
  13922. return Get(path, params, Headers(), std::move(progress));
  13923. }
  13924. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13925. const Headers &headers,
  13926. DownloadProgress progress) {
  13927. if (params.empty()) { return Get(path, headers); }
  13928. std::string path_with_query = append_query_params(path, params);
  13929. return Get(path_with_query, headers, std::move(progress));
  13930. }
  13931. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13932. DownloadProgress progress) {
  13933. Request req;
  13934. req.method = "GET";
  13935. req.path = path;
  13936. req.headers = headers;
  13937. req.download_progress = std::move(progress);
  13938. if (max_timeout_msec_ > 0) {
  13939. req.start_time_ = std::chrono::steady_clock::now();
  13940. }
  13941. return send_(std::move(req));
  13942. }
  13943. inline Result ClientImpl::Get(const std::string &path,
  13944. ContentReceiver content_receiver,
  13945. DownloadProgress progress) {
  13946. return Get(path, Headers(), nullptr, std::move(content_receiver),
  13947. std::move(progress));
  13948. }
  13949. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13950. ContentReceiver content_receiver,
  13951. DownloadProgress progress) {
  13952. return Get(path, headers, nullptr, std::move(content_receiver),
  13953. std::move(progress));
  13954. }
  13955. inline Result ClientImpl::Get(const std::string &path,
  13956. ResponseHandler response_handler,
  13957. ContentReceiver content_receiver,
  13958. DownloadProgress progress) {
  13959. return Get(path, Headers(), std::move(response_handler),
  13960. std::move(content_receiver), std::move(progress));
  13961. }
  13962. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  13963. ResponseHandler response_handler,
  13964. ContentReceiver content_receiver,
  13965. DownloadProgress progress) {
  13966. Request req;
  13967. req.method = "GET";
  13968. req.path = path;
  13969. req.headers = headers;
  13970. req.response_handler = std::move(response_handler);
  13971. req.content_receiver =
  13972. [content_receiver](const char *data, size_t data_length,
  13973. size_t /*offset*/, size_t /*total_length*/) {
  13974. return content_receiver(data, data_length);
  13975. };
  13976. req.download_progress = std::move(progress);
  13977. if (max_timeout_msec_ > 0) {
  13978. req.start_time_ = std::chrono::steady_clock::now();
  13979. }
  13980. return send_(std::move(req));
  13981. }
  13982. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13983. const Headers &headers,
  13984. ContentReceiver content_receiver,
  13985. DownloadProgress progress) {
  13986. return Get(path, params, headers, nullptr, std::move(content_receiver),
  13987. std::move(progress));
  13988. }
  13989. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  13990. const Headers &headers,
  13991. ResponseHandler response_handler,
  13992. ContentReceiver content_receiver,
  13993. DownloadProgress progress) {
  13994. if (params.empty()) {
  13995. return Get(path, headers, std::move(response_handler),
  13996. std::move(content_receiver), std::move(progress));
  13997. }
  13998. std::string path_with_query = append_query_params(path, params);
  13999. return Get(path_with_query, headers, std::move(response_handler),
  14000. std::move(content_receiver), std::move(progress));
  14001. }
  14002. inline Result ClientImpl::Head(const std::string &path) {
  14003. return Head(path, Headers());
  14004. }
  14005. inline Result ClientImpl::Head(const std::string &path,
  14006. const Headers &headers) {
  14007. Request req;
  14008. req.method = "HEAD";
  14009. req.headers = headers;
  14010. req.path = path;
  14011. if (max_timeout_msec_ > 0) {
  14012. req.start_time_ = std::chrono::steady_clock::now();
  14013. }
  14014. return send_(std::move(req));
  14015. }
  14016. inline Result ClientImpl::Post(const std::string &path) {
  14017. return Post(path, std::string(), std::string());
  14018. }
  14019. inline Result ClientImpl::Post(const std::string &path,
  14020. const Headers &headers) {
  14021. return Post(path, headers, nullptr, 0, std::string());
  14022. }
  14023. inline Result ClientImpl::Post(const std::string &path, const char *body,
  14024. size_t content_length,
  14025. const std::string &content_type,
  14026. UploadProgress progress) {
  14027. return Post(path, Headers(), body, content_length, content_type, progress);
  14028. }
  14029. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  14030. const std::string &content_type,
  14031. UploadProgress progress) {
  14032. return Post(path, Headers(), body, content_type, progress);
  14033. }
  14034. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  14035. return Post(path, Headers(), params);
  14036. }
  14037. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  14038. ContentProvider content_provider,
  14039. const std::string &content_type,
  14040. UploadProgress progress) {
  14041. return Post(path, Headers(), content_length, std::move(content_provider),
  14042. content_type, progress);
  14043. }
  14044. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  14045. ContentProvider content_provider,
  14046. const std::string &content_type,
  14047. ContentReceiver content_receiver,
  14048. UploadProgress progress) {
  14049. return Post(path, Headers(), content_length, std::move(content_provider),
  14050. content_type, std::move(content_receiver), progress);
  14051. }
  14052. inline Result ClientImpl::Post(const std::string &path,
  14053. ContentProviderWithoutLength content_provider,
  14054. const std::string &content_type,
  14055. UploadProgress progress) {
  14056. return Post(path, Headers(), std::move(content_provider), content_type,
  14057. progress);
  14058. }
  14059. inline Result ClientImpl::Post(const std::string &path,
  14060. ContentProviderWithoutLength content_provider,
  14061. const std::string &content_type,
  14062. ContentReceiver content_receiver,
  14063. UploadProgress progress) {
  14064. return Post(path, Headers(), std::move(content_provider), content_type,
  14065. std::move(content_receiver), progress);
  14066. }
  14067. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14068. const Params &params) {
  14069. auto query = detail::params_to_query_str(params);
  14070. return Post(path, headers, query, "application/x-www-form-urlencoded");
  14071. }
  14072. inline Result ClientImpl::Post(const std::string &path,
  14073. const UploadFormDataItems &items,
  14074. UploadProgress progress) {
  14075. return Post(path, Headers(), items, progress);
  14076. }
  14077. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14078. const UploadFormDataItems &items,
  14079. UploadProgress progress) {
  14080. const auto &boundary = detail::make_multipart_data_boundary();
  14081. const auto &content_type =
  14082. detail::serialize_multipart_formdata_get_content_type(boundary);
  14083. auto content_length = detail::get_multipart_content_length(items, boundary);
  14084. return Post(path, headers, content_length,
  14085. detail::make_multipart_content_provider(items, boundary),
  14086. content_type, progress);
  14087. }
  14088. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14089. const UploadFormDataItems &items,
  14090. const std::string &boundary,
  14091. UploadProgress progress) {
  14092. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14093. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14094. }
  14095. const auto &content_type =
  14096. detail::serialize_multipart_formdata_get_content_type(boundary);
  14097. auto content_length = detail::get_multipart_content_length(items, boundary);
  14098. return Post(path, headers, content_length,
  14099. detail::make_multipart_content_provider(items, boundary),
  14100. content_type, progress);
  14101. }
  14102. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14103. const char *body, size_t content_length,
  14104. const std::string &content_type,
  14105. UploadProgress progress) {
  14106. return send_with_content_provider_and_receiver(
  14107. "POST", path, headers, body, content_length, nullptr, nullptr,
  14108. content_type, nullptr, progress);
  14109. }
  14110. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14111. const std::string &body,
  14112. const std::string &content_type,
  14113. UploadProgress progress) {
  14114. return send_with_content_provider_and_receiver(
  14115. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  14116. content_type, nullptr, progress);
  14117. }
  14118. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14119. size_t content_length,
  14120. ContentProvider content_provider,
  14121. const std::string &content_type,
  14122. UploadProgress progress) {
  14123. return send_with_content_provider_and_receiver(
  14124. "POST", path, headers, nullptr, content_length,
  14125. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14126. }
  14127. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14128. size_t content_length,
  14129. ContentProvider content_provider,
  14130. const std::string &content_type,
  14131. ContentReceiver content_receiver,
  14132. DownloadProgress progress) {
  14133. return send_with_content_provider_and_receiver(
  14134. "POST", path, headers, nullptr, content_length,
  14135. std::move(content_provider), nullptr, content_type,
  14136. std::move(content_receiver), std::move(progress));
  14137. }
  14138. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14139. ContentProviderWithoutLength content_provider,
  14140. const std::string &content_type,
  14141. UploadProgress progress) {
  14142. return send_with_content_provider_and_receiver(
  14143. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14144. content_type, nullptr, progress);
  14145. }
  14146. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14147. ContentProviderWithoutLength content_provider,
  14148. const std::string &content_type,
  14149. ContentReceiver content_receiver,
  14150. DownloadProgress progress) {
  14151. return send_with_content_provider_and_receiver(
  14152. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14153. content_type, std::move(content_receiver), std::move(progress));
  14154. }
  14155. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14156. const UploadFormDataItems &items,
  14157. const FormDataProviderItems &provider_items,
  14158. UploadProgress progress) {
  14159. const auto &boundary = detail::make_multipart_data_boundary();
  14160. const auto &content_type =
  14161. detail::serialize_multipart_formdata_get_content_type(boundary);
  14162. return send_with_content_provider_and_receiver(
  14163. "POST", path, headers, nullptr, 0, nullptr,
  14164. get_multipart_content_provider(boundary, items, provider_items),
  14165. content_type, nullptr, progress);
  14166. }
  14167. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  14168. const std::string &body,
  14169. const std::string &content_type,
  14170. ContentReceiver content_receiver,
  14171. DownloadProgress progress) {
  14172. Request req;
  14173. req.method = "POST";
  14174. req.path = path;
  14175. req.headers = headers;
  14176. req.body = body;
  14177. req.content_receiver =
  14178. [content_receiver](const char *data, size_t data_length,
  14179. size_t /*offset*/, size_t /*total_length*/) {
  14180. return content_receiver(data, data_length);
  14181. };
  14182. req.download_progress = std::move(progress);
  14183. if (max_timeout_msec_ > 0) {
  14184. req.start_time_ = std::chrono::steady_clock::now();
  14185. }
  14186. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14187. return send_(std::move(req));
  14188. }
  14189. inline Result ClientImpl::Put(const std::string &path) {
  14190. return Put(path, std::string(), std::string());
  14191. }
  14192. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  14193. return Put(path, headers, nullptr, 0, std::string());
  14194. }
  14195. inline Result ClientImpl::Put(const std::string &path, const char *body,
  14196. size_t content_length,
  14197. const std::string &content_type,
  14198. UploadProgress progress) {
  14199. return Put(path, Headers(), body, content_length, content_type, progress);
  14200. }
  14201. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  14202. const std::string &content_type,
  14203. UploadProgress progress) {
  14204. return Put(path, Headers(), body, content_type, progress);
  14205. }
  14206. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  14207. return Put(path, Headers(), params);
  14208. }
  14209. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  14210. ContentProvider content_provider,
  14211. const std::string &content_type,
  14212. UploadProgress progress) {
  14213. return Put(path, Headers(), content_length, std::move(content_provider),
  14214. content_type, progress);
  14215. }
  14216. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  14217. ContentProvider content_provider,
  14218. const std::string &content_type,
  14219. ContentReceiver content_receiver,
  14220. UploadProgress progress) {
  14221. return Put(path, Headers(), content_length, std::move(content_provider),
  14222. content_type, std::move(content_receiver), progress);
  14223. }
  14224. inline Result ClientImpl::Put(const std::string &path,
  14225. ContentProviderWithoutLength content_provider,
  14226. const std::string &content_type,
  14227. UploadProgress progress) {
  14228. return Put(path, Headers(), std::move(content_provider), content_type,
  14229. progress);
  14230. }
  14231. inline Result ClientImpl::Put(const std::string &path,
  14232. ContentProviderWithoutLength content_provider,
  14233. const std::string &content_type,
  14234. ContentReceiver content_receiver,
  14235. UploadProgress progress) {
  14236. return Put(path, Headers(), std::move(content_provider), content_type,
  14237. std::move(content_receiver), progress);
  14238. }
  14239. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14240. const Params &params) {
  14241. auto query = detail::params_to_query_str(params);
  14242. return Put(path, headers, query, "application/x-www-form-urlencoded");
  14243. }
  14244. inline Result ClientImpl::Put(const std::string &path,
  14245. const UploadFormDataItems &items,
  14246. UploadProgress progress) {
  14247. return Put(path, Headers(), items, progress);
  14248. }
  14249. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14250. const UploadFormDataItems &items,
  14251. UploadProgress progress) {
  14252. const auto &boundary = detail::make_multipart_data_boundary();
  14253. const auto &content_type =
  14254. detail::serialize_multipart_formdata_get_content_type(boundary);
  14255. auto content_length = detail::get_multipart_content_length(items, boundary);
  14256. return Put(path, headers, content_length,
  14257. detail::make_multipart_content_provider(items, boundary),
  14258. content_type, progress);
  14259. }
  14260. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14261. const UploadFormDataItems &items,
  14262. const std::string &boundary,
  14263. UploadProgress progress) {
  14264. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14265. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14266. }
  14267. const auto &content_type =
  14268. detail::serialize_multipart_formdata_get_content_type(boundary);
  14269. auto content_length = detail::get_multipart_content_length(items, boundary);
  14270. return Put(path, headers, content_length,
  14271. detail::make_multipart_content_provider(items, boundary),
  14272. content_type, progress);
  14273. }
  14274. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14275. const char *body, size_t content_length,
  14276. const std::string &content_type,
  14277. UploadProgress progress) {
  14278. return send_with_content_provider_and_receiver(
  14279. "PUT", path, headers, body, content_length, nullptr, nullptr,
  14280. content_type, nullptr, progress);
  14281. }
  14282. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14283. const std::string &body,
  14284. const std::string &content_type,
  14285. UploadProgress progress) {
  14286. return send_with_content_provider_and_receiver(
  14287. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  14288. content_type, nullptr, progress);
  14289. }
  14290. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14291. size_t content_length,
  14292. ContentProvider content_provider,
  14293. const std::string &content_type,
  14294. UploadProgress progress) {
  14295. return send_with_content_provider_and_receiver(
  14296. "PUT", path, headers, nullptr, content_length,
  14297. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14298. }
  14299. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14300. size_t content_length,
  14301. ContentProvider content_provider,
  14302. const std::string &content_type,
  14303. ContentReceiver content_receiver,
  14304. UploadProgress progress) {
  14305. return send_with_content_provider_and_receiver(
  14306. "PUT", path, headers, nullptr, content_length,
  14307. std::move(content_provider), nullptr, content_type,
  14308. std::move(content_receiver), progress);
  14309. }
  14310. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14311. ContentProviderWithoutLength content_provider,
  14312. const std::string &content_type,
  14313. UploadProgress progress) {
  14314. return send_with_content_provider_and_receiver(
  14315. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14316. content_type, nullptr, progress);
  14317. }
  14318. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14319. ContentProviderWithoutLength content_provider,
  14320. const std::string &content_type,
  14321. ContentReceiver content_receiver,
  14322. UploadProgress progress) {
  14323. return send_with_content_provider_and_receiver(
  14324. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14325. content_type, std::move(content_receiver), progress);
  14326. }
  14327. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14328. const UploadFormDataItems &items,
  14329. const FormDataProviderItems &provider_items,
  14330. UploadProgress progress) {
  14331. const auto &boundary = detail::make_multipart_data_boundary();
  14332. const auto &content_type =
  14333. detail::serialize_multipart_formdata_get_content_type(boundary);
  14334. return send_with_content_provider_and_receiver(
  14335. "PUT", path, headers, nullptr, 0, nullptr,
  14336. get_multipart_content_provider(boundary, items, provider_items),
  14337. content_type, nullptr, progress);
  14338. }
  14339. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  14340. const std::string &body,
  14341. const std::string &content_type,
  14342. ContentReceiver content_receiver,
  14343. DownloadProgress progress) {
  14344. Request req;
  14345. req.method = "PUT";
  14346. req.path = path;
  14347. req.headers = headers;
  14348. req.body = body;
  14349. req.content_receiver =
  14350. [content_receiver](const char *data, size_t data_length,
  14351. size_t /*offset*/, size_t /*total_length*/) {
  14352. return content_receiver(data, data_length);
  14353. };
  14354. req.download_progress = std::move(progress);
  14355. if (max_timeout_msec_ > 0) {
  14356. req.start_time_ = std::chrono::steady_clock::now();
  14357. }
  14358. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14359. return send_(std::move(req));
  14360. }
  14361. inline Result ClientImpl::Patch(const std::string &path) {
  14362. return Patch(path, std::string(), std::string());
  14363. }
  14364. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14365. UploadProgress progress) {
  14366. return Patch(path, headers, nullptr, 0, std::string(), progress);
  14367. }
  14368. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  14369. size_t content_length,
  14370. const std::string &content_type,
  14371. UploadProgress progress) {
  14372. return Patch(path, Headers(), body, content_length, content_type, progress);
  14373. }
  14374. inline Result ClientImpl::Patch(const std::string &path,
  14375. const std::string &body,
  14376. const std::string &content_type,
  14377. UploadProgress progress) {
  14378. return Patch(path, Headers(), body, content_type, progress);
  14379. }
  14380. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  14381. return Patch(path, Headers(), params);
  14382. }
  14383. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  14384. ContentProvider content_provider,
  14385. const std::string &content_type,
  14386. UploadProgress progress) {
  14387. return Patch(path, Headers(), content_length, std::move(content_provider),
  14388. content_type, progress);
  14389. }
  14390. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  14391. ContentProvider content_provider,
  14392. const std::string &content_type,
  14393. ContentReceiver content_receiver,
  14394. UploadProgress progress) {
  14395. return Patch(path, Headers(), content_length, std::move(content_provider),
  14396. content_type, std::move(content_receiver), progress);
  14397. }
  14398. inline Result ClientImpl::Patch(const std::string &path,
  14399. ContentProviderWithoutLength content_provider,
  14400. const std::string &content_type,
  14401. UploadProgress progress) {
  14402. return Patch(path, Headers(), std::move(content_provider), content_type,
  14403. progress);
  14404. }
  14405. inline Result ClientImpl::Patch(const std::string &path,
  14406. ContentProviderWithoutLength content_provider,
  14407. const std::string &content_type,
  14408. ContentReceiver content_receiver,
  14409. UploadProgress progress) {
  14410. return Patch(path, Headers(), std::move(content_provider), content_type,
  14411. std::move(content_receiver), progress);
  14412. }
  14413. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14414. const Params &params) {
  14415. auto query = detail::params_to_query_str(params);
  14416. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  14417. }
  14418. inline Result ClientImpl::Patch(const std::string &path,
  14419. const UploadFormDataItems &items,
  14420. UploadProgress progress) {
  14421. return Patch(path, Headers(), items, progress);
  14422. }
  14423. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14424. const UploadFormDataItems &items,
  14425. UploadProgress progress) {
  14426. const auto &boundary = detail::make_multipart_data_boundary();
  14427. const auto &content_type =
  14428. detail::serialize_multipart_formdata_get_content_type(boundary);
  14429. auto content_length = detail::get_multipart_content_length(items, boundary);
  14430. return Patch(path, headers, content_length,
  14431. detail::make_multipart_content_provider(items, boundary),
  14432. content_type, progress);
  14433. }
  14434. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14435. const UploadFormDataItems &items,
  14436. const std::string &boundary,
  14437. UploadProgress progress) {
  14438. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  14439. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  14440. }
  14441. const auto &content_type =
  14442. detail::serialize_multipart_formdata_get_content_type(boundary);
  14443. auto content_length = detail::get_multipart_content_length(items, boundary);
  14444. return Patch(path, headers, content_length,
  14445. detail::make_multipart_content_provider(items, boundary),
  14446. content_type, progress);
  14447. }
  14448. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14449. const char *body, size_t content_length,
  14450. const std::string &content_type,
  14451. UploadProgress progress) {
  14452. return send_with_content_provider_and_receiver(
  14453. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  14454. content_type, nullptr, progress);
  14455. }
  14456. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14457. const std::string &body,
  14458. const std::string &content_type,
  14459. UploadProgress progress) {
  14460. return send_with_content_provider_and_receiver(
  14461. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  14462. content_type, nullptr, progress);
  14463. }
  14464. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14465. size_t content_length,
  14466. ContentProvider content_provider,
  14467. const std::string &content_type,
  14468. UploadProgress progress) {
  14469. return send_with_content_provider_and_receiver(
  14470. "PATCH", path, headers, nullptr, content_length,
  14471. std::move(content_provider), nullptr, content_type, nullptr, progress);
  14472. }
  14473. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14474. size_t content_length,
  14475. ContentProvider content_provider,
  14476. const std::string &content_type,
  14477. ContentReceiver content_receiver,
  14478. UploadProgress progress) {
  14479. return send_with_content_provider_and_receiver(
  14480. "PATCH", path, headers, nullptr, content_length,
  14481. std::move(content_provider), nullptr, content_type,
  14482. std::move(content_receiver), progress);
  14483. }
  14484. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14485. ContentProviderWithoutLength content_provider,
  14486. const std::string &content_type,
  14487. UploadProgress progress) {
  14488. return send_with_content_provider_and_receiver(
  14489. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14490. content_type, nullptr, progress);
  14491. }
  14492. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14493. ContentProviderWithoutLength content_provider,
  14494. const std::string &content_type,
  14495. ContentReceiver content_receiver,
  14496. UploadProgress progress) {
  14497. return send_with_content_provider_and_receiver(
  14498. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  14499. content_type, std::move(content_receiver), progress);
  14500. }
  14501. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14502. const UploadFormDataItems &items,
  14503. const FormDataProviderItems &provider_items,
  14504. UploadProgress progress) {
  14505. const auto &boundary = detail::make_multipart_data_boundary();
  14506. const auto &content_type =
  14507. detail::serialize_multipart_formdata_get_content_type(boundary);
  14508. return send_with_content_provider_and_receiver(
  14509. "PATCH", path, headers, nullptr, 0, nullptr,
  14510. get_multipart_content_provider(boundary, items, provider_items),
  14511. content_type, nullptr, progress);
  14512. }
  14513. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  14514. const std::string &body,
  14515. const std::string &content_type,
  14516. ContentReceiver content_receiver,
  14517. DownloadProgress progress) {
  14518. Request req;
  14519. req.method = "PATCH";
  14520. req.path = path;
  14521. req.headers = headers;
  14522. req.body = body;
  14523. req.content_receiver =
  14524. [content_receiver](const char *data, size_t data_length,
  14525. size_t /*offset*/, size_t /*total_length*/) {
  14526. return content_receiver(data, data_length);
  14527. };
  14528. req.download_progress = std::move(progress);
  14529. if (max_timeout_msec_ > 0) {
  14530. req.start_time_ = std::chrono::steady_clock::now();
  14531. }
  14532. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14533. return send_(std::move(req));
  14534. }
  14535. inline Result ClientImpl::Delete(const std::string &path,
  14536. DownloadProgress progress) {
  14537. return Delete(path, Headers(), std::string(), std::string(), progress);
  14538. }
  14539. inline Result ClientImpl::Delete(const std::string &path,
  14540. const Headers &headers,
  14541. DownloadProgress progress) {
  14542. return Delete(path, headers, std::string(), std::string(), progress);
  14543. }
  14544. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  14545. size_t content_length,
  14546. const std::string &content_type,
  14547. DownloadProgress progress) {
  14548. return Delete(path, Headers(), body, content_length, content_type, progress);
  14549. }
  14550. inline Result ClientImpl::Delete(const std::string &path,
  14551. const std::string &body,
  14552. const std::string &content_type,
  14553. DownloadProgress progress) {
  14554. return Delete(path, Headers(), body.data(), body.size(), content_type,
  14555. progress);
  14556. }
  14557. inline Result ClientImpl::Delete(const std::string &path,
  14558. const Headers &headers,
  14559. const std::string &body,
  14560. const std::string &content_type,
  14561. DownloadProgress progress) {
  14562. return Delete(path, headers, body.data(), body.size(), content_type,
  14563. progress);
  14564. }
  14565. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  14566. DownloadProgress progress) {
  14567. return Delete(path, Headers(), params, progress);
  14568. }
  14569. inline Result ClientImpl::Delete(const std::string &path,
  14570. const Headers &headers, const Params &params,
  14571. DownloadProgress progress) {
  14572. auto query = detail::params_to_query_str(params);
  14573. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  14574. progress);
  14575. }
  14576. inline Result ClientImpl::Delete(const std::string &path,
  14577. const Headers &headers, const char *body,
  14578. size_t content_length,
  14579. const std::string &content_type,
  14580. DownloadProgress progress) {
  14581. Request req;
  14582. req.method = "DELETE";
  14583. req.headers = headers;
  14584. req.path = path;
  14585. req.download_progress = std::move(progress);
  14586. if (max_timeout_msec_ > 0) {
  14587. req.start_time_ = std::chrono::steady_clock::now();
  14588. }
  14589. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  14590. req.body.assign(body, content_length);
  14591. return send_(std::move(req));
  14592. }
  14593. inline Result ClientImpl::Options(const std::string &path) {
  14594. return Options(path, Headers());
  14595. }
  14596. inline Result ClientImpl::Options(const std::string &path,
  14597. const Headers &headers) {
  14598. Request req;
  14599. req.method = "OPTIONS";
  14600. req.headers = headers;
  14601. req.path = path;
  14602. if (max_timeout_msec_ > 0) {
  14603. req.start_time_ = std::chrono::steady_clock::now();
  14604. }
  14605. return send_(std::move(req));
  14606. }
  14607. inline void ClientImpl::stop() {
  14608. std::lock_guard<std::mutex> guard(socket_mutex_);
  14609. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  14610. // do is to shutdown_socket, so that threads using this socket suddenly
  14611. // discover they can't read/write any more and error out. Everything else
  14612. // (closing the socket, shutting ssl down) is unsafe because these actions
  14613. // are not thread-safe.
  14614. if (socket_requests_in_flight_ > 0) {
  14615. shutdown_socket(socket_);
  14616. // Aside from that, we set a flag for the socket to be closed when we're
  14617. // done.
  14618. socket_should_be_closed_when_request_is_done_ = true;
  14619. return;
  14620. }
  14621. disconnect(/*gracefully=*/true);
  14622. }
  14623. inline std::string ClientImpl::host() const { return host_; }
  14624. inline int ClientImpl::port() const { return port_; }
  14625. inline size_t ClientImpl::is_socket_open() const {
  14626. std::lock_guard<std::mutex> guard(socket_mutex_);
  14627. return socket_.is_open();
  14628. }
  14629. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  14630. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  14631. connection_timeout_sec_ = sec;
  14632. connection_timeout_usec_ = usec;
  14633. }
  14634. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  14635. read_timeout_sec_ = sec;
  14636. read_timeout_usec_ = usec;
  14637. }
  14638. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  14639. write_timeout_sec_ = sec;
  14640. write_timeout_usec_ = usec;
  14641. }
  14642. inline void ClientImpl::set_max_timeout(time_t msec) {
  14643. max_timeout_msec_ = msec;
  14644. }
  14645. inline void ClientImpl::set_basic_auth(const std::string &username,
  14646. const std::string &password) {
  14647. basic_auth_username_ = username;
  14648. basic_auth_password_ = password;
  14649. }
  14650. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  14651. bearer_token_auth_token_ = token;
  14652. }
  14653. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  14654. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  14655. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  14656. inline void
  14657. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14658. addr_map_ = std::move(addr_map);
  14659. }
  14660. inline void ClientImpl::set_default_headers(Headers headers) {
  14661. default_headers_ = std::move(headers);
  14662. }
  14663. inline void ClientImpl::set_header_writer(
  14664. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14665. header_writer_ = writer;
  14666. }
  14667. inline void ClientImpl::set_address_family(int family) {
  14668. address_family_ = family;
  14669. }
  14670. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  14671. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  14672. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  14673. socket_options_ = std::move(socket_options);
  14674. }
  14675. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  14676. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  14677. inline void ClientImpl::set_payload_max_length(size_t length) {
  14678. payload_max_length_ = length;
  14679. has_payload_max_length_ = true;
  14680. }
  14681. inline void ClientImpl::set_interface(const std::string &intf) {
  14682. interface_ = intf;
  14683. }
  14684. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  14685. proxy_host_ = host;
  14686. proxy_port_ = port;
  14687. std::lock_guard<std::mutex> guard(socket_mutex_);
  14688. disconnect(/*gracefully=*/true);
  14689. }
  14690. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  14691. const std::string &password) {
  14692. proxy_basic_auth_username_ = username;
  14693. proxy_basic_auth_password_ = password;
  14694. }
  14695. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  14696. proxy_bearer_token_auth_token_ = token;
  14697. }
  14698. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  14699. std::vector<detail::NoProxyEntry> parsed;
  14700. parsed.reserve(patterns.size());
  14701. for (const auto &p : patterns) {
  14702. auto trimmed = detail::trim_copy(p);
  14703. if (trimmed.empty()) { continue; }
  14704. detail::NoProxyEntry entry;
  14705. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  14706. parsed.push_back(std::move(entry));
  14707. }
  14708. }
  14709. no_proxy_entries_ = std::move(parsed);
  14710. std::lock_guard<std::mutex> guard(socket_mutex_);
  14711. disconnect(/*gracefully=*/true);
  14712. }
  14713. #ifdef CPPHTTPLIB_SSL_ENABLED
  14714. inline void ClientImpl::set_digest_auth(const std::string &username,
  14715. const std::string &password) {
  14716. digest_auth_username_ = username;
  14717. digest_auth_password_ = password;
  14718. }
  14719. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  14720. const std::string &ca_cert_dir_path) {
  14721. ca_cert_file_path_ = ca_cert_file_path;
  14722. ca_cert_dir_path_ = ca_cert_dir_path;
  14723. }
  14724. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  14725. const std::string &password) {
  14726. proxy_digest_auth_username_ = username;
  14727. proxy_digest_auth_password_ = password;
  14728. }
  14729. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  14730. server_certificate_verification_ = enabled;
  14731. }
  14732. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  14733. server_hostname_verification_ = enabled;
  14734. }
  14735. inline void ClientImpl::enable_system_ca(bool enabled) {
  14736. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  14737. }
  14738. #endif
  14739. inline void ClientImpl::set_logger(Logger logger) {
  14740. logger_ = std::move(logger);
  14741. }
  14742. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  14743. error_logger_ = std::move(error_logger);
  14744. }
  14745. /*
  14746. * SSL/TLS Common Implementation
  14747. */
  14748. inline ClientConnection::~ClientConnection() {
  14749. #ifdef CPPHTTPLIB_SSL_ENABLED
  14750. if (session) {
  14751. tls::shutdown(session, true);
  14752. tls::free_session(session);
  14753. session = nullptr;
  14754. }
  14755. #endif
  14756. if (sock != INVALID_SOCKET) {
  14757. detail::close_socket(sock);
  14758. sock = INVALID_SOCKET;
  14759. }
  14760. }
  14761. // Universal client implementation
  14762. inline Client::Client(const std::string &scheme_host_port)
  14763. : Client(scheme_host_port, std::string(), std::string()) {}
  14764. inline Client::Client(const std::string &scheme_host_port,
  14765. const std::string &client_cert_path,
  14766. const std::string &client_key_path) {
  14767. detail::UrlComponents uc;
  14768. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  14769. auto &scheme = uc.scheme;
  14770. #ifdef CPPHTTPLIB_SSL_ENABLED
  14771. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  14772. #else
  14773. if (!scheme.empty() && scheme != "http") {
  14774. #endif
  14775. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14776. std::string msg = "'" + scheme + "' scheme is not supported.";
  14777. throw std::invalid_argument(msg);
  14778. #endif
  14779. return;
  14780. }
  14781. auto is_ssl = scheme == "https";
  14782. auto host = std::move(uc.host);
  14783. auto port = is_ssl ? 443 : 80;
  14784. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  14785. if (is_ssl) {
  14786. #ifdef CPPHTTPLIB_SSL_ENABLED
  14787. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  14788. client_key_path);
  14789. is_ssl_ = is_ssl;
  14790. #endif
  14791. } else {
  14792. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  14793. client_key_path);
  14794. }
  14795. } else {
  14796. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  14797. // if port param below changes.
  14798. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  14799. client_cert_path, client_key_path);
  14800. }
  14801. }
  14802. inline Client::Client(const std::string &host, int port)
  14803. : Client(host, port, std::string(), std::string()) {}
  14804. inline Client::Client(const std::string &host, int port,
  14805. const std::string &client_cert_path,
  14806. const std::string &client_key_path)
  14807. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  14808. client_key_path)) {}
  14809. inline Client::~Client() = default;
  14810. inline bool Client::is_valid() const {
  14811. return cli_ != nullptr && cli_->is_valid();
  14812. }
  14813. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  14814. return cli_->Get(path, std::move(progress));
  14815. }
  14816. inline Result Client::Get(const std::string &path, const Headers &headers,
  14817. DownloadProgress progress) {
  14818. return cli_->Get(path, headers, std::move(progress));
  14819. }
  14820. inline Result Client::Get(const std::string &path,
  14821. ContentReceiver content_receiver,
  14822. DownloadProgress progress) {
  14823. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  14824. }
  14825. inline Result Client::Get(const std::string &path, const Headers &headers,
  14826. ContentReceiver content_receiver,
  14827. DownloadProgress progress) {
  14828. return cli_->Get(path, headers, std::move(content_receiver),
  14829. std::move(progress));
  14830. }
  14831. inline Result Client::Get(const std::string &path,
  14832. ResponseHandler response_handler,
  14833. ContentReceiver content_receiver,
  14834. DownloadProgress progress) {
  14835. return cli_->Get(path, std::move(response_handler),
  14836. std::move(content_receiver), std::move(progress));
  14837. }
  14838. inline Result Client::Get(const std::string &path, const Headers &headers,
  14839. ResponseHandler response_handler,
  14840. ContentReceiver content_receiver,
  14841. DownloadProgress progress) {
  14842. return cli_->Get(path, headers, std::move(response_handler),
  14843. std::move(content_receiver), std::move(progress));
  14844. }
  14845. inline Result Client::Get(const std::string &path, const Params &params,
  14846. DownloadProgress progress) {
  14847. return cli_->Get(path, params, std::move(progress));
  14848. }
  14849. inline Result Client::Get(const std::string &path, const Params &params,
  14850. const Headers &headers, DownloadProgress progress) {
  14851. return cli_->Get(path, params, headers, std::move(progress));
  14852. }
  14853. inline Result Client::Get(const std::string &path, const Params &params,
  14854. const Headers &headers,
  14855. ContentReceiver content_receiver,
  14856. DownloadProgress progress) {
  14857. return cli_->Get(path, params, headers, std::move(content_receiver),
  14858. std::move(progress));
  14859. }
  14860. inline Result Client::Get(const std::string &path, const Params &params,
  14861. const Headers &headers,
  14862. ResponseHandler response_handler,
  14863. ContentReceiver content_receiver,
  14864. DownloadProgress progress) {
  14865. return cli_->Get(path, params, headers, std::move(response_handler),
  14866. std::move(content_receiver), std::move(progress));
  14867. }
  14868. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  14869. inline Result Client::Head(const std::string &path, const Headers &headers) {
  14870. return cli_->Head(path, headers);
  14871. }
  14872. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  14873. inline Result Client::Post(const std::string &path, const Headers &headers) {
  14874. return cli_->Post(path, headers);
  14875. }
  14876. inline Result Client::Post(const std::string &path, const char *body,
  14877. size_t content_length,
  14878. const std::string &content_type,
  14879. UploadProgress progress) {
  14880. return cli_->Post(path, body, content_length, content_type, progress);
  14881. }
  14882. inline Result Client::Post(const std::string &path, const Headers &headers,
  14883. const char *body, size_t content_length,
  14884. const std::string &content_type,
  14885. UploadProgress progress) {
  14886. return cli_->Post(path, headers, body, content_length, content_type,
  14887. progress);
  14888. }
  14889. inline Result Client::Post(const std::string &path, const std::string &body,
  14890. const std::string &content_type,
  14891. UploadProgress progress) {
  14892. return cli_->Post(path, body, content_type, progress);
  14893. }
  14894. inline Result Client::Post(const std::string &path, const Headers &headers,
  14895. const std::string &body,
  14896. const std::string &content_type,
  14897. UploadProgress progress) {
  14898. return cli_->Post(path, headers, body, content_type, progress);
  14899. }
  14900. inline Result Client::Post(const std::string &path, size_t content_length,
  14901. ContentProvider content_provider,
  14902. const std::string &content_type,
  14903. UploadProgress progress) {
  14904. return cli_->Post(path, content_length, std::move(content_provider),
  14905. content_type, progress);
  14906. }
  14907. inline Result Client::Post(const std::string &path, size_t content_length,
  14908. ContentProvider content_provider,
  14909. const std::string &content_type,
  14910. ContentReceiver content_receiver,
  14911. UploadProgress progress) {
  14912. return cli_->Post(path, content_length, std::move(content_provider),
  14913. content_type, std::move(content_receiver), progress);
  14914. }
  14915. inline Result Client::Post(const std::string &path,
  14916. ContentProviderWithoutLength content_provider,
  14917. const std::string &content_type,
  14918. UploadProgress progress) {
  14919. return cli_->Post(path, std::move(content_provider), content_type, progress);
  14920. }
  14921. inline Result Client::Post(const std::string &path,
  14922. ContentProviderWithoutLength content_provider,
  14923. const std::string &content_type,
  14924. ContentReceiver content_receiver,
  14925. UploadProgress progress) {
  14926. return cli_->Post(path, std::move(content_provider), content_type,
  14927. std::move(content_receiver), progress);
  14928. }
  14929. inline Result Client::Post(const std::string &path, const Headers &headers,
  14930. size_t content_length,
  14931. ContentProvider content_provider,
  14932. const std::string &content_type,
  14933. UploadProgress progress) {
  14934. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14935. content_type, progress);
  14936. }
  14937. inline Result Client::Post(const std::string &path, const Headers &headers,
  14938. size_t content_length,
  14939. ContentProvider content_provider,
  14940. const std::string &content_type,
  14941. ContentReceiver content_receiver,
  14942. DownloadProgress progress) {
  14943. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14944. content_type, std::move(content_receiver), progress);
  14945. }
  14946. inline Result Client::Post(const std::string &path, const Headers &headers,
  14947. ContentProviderWithoutLength content_provider,
  14948. const std::string &content_type,
  14949. UploadProgress progress) {
  14950. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14951. progress);
  14952. }
  14953. inline Result Client::Post(const std::string &path, const Headers &headers,
  14954. ContentProviderWithoutLength content_provider,
  14955. const std::string &content_type,
  14956. ContentReceiver content_receiver,
  14957. DownloadProgress progress) {
  14958. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14959. std::move(content_receiver), progress);
  14960. }
  14961. inline Result Client::Post(const std::string &path, const Params &params) {
  14962. return cli_->Post(path, params);
  14963. }
  14964. inline Result Client::Post(const std::string &path, const Headers &headers,
  14965. const Params &params) {
  14966. return cli_->Post(path, headers, params);
  14967. }
  14968. inline Result Client::Post(const std::string &path,
  14969. const UploadFormDataItems &items,
  14970. UploadProgress progress) {
  14971. return cli_->Post(path, items, progress);
  14972. }
  14973. inline Result Client::Post(const std::string &path, const Headers &headers,
  14974. const UploadFormDataItems &items,
  14975. UploadProgress progress) {
  14976. return cli_->Post(path, headers, items, progress);
  14977. }
  14978. inline Result Client::Post(const std::string &path, const Headers &headers,
  14979. const UploadFormDataItems &items,
  14980. const std::string &boundary,
  14981. UploadProgress progress) {
  14982. return cli_->Post(path, headers, items, boundary, progress);
  14983. }
  14984. inline Result Client::Post(const std::string &path, const Headers &headers,
  14985. const UploadFormDataItems &items,
  14986. const FormDataProviderItems &provider_items,
  14987. UploadProgress progress) {
  14988. return cli_->Post(path, headers, items, provider_items, progress);
  14989. }
  14990. inline Result Client::Post(const std::string &path, const Headers &headers,
  14991. const std::string &body,
  14992. const std::string &content_type,
  14993. ContentReceiver content_receiver,
  14994. DownloadProgress progress) {
  14995. return cli_->Post(path, headers, body, content_type,
  14996. std::move(content_receiver), progress);
  14997. }
  14998. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  14999. inline Result Client::Put(const std::string &path, const Headers &headers) {
  15000. return cli_->Put(path, headers);
  15001. }
  15002. inline Result Client::Put(const std::string &path, const char *body,
  15003. size_t content_length,
  15004. const std::string &content_type,
  15005. UploadProgress progress) {
  15006. return cli_->Put(path, body, content_length, content_type, progress);
  15007. }
  15008. inline Result Client::Put(const std::string &path, const Headers &headers,
  15009. const char *body, size_t content_length,
  15010. const std::string &content_type,
  15011. UploadProgress progress) {
  15012. return cli_->Put(path, headers, body, content_length, content_type, progress);
  15013. }
  15014. inline Result Client::Put(const std::string &path, const std::string &body,
  15015. const std::string &content_type,
  15016. UploadProgress progress) {
  15017. return cli_->Put(path, body, content_type, progress);
  15018. }
  15019. inline Result Client::Put(const std::string &path, const Headers &headers,
  15020. const std::string &body,
  15021. const std::string &content_type,
  15022. UploadProgress progress) {
  15023. return cli_->Put(path, headers, body, content_type, progress);
  15024. }
  15025. inline Result Client::Put(const std::string &path, size_t content_length,
  15026. ContentProvider content_provider,
  15027. const std::string &content_type,
  15028. UploadProgress progress) {
  15029. return cli_->Put(path, content_length, std::move(content_provider),
  15030. content_type, progress);
  15031. }
  15032. inline Result Client::Put(const std::string &path, size_t content_length,
  15033. ContentProvider content_provider,
  15034. const std::string &content_type,
  15035. ContentReceiver content_receiver,
  15036. UploadProgress progress) {
  15037. return cli_->Put(path, content_length, std::move(content_provider),
  15038. content_type, std::move(content_receiver), progress);
  15039. }
  15040. inline Result Client::Put(const std::string &path,
  15041. ContentProviderWithoutLength content_provider,
  15042. const std::string &content_type,
  15043. UploadProgress progress) {
  15044. return cli_->Put(path, std::move(content_provider), content_type, progress);
  15045. }
  15046. inline Result Client::Put(const std::string &path,
  15047. ContentProviderWithoutLength content_provider,
  15048. const std::string &content_type,
  15049. ContentReceiver content_receiver,
  15050. UploadProgress progress) {
  15051. return cli_->Put(path, std::move(content_provider), content_type,
  15052. std::move(content_receiver), progress);
  15053. }
  15054. inline Result Client::Put(const std::string &path, const Headers &headers,
  15055. size_t content_length,
  15056. ContentProvider content_provider,
  15057. const std::string &content_type,
  15058. UploadProgress progress) {
  15059. return cli_->Put(path, headers, content_length, std::move(content_provider),
  15060. content_type, progress);
  15061. }
  15062. inline Result Client::Put(const std::string &path, const Headers &headers,
  15063. size_t content_length,
  15064. ContentProvider content_provider,
  15065. const std::string &content_type,
  15066. ContentReceiver content_receiver,
  15067. UploadProgress progress) {
  15068. return cli_->Put(path, headers, content_length, std::move(content_provider),
  15069. content_type, std::move(content_receiver), progress);
  15070. }
  15071. inline Result Client::Put(const std::string &path, const Headers &headers,
  15072. ContentProviderWithoutLength content_provider,
  15073. const std::string &content_type,
  15074. UploadProgress progress) {
  15075. return cli_->Put(path, headers, std::move(content_provider), content_type,
  15076. progress);
  15077. }
  15078. inline Result Client::Put(const std::string &path, const Headers &headers,
  15079. ContentProviderWithoutLength content_provider,
  15080. const std::string &content_type,
  15081. ContentReceiver content_receiver,
  15082. UploadProgress progress) {
  15083. return cli_->Put(path, headers, std::move(content_provider), content_type,
  15084. std::move(content_receiver), progress);
  15085. }
  15086. inline Result Client::Put(const std::string &path, const Params &params) {
  15087. return cli_->Put(path, params);
  15088. }
  15089. inline Result Client::Put(const std::string &path, const Headers &headers,
  15090. const Params &params) {
  15091. return cli_->Put(path, headers, params);
  15092. }
  15093. inline Result Client::Put(const std::string &path,
  15094. const UploadFormDataItems &items,
  15095. UploadProgress progress) {
  15096. return cli_->Put(path, items, progress);
  15097. }
  15098. inline Result Client::Put(const std::string &path, const Headers &headers,
  15099. const UploadFormDataItems &items,
  15100. UploadProgress progress) {
  15101. return cli_->Put(path, headers, items, progress);
  15102. }
  15103. inline Result Client::Put(const std::string &path, const Headers &headers,
  15104. const UploadFormDataItems &items,
  15105. const std::string &boundary,
  15106. UploadProgress progress) {
  15107. return cli_->Put(path, headers, items, boundary, progress);
  15108. }
  15109. inline Result Client::Put(const std::string &path, const Headers &headers,
  15110. const UploadFormDataItems &items,
  15111. const FormDataProviderItems &provider_items,
  15112. UploadProgress progress) {
  15113. return cli_->Put(path, headers, items, provider_items, progress);
  15114. }
  15115. inline Result Client::Put(const std::string &path, const Headers &headers,
  15116. const std::string &body,
  15117. const std::string &content_type,
  15118. ContentReceiver content_receiver,
  15119. DownloadProgress progress) {
  15120. return cli_->Put(path, headers, body, content_type, content_receiver,
  15121. progress);
  15122. }
  15123. inline Result Client::Patch(const std::string &path) {
  15124. return cli_->Patch(path);
  15125. }
  15126. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  15127. return cli_->Patch(path, headers);
  15128. }
  15129. inline Result Client::Patch(const std::string &path, const char *body,
  15130. size_t content_length,
  15131. const std::string &content_type,
  15132. UploadProgress progress) {
  15133. return cli_->Patch(path, body, content_length, content_type, progress);
  15134. }
  15135. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15136. const char *body, size_t content_length,
  15137. const std::string &content_type,
  15138. UploadProgress progress) {
  15139. return cli_->Patch(path, headers, body, content_length, content_type,
  15140. progress);
  15141. }
  15142. inline Result Client::Patch(const std::string &path, const std::string &body,
  15143. const std::string &content_type,
  15144. UploadProgress progress) {
  15145. return cli_->Patch(path, body, content_type, progress);
  15146. }
  15147. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15148. const std::string &body,
  15149. const std::string &content_type,
  15150. UploadProgress progress) {
  15151. return cli_->Patch(path, headers, body, content_type, progress);
  15152. }
  15153. inline Result Client::Patch(const std::string &path, size_t content_length,
  15154. ContentProvider content_provider,
  15155. const std::string &content_type,
  15156. UploadProgress progress) {
  15157. return cli_->Patch(path, content_length, std::move(content_provider),
  15158. content_type, progress);
  15159. }
  15160. inline Result Client::Patch(const std::string &path, size_t content_length,
  15161. ContentProvider content_provider,
  15162. const std::string &content_type,
  15163. ContentReceiver content_receiver,
  15164. UploadProgress progress) {
  15165. return cli_->Patch(path, content_length, std::move(content_provider),
  15166. content_type, std::move(content_receiver), progress);
  15167. }
  15168. inline Result Client::Patch(const std::string &path,
  15169. ContentProviderWithoutLength content_provider,
  15170. const std::string &content_type,
  15171. UploadProgress progress) {
  15172. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  15173. }
  15174. inline Result Client::Patch(const std::string &path,
  15175. ContentProviderWithoutLength content_provider,
  15176. const std::string &content_type,
  15177. ContentReceiver content_receiver,
  15178. UploadProgress progress) {
  15179. return cli_->Patch(path, std::move(content_provider), content_type,
  15180. std::move(content_receiver), progress);
  15181. }
  15182. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15183. size_t content_length,
  15184. ContentProvider content_provider,
  15185. const std::string &content_type,
  15186. UploadProgress progress) {
  15187. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  15188. content_type, progress);
  15189. }
  15190. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15191. size_t content_length,
  15192. ContentProvider content_provider,
  15193. const std::string &content_type,
  15194. ContentReceiver content_receiver,
  15195. UploadProgress progress) {
  15196. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  15197. content_type, std::move(content_receiver), progress);
  15198. }
  15199. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15200. ContentProviderWithoutLength content_provider,
  15201. const std::string &content_type,
  15202. UploadProgress progress) {
  15203. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  15204. progress);
  15205. }
  15206. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15207. ContentProviderWithoutLength content_provider,
  15208. const std::string &content_type,
  15209. ContentReceiver content_receiver,
  15210. UploadProgress progress) {
  15211. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  15212. std::move(content_receiver), progress);
  15213. }
  15214. inline Result Client::Patch(const std::string &path, const Params &params) {
  15215. return cli_->Patch(path, params);
  15216. }
  15217. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15218. const Params &params) {
  15219. return cli_->Patch(path, headers, params);
  15220. }
  15221. inline Result Client::Patch(const std::string &path,
  15222. const UploadFormDataItems &items,
  15223. UploadProgress progress) {
  15224. return cli_->Patch(path, items, progress);
  15225. }
  15226. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15227. const UploadFormDataItems &items,
  15228. UploadProgress progress) {
  15229. return cli_->Patch(path, headers, items, progress);
  15230. }
  15231. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15232. const UploadFormDataItems &items,
  15233. const std::string &boundary,
  15234. UploadProgress progress) {
  15235. return cli_->Patch(path, headers, items, boundary, progress);
  15236. }
  15237. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15238. const UploadFormDataItems &items,
  15239. const FormDataProviderItems &provider_items,
  15240. UploadProgress progress) {
  15241. return cli_->Patch(path, headers, items, provider_items, progress);
  15242. }
  15243. inline Result Client::Patch(const std::string &path, const Headers &headers,
  15244. const std::string &body,
  15245. const std::string &content_type,
  15246. ContentReceiver content_receiver,
  15247. DownloadProgress progress) {
  15248. return cli_->Patch(path, headers, body, content_type, content_receiver,
  15249. progress);
  15250. }
  15251. inline Result Client::Delete(const std::string &path,
  15252. DownloadProgress progress) {
  15253. return cli_->Delete(path, progress);
  15254. }
  15255. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15256. DownloadProgress progress) {
  15257. return cli_->Delete(path, headers, progress);
  15258. }
  15259. inline Result Client::Delete(const std::string &path, const char *body,
  15260. size_t content_length,
  15261. const std::string &content_type,
  15262. DownloadProgress progress) {
  15263. return cli_->Delete(path, body, content_length, content_type, progress);
  15264. }
  15265. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15266. const char *body, size_t content_length,
  15267. const std::string &content_type,
  15268. DownloadProgress progress) {
  15269. return cli_->Delete(path, headers, body, content_length, content_type,
  15270. progress);
  15271. }
  15272. inline Result Client::Delete(const std::string &path, const std::string &body,
  15273. const std::string &content_type,
  15274. DownloadProgress progress) {
  15275. return cli_->Delete(path, body, content_type, progress);
  15276. }
  15277. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15278. const std::string &body,
  15279. const std::string &content_type,
  15280. DownloadProgress progress) {
  15281. return cli_->Delete(path, headers, body, content_type, progress);
  15282. }
  15283. inline Result Client::Delete(const std::string &path, const Params &params,
  15284. DownloadProgress progress) {
  15285. return cli_->Delete(path, params, progress);
  15286. }
  15287. inline Result Client::Delete(const std::string &path, const Headers &headers,
  15288. const Params &params, DownloadProgress progress) {
  15289. return cli_->Delete(path, headers, params, progress);
  15290. }
  15291. inline Result Client::Options(const std::string &path) {
  15292. return cli_->Options(path);
  15293. }
  15294. inline Result Client::Options(const std::string &path, const Headers &headers) {
  15295. return cli_->Options(path, headers);
  15296. }
  15297. inline ClientImpl::StreamHandle
  15298. Client::open_stream(const std::string &method, const std::string &path,
  15299. const Params &params, const Headers &headers,
  15300. const std::string &body, const std::string &content_type) {
  15301. return cli_->open_stream(method, path, params, headers, body, content_type);
  15302. }
  15303. inline bool Client::send(Request &req, Response &res, Error &error) {
  15304. return cli_->send(req, res, error);
  15305. }
  15306. inline Result Client::send(const Request &req) { return cli_->send(req); }
  15307. inline void Client::stop() { cli_->stop(); }
  15308. inline std::string Client::host() const { return cli_->host(); }
  15309. inline int Client::port() const { return cli_->port(); }
  15310. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  15311. inline socket_t Client::socket() const { return cli_->socket(); }
  15312. inline void
  15313. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  15314. cli_->set_hostname_addr_map(std::move(addr_map));
  15315. }
  15316. inline void Client::set_default_headers(Headers headers) {
  15317. cli_->set_default_headers(std::move(headers));
  15318. }
  15319. inline void Client::set_header_writer(
  15320. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  15321. cli_->set_header_writer(writer);
  15322. }
  15323. inline void Client::set_address_family(int family) {
  15324. cli_->set_address_family(family);
  15325. }
  15326. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  15327. inline void Client::set_socket_options(SocketOptions socket_options) {
  15328. cli_->set_socket_options(std::move(socket_options));
  15329. }
  15330. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  15331. cli_->set_connection_timeout(sec, usec);
  15332. }
  15333. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  15334. cli_->set_read_timeout(sec, usec);
  15335. }
  15336. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  15337. cli_->set_write_timeout(sec, usec);
  15338. }
  15339. inline void Client::set_basic_auth(const std::string &username,
  15340. const std::string &password) {
  15341. cli_->set_basic_auth(username, password);
  15342. }
  15343. inline void Client::set_bearer_token_auth(const std::string &token) {
  15344. cli_->set_bearer_token_auth(token);
  15345. }
  15346. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  15347. inline void Client::set_follow_location(bool on) {
  15348. cli_->set_follow_location(on);
  15349. }
  15350. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  15351. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  15352. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  15353. inline void Client::set_payload_max_length(size_t length) {
  15354. cli_->set_payload_max_length(length);
  15355. }
  15356. inline void Client::set_interface(const std::string &intf) {
  15357. cli_->set_interface(intf);
  15358. }
  15359. inline void Client::set_proxy(const std::string &host, int port) {
  15360. cli_->set_proxy(host, port);
  15361. }
  15362. inline void Client::set_proxy_basic_auth(const std::string &username,
  15363. const std::string &password) {
  15364. cli_->set_proxy_basic_auth(username, password);
  15365. }
  15366. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  15367. cli_->set_proxy_bearer_token_auth(token);
  15368. }
  15369. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  15370. cli_->set_no_proxy(patterns);
  15371. }
  15372. inline void Client::set_logger(Logger logger) {
  15373. cli_->set_logger(std::move(logger));
  15374. }
  15375. inline void Client::set_error_logger(ErrorLogger error_logger) {
  15376. cli_->set_error_logger(std::move(error_logger));
  15377. }
  15378. /*
  15379. * Group 6: SSL Server and Client implementation
  15380. */
  15381. #ifdef CPPHTTPLIB_SSL_ENABLED
  15382. // SSL HTTP server implementation
  15383. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  15384. const char *client_ca_cert_file_path,
  15385. const char *client_ca_cert_dir_path,
  15386. const char *private_key_password) {
  15387. using namespace tls;
  15388. ctx_ = create_server_context();
  15389. if (!ctx_) { return; }
  15390. // Load server certificate and private key
  15391. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  15392. private_key_password)) {
  15393. last_ssl_error_ = static_cast<int>(get_error());
  15394. free_context(ctx_);
  15395. ctx_ = nullptr;
  15396. return;
  15397. }
  15398. // Load client CA certificates for client authentication
  15399. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  15400. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  15401. client_ca_cert_dir_path)) {
  15402. last_ssl_error_ = static_cast<int>(get_error());
  15403. free_context(ctx_);
  15404. ctx_ = nullptr;
  15405. return;
  15406. }
  15407. // Enable client certificate verification
  15408. set_verify_client(ctx_, true);
  15409. }
  15410. }
  15411. inline SSLServer::SSLServer(const PemMemory &pem) {
  15412. using namespace tls;
  15413. ctx_ = create_server_context();
  15414. if (ctx_) {
  15415. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  15416. pem.private_key_password)) {
  15417. last_ssl_error_ = static_cast<int>(get_error());
  15418. free_context(ctx_);
  15419. ctx_ = nullptr;
  15420. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  15421. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  15422. last_ssl_error_ = static_cast<int>(get_error());
  15423. free_context(ctx_);
  15424. ctx_ = nullptr;
  15425. } else {
  15426. set_verify_client(ctx_, true);
  15427. }
  15428. }
  15429. }
  15430. }
  15431. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  15432. using namespace tls;
  15433. ctx_ = create_server_context();
  15434. if (ctx_) {
  15435. if (!setup_callback(ctx_)) {
  15436. free_context(ctx_);
  15437. ctx_ = nullptr;
  15438. }
  15439. }
  15440. }
  15441. inline SSLServer::~SSLServer() {
  15442. if (ctx_) { tls::free_context(ctx_); }
  15443. }
  15444. inline bool SSLServer::is_valid() const {
  15445. return ctx_ != nullptr && Server::is_valid();
  15446. }
  15447. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  15448. using namespace tls;
  15449. // Create TLS session with mutex protection
  15450. session_t session = nullptr;
  15451. {
  15452. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15453. session = create_session(static_cast<ctx_t>(ctx_), sock);
  15454. }
  15455. if (!session) {
  15456. last_ssl_error_ = static_cast<int>(get_error());
  15457. detail::shutdown_socket(sock);
  15458. detail::close_socket(sock);
  15459. return false;
  15460. }
  15461. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  15462. bool handshake_done = false;
  15463. bool ret = false;
  15464. bool websocket_upgraded = false;
  15465. auto cleanup = detail::scope_exit([&] {
  15466. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  15467. free_session(session);
  15468. detail::shutdown_socket(sock);
  15469. detail::close_socket(sock);
  15470. });
  15471. // Perform TLS accept handshake with timeout
  15472. TlsError tls_err;
  15473. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  15474. &tls_err)) {
  15475. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15476. // Map TlsError to legacy ssl_error for backward compatibility
  15477. if (tls_err.code == ErrorCode::WantRead) {
  15478. last_ssl_error_ = SSL_ERROR_WANT_READ;
  15479. } else if (tls_err.code == ErrorCode::WantWrite) {
  15480. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  15481. } else {
  15482. last_ssl_error_ = SSL_ERROR_SSL;
  15483. }
  15484. #else
  15485. last_ssl_error_ = static_cast<int>(get_error());
  15486. #endif
  15487. return false;
  15488. }
  15489. handshake_done = true;
  15490. std::string remote_addr;
  15491. int remote_port = 0;
  15492. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  15493. std::string local_addr;
  15494. int local_port = 0;
  15495. detail::get_local_ip_and_port(sock, local_addr, local_port);
  15496. ret = serve_guarded([&]() {
  15497. return detail::process_server_socket_ssl(
  15498. svr_sock_, session, sock, keep_alive_max_count_,
  15499. keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
  15500. write_timeout_sec_, write_timeout_usec_,
  15501. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  15502. return process_request(
  15503. strm, remote_addr, remote_port, local_addr, local_port,
  15504. close_connection, connection_closed,
  15505. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  15506. });
  15507. });
  15508. return ret;
  15509. }
  15510. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  15511. const char *key_pem,
  15512. const char *client_ca_pem,
  15513. const char *password) {
  15514. if (!ctx_) { return false; }
  15515. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15516. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  15517. return false;
  15518. }
  15519. if (client_ca_pem) {
  15520. return tls::update_server_client_ca(ctx_, client_ca_pem);
  15521. }
  15522. return true;
  15523. }
  15524. // SSL HTTP client implementation
  15525. inline SSLClient::~SSLClient() {
  15526. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  15527. // base function rather than the derived function once we get to the
  15528. // base class destructor, and won't free the SSL (causing a leak).
  15529. // This must happen before the context is freed below: some backends
  15530. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  15531. // context, so freeing the context first leaves close_notify reading
  15532. // freed memory.
  15533. shutdown_ssl_impl(socket_, true);
  15534. if (ctx_) {
  15535. tls::free_context(ctx_);
  15536. ctx_ = nullptr;
  15537. }
  15538. }
  15539. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  15540. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  15541. shutdown_ssl_impl(socket, shutdown_gracefully);
  15542. }
  15543. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  15544. bool shutdown_gracefully) {
  15545. if (socket.sock == INVALID_SOCKET) {
  15546. assert(socket.ssl == nullptr);
  15547. return;
  15548. }
  15549. if (socket.ssl) {
  15550. tls::shutdown(socket.ssl, shutdown_gracefully);
  15551. {
  15552. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15553. tls::free_session(socket.ssl);
  15554. }
  15555. socket.ssl = nullptr;
  15556. }
  15557. assert(socket.ssl == nullptr);
  15558. }
  15559. inline bool SSLClient::process_socket(
  15560. const Socket &socket,
  15561. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15562. std::function<bool(Stream &strm)> callback) {
  15563. assert(socket.ssl);
  15564. return detail::process_client_socket_ssl(
  15565. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  15566. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  15567. std::move(callback));
  15568. }
  15569. inline bool SSLClient::is_ssl() const { return true; }
  15570. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  15571. if (!is_valid()) {
  15572. error = Error::SSLConnection;
  15573. return false;
  15574. }
  15575. return ClientImpl::create_and_connect_socket(socket, error);
  15576. }
  15577. inline bool SSLClient::setup_proxy_connection(
  15578. Socket &socket,
  15579. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15580. Response &res, bool &success, Error &error) {
  15581. if (!is_proxy_enabled_for_host(host_)) { return true; }
  15582. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  15583. return false;
  15584. }
  15585. if (!initialize_ssl(socket, error)) {
  15586. success = false;
  15587. return false;
  15588. }
  15589. return true;
  15590. }
  15591. // Assumes that socket_mutex_ is locked and that there are no requests in
  15592. // flight
  15593. inline bool SSLClient::connect_with_proxy(
  15594. Socket &socket,
  15595. std::chrono::time_point<std::chrono::steady_clock> start_time,
  15596. Response &res, bool &success, Error &error) {
  15597. success = true;
  15598. Response proxy_res;
  15599. if (!detail::process_client_socket(
  15600. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15601. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15602. start_time, [&](Stream &strm) {
  15603. Request req2;
  15604. req2.method = "CONNECT";
  15605. req2.path =
  15606. detail::make_host_and_port_string_always_port(host_, port_);
  15607. if (max_timeout_msec_ > 0) {
  15608. req2.start_time_ = std::chrono::steady_clock::now();
  15609. }
  15610. return process_request(strm, req2, proxy_res, false, error);
  15611. })) {
  15612. // Thread-safe to close everything because we are assuming there are no
  15613. // requests in flight
  15614. shutdown_ssl(socket, true);
  15615. shutdown_socket(socket);
  15616. close_socket(socket);
  15617. success = false;
  15618. return false;
  15619. }
  15620. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  15621. if (!proxy_digest_auth_username_.empty() &&
  15622. !proxy_digest_auth_password_.empty()) {
  15623. std::map<std::string, std::string> auth;
  15624. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  15625. // Close the current socket and create a new one for the authenticated
  15626. // request
  15627. shutdown_ssl(socket, true);
  15628. shutdown_socket(socket);
  15629. close_socket(socket);
  15630. // Create a new socket for the authenticated CONNECT request
  15631. if (!ensure_socket_connection(socket, error)) {
  15632. success = false;
  15633. output_error_log(error, nullptr);
  15634. return false;
  15635. }
  15636. proxy_res = Response();
  15637. if (!detail::process_client_socket(
  15638. socket.sock, read_timeout_sec_, read_timeout_usec_,
  15639. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  15640. start_time, [&](Stream &strm) {
  15641. Request req3;
  15642. req3.method = "CONNECT";
  15643. req3.path = detail::make_host_and_port_string_always_port(
  15644. host_, port_);
  15645. req3.headers.insert(detail::make_digest_authentication_header(
  15646. req3, auth, 1, detail::random_string(10),
  15647. proxy_digest_auth_username_, proxy_digest_auth_password_,
  15648. true));
  15649. if (max_timeout_msec_ > 0) {
  15650. req3.start_time_ = std::chrono::steady_clock::now();
  15651. }
  15652. return process_request(strm, req3, proxy_res, false, error);
  15653. })) {
  15654. // Thread-safe to close everything because we are assuming there are
  15655. // no requests in flight
  15656. shutdown_ssl(socket, true);
  15657. shutdown_socket(socket);
  15658. close_socket(socket);
  15659. success = false;
  15660. return false;
  15661. }
  15662. }
  15663. }
  15664. }
  15665. // If status code is not 200, proxy request is failed.
  15666. // Set error to ProxyConnection and return proxy response
  15667. // as the response of the request
  15668. if (proxy_res.status != StatusCode::OK_200) {
  15669. error = Error::ProxyConnection;
  15670. output_error_log(error, nullptr);
  15671. res = std::move(proxy_res);
  15672. // Thread-safe to close everything because we are assuming there are
  15673. // no requests in flight
  15674. shutdown_ssl(socket, true);
  15675. shutdown_socket(socket);
  15676. close_socket(socket);
  15677. return false;
  15678. }
  15679. return true;
  15680. }
  15681. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  15682. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  15683. if (is_proxy_enabled_for_host(host_)) { return true; }
  15684. if (!initialize_ssl(socket, error)) {
  15685. shutdown_socket(socket);
  15686. close_socket(socket);
  15687. return false;
  15688. }
  15689. return true;
  15690. }
  15691. // SSL HTTP client implementation
  15692. inline SSLClient::SSLClient(const std::string &host)
  15693. : SSLClient(host, 443, std::string(), std::string()) {}
  15694. inline SSLClient::SSLClient(const std::string &host, int port)
  15695. : SSLClient(host, port, std::string(), std::string()) {}
  15696. inline void SSLClient::init_ctx() {
  15697. ctx_ = tls::create_client_context();
  15698. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  15699. }
  15700. inline void SSLClient::reset_ctx_on_error() {
  15701. last_backend_error_ = tls::get_error();
  15702. tls::free_context(ctx_);
  15703. ctx_ = nullptr;
  15704. }
  15705. inline SSLClient::SSLClient(const std::string &host, int port,
  15706. const std::string &client_cert_path,
  15707. const std::string &client_key_path,
  15708. const std::string &private_key_password)
  15709. : ClientImpl(host, port, client_cert_path, client_key_path) {
  15710. init_ctx();
  15711. if (!ctx_) { return; }
  15712. if (!client_cert_path.empty() && !client_key_path.empty()) {
  15713. const char *password =
  15714. private_key_password.empty() ? nullptr : private_key_password.c_str();
  15715. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  15716. client_key_path.c_str(), password)) {
  15717. reset_ctx_on_error();
  15718. }
  15719. }
  15720. }
  15721. inline SSLClient::SSLClient(const std::string &host, int port,
  15722. const PemMemory &pem)
  15723. : ClientImpl(host, port) {
  15724. init_ctx();
  15725. if (!ctx_) { return; }
  15726. if (pem.cert_pem && pem.key_pem) {
  15727. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  15728. pem.private_key_password)) {
  15729. reset_ctx_on_error();
  15730. }
  15731. }
  15732. }
  15733. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  15734. if (ca_cert_store && ctx_) {
  15735. // set_ca_store takes ownership of ca_cert_store
  15736. tls::set_ca_store(ctx_, ca_cert_store);
  15737. ca_cert_store_set_ = true;
  15738. } else if (ca_cert_store) {
  15739. tls::free_ca_store(ca_cert_store);
  15740. }
  15741. }
  15742. inline void
  15743. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  15744. if (!ctx_) { return; }
  15745. tls::set_verify_callback(ctx_, verifier);
  15746. }
  15747. inline void SSLClient::set_session_verifier(
  15748. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  15749. session_verifier_ = std::move(verifier);
  15750. }
  15751. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15752. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  15753. enable_windows_cert_verification_ = enabled;
  15754. }
  15755. #endif
  15756. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  15757. std::size_t size) {
  15758. if (ctx_ && ca_cert && size > 0) {
  15759. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  15760. tls::load_ca_pem(ctx_, ca_cert, size);
  15761. }
  15762. }
  15763. inline bool SSLClient::load_certs() {
  15764. auto ret = true;
  15765. // call_once rather than the plain flag WebSocketClient::create_stream() uses:
  15766. // one client is shared across concurrent requests here.
  15767. std::call_once(initialize_cert_, [&]() {
  15768. std::lock_guard<std::mutex> guard(ctx_mutex_);
  15769. ret = detail::load_client_ca_config(
  15770. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  15771. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  15772. last_backend_error_);
  15773. });
  15774. return ret;
  15775. }
  15776. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  15777. // Load CA certificates if server verification is enabled
  15778. if (server_certificate_verification_) {
  15779. if (!load_certs()) {
  15780. error = Error::SSLLoadingCerts;
  15781. output_error_log(error, nullptr);
  15782. return false;
  15783. }
  15784. }
  15785. detail::ClientTlsSessionOptions options;
  15786. options.server_hostname_verification = server_hostname_verification_;
  15787. options.session_verifier = session_verifier_;
  15788. options.ctx_mutex = &ctx_mutex_;
  15789. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15790. // Skip Schannel when a custom CA cert is specified, as the Windows
  15791. // certificate store would not know about user-provided CA certificates.
  15792. // Also skip when system CA trust is explicitly disabled.
  15793. options.windows_cert_verification =
  15794. enable_windows_cert_verification_ &&
  15795. system_ca_mode_ != SystemCAMode::Disabled && ca_cert_file_path_.empty() &&
  15796. ca_cert_dir_path_.empty() && ca_cert_pem_.empty() && !ca_cert_store_set_;
  15797. #endif
  15798. tls::session_t session = nullptr;
  15799. // Use scope_exit to ensure session is freed on error paths
  15800. bool success = false;
  15801. auto session_guard = detail::scope_exit([&] {
  15802. if (!success) { tls::free_session(session); }
  15803. });
  15804. detail::ClientTlsSessionError tls_error;
  15805. if (!detail::setup_client_tls_session(
  15806. host_, ctx_, session, socket.sock, server_certificate_verification_,
  15807. connection_timeout_sec_, connection_timeout_usec_, &tls_error,
  15808. options)) {
  15809. error = tls_error.error;
  15810. last_ssl_error_ = tls_error.ssl_error;
  15811. last_backend_error_ = tls_error.backend_error;
  15812. output_error_log(error, nullptr);
  15813. return false;
  15814. }
  15815. success = true;
  15816. socket.ssl = session;
  15817. return true;
  15818. }
  15819. inline void Client::set_digest_auth(const std::string &username,
  15820. const std::string &password) {
  15821. cli_->set_digest_auth(username, password);
  15822. }
  15823. inline void Client::set_proxy_digest_auth(const std::string &username,
  15824. const std::string &password) {
  15825. cli_->set_proxy_digest_auth(username, password);
  15826. }
  15827. inline void Client::enable_server_certificate_verification(bool enabled) {
  15828. cli_->enable_server_certificate_verification(enabled);
  15829. }
  15830. inline void Client::enable_server_hostname_verification(bool enabled) {
  15831. cli_->enable_server_hostname_verification(enabled);
  15832. }
  15833. inline void Client::enable_system_ca(bool enabled) {
  15834. cli_->enable_system_ca(enabled);
  15835. }
  15836. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  15837. inline void Client::enable_windows_certificate_verification(bool enabled) {
  15838. if (is_ssl_) {
  15839. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  15840. enabled);
  15841. }
  15842. }
  15843. #endif
  15844. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  15845. const std::string &ca_cert_dir_path) {
  15846. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  15847. }
  15848. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  15849. if (is_ssl_) {
  15850. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  15851. } else if (ca_cert_store) {
  15852. tls::free_ca_store(ca_cert_store);
  15853. }
  15854. }
  15855. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  15856. if (is_ssl_) {
  15857. // Use the PEM-based path so the CA data is retained for redirect transfer
  15858. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  15859. }
  15860. }
  15861. inline void
  15862. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  15863. if (is_ssl_) {
  15864. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  15865. std::move(verifier));
  15866. }
  15867. }
  15868. inline void Client::set_session_verifier(
  15869. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  15870. if (is_ssl_) {
  15871. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  15872. }
  15873. }
  15874. inline tls::ctx_t Client::tls_context() const {
  15875. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  15876. return nullptr;
  15877. }
  15878. #endif // CPPHTTPLIB_SSL_ENABLED
  15879. /*
  15880. * Group 7: TLS abstraction layer - Common API
  15881. */
  15882. #ifdef CPPHTTPLIB_SSL_ENABLED
  15883. namespace tls {
  15884. // Helper for PeerCert construction
  15885. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  15886. return PeerCert(get_peer_cert(session));
  15887. }
  15888. namespace impl {
  15889. inline VerifyCallback &get_verify_callback() {
  15890. static thread_local VerifyCallback callback;
  15891. return callback;
  15892. }
  15893. inline VerifyCallback &get_mbedtls_verify_callback() {
  15894. static thread_local VerifyCallback callback;
  15895. return callback;
  15896. }
  15897. // Check if a string is an IPv4 address
  15898. inline bool is_ipv4_address(const std::string &str) {
  15899. int dots = 0;
  15900. for (char c : str) {
  15901. if (c == '.') {
  15902. dots++;
  15903. } else if (!detail::is_ascii_digit(c)) {
  15904. return false;
  15905. }
  15906. }
  15907. return dots == 3;
  15908. }
  15909. // Parse IPv4 address string to bytes
  15910. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  15911. const char *p = str.c_str();
  15912. for (int i = 0; i < 4; i++) {
  15913. if (i > 0) {
  15914. if (*p != '.') { return false; }
  15915. p++;
  15916. }
  15917. int val = 0;
  15918. int digits = 0;
  15919. while (detail::is_ascii_digit(*p)) {
  15920. val = val * 10 + (*p - '0');
  15921. if (val > 255) { return false; }
  15922. p++;
  15923. digits++;
  15924. }
  15925. if (digits == 0) { return false; }
  15926. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  15927. if (digits > 1 && *(p - digits) == '0') { return false; }
  15928. out[i] = static_cast<unsigned char>(val);
  15929. }
  15930. return *p == '\0';
  15931. }
  15932. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  15933. // `out` must have room for at least 16 bytes. Returns the address length
  15934. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  15935. // literal. Used to match a host against iPAddress SANs the same way the
  15936. // OpenSSL backend does via X509_check_ip.
  15937. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  15938. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  15939. struct in6_addr addr6 = {};
  15940. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  15941. memcpy(out, &addr6, 16);
  15942. return 16;
  15943. }
  15944. return 0;
  15945. }
  15946. #ifdef _WIN32
  15947. // Enumerate Windows system certificates and call callback with DER data
  15948. template <typename Callback>
  15949. inline bool enumerate_windows_system_certs(Callback cb) {
  15950. bool loaded = false;
  15951. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  15952. for (auto store_name : store_names) {
  15953. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  15954. if (hStore) {
  15955. PCCERT_CONTEXT pContext = nullptr;
  15956. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  15957. nullptr) {
  15958. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  15959. loaded = true;
  15960. }
  15961. }
  15962. CertCloseStore(hStore, 0);
  15963. }
  15964. }
  15965. return loaded;
  15966. }
  15967. #endif
  15968. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15969. // Enumerate macOS Keychain certificates and call callback with DER data
  15970. template <typename Callback>
  15971. inline bool enumerate_macos_keychain_certs(Callback cb) {
  15972. bool loaded = false;
  15973. const SecTrustSettingsDomain domains[] = {
  15974. kSecTrustSettingsDomainSystem,
  15975. kSecTrustSettingsDomainAdmin,
  15976. kSecTrustSettingsDomainUser,
  15977. };
  15978. for (auto domain : domains) {
  15979. CFArrayRef certs = nullptr;
  15980. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  15981. if (status != errSecSuccess || !certs) {
  15982. if (certs) CFRelease(certs);
  15983. continue;
  15984. }
  15985. CFIndex count = CFArrayGetCount(certs);
  15986. for (CFIndex i = 0; i < count; i++) {
  15987. SecCertificateRef cert =
  15988. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  15989. CFDataRef data = SecCertificateCopyData(cert);
  15990. if (data) {
  15991. if (cb(CFDataGetBytePtr(data),
  15992. static_cast<size_t>(CFDataGetLength(data)))) {
  15993. loaded = true;
  15994. }
  15995. CFRelease(data);
  15996. }
  15997. }
  15998. CFRelease(certs);
  15999. }
  16000. return loaded;
  16001. }
  16002. #endif
  16003. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  16004. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  16005. // Common CA certificate file paths on Linux/Unix
  16006. inline const char **system_ca_paths() {
  16007. static const char *paths[] = {
  16008. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  16009. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  16010. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  16011. "/etc/pki/tls/cacert.pem", // OpenELEC
  16012. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  16013. nullptr};
  16014. return paths;
  16015. }
  16016. // Common CA certificate directory paths on Linux/Unix
  16017. inline const char **system_ca_dirs() {
  16018. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  16019. "/etc/pki/tls/certs", // RHEL/CentOS
  16020. "/usr/share/ca-certificates", // Other
  16021. nullptr};
  16022. return dirs;
  16023. }
  16024. #endif
  16025. } // namespace impl
  16026. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  16027. const char *ca_dir) {
  16028. if (!ctx) { return false; }
  16029. bool success = true;
  16030. if (ca_file && *ca_file) {
  16031. if (!load_ca_file(ctx, ca_file)) { success = false; }
  16032. }
  16033. if (ca_dir && *ca_dir) {
  16034. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  16035. }
  16036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16037. // Set CA list for client certificate request (CertificateRequest message)
  16038. if (ca_file && *ca_file) {
  16039. auto list = SSL_load_client_CA_file(ca_file);
  16040. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  16041. }
  16042. #endif
  16043. return success;
  16044. }
  16045. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16046. const char *password) {
  16047. return set_client_cert_pem(ctx, cert, key, password);
  16048. }
  16049. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  16050. const char *key_path, const char *password) {
  16051. return set_client_cert_file(ctx, cert_path, key_path, password);
  16052. }
  16053. // PeerCert implementation
  16054. inline PeerCert::PeerCert() = default;
  16055. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  16056. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  16057. other.cert_ = nullptr;
  16058. }
  16059. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  16060. if (this != &other) {
  16061. if (cert_) { free_cert(cert_); }
  16062. cert_ = other.cert_;
  16063. other.cert_ = nullptr;
  16064. }
  16065. return *this;
  16066. }
  16067. inline PeerCert::~PeerCert() {
  16068. if (cert_) { free_cert(cert_); }
  16069. }
  16070. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  16071. inline std::string PeerCert::subject_cn() const {
  16072. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  16073. }
  16074. inline std::string PeerCert::issuer_name() const {
  16075. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  16076. }
  16077. inline bool PeerCert::check_hostname(const char *hostname) const {
  16078. return cert_ ? verify_hostname(cert_, hostname) : false;
  16079. }
  16080. inline std::vector<SanEntry> PeerCert::sans() const {
  16081. std::vector<SanEntry> result;
  16082. if (cert_) { get_cert_sans(cert_, result); }
  16083. return result;
  16084. }
  16085. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  16086. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  16087. }
  16088. inline std::string PeerCert::serial() const {
  16089. return cert_ ? get_cert_serial(cert_) : std::string();
  16090. }
  16091. // VerifyContext method implementations
  16092. inline std::string VerifyContext::subject_cn() const {
  16093. return cert ? get_cert_subject_cn(cert) : std::string();
  16094. }
  16095. inline std::string VerifyContext::issuer_name() const {
  16096. return cert ? get_cert_issuer_name(cert) : std::string();
  16097. }
  16098. inline bool VerifyContext::check_hostname(const char *hostname) const {
  16099. return cert ? verify_hostname(cert, hostname) : false;
  16100. }
  16101. inline std::vector<SanEntry> VerifyContext::sans() const {
  16102. std::vector<SanEntry> result;
  16103. if (cert) { get_cert_sans(cert, result); }
  16104. return result;
  16105. }
  16106. inline bool VerifyContext::validity(time_t &not_before,
  16107. time_t &not_after) const {
  16108. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  16109. }
  16110. inline std::string VerifyContext::serial() const {
  16111. return cert ? get_cert_serial(cert) : std::string();
  16112. }
  16113. // TlsError static method implementation
  16114. inline std::string TlsError::verify_error_to_string(long error_code) {
  16115. return verify_error_string(error_code);
  16116. }
  16117. } // namespace tls
  16118. // Request::peer_cert() implementation
  16119. inline tls::PeerCert Request::peer_cert() const {
  16120. return tls::get_peer_cert_from_session(ssl);
  16121. }
  16122. // Request::sni() implementation
  16123. inline std::string Request::sni() const {
  16124. if (!ssl) { return std::string(); }
  16125. const char *s = tls::get_sni(ssl);
  16126. return s ? std::string(s) : std::string();
  16127. }
  16128. #endif // CPPHTTPLIB_SSL_ENABLED
  16129. /*
  16130. * Group 8: TLS abstraction layer - OpenSSL backend
  16131. */
  16132. /*
  16133. * OpenSSL Backend Implementation
  16134. */
  16135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16136. namespace tls {
  16137. namespace impl {
  16138. // Helper to map OpenSSL SSL_get_error to ErrorCode
  16139. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  16140. switch (ssl_error) {
  16141. case SSL_ERROR_NONE: return ErrorCode::Success;
  16142. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16143. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16144. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16145. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16146. case SSL_ERROR_SSL:
  16147. default: return ErrorCode::Fatal;
  16148. }
  16149. }
  16150. // Helper: Create client CA list from PEM string
  16151. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  16152. // Caller takes ownership of returned list
  16153. inline STACK_OF(X509_NAME) *
  16154. create_client_ca_list_from_pem(const char *ca_pem) {
  16155. if (!ca_pem) { return nullptr; }
  16156. auto ca_list = sk_X509_NAME_new_null();
  16157. if (!ca_list) { return nullptr; }
  16158. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  16159. if (!bio) {
  16160. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  16161. return nullptr;
  16162. }
  16163. X509 *cert = nullptr;
  16164. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  16165. nullptr) {
  16166. const X509_NAME *name = X509_get_subject_name(cert);
  16167. if (name) {
  16168. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  16169. }
  16170. X509_free(cert);
  16171. }
  16172. BIO_free(bio);
  16173. return ca_list;
  16174. }
  16175. // OpenSSL verify callback wrapper
  16176. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  16177. auto &callback = get_verify_callback();
  16178. if (!callback) { return preverify_ok; }
  16179. // Get SSL object from X509_STORE_CTX
  16180. auto ssl = static_cast<SSL *>(
  16181. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  16182. if (!ssl) { return preverify_ok; }
  16183. // Get current certificate and depth
  16184. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  16185. int depth = X509_STORE_CTX_get_error_depth(ctx);
  16186. int error = X509_STORE_CTX_get_error(ctx);
  16187. // Build context
  16188. VerifyContext verify_ctx;
  16189. verify_ctx.session = static_cast<session_t>(ssl);
  16190. verify_ctx.cert = static_cast<cert_t>(cert);
  16191. verify_ctx.depth = depth;
  16192. verify_ctx.preverify_ok = (preverify_ok != 0);
  16193. verify_ctx.error_code = error;
  16194. verify_ctx.error_string =
  16195. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  16196. return callback(verify_ctx) ? 1 : 0;
  16197. }
  16198. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  16199. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  16200. // that must be released with release_store_objects
  16201. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  16202. OPENSSL_VERSION_NUMBER >= 0x30300000L
  16203. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16204. #endif
  16205. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  16206. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16207. return X509_STORE_get1_objects(store);
  16208. #else
  16209. return X509_STORE_get0_objects(store);
  16210. #endif
  16211. }
  16212. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  16213. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  16214. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  16215. #else
  16216. (void)objs; // get0 variant returns an internal pointer; nothing to free
  16217. #endif
  16218. }
  16219. } // namespace impl
  16220. inline ctx_t create_client_context() {
  16221. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  16222. if (ctx) {
  16223. // Disable auto-retry to properly handle non-blocking I/O
  16224. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  16225. // Set minimum TLS version
  16226. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  16227. }
  16228. return static_cast<ctx_t>(ctx);
  16229. }
  16230. inline void free_context(ctx_t ctx) {
  16231. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  16232. }
  16233. inline bool set_min_version(ctx_t ctx, Version version) {
  16234. if (!ctx) return false;
  16235. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  16236. static_cast<int>(version)) == 1;
  16237. }
  16238. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16239. if (!ctx || !pem || len == 0) return false;
  16240. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16241. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16242. if (!store) return false;
  16243. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  16244. if (!bio) return false;
  16245. bool ok = true;
  16246. X509 *cert = nullptr;
  16247. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  16248. nullptr) {
  16249. if (X509_STORE_add_cert(store, cert) != 1) {
  16250. // Ignore duplicate errors
  16251. auto err = ERR_peek_last_error();
  16252. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  16253. ok = false;
  16254. }
  16255. }
  16256. X509_free(cert);
  16257. if (!ok) break;
  16258. }
  16259. BIO_free(bio);
  16260. // Clear any "no more certificates" errors
  16261. ERR_clear_error();
  16262. return ok;
  16263. }
  16264. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16265. if (!ctx || !file_path) return false;
  16266. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  16267. nullptr) == 1;
  16268. }
  16269. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16270. if (!ctx || !dir_path) return false;
  16271. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  16272. dir_path) == 1;
  16273. }
  16274. inline bool load_system_certs(ctx_t ctx) {
  16275. if (!ctx) return false;
  16276. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16277. #ifdef _WIN32
  16278. // Windows: Load from system certificate store (ROOT and CA)
  16279. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16280. if (!store) return false;
  16281. bool loaded_any = false;
  16282. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  16283. for (auto store_name : store_names) {
  16284. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  16285. if (!hStore) continue;
  16286. PCCERT_CONTEXT pContext = nullptr;
  16287. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  16288. nullptr) {
  16289. const unsigned char *data = pContext->pbCertEncoded;
  16290. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  16291. if (x509) {
  16292. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  16293. X509_free(x509);
  16294. }
  16295. }
  16296. CertCloseStore(hStore, 0);
  16297. }
  16298. return loaded_any;
  16299. #elif defined(__APPLE__)
  16300. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16301. // macOS: Load from Keychain
  16302. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16303. if (!store) return false;
  16304. bool loaded_any = false;
  16305. const SecTrustSettingsDomain domains[] = {
  16306. kSecTrustSettingsDomainSystem,
  16307. kSecTrustSettingsDomainAdmin,
  16308. kSecTrustSettingsDomainUser,
  16309. };
  16310. for (auto domain : domains) {
  16311. CFArrayRef certs = nullptr;
  16312. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  16313. !certs) {
  16314. if (certs) CFRelease(certs);
  16315. continue;
  16316. }
  16317. auto count = CFArrayGetCount(certs);
  16318. for (CFIndex i = 0; i < count; i++) {
  16319. auto cert = reinterpret_cast<SecCertificateRef>(
  16320. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  16321. CFDataRef der = SecCertificateCopyData(cert);
  16322. if (der) {
  16323. const unsigned char *data = CFDataGetBytePtr(der);
  16324. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  16325. if (x509) {
  16326. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  16327. X509_free(x509);
  16328. }
  16329. CFRelease(der);
  16330. }
  16331. }
  16332. CFRelease(certs);
  16333. }
  16334. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16335. #else
  16336. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16337. #endif
  16338. #else
  16339. // Other Unix: use default verify paths
  16340. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  16341. #endif
  16342. }
  16343. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16344. const char *password) {
  16345. if (!ctx || !cert || !key) return false;
  16346. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16347. // Load certificate
  16348. auto cert_bio = BIO_new_mem_buf(cert, -1);
  16349. if (!cert_bio) return false;
  16350. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  16351. BIO_free(cert_bio);
  16352. if (!x509) return false;
  16353. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  16354. X509_free(x509);
  16355. if (!cert_ok) return false;
  16356. // Load private key
  16357. auto key_bio = BIO_new_mem_buf(key, -1);
  16358. if (!key_bio) return false;
  16359. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  16360. password ? const_cast<char *>(password)
  16361. : nullptr);
  16362. BIO_free(key_bio);
  16363. if (!pkey) return false;
  16364. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  16365. EVP_PKEY_free(pkey);
  16366. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  16367. }
  16368. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16369. const char *key_path, const char *password) {
  16370. if (!ctx || !cert_path || !key_path) return false;
  16371. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16372. if (password && password[0] != '\0') {
  16373. SSL_CTX_set_default_passwd_cb_userdata(
  16374. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  16375. }
  16376. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  16377. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  16378. }
  16379. inline ctx_t create_server_context() {
  16380. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16381. if (ctx) {
  16382. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  16383. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  16384. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  16385. }
  16386. return static_cast<ctx_t>(ctx);
  16387. }
  16388. inline void set_verify_client(ctx_t ctx, bool require) {
  16389. if (!ctx) return;
  16390. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  16391. require
  16392. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  16393. : SSL_VERIFY_NONE,
  16394. nullptr);
  16395. }
  16396. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16397. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  16398. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16399. SSL *ssl = SSL_new(ssl_ctx);
  16400. if (!ssl) return nullptr;
  16401. // Disable auto-retry for proper non-blocking I/O handling
  16402. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  16403. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  16404. if (!bio) {
  16405. SSL_free(ssl);
  16406. return nullptr;
  16407. }
  16408. SSL_set_bio(ssl, bio, bio);
  16409. return static_cast<session_t>(ssl);
  16410. }
  16411. inline void free_session(session_t session) {
  16412. if (session) { SSL_free(static_cast<SSL *>(session)); }
  16413. }
  16414. inline bool set_sni(session_t session, const char *hostname,
  16415. bool /*verify_hostname*/) {
  16416. if (!session || !hostname) return false;
  16417. auto ssl = static_cast<SSL *>(session);
  16418. // Set SNI (Server Name Indication) only - does not enable verification.
  16419. // OpenSSL never binds identity checking to SNI (that happens post-
  16420. // handshake in setup_client_tls_session()), so verify_hostname is unused.
  16421. #if defined(OPENSSL_IS_BORINGSSL)
  16422. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  16423. #else
  16424. // Direct call instead of macro to suppress -Wold-style-cast warning
  16425. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  16426. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  16427. #endif
  16428. }
  16429. inline TlsError connect(session_t session) {
  16430. if (!session) { return TlsError(); }
  16431. auto ssl = static_cast<SSL *>(session);
  16432. auto ret = SSL_connect(ssl);
  16433. TlsError err;
  16434. if (ret == 1) {
  16435. err.code = ErrorCode::Success;
  16436. } else {
  16437. auto ssl_err = SSL_get_error(ssl, ret);
  16438. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16439. err.backend_code = ERR_get_error();
  16440. }
  16441. return err;
  16442. }
  16443. inline TlsError accept(session_t session) {
  16444. if (!session) { return TlsError(); }
  16445. auto ssl = static_cast<SSL *>(session);
  16446. auto ret = SSL_accept(ssl);
  16447. TlsError err;
  16448. if (ret == 1) {
  16449. err.code = ErrorCode::Success;
  16450. } else {
  16451. auto ssl_err = SSL_get_error(ssl, ret);
  16452. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16453. err.backend_code = ERR_get_error();
  16454. }
  16455. return err;
  16456. }
  16457. inline bool connect_nonblocking(session_t session, socket_t sock,
  16458. time_t timeout_sec, time_t timeout_usec,
  16459. TlsError *err) {
  16460. if (!session) {
  16461. if (err) { err->code = ErrorCode::Fatal; }
  16462. return false;
  16463. }
  16464. auto ssl = static_cast<SSL *>(session);
  16465. auto bio = SSL_get_rbio(ssl);
  16466. // Set non-blocking mode for handshake
  16467. detail::set_nonblocking(sock, true);
  16468. if (bio) { BIO_set_nbio(bio, 1); }
  16469. auto cleanup = detail::scope_exit([&]() {
  16470. // Restore blocking mode after handshake
  16471. if (bio) { BIO_set_nbio(bio, 0); }
  16472. detail::set_nonblocking(sock, false);
  16473. });
  16474. auto res = 0;
  16475. while ((res = SSL_connect(ssl)) != 1) {
  16476. auto ssl_err = SSL_get_error(ssl, res);
  16477. switch (ssl_err) {
  16478. case SSL_ERROR_WANT_READ:
  16479. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16480. continue;
  16481. }
  16482. break;
  16483. case SSL_ERROR_WANT_WRITE:
  16484. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16485. continue;
  16486. }
  16487. break;
  16488. default: break;
  16489. }
  16490. if (err) {
  16491. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  16492. err->backend_code = ERR_get_error();
  16493. }
  16494. return false;
  16495. }
  16496. if (err) { err->code = ErrorCode::Success; }
  16497. return true;
  16498. }
  16499. inline bool accept_nonblocking(session_t session, socket_t sock,
  16500. time_t timeout_sec, time_t timeout_usec,
  16501. TlsError *err) {
  16502. if (!session) {
  16503. if (err) { err->code = ErrorCode::Fatal; }
  16504. return false;
  16505. }
  16506. auto ssl = static_cast<SSL *>(session);
  16507. auto bio = SSL_get_rbio(ssl);
  16508. // Set non-blocking mode for handshake
  16509. detail::set_nonblocking(sock, true);
  16510. if (bio) { BIO_set_nbio(bio, 1); }
  16511. auto cleanup = detail::scope_exit([&]() {
  16512. // Restore blocking mode after handshake
  16513. if (bio) { BIO_set_nbio(bio, 0); }
  16514. detail::set_nonblocking(sock, false);
  16515. });
  16516. auto res = 0;
  16517. while ((res = SSL_accept(ssl)) != 1) {
  16518. auto ssl_err = SSL_get_error(ssl, res);
  16519. switch (ssl_err) {
  16520. case SSL_ERROR_WANT_READ:
  16521. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16522. continue;
  16523. }
  16524. break;
  16525. case SSL_ERROR_WANT_WRITE:
  16526. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16527. continue;
  16528. }
  16529. break;
  16530. default: break;
  16531. }
  16532. if (err) {
  16533. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  16534. err->backend_code = ERR_get_error();
  16535. }
  16536. return false;
  16537. }
  16538. if (err) { err->code = ErrorCode::Success; }
  16539. return true;
  16540. }
  16541. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16542. if (!session || !buf) {
  16543. err.code = ErrorCode::Fatal;
  16544. return -1;
  16545. }
  16546. auto ssl = static_cast<SSL *>(session);
  16547. constexpr auto max_len =
  16548. static_cast<size_t>((std::numeric_limits<int>::max)());
  16549. if (len > max_len) { len = max_len; }
  16550. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  16551. if (ret > 0) {
  16552. err.code = ErrorCode::Success;
  16553. return ret;
  16554. }
  16555. auto ssl_err = SSL_get_error(ssl, ret);
  16556. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16557. if (err.code == ErrorCode::PeerClosed) {
  16558. return 0;
  16559. } // Gracefully handle the peer closed state.
  16560. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  16561. return -1;
  16562. }
  16563. inline ssize_t write(session_t session, const void *buf, size_t len,
  16564. TlsError &err) {
  16565. if (!session || !buf) {
  16566. err.code = ErrorCode::Fatal;
  16567. return -1;
  16568. }
  16569. auto ssl = static_cast<SSL *>(session);
  16570. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  16571. if (ret > 0) {
  16572. err.code = ErrorCode::Success;
  16573. return ret;
  16574. }
  16575. auto ssl_err = SSL_get_error(ssl, ret);
  16576. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  16577. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  16578. return -1;
  16579. }
  16580. inline int pending(const_session_t session) {
  16581. if (!session) return 0;
  16582. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  16583. }
  16584. inline void shutdown(session_t session, bool graceful) {
  16585. if (!session) return;
  16586. auto ssl = static_cast<SSL *>(session);
  16587. if (graceful) {
  16588. // Send close_notify without waiting for the peer's. The connection is
  16589. // closed right after this, so a unidirectional shutdown is enough, and an
  16590. // idle peer that never answers would otherwise hold this thread until the
  16591. // read timeout. The other backends do not wait either.
  16592. SSL_shutdown(ssl);
  16593. }
  16594. }
  16595. inline bool is_peer_closed(session_t session, socket_t sock) {
  16596. if (!session) return true;
  16597. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  16598. detail::set_nonblocking(sock, true);
  16599. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16600. auto ssl = static_cast<SSL *>(session);
  16601. char buf;
  16602. auto ret = SSL_peek(ssl, &buf, 1);
  16603. if (ret > 0) return false;
  16604. auto err = SSL_get_error(ssl, ret);
  16605. return err == SSL_ERROR_ZERO_RETURN;
  16606. }
  16607. inline cert_t get_peer_cert(const_session_t session) {
  16608. if (!session) return nullptr;
  16609. return static_cast<cert_t>(SSL_get1_peer_certificate(
  16610. static_cast<SSL *>(const_cast<void *>(session))));
  16611. }
  16612. inline void free_cert(cert_t cert) {
  16613. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  16614. }
  16615. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16616. if (!cert || !hostname) return false;
  16617. auto x509 = static_cast<X509 *>(cert);
  16618. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  16619. if (detail::is_ip_address(hostname)) {
  16620. return X509_check_ip_asc(x509, hostname, 0) == 1;
  16621. }
  16622. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  16623. }
  16624. inline uint64_t hostname_mismatch_code() {
  16625. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  16626. }
  16627. inline long get_verify_result(const_session_t session) {
  16628. if (!session) return X509_V_ERR_UNSPECIFIED;
  16629. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  16630. }
  16631. inline std::string get_cert_subject_cn(cert_t cert) {
  16632. if (!cert) return "";
  16633. auto x509 = static_cast<X509 *>(cert);
  16634. auto subject_name = X509_get_subject_name(x509);
  16635. if (!subject_name) return "";
  16636. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  16637. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  16638. if (idx < 0) return "";
  16639. auto entry = X509_NAME_get_entry(subject_name, idx);
  16640. if (!entry) return "";
  16641. auto data = X509_NAME_ENTRY_get_data(entry);
  16642. if (!data) return "";
  16643. return std::string(
  16644. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  16645. static_cast<size_t>(ASN1_STRING_length(data)));
  16646. }
  16647. inline std::string get_cert_issuer_name(cert_t cert) {
  16648. if (!cert) return "";
  16649. auto x509 = static_cast<X509 *>(cert);
  16650. auto issuer_name = X509_get_issuer_name(x509);
  16651. if (!issuer_name) return "";
  16652. char buf[256];
  16653. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  16654. return std::string(buf);
  16655. }
  16656. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16657. sans.clear();
  16658. if (!cert) return false;
  16659. auto x509 = static_cast<X509 *>(cert);
  16660. auto names = static_cast<GENERAL_NAMES *>(
  16661. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16662. if (!names) return true; // No SANs is valid
  16663. auto count = sk_GENERAL_NAME_num(names);
  16664. for (decltype(count) i = 0; i < count; i++) {
  16665. auto gen = sk_GENERAL_NAME_value(names, i);
  16666. if (!gen) continue;
  16667. SanEntry entry;
  16668. switch (gen->type) {
  16669. case GEN_DNS:
  16670. entry.type = SanType::DNS;
  16671. if (gen->d.dNSName) {
  16672. entry.value = std::string(
  16673. reinterpret_cast<const char *>(
  16674. ASN1_STRING_get0_data(gen->d.dNSName)),
  16675. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  16676. }
  16677. break;
  16678. case GEN_IPADD:
  16679. entry.type = SanType::IP;
  16680. if (gen->d.iPAddress) {
  16681. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  16682. auto len = ASN1_STRING_length(gen->d.iPAddress);
  16683. if (len == 4) {
  16684. // IPv4
  16685. char buf[INET_ADDRSTRLEN];
  16686. inet_ntop(AF_INET, data, buf, sizeof(buf));
  16687. entry.value = buf;
  16688. } else if (len == 16) {
  16689. // IPv6
  16690. char buf[INET6_ADDRSTRLEN];
  16691. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  16692. entry.value = buf;
  16693. }
  16694. }
  16695. break;
  16696. case GEN_EMAIL:
  16697. entry.type = SanType::EMAIL;
  16698. if (gen->d.rfc822Name) {
  16699. entry.value = std::string(
  16700. reinterpret_cast<const char *>(
  16701. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  16702. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  16703. }
  16704. break;
  16705. case GEN_URI:
  16706. entry.type = SanType::URI;
  16707. if (gen->d.uniformResourceIdentifier) {
  16708. entry.value = std::string(
  16709. reinterpret_cast<const char *>(
  16710. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  16711. static_cast<size_t>(
  16712. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  16713. }
  16714. break;
  16715. default: entry.type = SanType::OTHER; break;
  16716. }
  16717. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16718. }
  16719. GENERAL_NAMES_free(names);
  16720. return true;
  16721. }
  16722. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16723. time_t &not_after) {
  16724. if (!cert) return false;
  16725. auto x509 = static_cast<X509 *>(cert);
  16726. auto nb = X509_get0_notBefore(x509);
  16727. auto na = X509_get0_notAfter(x509);
  16728. if (!nb || !na) return false;
  16729. ASN1_TIME *epoch = ASN1_TIME_new();
  16730. if (!epoch) return false;
  16731. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  16732. if (!ASN1_TIME_set(epoch, 0)) return false;
  16733. int pday, psec;
  16734. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  16735. not_before = 86400 * (time_t)pday + psec;
  16736. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  16737. not_after = 86400 * (time_t)pday + psec;
  16738. return true;
  16739. }
  16740. inline std::string get_cert_serial(cert_t cert) {
  16741. if (!cert) return "";
  16742. auto x509 = static_cast<X509 *>(cert);
  16743. auto serial = X509_get_serialNumber(x509);
  16744. if (!serial) return "";
  16745. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  16746. if (!bn) return "";
  16747. auto hex = BN_bn2hex(bn);
  16748. BN_free(bn);
  16749. if (!hex) return "";
  16750. std::string result(hex);
  16751. OPENSSL_free(hex);
  16752. return result;
  16753. }
  16754. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16755. if (!cert) return false;
  16756. auto x509 = static_cast<X509 *>(cert);
  16757. auto len = i2d_X509(x509, nullptr);
  16758. if (len < 0) return false;
  16759. der.resize(static_cast<size_t>(len));
  16760. auto p = der.data();
  16761. i2d_X509(x509, &p);
  16762. return true;
  16763. }
  16764. inline const char *get_sni(const_session_t session) {
  16765. if (!session) return nullptr;
  16766. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  16767. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  16768. }
  16769. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  16770. inline uint64_t get_error() { return ERR_get_error(); }
  16771. inline std::string error_string(uint64_t code) {
  16772. char buf[256];
  16773. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  16774. return std::string(buf);
  16775. }
  16776. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16777. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  16778. if (!mem) { return nullptr; }
  16779. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  16780. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  16781. if (!inf) { return nullptr; }
  16782. auto store = X509_STORE_new();
  16783. if (store) {
  16784. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  16785. auto itmp = sk_X509_INFO_value(inf, i);
  16786. if (!itmp) { continue; }
  16787. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  16788. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  16789. }
  16790. }
  16791. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  16792. return static_cast<ca_store_t>(store);
  16793. }
  16794. inline void free_ca_store(ca_store_t store) {
  16795. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  16796. }
  16797. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16798. if (!ctx || !store) { return false; }
  16799. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16800. auto x509_store = static_cast<X509_STORE *>(store);
  16801. // Check if same store is already set
  16802. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  16803. // SSL_CTX_set_cert_store takes ownership and frees the old store
  16804. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  16805. return true;
  16806. }
  16807. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16808. certs.clear();
  16809. if (!ctx) { return 0; }
  16810. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16811. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16812. if (!store) { return 0; }
  16813. auto objs = impl::get_store_objects(store);
  16814. if (!objs) { return 0; }
  16815. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  16816. auto count = sk_X509_OBJECT_num(objs);
  16817. for (decltype(count) i = 0; i < count; i++) {
  16818. auto obj = sk_X509_OBJECT_value(objs, i);
  16819. if (!obj) { continue; }
  16820. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  16821. auto x509 = X509_OBJECT_get0_X509(obj);
  16822. if (x509) {
  16823. // Increment reference count so caller can free it
  16824. X509_up_ref(x509);
  16825. certs.push_back(static_cast<cert_t>(x509));
  16826. }
  16827. }
  16828. }
  16829. return certs.size();
  16830. }
  16831. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16832. std::vector<std::string> names;
  16833. if (!ctx) { return names; }
  16834. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16835. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  16836. if (!store) { return names; }
  16837. auto objs = impl::get_store_objects(store);
  16838. if (!objs) { return names; }
  16839. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  16840. auto count = sk_X509_OBJECT_num(objs);
  16841. for (decltype(count) i = 0; i < count; i++) {
  16842. auto obj = sk_X509_OBJECT_value(objs, i);
  16843. if (!obj) { continue; }
  16844. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  16845. auto x509 = X509_OBJECT_get0_X509(obj);
  16846. if (x509) {
  16847. auto subject = X509_get_subject_name(x509);
  16848. if (subject) {
  16849. char buf[512];
  16850. X509_NAME_oneline(subject, buf, sizeof(buf));
  16851. names.push_back(buf);
  16852. }
  16853. }
  16854. }
  16855. }
  16856. return names;
  16857. }
  16858. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16859. const char *key_pem, const char *password) {
  16860. if (!ctx || !cert_pem || !key_pem) { return false; }
  16861. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16862. // Load certificate from PEM
  16863. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  16864. if (!cert_bio) { return false; }
  16865. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  16866. BIO_free(cert_bio);
  16867. if (!cert) { return false; }
  16868. // Load private key from PEM
  16869. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  16870. if (!key_bio) {
  16871. X509_free(cert);
  16872. return false;
  16873. }
  16874. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  16875. password ? const_cast<char *>(password)
  16876. : nullptr);
  16877. BIO_free(key_bio);
  16878. if (!key) {
  16879. X509_free(cert);
  16880. return false;
  16881. }
  16882. // Update certificate and key
  16883. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  16884. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  16885. X509_free(cert);
  16886. EVP_PKEY_free(key);
  16887. return ret;
  16888. }
  16889. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16890. if (!ctx || !ca_pem) { return false; }
  16891. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16892. // Create new X509_STORE from PEM
  16893. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  16894. if (!store) { return false; }
  16895. // SSL_CTX_set_cert_store takes ownership
  16896. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  16897. // Set client CA list for client certificate request
  16898. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  16899. if (ca_list) {
  16900. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  16901. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  16902. }
  16903. return true;
  16904. }
  16905. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16906. if (!ctx) { return false; }
  16907. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  16908. impl::get_verify_callback() = std::move(callback);
  16909. if (impl::get_verify_callback()) {
  16910. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  16911. } else {
  16912. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  16913. }
  16914. return true;
  16915. }
  16916. inline long get_verify_error(const_session_t session) {
  16917. if (!session) { return -1; }
  16918. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  16919. return SSL_get_verify_result(ssl);
  16920. }
  16921. inline std::string verify_error_string(long error_code) {
  16922. if (error_code == X509_V_OK) { return ""; }
  16923. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  16924. return str ? str : "unknown error";
  16925. }
  16926. } // namespace tls
  16927. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  16928. /*
  16929. * Group 9: TLS abstraction layer - Mbed TLS backend
  16930. */
  16931. /*
  16932. * Mbed TLS Backend Implementation
  16933. */
  16934. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16935. namespace tls {
  16936. namespace impl {
  16937. // Mbed TLS session wrapper
  16938. struct MbedTlsSession {
  16939. mbedtls_ssl_context ssl;
  16940. socket_t sock = INVALID_SOCKET;
  16941. std::string hostname; // For client: set via set_sni
  16942. std::string sni_hostname; // For server: received from client via SNI callback
  16943. // Mbed TLS has no SSL_peek() equivalent, so is_peer_closed() must probe with
  16944. // a real 1-byte mbedtls_ssl_read(). If that probe lands on application data
  16945. // (e.g. a response that arrived while this side was still in its post-write
  16946. // check), the byte is pushed back here and served by the next read().
  16947. unsigned char peeked_byte = 0;
  16948. bool has_peeked_byte = false;
  16949. // Set by set_sni() when the caller disabled hostname verification, so the
  16950. // verify callback can clear the CN/SAN mismatch flag while still enforcing
  16951. // the rest of the chain (Mbed TLS ties SNI and identity checking together;
  16952. // OpenSSL and wolfSSL keep them independent).
  16953. bool suppress_hostname_mismatch = false;
  16954. // Copied from the owning MbedTlsContext at creation. set_sni() uses this to
  16955. // decide which verify callback to install when hostname verification is
  16956. // disabled: mbedtls_verify_callback() when a user callback is genuinely
  16957. // wired for this context, or a self-contained one otherwise, so a session
  16958. // that never opted into a callback never consults the process-wide
  16959. // set_verify_callback() slot (which some other, unrelated client may have
  16960. // populated).
  16961. bool has_verify_callback = false;
  16962. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  16963. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  16964. MbedTlsSession(const MbedTlsSession &) = delete;
  16965. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  16966. };
  16967. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  16968. // queue)
  16969. inline int &mbedtls_last_error() {
  16970. static thread_local int err = 0;
  16971. return err;
  16972. }
  16973. // Helper to map Mbed TLS error to ErrorCode
  16974. inline ErrorCode map_mbedtls_error(int ret, int &out_errno,
  16975. uint32_t verify_flags) {
  16976. if (ret == 0) { return ErrorCode::Success; }
  16977. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  16978. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  16979. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  16980. return ErrorCode::PeerClosed;
  16981. }
  16982. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  16983. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  16984. out_errno = errno;
  16985. return ErrorCode::SyscallError;
  16986. }
  16987. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  16988. // Unlike OpenSSL/wolfSSL, Mbed TLS folds the CN/SAN identity check into
  16989. // the handshake's chain verification (see set_sni()); a mismatch there
  16990. // is reported the same way as any other verify_flags bit. Report it as
  16991. // HostnameMismatch, matching the other backends and the post-handshake
  16992. // identity check below, but only when naming is the sole problem -
  16993. // if the chain itself is also untrusted/expired/etc., that takes
  16994. // priority over the naming detail.
  16995. if (verify_flags == static_cast<uint32_t>(hostname_mismatch_code())) {
  16996. return ErrorCode::HostnameMismatch;
  16997. }
  16998. return ErrorCode::CertVerifyFailed;
  16999. }
  17000. return ErrorCode::Fatal;
  17001. }
  17002. // Populates a TlsError from a failed (non-zero) mbedtls_ssl_handshake()
  17003. // return value, including the verify-flags-dependent HostnameMismatch
  17004. // mapping; shared by connect() and connect_nonblocking() so the
  17005. // backend_code policy for that mapping only lives in one place.
  17006. inline void fill_mbedtls_tls_error(TlsError &err, mbedtls_ssl_context &ssl,
  17007. int ret) {
  17008. auto verify_flags = mbedtls_ssl_get_verify_result(&ssl);
  17009. err.code = map_mbedtls_error(ret, err.sys_errno, verify_flags);
  17010. err.backend_code = err.code == ErrorCode::HostnameMismatch
  17011. ? static_cast<uint64_t>(verify_flags)
  17012. : static_cast<uint64_t>(-ret);
  17013. }
  17014. // A TLS 1.3 NewSessionTicket (signaled by default on Mbed TLS 4.x) is a
  17015. // non-fatal notification delivered between records, not an error and not
  17016. // application data, so I/O calls that see it should just be retried. Kept in
  17017. // one helper so the retry loops keep an intact "do { } while (...)" instead of
  17018. // splitting the closing brace across an #if.
  17019. inline bool mbedtls_is_session_ticket(int ret) {
  17020. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  17021. return ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
  17022. #else
  17023. (void)ret;
  17024. return false;
  17025. #endif
  17026. }
  17027. // BIO-like send callback for Mbed TLS
  17028. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  17029. size_t len) {
  17030. auto sock = *static_cast<socket_t *>(ctx);
  17031. #ifdef _WIN32
  17032. auto ret =
  17033. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  17034. if (ret == SOCKET_ERROR) {
  17035. int err = WSAGetLastError();
  17036. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  17037. return MBEDTLS_ERR_NET_SEND_FAILED;
  17038. }
  17039. #else
  17040. auto ret = send(sock, buf, len, 0);
  17041. if (ret < 0) {
  17042. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  17043. return MBEDTLS_ERR_SSL_WANT_WRITE;
  17044. }
  17045. return MBEDTLS_ERR_NET_SEND_FAILED;
  17046. }
  17047. #endif
  17048. return static_cast<int>(ret);
  17049. }
  17050. // BIO-like recv callback for Mbed TLS
  17051. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  17052. auto sock = *static_cast<socket_t *>(ctx);
  17053. #ifdef _WIN32
  17054. auto ret =
  17055. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  17056. if (ret == SOCKET_ERROR) {
  17057. int err = WSAGetLastError();
  17058. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  17059. return MBEDTLS_ERR_NET_RECV_FAILED;
  17060. }
  17061. #else
  17062. auto ret = recv(sock, buf, len, 0);
  17063. if (ret < 0) {
  17064. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  17065. return MBEDTLS_ERR_SSL_WANT_READ;
  17066. }
  17067. return MBEDTLS_ERR_NET_RECV_FAILED;
  17068. }
  17069. #endif
  17070. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  17071. return static_cast<int>(ret);
  17072. }
  17073. // MbedTlsContext constructor/destructor implementations
  17074. inline MbedTlsContext::MbedTlsContext() {
  17075. mbedtls_ssl_config_init(&conf);
  17076. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17077. mbedtls_entropy_init(&entropy);
  17078. mbedtls_ctr_drbg_init(&ctr_drbg);
  17079. #endif
  17080. mbedtls_x509_crt_init(&ca_chain);
  17081. mbedtls_x509_crt_init(&own_cert);
  17082. mbedtls_pk_init(&own_key);
  17083. }
  17084. inline MbedTlsContext::~MbedTlsContext() {
  17085. mbedtls_pk_free(&own_key);
  17086. mbedtls_x509_crt_free(&own_cert);
  17087. mbedtls_x509_crt_free(&ca_chain);
  17088. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17089. mbedtls_ctr_drbg_free(&ctr_drbg);
  17090. mbedtls_entropy_free(&entropy);
  17091. #endif
  17092. mbedtls_ssl_config_free(&conf);
  17093. }
  17094. // Thread-local storage for SNI captured during handshake
  17095. // This is needed because the SNI callback doesn't have a way to pass
  17096. // session-specific data before the session is fully set up
  17097. inline std::string &mbedpending_sni() {
  17098. static thread_local std::string sni;
  17099. return sni;
  17100. }
  17101. // SNI callback for Mbed TLS server to capture client's SNI hostname
  17102. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  17103. const unsigned char *name, size_t name_len) {
  17104. (void)p_ctx;
  17105. (void)ssl;
  17106. // Store SNI name in thread-local storage
  17107. // It will be retrieved and stored in the session after handshake
  17108. if (name && name_len > 0) {
  17109. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  17110. } else {
  17111. mbedpending_sni().clear();
  17112. }
  17113. return 0; // Accept any SNI
  17114. }
  17115. inline void mbedtls_clear_cn_mismatch(uint32_t *flags) {
  17116. *flags &= ~static_cast<uint32_t>(hostname_mismatch_code());
  17117. }
  17118. // Verify callback used when hostname verification is disabled for a session
  17119. // that has no user-supplied verify callback of its own (MbedTlsSession::
  17120. // has_verify_callback is false). Deliberately does not consult
  17121. // get_verify_callback(): that slot is process-wide, so reading it here would
  17122. // pick up whatever another, unrelated client last installed there.
  17123. inline int mbedtls_mask_hostname_mismatch_callback(void *data,
  17124. mbedtls_x509_crt *, int,
  17125. uint32_t *flags) {
  17126. (void)data;
  17127. mbedtls_clear_cn_mismatch(flags);
  17128. return 0;
  17129. }
  17130. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  17131. int cert_depth, uint32_t *flags);
  17132. // MbedTLS verify callback wrapper
  17133. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  17134. int cert_depth, uint32_t *flags) {
  17135. // data points to the MbedTlsSession
  17136. auto *session = static_cast<MbedTlsSession *>(data);
  17137. // set_sni() disabled hostname verification for this session: drop the
  17138. // CN/SAN mismatch flag so it doesn't fail the chain check below, mirroring
  17139. // the OpenSSL/wolfSSL backends where identity checking is independent of
  17140. // SNI. The final pass/fail decision still comes from the remaining flags
  17141. // (or, below, from the user's own verify callback).
  17142. if (session && session->suppress_hostname_mismatch) {
  17143. mbedtls_clear_cn_mismatch(flags);
  17144. }
  17145. auto &callback = get_verify_callback();
  17146. if (!callback) { return 0; } // Continue with default verification
  17147. // Build context
  17148. VerifyContext verify_ctx;
  17149. verify_ctx.session = static_cast<session_t>(session);
  17150. verify_ctx.cert = static_cast<cert_t>(crt);
  17151. verify_ctx.depth = cert_depth;
  17152. verify_ctx.preverify_ok = (*flags == 0);
  17153. verify_ctx.error_code = static_cast<long>(*flags);
  17154. // Convert Mbed TLS flags to error string
  17155. static thread_local char error_buf[256];
  17156. if (*flags != 0) {
  17157. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  17158. verify_ctx.error_string = error_buf;
  17159. } else {
  17160. verify_ctx.error_string = nullptr;
  17161. }
  17162. bool accepted = callback(verify_ctx);
  17163. if (accepted) {
  17164. *flags = 0; // Clear all error flags
  17165. return 0;
  17166. }
  17167. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  17168. }
  17169. } // namespace impl
  17170. inline ctx_t create_client_context() {
  17171. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  17172. if (!ctx) { return nullptr; }
  17173. ctx->is_server = false;
  17174. #ifdef CPPHTTPLIB_MBEDTLS_V4
  17175. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  17176. if (!detail::ensure_mbedtls_psa_crypto()) {
  17177. delete ctx;
  17178. return nullptr;
  17179. }
  17180. int ret;
  17181. #else
  17182. // Seed the random number generator
  17183. const char *pers = "httplib_client";
  17184. int ret = mbedtls_ctr_drbg_seed(
  17185. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  17186. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  17187. if (ret != 0) {
  17188. impl::mbedtls_last_error() = ret;
  17189. delete ctx;
  17190. return nullptr;
  17191. }
  17192. #endif
  17193. // Set up SSL config for client
  17194. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  17195. MBEDTLS_SSL_TRANSPORT_STREAM,
  17196. MBEDTLS_SSL_PRESET_DEFAULT);
  17197. if (ret != 0) {
  17198. impl::mbedtls_last_error() = ret;
  17199. delete ctx;
  17200. return nullptr;
  17201. }
  17202. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17203. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  17204. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  17205. #endif
  17206. // Default: verify peer certificate
  17207. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17208. // Set minimum TLS version to 1.2
  17209. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17210. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17211. #else
  17212. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17213. MBEDTLS_SSL_MINOR_VERSION_3);
  17214. #endif
  17215. return static_cast<ctx_t>(ctx);
  17216. }
  17217. inline ctx_t create_server_context() {
  17218. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  17219. if (!ctx) { return nullptr; }
  17220. ctx->is_server = true;
  17221. #ifdef CPPHTTPLIB_MBEDTLS_V4
  17222. // Mbed TLS 4.x draws randomness from PSA Crypto; just ensure it is ready.
  17223. if (!detail::ensure_mbedtls_psa_crypto()) {
  17224. delete ctx;
  17225. return nullptr;
  17226. }
  17227. int ret;
  17228. #else
  17229. // Seed the random number generator
  17230. const char *pers = "httplib_server";
  17231. int ret = mbedtls_ctr_drbg_seed(
  17232. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  17233. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  17234. if (ret != 0) {
  17235. impl::mbedtls_last_error() = ret;
  17236. delete ctx;
  17237. return nullptr;
  17238. }
  17239. #endif
  17240. // Set up SSL config for server
  17241. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  17242. MBEDTLS_SSL_TRANSPORT_STREAM,
  17243. MBEDTLS_SSL_PRESET_DEFAULT);
  17244. if (ret != 0) {
  17245. impl::mbedtls_last_error() = ret;
  17246. delete ctx;
  17247. return nullptr;
  17248. }
  17249. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17250. // Set random number generator (Mbed TLS 4.x uses the PSA RNG implicitly)
  17251. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  17252. #endif
  17253. // Default: don't verify client
  17254. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  17255. // Set minimum TLS version to 1.2
  17256. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17257. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17258. #else
  17259. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17260. MBEDTLS_SSL_MINOR_VERSION_3);
  17261. #endif
  17262. // Set SNI callback to capture client's SNI hostname
  17263. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  17264. return static_cast<ctx_t>(ctx);
  17265. }
  17266. inline void free_context(ctx_t ctx) {
  17267. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  17268. }
  17269. inline bool set_min_version(ctx_t ctx, Version version) {
  17270. if (!ctx) { return false; }
  17271. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17272. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17273. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  17274. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  17275. if (version >= Version::TLS1_3) {
  17276. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  17277. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  17278. #endif
  17279. }
  17280. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  17281. #else
  17282. // Mbed TLS 2.x uses major/minor version numbers
  17283. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  17284. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  17285. if (version >= Version::TLS1_3) {
  17286. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  17287. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  17288. #else
  17289. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  17290. #endif
  17291. }
  17292. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  17293. #endif
  17294. return true;
  17295. }
  17296. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  17297. if (!ctx || !pem) { return false; }
  17298. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17299. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  17300. // Add null terminator if not present
  17301. std::string pem_str(pem, len);
  17302. int ret = mbedtls_x509_crt_parse(
  17303. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  17304. pem_str.size() + 1);
  17305. if (ret != 0) {
  17306. impl::mbedtls_last_error() = ret;
  17307. return false;
  17308. }
  17309. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17310. return true;
  17311. }
  17312. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  17313. if (!ctx || !file_path) { return false; }
  17314. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17315. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  17316. if (ret != 0) {
  17317. impl::mbedtls_last_error() = ret;
  17318. return false;
  17319. }
  17320. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17321. return true;
  17322. }
  17323. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  17324. if (!ctx || !dir_path) { return false; }
  17325. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17326. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  17327. if (ret < 0) { // Returns number of certs on success, negative on error
  17328. impl::mbedtls_last_error() = ret;
  17329. return false;
  17330. }
  17331. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17332. return true;
  17333. }
  17334. inline bool load_system_certs(ctx_t ctx) {
  17335. if (!ctx) { return false; }
  17336. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17337. bool loaded = false;
  17338. #ifdef _WIN32
  17339. loaded = impl::enumerate_windows_system_certs(
  17340. [&](const unsigned char *data, size_t len) {
  17341. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  17342. });
  17343. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  17344. loaded = impl::enumerate_macos_keychain_certs(
  17345. [&](const unsigned char *data, size_t len) {
  17346. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  17347. });
  17348. #else
  17349. for (auto path = impl::system_ca_paths(); *path; ++path) {
  17350. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  17351. loaded = true;
  17352. break;
  17353. }
  17354. }
  17355. if (!loaded) {
  17356. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  17357. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  17358. loaded = true;
  17359. break;
  17360. }
  17361. }
  17362. }
  17363. #endif
  17364. if (loaded) {
  17365. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  17366. }
  17367. return loaded;
  17368. }
  17369. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  17370. const char *password) {
  17371. if (!ctx || !cert || !key) { return false; }
  17372. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17373. // Parse certificate
  17374. std::string cert_str(cert);
  17375. int ret = mbedtls_x509_crt_parse(
  17376. &mctx->own_cert,
  17377. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  17378. cert_str.size() + 1);
  17379. if (ret != 0) {
  17380. impl::mbedtls_last_error() = ret;
  17381. return false;
  17382. }
  17383. // Parse private key
  17384. std::string key_str(key);
  17385. const unsigned char *pwd =
  17386. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  17387. size_t pwd_len = password ? strlen(password) : 0;
  17388. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17389. ret = mbedtls_pk_parse_key(
  17390. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  17391. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  17392. &mctx->ctr_drbg);
  17393. #else
  17394. ret = mbedtls_pk_parse_key(
  17395. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  17396. key_str.size() + 1, pwd, pwd_len);
  17397. #endif
  17398. if (ret != 0) {
  17399. impl::mbedtls_last_error() = ret;
  17400. return false;
  17401. }
  17402. // Verify that the certificate and private key match.
  17403. // Mbed TLS 4.x: mbedtls_pk_check_pair() reports a spurious mismatch for
  17404. // PSA-backed keys, so skip it and let the handshake surface a real mismatch.
  17405. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17406. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17407. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  17408. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17409. #else
  17410. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  17411. #endif
  17412. if (ret != 0) {
  17413. impl::mbedtls_last_error() = ret;
  17414. return false;
  17415. }
  17416. #endif
  17417. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  17418. if (ret != 0) {
  17419. impl::mbedtls_last_error() = ret;
  17420. return false;
  17421. }
  17422. return true;
  17423. }
  17424. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  17425. const char *key_path, const char *password) {
  17426. if (!ctx || !cert_path || !key_path) { return false; }
  17427. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17428. // Parse certificate file
  17429. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  17430. if (ret != 0) {
  17431. impl::mbedtls_last_error() = ret;
  17432. return false;
  17433. }
  17434. // Parse private key file
  17435. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  17436. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  17437. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17438. #else
  17439. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  17440. #endif
  17441. if (ret != 0) {
  17442. impl::mbedtls_last_error() = ret;
  17443. return false;
  17444. }
  17445. // Verify that the certificate and private key match.
  17446. // Mbed TLS 4.x: see set_client_cert() — skip the spurious check_pair.
  17447. #ifndef CPPHTTPLIB_MBEDTLS_V4
  17448. #ifdef CPPHTTPLIB_MBEDTLS_V3
  17449. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  17450. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  17451. #else
  17452. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  17453. #endif
  17454. if (ret != 0) {
  17455. impl::mbedtls_last_error() = ret;
  17456. return false;
  17457. }
  17458. #endif
  17459. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  17460. if (ret != 0) {
  17461. impl::mbedtls_last_error() = ret;
  17462. return false;
  17463. }
  17464. return true;
  17465. }
  17466. inline void set_verify_client(ctx_t ctx, bool require) {
  17467. if (!ctx) { return; }
  17468. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17469. mctx->verify_client = require;
  17470. if (require) {
  17471. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17472. } else {
  17473. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  17474. // is called (matching OpenSSL behavior). Otherwise use NONE.
  17475. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  17476. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  17477. : MBEDTLS_SSL_VERIFY_NONE);
  17478. }
  17479. }
  17480. inline session_t create_session(ctx_t ctx, socket_t sock) {
  17481. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  17482. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  17483. auto session = new (std::nothrow) impl::MbedTlsSession();
  17484. if (!session) { return nullptr; }
  17485. session->sock = sock;
  17486. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  17487. if (ret != 0) {
  17488. impl::mbedtls_last_error() = ret;
  17489. delete session;
  17490. return nullptr;
  17491. }
  17492. // Explicitly opt out of in-handshake hostname verification by default;
  17493. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  17494. // fails outright when no hostname was set. set_sni() installs the real
  17495. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  17496. // caller verifies the certificate identity post-handshake via
  17497. // verify_hostname().
  17498. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  17499. // Set BIO callbacks
  17500. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  17501. impl::mbedtls_net_recv_cb, nullptr);
  17502. // Set per-session verify callback with session pointer if callback is
  17503. // registered
  17504. session->has_verify_callback = mctx->has_verify_callback;
  17505. if (mctx->has_verify_callback) {
  17506. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  17507. session);
  17508. }
  17509. return static_cast<session_t>(session);
  17510. }
  17511. inline void free_session(session_t session) {
  17512. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  17513. }
  17514. inline bool set_sni(session_t session, const char *hostname,
  17515. bool verify_hostname) {
  17516. if (!session || !hostname) { return false; }
  17517. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17518. // mbedtls_ssl_set_hostname() both sends the SNI extension and binds the
  17519. // handshake-time CN/SAN check to `hostname`; the two can't be requested
  17520. // independently, so a disabled hostname check is handled below by masking
  17521. // the resulting mismatch flag instead of skipping this call.
  17522. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  17523. if (ret != 0) {
  17524. impl::mbedtls_last_error() = ret;
  17525. return false;
  17526. }
  17527. msession->hostname = hostname;
  17528. if (!verify_hostname) {
  17529. msession->suppress_hostname_mismatch = true;
  17530. // If a user verify callback is already wired for this session,
  17531. // mbedtls_verify_callback() masks the mismatch flag itself before
  17532. // consulting it (see suppress_hostname_mismatch above) - reinstalling it
  17533. // here would be redundant. Otherwise install the self-contained masking
  17534. // callback, which never touches the process-wide callback slot.
  17535. if (!msession->has_verify_callback) {
  17536. mbedtls_ssl_set_verify(&msession->ssl,
  17537. impl::mbedtls_mask_hostname_mismatch_callback,
  17538. msession);
  17539. }
  17540. }
  17541. return true;
  17542. }
  17543. inline TlsError connect(session_t session) {
  17544. TlsError err;
  17545. if (!session) {
  17546. err.code = ErrorCode::Fatal;
  17547. return err;
  17548. }
  17549. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17550. int ret;
  17551. do {
  17552. ret = mbedtls_ssl_handshake(&msession->ssl);
  17553. } while (impl::mbedtls_is_session_ticket(ret));
  17554. if (ret == 0) {
  17555. err.code = ErrorCode::Success;
  17556. } else {
  17557. impl::fill_mbedtls_tls_error(err, msession->ssl, ret);
  17558. impl::mbedtls_last_error() = ret;
  17559. }
  17560. return err;
  17561. }
  17562. inline TlsError accept(session_t session) {
  17563. // Same as connect for Mbed TLS - handshake works for both client and server
  17564. auto result = connect(session);
  17565. // After successful handshake, capture SNI from thread-local storage
  17566. if (result.code == ErrorCode::Success && session) {
  17567. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17568. msession->sni_hostname = std::move(impl::mbedpending_sni());
  17569. impl::mbedpending_sni().clear();
  17570. }
  17571. return result;
  17572. }
  17573. inline bool connect_nonblocking(session_t session, socket_t sock,
  17574. time_t timeout_sec, time_t timeout_usec,
  17575. TlsError *err) {
  17576. if (!session) {
  17577. if (err) { err->code = ErrorCode::Fatal; }
  17578. return false;
  17579. }
  17580. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17581. // Set socket to non-blocking mode
  17582. detail::set_nonblocking(sock, true);
  17583. auto cleanup =
  17584. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17585. int ret;
  17586. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  17587. // Non-fatal TLS 1.3 ticket; retry immediately.
  17588. if (impl::mbedtls_is_session_ticket(ret)) { continue; }
  17589. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  17590. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  17591. continue;
  17592. }
  17593. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  17594. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  17595. continue;
  17596. }
  17597. }
  17598. // TlsError or timeout
  17599. if (err) { impl::fill_mbedtls_tls_error(*err, msession->ssl, ret); }
  17600. impl::mbedtls_last_error() = ret;
  17601. return false;
  17602. }
  17603. if (err) { err->code = ErrorCode::Success; }
  17604. return true;
  17605. }
  17606. inline bool accept_nonblocking(session_t session, socket_t sock,
  17607. time_t timeout_sec, time_t timeout_usec,
  17608. TlsError *err) {
  17609. // Same implementation as connect for Mbed TLS
  17610. bool result =
  17611. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  17612. // After successful handshake, capture SNI from thread-local storage
  17613. if (result && session) {
  17614. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17615. msession->sni_hostname = std::move(impl::mbedpending_sni());
  17616. impl::mbedpending_sni().clear();
  17617. }
  17618. return result;
  17619. }
  17620. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  17621. if (!session || !buf) {
  17622. err.code = ErrorCode::Fatal;
  17623. return -1;
  17624. }
  17625. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17626. // Serve a byte consumed by the is_peer_closed() probe before reading more.
  17627. if (msession->has_peeked_byte) {
  17628. if (len == 0) { return 0; }
  17629. auto p = static_cast<unsigned char *>(buf);
  17630. p[0] = msession->peeked_byte;
  17631. msession->has_peeked_byte = false;
  17632. size_t n = 1;
  17633. // Top up with any already-decrypted bytes without risking a block.
  17634. if (len > 1 && mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17635. int extra = mbedtls_ssl_read(&msession->ssl, p + 1, len - 1);
  17636. if (extra > 0) { n += static_cast<size_t>(extra); }
  17637. }
  17638. err.code = ErrorCode::Success;
  17639. return static_cast<ssize_t>(n);
  17640. }
  17641. int ret;
  17642. do {
  17643. ret = mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf),
  17644. len);
  17645. } while (impl::mbedtls_is_session_ticket(ret));
  17646. if (ret > 0) {
  17647. err.code = ErrorCode::Success;
  17648. return static_cast<ssize_t>(ret);
  17649. }
  17650. if (ret == 0) {
  17651. err.code = ErrorCode::PeerClosed;
  17652. return 0;
  17653. }
  17654. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17655. err.backend_code = static_cast<uint64_t>(-ret);
  17656. impl::mbedtls_last_error() = ret;
  17657. // mbedTLS signals a clean close_notify via a negative error code rather
  17658. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  17659. if (err.code == ErrorCode::PeerClosed) { return 0; }
  17660. return -1;
  17661. }
  17662. inline ssize_t write(session_t session, const void *buf, size_t len,
  17663. TlsError &err) {
  17664. if (!session || !buf) {
  17665. err.code = ErrorCode::Fatal;
  17666. return -1;
  17667. }
  17668. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17669. int ret;
  17670. do {
  17671. ret = mbedtls_ssl_write(&msession->ssl,
  17672. static_cast<const unsigned char *>(buf), len);
  17673. } while (impl::mbedtls_is_session_ticket(ret));
  17674. if (ret > 0) {
  17675. err.code = ErrorCode::Success;
  17676. return static_cast<ssize_t>(ret);
  17677. }
  17678. if (ret == 0) {
  17679. err.code = ErrorCode::PeerClosed;
  17680. return 0;
  17681. }
  17682. err.code = impl::map_mbedtls_error(ret, err.sys_errno, 0);
  17683. err.backend_code = static_cast<uint64_t>(-ret);
  17684. impl::mbedtls_last_error() = ret;
  17685. return -1;
  17686. }
  17687. inline int pending(const_session_t session) {
  17688. if (!session) { return 0; }
  17689. auto msession =
  17690. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17691. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl)) +
  17692. (msession->has_peeked_byte ? 1 : 0);
  17693. }
  17694. inline void shutdown(session_t session, bool graceful) {
  17695. if (!session) { return; }
  17696. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17697. if (graceful) {
  17698. // Try to send close_notify, but don't block forever
  17699. int ret;
  17700. int attempts = 0;
  17701. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  17702. attempts < 3) {
  17703. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  17704. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  17705. break;
  17706. }
  17707. attempts++;
  17708. }
  17709. }
  17710. }
  17711. inline bool is_peer_closed(session_t session, socket_t sock) {
  17712. if (!session || sock == INVALID_SOCKET) { return true; }
  17713. auto msession = static_cast<impl::MbedTlsSession *>(session);
  17714. // Check if there's already decrypted or pushed-back data available.
  17715. // If so, the connection is definitely alive.
  17716. if (msession->has_peeked_byte ||
  17717. mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) {
  17718. return false;
  17719. }
  17720. // Set socket to non-blocking to avoid blocking on read
  17721. detail::set_nonblocking(sock, true);
  17722. auto cleanup =
  17723. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  17724. // Probe with a 1-byte read (Mbed TLS has no peek API). If the probe lands
  17725. // on application data — e.g. a response that already arrived — push the
  17726. // byte back so the next read() delivers it instead of losing it.
  17727. unsigned char buf;
  17728. int ret;
  17729. do {
  17730. ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  17731. } while (impl::mbedtls_is_session_ticket(ret));
  17732. // If we got data or WANT_READ (would block), connection is alive
  17733. if (ret > 0) {
  17734. msession->peeked_byte = buf;
  17735. msession->has_peeked_byte = true;
  17736. return false;
  17737. }
  17738. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  17739. // If we get a peer close notify or a connection reset, the peer is closed
  17740. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  17741. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  17742. }
  17743. inline cert_t get_peer_cert(const_session_t session) {
  17744. if (!session) { return nullptr; }
  17745. auto msession =
  17746. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17747. // Mbed TLS returns a pointer to the internal peer cert chain.
  17748. // WARNING: This pointer is only valid while the session is active.
  17749. // Do not use the certificate after calling free_session().
  17750. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  17751. return const_cast<mbedtls_x509_crt *>(cert);
  17752. }
  17753. inline void free_cert(cert_t cert) {
  17754. // Mbed TLS: peer certificate is owned by the SSL context.
  17755. // No-op here, but callers should still call this for cross-backend
  17756. // portability.
  17757. (void)cert;
  17758. }
  17759. inline bool verify_hostname(cert_t cert, const char *hostname) {
  17760. if (!cert || !hostname) { return false; }
  17761. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  17762. std::string host_str(hostname);
  17763. // Check if hostname is an IP address (IPv4 or IPv6)
  17764. unsigned char ip_bytes[16];
  17765. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  17766. auto is_ip = ip_len > 0;
  17767. // Check Subject Alternative Names (SAN)
  17768. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  17769. // - DNS names: raw string bytes
  17770. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  17771. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  17772. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  17773. const unsigned char *p = san->buf.p;
  17774. size_t len = san->buf.len;
  17775. if (is_ip) {
  17776. // For an IP host, only a matching iPAddress SAN of the same family
  17777. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  17778. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  17779. } else {
  17780. // Check if this SAN is a DNS name (printable ASCII string)
  17781. bool is_dns = len > 0;
  17782. for (size_t i = 0; i < len && is_dns; i++) {
  17783. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  17784. }
  17785. if (is_dns) {
  17786. std::string san_name(reinterpret_cast<const char *>(p), len);
  17787. if (detail::match_hostname(san_name, host_str)) { return true; }
  17788. }
  17789. }
  17790. san = san->next;
  17791. }
  17792. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  17793. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  17794. // the OpenSSL backend's X509_check_ip behaves the same way).
  17795. if (!is_ip) {
  17796. char cn[256];
  17797. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  17798. if (ret > 0) {
  17799. std::string cn_str(cn);
  17800. // Look for "CN=" in the DN string
  17801. size_t cn_pos = cn_str.find("CN=");
  17802. if (cn_pos != std::string::npos) {
  17803. size_t start = cn_pos + 3;
  17804. size_t end = cn_str.find(',', start);
  17805. std::string cn_value =
  17806. cn_str.substr(start, end == std::string::npos ? end : end - start);
  17807. if (detail::match_hostname(cn_value, host_str)) { return true; }
  17808. }
  17809. }
  17810. }
  17811. return false;
  17812. }
  17813. inline uint64_t hostname_mismatch_code() {
  17814. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  17815. }
  17816. inline long get_verify_result(const_session_t session) {
  17817. if (!session) { return -1; }
  17818. auto msession =
  17819. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  17820. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  17821. // Return 0 (X509_V_OK equivalent) if verification passed
  17822. return flags == 0 ? 0 : static_cast<long>(flags);
  17823. }
  17824. inline std::string get_cert_subject_cn(cert_t cert) {
  17825. if (!cert) return "";
  17826. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17827. // Find the CN in the subject
  17828. const mbedtls_x509_name *name = &x509->subject;
  17829. while (name != nullptr) {
  17830. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  17831. return std::string(reinterpret_cast<const char *>(name->val.p),
  17832. name->val.len);
  17833. }
  17834. name = name->next;
  17835. }
  17836. return "";
  17837. }
  17838. inline std::string get_cert_issuer_name(cert_t cert) {
  17839. if (!cert) return "";
  17840. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17841. // Build a human-readable issuer name string
  17842. char buf[512];
  17843. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  17844. if (ret < 0) return "";
  17845. return std::string(buf);
  17846. }
  17847. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  17848. sans.clear();
  17849. if (!cert) return false;
  17850. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17851. // Parse the Subject Alternative Name extension
  17852. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  17853. while (cur != nullptr) {
  17854. if (cur->buf.len > 0) {
  17855. // Mbed TLS stores SAN as ASN.1 sequences
  17856. // The tag byte indicates the type
  17857. const unsigned char *p = cur->buf.p;
  17858. size_t len = cur->buf.len;
  17859. // First byte is the tag
  17860. unsigned char tag = *p;
  17861. p++;
  17862. len--;
  17863. // Parse length (simple single-byte length assumed)
  17864. if (len > 0 && *p < 0x80) {
  17865. size_t value_len = *p;
  17866. p++;
  17867. len--;
  17868. if (value_len <= len) {
  17869. SanEntry entry;
  17870. // ASN.1 context tags for GeneralName
  17871. switch (tag & 0x1F) {
  17872. case 2: // dNSName
  17873. entry.type = SanType::DNS;
  17874. entry.value =
  17875. std::string(reinterpret_cast<const char *>(p), value_len);
  17876. break;
  17877. case 7: // iPAddress
  17878. entry.type = SanType::IP;
  17879. if (value_len == 4) {
  17880. // IPv4
  17881. char buf[16];
  17882. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  17883. entry.value = buf;
  17884. } else if (value_len == 16) {
  17885. // IPv6
  17886. char buf[64];
  17887. snprintf(buf, sizeof(buf),
  17888. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  17889. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  17890. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  17891. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  17892. entry.value = buf;
  17893. }
  17894. break;
  17895. case 1: // rfc822Name (email)
  17896. entry.type = SanType::EMAIL;
  17897. entry.value =
  17898. std::string(reinterpret_cast<const char *>(p), value_len);
  17899. break;
  17900. case 6: // uniformResourceIdentifier
  17901. entry.type = SanType::URI;
  17902. entry.value =
  17903. std::string(reinterpret_cast<const char *>(p), value_len);
  17904. break;
  17905. default: entry.type = SanType::OTHER; break;
  17906. }
  17907. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17908. }
  17909. }
  17910. }
  17911. cur = cur->next;
  17912. }
  17913. return true;
  17914. }
  17915. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17916. time_t &not_after) {
  17917. if (!cert) return false;
  17918. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17919. // Convert mbedtls_x509_time to time_t
  17920. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  17921. struct tm tm_time = {};
  17922. tm_time.tm_year = t.year - 1900;
  17923. tm_time.tm_mon = t.mon - 1;
  17924. tm_time.tm_mday = t.day;
  17925. tm_time.tm_hour = t.hour;
  17926. tm_time.tm_min = t.min;
  17927. tm_time.tm_sec = t.sec;
  17928. #ifdef _WIN32
  17929. return _mkgmtime(&tm_time);
  17930. #else
  17931. return timegm(&tm_time);
  17932. #endif
  17933. };
  17934. not_before = to_time_t(x509->valid_from);
  17935. not_after = to_time_t(x509->valid_to);
  17936. return true;
  17937. }
  17938. inline std::string get_cert_serial(cert_t cert) {
  17939. if (!cert) return "";
  17940. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  17941. // Convert serial number to hex string
  17942. std::string result;
  17943. result.reserve(x509->serial.len * 2);
  17944. for (size_t i = 0; i < x509->serial.len; i++) {
  17945. char hex[3];
  17946. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  17947. result += hex;
  17948. }
  17949. return result;
  17950. }
  17951. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17952. if (!cert) return false;
  17953. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  17954. if (!crt->raw.p || crt->raw.len == 0) return false;
  17955. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  17956. return true;
  17957. }
  17958. inline const char *get_sni(const_session_t session) {
  17959. if (!session) return nullptr;
  17960. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  17961. // For server: return SNI received from client during handshake
  17962. if (!msession->sni_hostname.empty()) {
  17963. return msession->sni_hostname.c_str();
  17964. }
  17965. // For client: return the hostname set via set_sni
  17966. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  17967. return nullptr;
  17968. }
  17969. inline uint64_t peek_error() {
  17970. // Mbed TLS doesn't have an error queue, return the last error
  17971. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  17972. }
  17973. inline uint64_t get_error() {
  17974. // Mbed TLS doesn't have an error queue, return and clear the last error
  17975. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  17976. impl::mbedtls_last_error() = 0;
  17977. return err;
  17978. }
  17979. inline std::string error_string(uint64_t code) {
  17980. char buf[256];
  17981. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  17982. return std::string(buf);
  17983. }
  17984. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17985. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  17986. if (!ca_chain) { return nullptr; }
  17987. mbedtls_x509_crt_init(ca_chain);
  17988. // mbedtls_x509_crt_parse expects null-terminated PEM
  17989. int ret = mbedtls_x509_crt_parse(ca_chain,
  17990. reinterpret_cast<const unsigned char *>(pem),
  17991. len + 1); // +1 for null terminator
  17992. if (ret != 0) {
  17993. // Try without +1 in case PEM is already null-terminated
  17994. ret = mbedtls_x509_crt_parse(
  17995. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  17996. if (ret != 0) {
  17997. mbedtls_x509_crt_free(ca_chain);
  17998. delete ca_chain;
  17999. return nullptr;
  18000. }
  18001. }
  18002. return static_cast<ca_store_t>(ca_chain);
  18003. }
  18004. inline void free_ca_store(ca_store_t store) {
  18005. if (store) {
  18006. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  18007. mbedtls_x509_crt_free(ca_chain);
  18008. delete ca_chain;
  18009. }
  18010. }
  18011. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  18012. if (!ctx || !store) { return false; }
  18013. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18014. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  18015. // Free existing CA chain
  18016. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  18017. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  18018. // Copy the CA chain (deep copy)
  18019. // Parse from the raw data of the source cert
  18020. mbedtls_x509_crt *src = ca_chain;
  18021. while (src != nullptr) {
  18022. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  18023. src->raw.len);
  18024. if (ret != 0) {
  18025. free_ca_store(store);
  18026. return false;
  18027. }
  18028. src = src->next;
  18029. }
  18030. // This function takes ownership of the store; the chain was deep-copied
  18031. // above, so release the source
  18032. free_ca_store(store);
  18033. // Update the SSL config to use the new CA chain
  18034. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  18035. return true;
  18036. }
  18037. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  18038. certs.clear();
  18039. if (!ctx) { return 0; }
  18040. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18041. // Iterate through the CA chain
  18042. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  18043. while (cert != nullptr && cert->raw.len > 0) {
  18044. // Create a copy of the certificate for the caller
  18045. auto *copy = new mbedtls_x509_crt;
  18046. mbedtls_x509_crt_init(copy);
  18047. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  18048. if (ret == 0) {
  18049. certs.push_back(static_cast<cert_t>(copy));
  18050. } else {
  18051. mbedtls_x509_crt_free(copy);
  18052. delete copy;
  18053. }
  18054. cert = cert->next;
  18055. }
  18056. return certs.size();
  18057. }
  18058. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  18059. std::vector<std::string> names;
  18060. if (!ctx) { return names; }
  18061. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18062. // Iterate through the CA chain
  18063. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  18064. while (cert != nullptr && cert->raw.len > 0) {
  18065. char buf[512];
  18066. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  18067. if (ret > 0) { names.push_back(buf); }
  18068. cert = cert->next;
  18069. }
  18070. return names;
  18071. }
  18072. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  18073. const char *key_pem, const char *password) {
  18074. if (!ctx || !cert_pem || !key_pem) { return false; }
  18075. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18076. // Free existing certificate and key
  18077. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  18078. mbedtls_pk_free(&mbed_ctx->own_key);
  18079. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  18080. mbedtls_pk_init(&mbed_ctx->own_key);
  18081. // Parse certificate PEM
  18082. int ret = mbedtls_x509_crt_parse(
  18083. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  18084. strlen(cert_pem) + 1);
  18085. if (ret != 0) {
  18086. impl::mbedtls_last_error() = ret;
  18087. return false;
  18088. }
  18089. // Parse private key PEM
  18090. #if defined(CPPHTTPLIB_MBEDTLS_V3) && !defined(CPPHTTPLIB_MBEDTLS_V4)
  18091. ret = mbedtls_pk_parse_key(
  18092. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  18093. strlen(key_pem) + 1,
  18094. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  18095. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  18096. &mbed_ctx->ctr_drbg);
  18097. #else
  18098. ret = mbedtls_pk_parse_key(
  18099. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  18100. strlen(key_pem) + 1,
  18101. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  18102. password ? strlen(password) : 0);
  18103. #endif
  18104. if (ret != 0) {
  18105. impl::mbedtls_last_error() = ret;
  18106. return false;
  18107. }
  18108. // Configure SSL to use the new certificate and key
  18109. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  18110. &mbed_ctx->own_key);
  18111. if (ret != 0) {
  18112. impl::mbedtls_last_error() = ret;
  18113. return false;
  18114. }
  18115. return true;
  18116. }
  18117. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  18118. if (!ctx || !ca_pem) { return false; }
  18119. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18120. // Free existing CA chain
  18121. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  18122. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  18123. // Parse CA PEM
  18124. int ret = mbedtls_x509_crt_parse(
  18125. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  18126. strlen(ca_pem) + 1);
  18127. if (ret != 0) {
  18128. impl::mbedtls_last_error() = ret;
  18129. return false;
  18130. }
  18131. // Update SSL config to use new CA chain
  18132. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  18133. return true;
  18134. }
  18135. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  18136. if (!ctx) { return false; }
  18137. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  18138. impl::get_verify_callback() = std::move(callback);
  18139. mbed_ctx->has_verify_callback =
  18140. static_cast<bool>(impl::get_verify_callback());
  18141. if (mbed_ctx->has_verify_callback) {
  18142. // Set OPTIONAL mode to ensure callback is called even when verification
  18143. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  18144. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  18145. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  18146. nullptr);
  18147. } else {
  18148. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  18149. }
  18150. return true;
  18151. }
  18152. inline long get_verify_error(const_session_t session) {
  18153. if (!session) { return -1; }
  18154. auto *msession =
  18155. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  18156. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  18157. }
  18158. inline std::string verify_error_string(long error_code) {
  18159. if (error_code == 0) { return ""; }
  18160. char buf[256];
  18161. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  18162. static_cast<uint32_t>(error_code));
  18163. // Remove trailing newline if present
  18164. std::string result(buf);
  18165. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  18166. result.pop_back();
  18167. }
  18168. return result;
  18169. }
  18170. } // namespace tls
  18171. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  18172. /*
  18173. * Group 10: TLS abstraction layer - wolfSSL backend
  18174. */
  18175. /*
  18176. * wolfSSL Backend Implementation
  18177. */
  18178. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  18179. namespace tls {
  18180. namespace impl {
  18181. // wolfSSL session wrapper
  18182. struct WolfSSLSession {
  18183. WOLFSSL *ssl = nullptr;
  18184. socket_t sock = INVALID_SOCKET;
  18185. std::string hostname; // For client: set via set_sni
  18186. std::string sni_hostname; // For server: received from client via SNI callback
  18187. WolfSSLSession() = default;
  18188. ~WolfSSLSession() {
  18189. if (ssl) { wolfSSL_free(ssl); }
  18190. }
  18191. WolfSSLSession(const WolfSSLSession &) = delete;
  18192. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  18193. };
  18194. // Thread-local error code accessor for wolfSSL
  18195. inline uint64_t &wolfssl_last_error() {
  18196. static thread_local uint64_t err = 0;
  18197. return err;
  18198. }
  18199. // Helper to map wolfSSL error to ErrorCode.
  18200. // ssl_error is the value from wolfSSL_get_error().
  18201. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  18202. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  18203. int &out_errno) {
  18204. switch (ssl_error) {
  18205. case SSL_ERROR_NONE: return ErrorCode::Success;
  18206. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  18207. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  18208. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  18209. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  18210. default:
  18211. if (ssl) {
  18212. // wolfSSL stores the low-level error code as a negative value.
  18213. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  18214. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  18215. if (low_err == DOMAIN_NAME_MISMATCH) {
  18216. return ErrorCode::HostnameMismatch;
  18217. }
  18218. // Check verify result to distinguish cert verification from generic SSL
  18219. // errors.
  18220. long vr = wolfSSL_get_verify_result(ssl);
  18221. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  18222. }
  18223. return ErrorCode::Fatal;
  18224. }
  18225. }
  18226. // WolfSSLContext constructor/destructor implementations
  18227. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  18228. inline WolfSSLContext::~WolfSSLContext() {
  18229. if (ctx) { wolfSSL_CTX_free(ctx); }
  18230. }
  18231. // Thread-local storage for SNI captured during handshake
  18232. inline std::string &wolfssl_pending_sni() {
  18233. static thread_local std::string sni;
  18234. return sni;
  18235. }
  18236. // SNI callback for wolfSSL server to capture client's SNI hostname
  18237. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  18238. (void)ret;
  18239. (void)exArg;
  18240. void *name_data = nullptr;
  18241. unsigned short name_len =
  18242. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  18243. if (name_data && name_len > 0) {
  18244. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  18245. name_len);
  18246. } else {
  18247. wolfssl_pending_sni().clear();
  18248. }
  18249. return 0; // Continue regardless
  18250. }
  18251. // wolfSSL verify callback wrapper
  18252. inline int wolfssl_verify_callback(int preverify_ok,
  18253. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  18254. auto &callback = get_verify_callback();
  18255. if (!callback) { return preverify_ok; }
  18256. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  18257. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  18258. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  18259. // Get the WOLFSSL object from the X509_STORE_CTX
  18260. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  18261. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  18262. VerifyContext verify_ctx;
  18263. verify_ctx.session = static_cast<session_t>(ssl);
  18264. verify_ctx.cert = static_cast<cert_t>(cert);
  18265. verify_ctx.depth = depth;
  18266. verify_ctx.preverify_ok = (preverify_ok != 0);
  18267. verify_ctx.error_code = static_cast<long>(err);
  18268. if (err != 0) {
  18269. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  18270. } else {
  18271. verify_ctx.error_string = nullptr;
  18272. }
  18273. bool accepted = callback(verify_ctx);
  18274. return accepted ? 1 : 0;
  18275. }
  18276. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  18277. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  18278. wolfSSL_CTX_set_default_passwd_cb(
  18279. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  18280. auto *pwd = static_cast<const char *>(userdata);
  18281. if (!pwd) return 0;
  18282. auto len = static_cast<int>(strlen(pwd));
  18283. if (len > size) len = size;
  18284. memcpy(buf, pwd, static_cast<size_t>(len));
  18285. return len;
  18286. });
  18287. }
  18288. } // namespace impl
  18289. inline ctx_t create_client_context() {
  18290. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  18291. if (!ctx) { return nullptr; }
  18292. ctx->is_server = false;
  18293. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  18294. if (!method) {
  18295. delete ctx;
  18296. return nullptr;
  18297. }
  18298. ctx->ctx = wolfSSL_CTX_new(method);
  18299. if (!ctx->ctx) {
  18300. delete ctx;
  18301. return nullptr;
  18302. }
  18303. // Default: verify peer certificate
  18304. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  18305. return static_cast<ctx_t>(ctx);
  18306. }
  18307. inline ctx_t create_server_context() {
  18308. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  18309. if (!ctx) { return nullptr; }
  18310. ctx->is_server = true;
  18311. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  18312. if (!method) {
  18313. delete ctx;
  18314. return nullptr;
  18315. }
  18316. ctx->ctx = wolfSSL_CTX_new(method);
  18317. if (!ctx->ctx) {
  18318. delete ctx;
  18319. return nullptr;
  18320. }
  18321. // Default: don't verify client
  18322. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  18323. // Enable SNI on server
  18324. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  18325. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  18326. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  18327. return static_cast<ctx_t>(ctx);
  18328. }
  18329. inline void free_context(ctx_t ctx) {
  18330. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  18331. }
  18332. inline bool set_min_version(ctx_t ctx, Version version) {
  18333. if (!ctx) { return false; }
  18334. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18335. int min_ver = WOLFSSL_TLSV1_2;
  18336. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  18337. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  18338. }
  18339. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  18340. if (!ctx || !pem) { return false; }
  18341. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18342. int ret = wolfSSL_CTX_load_verify_buffer(
  18343. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  18344. static_cast<long>(len), SSL_FILETYPE_PEM);
  18345. if (ret != SSL_SUCCESS) {
  18346. impl::wolfssl_last_error() =
  18347. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18348. return false;
  18349. }
  18350. wctx->ca_pem_data_.append(pem, len);
  18351. return true;
  18352. }
  18353. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  18354. if (!ctx || !file_path) { return false; }
  18355. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18356. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  18357. if (ret != SSL_SUCCESS) {
  18358. impl::wolfssl_last_error() =
  18359. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18360. return false;
  18361. }
  18362. return true;
  18363. }
  18364. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  18365. if (!ctx || !dir_path) { return false; }
  18366. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18367. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  18368. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  18369. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  18370. // immediately. Return true even on failure since the CA file may have
  18371. // already been loaded, matching OpenSSL's lenient behavior.
  18372. (void)ret;
  18373. return true;
  18374. }
  18375. inline bool load_system_certs(ctx_t ctx) {
  18376. if (!ctx) { return false; }
  18377. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18378. bool loaded = false;
  18379. #ifdef _WIN32
  18380. loaded = impl::enumerate_windows_system_certs(
  18381. [&](const unsigned char *data, size_t len) {
  18382. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  18383. static_cast<long>(len),
  18384. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  18385. });
  18386. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  18387. loaded = impl::enumerate_macos_keychain_certs(
  18388. [&](const unsigned char *data, size_t len) {
  18389. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  18390. static_cast<long>(len),
  18391. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  18392. });
  18393. #else
  18394. for (auto path = impl::system_ca_paths(); *path; ++path) {
  18395. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  18396. SSL_SUCCESS) {
  18397. loaded = true;
  18398. break;
  18399. }
  18400. }
  18401. if (!loaded) {
  18402. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  18403. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  18404. SSL_SUCCESS) {
  18405. loaded = true;
  18406. break;
  18407. }
  18408. }
  18409. }
  18410. #endif
  18411. return loaded;
  18412. }
  18413. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  18414. const char *password) {
  18415. if (!ctx || !cert || !key) { return false; }
  18416. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18417. // Load certificate
  18418. int ret = wolfSSL_CTX_use_certificate_buffer(
  18419. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  18420. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  18421. if (ret != SSL_SUCCESS) {
  18422. impl::wolfssl_last_error() =
  18423. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18424. return false;
  18425. }
  18426. // Set password callback if password is provided
  18427. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18428. // Load private key
  18429. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  18430. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  18431. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  18432. if (ret != SSL_SUCCESS) {
  18433. impl::wolfssl_last_error() =
  18434. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18435. return false;
  18436. }
  18437. // Verify that the certificate and private key match
  18438. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  18439. }
  18440. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  18441. const char *key_path, const char *password) {
  18442. if (!ctx || !cert_path || !key_path) { return false; }
  18443. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18444. // Load certificate file
  18445. int ret =
  18446. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  18447. if (ret != SSL_SUCCESS) {
  18448. impl::wolfssl_last_error() =
  18449. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18450. return false;
  18451. }
  18452. // Set password callback if password is provided
  18453. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  18454. // Load private key file
  18455. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  18456. if (ret != SSL_SUCCESS) {
  18457. impl::wolfssl_last_error() =
  18458. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18459. return false;
  18460. }
  18461. // Verify that the certificate and private key match
  18462. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  18463. }
  18464. inline void set_verify_client(ctx_t ctx, bool require) {
  18465. if (!ctx) { return; }
  18466. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18467. wctx->verify_client = require;
  18468. if (require) {
  18469. wolfSSL_CTX_set_verify(
  18470. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  18471. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  18472. } else {
  18473. if (wctx->has_verify_callback) {
  18474. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  18475. impl::wolfssl_verify_callback);
  18476. } else {
  18477. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  18478. }
  18479. }
  18480. }
  18481. inline session_t create_session(ctx_t ctx, socket_t sock) {
  18482. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  18483. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18484. auto session = new (std::nothrow) impl::WolfSSLSession();
  18485. if (!session) { return nullptr; }
  18486. session->sock = sock;
  18487. session->ssl = wolfSSL_new(wctx->ctx);
  18488. if (!session->ssl) {
  18489. impl::wolfssl_last_error() =
  18490. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18491. delete session;
  18492. return nullptr;
  18493. }
  18494. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  18495. return static_cast<session_t>(session);
  18496. }
  18497. inline void free_session(session_t session) {
  18498. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  18499. }
  18500. inline bool set_sni(session_t session, const char *hostname,
  18501. bool verify_hostname) {
  18502. if (!session || !hostname) { return false; }
  18503. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18504. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  18505. static_cast<word16>(strlen(hostname)));
  18506. if (ret != WOLFSSL_SUCCESS) {
  18507. impl::wolfssl_last_error() =
  18508. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18509. return false;
  18510. }
  18511. // wolfSSL_check_domain_name binds identity checking to the handshake,
  18512. // separately from the SNI extension sent above; skip it when hostname
  18513. // verification is disabled so only the chain is checked, matching OpenSSL.
  18514. if (verify_hostname) { wolfSSL_check_domain_name(wsession->ssl, hostname); }
  18515. wsession->hostname = hostname;
  18516. return true;
  18517. }
  18518. inline TlsError connect(session_t session) {
  18519. TlsError err;
  18520. if (!session) {
  18521. err.code = ErrorCode::Fatal;
  18522. return err;
  18523. }
  18524. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18525. int ret = wolfSSL_connect(wsession->ssl);
  18526. if (ret == SSL_SUCCESS) {
  18527. err.code = ErrorCode::Success;
  18528. } else {
  18529. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18530. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18531. err.backend_code = static_cast<uint64_t>(ssl_error);
  18532. impl::wolfssl_last_error() = err.backend_code;
  18533. }
  18534. return err;
  18535. }
  18536. inline TlsError accept(session_t session) {
  18537. TlsError err;
  18538. if (!session) {
  18539. err.code = ErrorCode::Fatal;
  18540. return err;
  18541. }
  18542. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18543. int ret = wolfSSL_accept(wsession->ssl);
  18544. if (ret == SSL_SUCCESS) {
  18545. err.code = ErrorCode::Success;
  18546. // Capture SNI from thread-local storage after successful handshake
  18547. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  18548. impl::wolfssl_pending_sni().clear();
  18549. } else {
  18550. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18551. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18552. err.backend_code = static_cast<uint64_t>(ssl_error);
  18553. impl::wolfssl_last_error() = err.backend_code;
  18554. }
  18555. return err;
  18556. }
  18557. inline bool connect_nonblocking(session_t session, socket_t sock,
  18558. time_t timeout_sec, time_t timeout_usec,
  18559. TlsError *err) {
  18560. if (!session) {
  18561. if (err) { err->code = ErrorCode::Fatal; }
  18562. return false;
  18563. }
  18564. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18565. // Set socket to non-blocking mode
  18566. detail::set_nonblocking(sock, true);
  18567. auto cleanup =
  18568. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18569. int ret;
  18570. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  18571. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18572. if (ssl_error == SSL_ERROR_WANT_READ) {
  18573. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  18574. continue;
  18575. }
  18576. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18577. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18578. continue;
  18579. }
  18580. }
  18581. // Error or timeout
  18582. if (err) {
  18583. err->code =
  18584. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18585. err->backend_code = static_cast<uint64_t>(ssl_error);
  18586. }
  18587. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18588. return false;
  18589. }
  18590. if (err) { err->code = ErrorCode::Success; }
  18591. return true;
  18592. }
  18593. inline bool accept_nonblocking(session_t session, socket_t sock,
  18594. time_t timeout_sec, time_t timeout_usec,
  18595. TlsError *err) {
  18596. if (!session) {
  18597. if (err) { err->code = ErrorCode::Fatal; }
  18598. return false;
  18599. }
  18600. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18601. // Set socket to non-blocking mode
  18602. detail::set_nonblocking(sock, true);
  18603. auto cleanup =
  18604. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18605. int ret;
  18606. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  18607. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18608. if (ssl_error == SSL_ERROR_WANT_READ) {
  18609. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  18610. continue;
  18611. }
  18612. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  18613. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  18614. continue;
  18615. }
  18616. }
  18617. // Error or timeout
  18618. if (err) {
  18619. err->code =
  18620. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  18621. err->backend_code = static_cast<uint64_t>(ssl_error);
  18622. }
  18623. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  18624. return false;
  18625. }
  18626. if (err) { err->code = ErrorCode::Success; }
  18627. // Capture SNI from thread-local storage after successful handshake
  18628. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  18629. impl::wolfssl_pending_sni().clear();
  18630. return true;
  18631. }
  18632. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  18633. if (!session || !buf) {
  18634. err.code = ErrorCode::Fatal;
  18635. return -1;
  18636. }
  18637. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18638. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  18639. if (ret > 0) {
  18640. err.code = ErrorCode::Success;
  18641. return static_cast<ssize_t>(ret);
  18642. }
  18643. if (ret == 0) {
  18644. err.code = ErrorCode::PeerClosed;
  18645. return 0;
  18646. }
  18647. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18648. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18649. err.backend_code = static_cast<uint64_t>(ssl_error);
  18650. impl::wolfssl_last_error() = err.backend_code;
  18651. return -1;
  18652. }
  18653. inline ssize_t write(session_t session, const void *buf, size_t len,
  18654. TlsError &err) {
  18655. if (!session || !buf) {
  18656. err.code = ErrorCode::Fatal;
  18657. return -1;
  18658. }
  18659. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18660. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  18661. if (ret > 0) {
  18662. err.code = ErrorCode::Success;
  18663. return static_cast<ssize_t>(ret);
  18664. }
  18665. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  18666. // Treat this as an error (return -1) so callers don't spin in a
  18667. // write loop adding zero to the offset.
  18668. if (ret == 0) {
  18669. err.code = ErrorCode::PeerClosed;
  18670. return -1;
  18671. }
  18672. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18673. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  18674. err.backend_code = static_cast<uint64_t>(ssl_error);
  18675. impl::wolfssl_last_error() = err.backend_code;
  18676. return -1;
  18677. }
  18678. inline int pending(const_session_t session) {
  18679. if (!session) { return 0; }
  18680. auto wsession =
  18681. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18682. return wolfSSL_pending(wsession->ssl);
  18683. }
  18684. inline void shutdown(session_t session, bool graceful) {
  18685. if (!session) { return; }
  18686. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18687. if (graceful) {
  18688. int ret;
  18689. int attempts = 0;
  18690. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  18691. attempts < 3) {
  18692. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18693. if (ssl_error != SSL_ERROR_WANT_READ &&
  18694. ssl_error != SSL_ERROR_WANT_WRITE) {
  18695. break;
  18696. }
  18697. attempts++;
  18698. }
  18699. } else {
  18700. wolfSSL_shutdown(wsession->ssl);
  18701. }
  18702. }
  18703. inline bool is_peer_closed(session_t session, socket_t sock) {
  18704. if (!session || sock == INVALID_SOCKET) { return true; }
  18705. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  18706. // Check if there's already decrypted data available
  18707. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  18708. // Set socket to non-blocking to avoid blocking on read
  18709. detail::set_nonblocking(sock, true);
  18710. auto cleanup =
  18711. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  18712. // Peek 1 byte to check connection status without consuming data
  18713. unsigned char buf;
  18714. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  18715. // If we got data or WANT_READ (would block), connection is alive
  18716. if (ret > 0) { return false; }
  18717. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  18718. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  18719. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  18720. ret == 0;
  18721. }
  18722. inline cert_t get_peer_cert(const_session_t session) {
  18723. if (!session) { return nullptr; }
  18724. auto wsession =
  18725. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18726. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  18727. return static_cast<cert_t>(cert);
  18728. }
  18729. inline void free_cert(cert_t cert) {
  18730. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  18731. }
  18732. inline bool verify_hostname(cert_t cert, const char *hostname) {
  18733. if (!cert || !hostname) { return false; }
  18734. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18735. std::string host_str(hostname);
  18736. // Check if hostname is an IP address (IPv4 or IPv6)
  18737. unsigned char ip_bytes[16];
  18738. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  18739. auto is_ip = ip_len > 0;
  18740. // Check Subject Alternative Names
  18741. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  18742. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18743. if (san_names) {
  18744. int san_count = wolfSSL_sk_num(san_names);
  18745. for (int i = 0; i < san_count; i++) {
  18746. auto *names =
  18747. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  18748. if (!names) continue;
  18749. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  18750. // DNS name
  18751. unsigned char *dns_name = nullptr;
  18752. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  18753. if (dns_name && dns_len > 0) {
  18754. std::string san_name(reinterpret_cast<char *>(dns_name),
  18755. static_cast<size_t>(dns_len));
  18756. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  18757. if (detail::match_hostname(san_name, host_str)) {
  18758. wolfSSL_sk_free(san_names);
  18759. return true;
  18760. }
  18761. }
  18762. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  18763. // IP address: only an iPAddress SAN of the same family (4 bytes for
  18764. // IPv4, 16 bytes for IPv6) may authenticate the host.
  18765. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  18766. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  18767. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  18768. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  18769. wolfSSL_sk_free(san_names);
  18770. return true;
  18771. }
  18772. }
  18773. }
  18774. wolfSSL_sk_free(san_names);
  18775. }
  18776. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  18777. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  18778. // the OpenSSL backend's X509_check_ip behaves the same way).
  18779. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  18780. if (subject) {
  18781. char cn[256] = {};
  18782. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  18783. sizeof(cn));
  18784. if (cn_len > 0) {
  18785. std::string cn_str(cn, static_cast<size_t>(cn_len));
  18786. if (detail::match_hostname(cn_str, host_str)) { return true; }
  18787. }
  18788. }
  18789. return false;
  18790. }
  18791. inline uint64_t hostname_mismatch_code() {
  18792. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  18793. }
  18794. inline long get_verify_result(const_session_t session) {
  18795. if (!session) { return -1; }
  18796. auto wsession =
  18797. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  18798. long result = wolfSSL_get_verify_result(wsession->ssl);
  18799. return result;
  18800. }
  18801. inline std::string get_cert_subject_cn(cert_t cert) {
  18802. if (!cert) return "";
  18803. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18804. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  18805. if (!subject) return "";
  18806. char cn[256] = {};
  18807. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  18808. sizeof(cn));
  18809. if (cn_len <= 0) return "";
  18810. return std::string(cn, static_cast<size_t>(cn_len));
  18811. }
  18812. inline std::string get_cert_issuer_name(cert_t cert) {
  18813. if (!cert) return "";
  18814. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18815. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  18816. if (!issuer) return "";
  18817. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  18818. if (!name_str) return "";
  18819. std::string result(name_str);
  18820. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  18821. return result;
  18822. }
  18823. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  18824. sans.clear();
  18825. if (!cert) return false;
  18826. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18827. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  18828. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  18829. if (!san_names) return true; // No SANs is not an error
  18830. int count = wolfSSL_sk_num(san_names);
  18831. for (int i = 0; i < count; i++) {
  18832. auto *name =
  18833. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  18834. if (!name) continue;
  18835. SanEntry entry;
  18836. switch (name->type) {
  18837. case WOLFSSL_GEN_DNS: {
  18838. entry.type = SanType::DNS;
  18839. unsigned char *dns_name = nullptr;
  18840. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  18841. if (dns_name && dns_len > 0) {
  18842. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  18843. static_cast<size_t>(dns_len));
  18844. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  18845. }
  18846. break;
  18847. }
  18848. case WOLFSSL_GEN_IPADD: {
  18849. entry.type = SanType::IP;
  18850. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  18851. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  18852. if (ip_data && ip_len == 4) {
  18853. char buf[16];
  18854. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  18855. ip_data[2], ip_data[3]);
  18856. entry.value = buf;
  18857. } else if (ip_data && ip_len == 16) {
  18858. char buf[64];
  18859. snprintf(buf, sizeof(buf),
  18860. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  18861. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  18862. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  18863. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  18864. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  18865. ip_data[14], ip_data[15]);
  18866. entry.value = buf;
  18867. }
  18868. break;
  18869. }
  18870. case WOLFSSL_GEN_EMAIL:
  18871. entry.type = SanType::EMAIL;
  18872. {
  18873. unsigned char *email = nullptr;
  18874. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  18875. if (email && email_len > 0) {
  18876. entry.value = std::string(reinterpret_cast<char *>(email),
  18877. static_cast<size_t>(email_len));
  18878. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  18879. }
  18880. }
  18881. break;
  18882. case WOLFSSL_GEN_URI:
  18883. entry.type = SanType::URI;
  18884. {
  18885. unsigned char *uri = nullptr;
  18886. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  18887. &uri, name->d.uniformResourceIdentifier);
  18888. if (uri && uri_len > 0) {
  18889. entry.value = std::string(reinterpret_cast<char *>(uri),
  18890. static_cast<size_t>(uri_len));
  18891. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  18892. }
  18893. }
  18894. break;
  18895. default: entry.type = SanType::OTHER; break;
  18896. }
  18897. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  18898. }
  18899. wolfSSL_sk_free(san_names);
  18900. return true;
  18901. }
  18902. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  18903. time_t &not_after) {
  18904. if (!cert) return false;
  18905. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18906. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  18907. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  18908. if (!nb || !na) return false;
  18909. // wolfSSL_ASN1_TIME_to_tm is available
  18910. struct tm tm_nb = {}, tm_na = {};
  18911. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  18912. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  18913. #ifdef _WIN32
  18914. not_before = _mkgmtime(&tm_nb);
  18915. not_after = _mkgmtime(&tm_na);
  18916. #else
  18917. not_before = timegm(&tm_nb);
  18918. not_after = timegm(&tm_na);
  18919. #endif
  18920. return true;
  18921. }
  18922. inline std::string get_cert_serial(cert_t cert) {
  18923. if (!cert) return "";
  18924. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18925. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  18926. if (!serial_asn1) return "";
  18927. // Get the serial number data
  18928. int len = serial_asn1->length;
  18929. unsigned char *data = serial_asn1->data;
  18930. if (!data || len <= 0) return "";
  18931. std::string result;
  18932. result.reserve(static_cast<size_t>(len) * 2);
  18933. for (int i = 0; i < len; i++) {
  18934. char hex[3];
  18935. snprintf(hex, sizeof(hex), "%02X", data[i]);
  18936. result += hex;
  18937. }
  18938. return result;
  18939. }
  18940. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  18941. if (!cert) return false;
  18942. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  18943. int der_len = 0;
  18944. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  18945. if (!der_data || der_len <= 0) return false;
  18946. der.assign(der_data, der_data + der_len);
  18947. return true;
  18948. }
  18949. inline const char *get_sni(const_session_t session) {
  18950. if (!session) return nullptr;
  18951. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  18952. // For server: return SNI received from client during handshake
  18953. if (!wsession->sni_hostname.empty()) {
  18954. return wsession->sni_hostname.c_str();
  18955. }
  18956. // For client: return the hostname set via set_sni
  18957. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  18958. return nullptr;
  18959. }
  18960. inline uint64_t peek_error() {
  18961. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  18962. }
  18963. inline uint64_t get_error() {
  18964. uint64_t err = impl::wolfssl_last_error();
  18965. impl::wolfssl_last_error() = 0;
  18966. return err;
  18967. }
  18968. inline std::string error_string(uint64_t code) {
  18969. char buf[256];
  18970. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  18971. return std::string(buf);
  18972. }
  18973. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  18974. if (!pem || len == 0) { return nullptr; }
  18975. // Validate by attempting to load into a temporary ctx
  18976. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  18977. if (!tmp_ctx) { return nullptr; }
  18978. int ret = wolfSSL_CTX_load_verify_buffer(
  18979. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  18980. static_cast<long>(len), SSL_FILETYPE_PEM);
  18981. wolfSSL_CTX_free(tmp_ctx);
  18982. if (ret != SSL_SUCCESS) { return nullptr; }
  18983. return static_cast<ca_store_t>(
  18984. new impl::WolfSSLCAStore{std::string(pem, len)});
  18985. }
  18986. inline void free_ca_store(ca_store_t store) {
  18987. delete static_cast<impl::WolfSSLCAStore *>(store);
  18988. }
  18989. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  18990. if (!ctx || !store) { return false; }
  18991. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  18992. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  18993. int ret = wolfSSL_CTX_load_verify_buffer(
  18994. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  18995. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  18996. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  18997. // This function takes ownership of the store; the PEM data was copied into
  18998. // the context, so release the source
  18999. free_ca_store(store);
  19000. return ret == SSL_SUCCESS;
  19001. }
  19002. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  19003. certs.clear();
  19004. if (!ctx) { return 0; }
  19005. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19006. if (wctx->ca_pem_data_.empty()) { return 0; }
  19007. const std::string &pem = wctx->ca_pem_data_;
  19008. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  19009. const std::string end_marker = "-----END CERTIFICATE-----";
  19010. size_t pos = 0;
  19011. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  19012. size_t end_pos = pem.find(end_marker, pos);
  19013. if (end_pos == std::string::npos) { break; }
  19014. end_pos += end_marker.size();
  19015. std::string cert_pem = pem.substr(pos, end_pos - pos);
  19016. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  19017. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  19018. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  19019. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  19020. pos = end_pos;
  19021. }
  19022. return certs.size();
  19023. }
  19024. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  19025. std::vector<std::string> names;
  19026. if (!ctx) { return names; }
  19027. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19028. if (wctx->ca_pem_data_.empty()) { return names; }
  19029. const std::string &pem = wctx->ca_pem_data_;
  19030. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  19031. const std::string end_marker = "-----END CERTIFICATE-----";
  19032. size_t pos = 0;
  19033. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  19034. size_t end_pos = pem.find(end_marker, pos);
  19035. if (end_pos == std::string::npos) { break; }
  19036. end_pos += end_marker.size();
  19037. std::string cert_pem = pem.substr(pos, end_pos - pos);
  19038. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  19039. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  19040. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  19041. if (x509) {
  19042. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  19043. if (subject) {
  19044. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  19045. if (name_str) {
  19046. names.push_back(name_str);
  19047. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  19048. }
  19049. }
  19050. wolfSSL_X509_free(x509);
  19051. }
  19052. pos = end_pos;
  19053. }
  19054. return names;
  19055. }
  19056. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  19057. const char *key_pem, const char *password) {
  19058. if (!ctx || !cert_pem || !key_pem) { return false; }
  19059. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19060. // Load new certificate
  19061. int ret = wolfSSL_CTX_use_certificate_buffer(
  19062. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  19063. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  19064. if (ret != SSL_SUCCESS) {
  19065. impl::wolfssl_last_error() =
  19066. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  19067. return false;
  19068. }
  19069. // Set password if provided
  19070. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  19071. // Load new private key
  19072. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  19073. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  19074. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  19075. if (ret != SSL_SUCCESS) {
  19076. impl::wolfssl_last_error() =
  19077. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  19078. return false;
  19079. }
  19080. return true;
  19081. }
  19082. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  19083. if (!ctx || !ca_pem) { return false; }
  19084. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19085. int ret = wolfSSL_CTX_load_verify_buffer(
  19086. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  19087. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  19088. if (ret != SSL_SUCCESS) {
  19089. impl::wolfssl_last_error() =
  19090. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  19091. return false;
  19092. }
  19093. return true;
  19094. }
  19095. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  19096. if (!ctx) { return false; }
  19097. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  19098. impl::get_verify_callback() = std::move(callback);
  19099. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  19100. if (wctx->has_verify_callback) {
  19101. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  19102. impl::wolfssl_verify_callback);
  19103. } else {
  19104. wolfSSL_CTX_set_verify(
  19105. wctx->ctx,
  19106. wctx->verify_client
  19107. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  19108. : SSL_VERIFY_NONE,
  19109. nullptr);
  19110. }
  19111. return true;
  19112. }
  19113. inline long get_verify_error(const_session_t session) {
  19114. if (!session) { return -1; }
  19115. auto *wsession =
  19116. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  19117. return wolfSSL_get_verify_result(wsession->ssl);
  19118. }
  19119. inline std::string verify_error_string(long error_code) {
  19120. if (error_code == 0) { return ""; }
  19121. const char *str =
  19122. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  19123. return str ? std::string(str) : std::string();
  19124. }
  19125. } // namespace tls
  19126. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  19127. // WebSocket implementation
  19128. namespace ws {
  19129. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  19130. bool fin) {
  19131. std::lock_guard<std::mutex> lock(write_mutex_);
  19132. if (closed_) { return false; }
  19133. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  19134. }
  19135. inline ReadResult WebSocket::read(std::string &msg) {
  19136. std::unique_lock<std::mutex> read_lock(read_mutex_);
  19137. while (!closed_) {
  19138. Opcode opcode;
  19139. std::string payload;
  19140. bool fin;
  19141. impl::FrameRead r =
  19142. impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  19143. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH);
  19144. // A timeout landed on a frame boundary: the connection is untouched and
  19145. // still usable, so hand control back without closing it. That is only
  19146. // useful to a caller who asked for the timeout; the compile-time default
  19147. // is a backstop against a peer gone quiet, and elapsing it closes the
  19148. // connection so a plain `while (ws.read(msg))` loop ends.
  19149. if (r == impl::FrameRead::Timeout && read_timeout_set_) { return Timeout; }
  19150. if (r != impl::FrameRead::Ok) {
  19151. closed_ = true;
  19152. return Fail;
  19153. }
  19154. switch (opcode) {
  19155. case Opcode::Ping: {
  19156. std::lock_guard<std::mutex> lock(write_mutex_);
  19157. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  19158. payload.size(), true, !is_server_);
  19159. continue;
  19160. }
  19161. case Opcode::Pong: {
  19162. std::lock_guard<std::mutex> lock(ping_mutex_);
  19163. unacked_pings_ = 0;
  19164. continue;
  19165. }
  19166. case Opcode::Close: {
  19167. if (!closed_.exchange(true)) {
  19168. // Echo close frame back
  19169. std::lock_guard<std::mutex> lock(write_mutex_);
  19170. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  19171. payload.size(), true, !is_server_);
  19172. }
  19173. return Fail;
  19174. }
  19175. case Opcode::Text:
  19176. case Opcode::Binary: {
  19177. auto result = opcode == Opcode::Text ? Text : Binary;
  19178. msg = std::move(payload);
  19179. // Handle fragmentation
  19180. if (!fin) {
  19181. while (true) {
  19182. Opcode cont_opcode;
  19183. std::string cont_payload;
  19184. bool cont_fin;
  19185. // A timeout is not reportable here: half of a fragmented message is
  19186. // already in `msg` and read() has no way to resume it, so it is a
  19187. // failure like any other. Timeouts are only ever seen on a message
  19188. // boundary.
  19189. if (impl::read_websocket_frame(
  19190. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  19191. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) !=
  19192. impl::FrameRead::Ok) {
  19193. closed_ = true;
  19194. return Fail;
  19195. }
  19196. if (cont_opcode == Opcode::Ping) {
  19197. std::lock_guard<std::mutex> lock(write_mutex_);
  19198. detail::write_websocket_frame(
  19199. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  19200. true, !is_server_);
  19201. continue;
  19202. }
  19203. if (cont_opcode == Opcode::Pong) {
  19204. std::lock_guard<std::mutex> lock(ping_mutex_);
  19205. unacked_pings_ = 0;
  19206. continue;
  19207. }
  19208. if (cont_opcode == Opcode::Close) {
  19209. if (!closed_.exchange(true)) {
  19210. std::lock_guard<std::mutex> lock(write_mutex_);
  19211. detail::write_websocket_frame(
  19212. strm_, Opcode::Close, cont_payload.data(),
  19213. cont_payload.size(), true, !is_server_);
  19214. }
  19215. return Fail;
  19216. }
  19217. // RFC 6455: continuation frames must use opcode 0x0
  19218. if (cont_opcode != Opcode::Continuation) {
  19219. closed_ = true;
  19220. return Fail;
  19221. }
  19222. msg += cont_payload;
  19223. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  19224. closed_ = true;
  19225. return Fail;
  19226. }
  19227. if (cont_fin) { break; }
  19228. }
  19229. }
  19230. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  19231. if (result == Text && !impl::is_valid_utf8(msg)) {
  19232. // close() takes the read lock to wait for the peer's Close reply, so
  19233. // it must not run while this thread still holds it.
  19234. read_lock.unlock();
  19235. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  19236. return Fail;
  19237. }
  19238. return result;
  19239. }
  19240. default: closed_ = true; return Fail;
  19241. }
  19242. }
  19243. return Fail;
  19244. }
  19245. inline bool WebSocket::send(const std::string &data) {
  19246. return send_frame(Opcode::Text, data.data(), data.size());
  19247. }
  19248. inline bool WebSocket::send(const char *data, size_t len) {
  19249. return send_frame(Opcode::Binary, data, len);
  19250. }
  19251. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  19252. if (closed_.exchange(true)) { return; }
  19253. ping_cv_.notify_all();
  19254. std::string payload;
  19255. auto code = static_cast<uint16_t>(status);
  19256. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  19257. payload.push_back(static_cast<char>(code & 0xFF));
  19258. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  19259. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  19260. payload += reason.substr(0, 123);
  19261. {
  19262. std::lock_guard<std::mutex> lock(write_mutex_);
  19263. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  19264. payload.size(), true, !is_server_);
  19265. }
  19266. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  19267. // Close response before closing the TCP connection.
  19268. //
  19269. // Wait only when no other thread is parsing frames. When one is, it is the
  19270. // thread positioned to see the peer's reply, and reading here would take
  19271. // bytes out of the message it is assembling. Bailing out also leaves the
  19272. // stream, including its read timeout, entirely to that thread.
  19273. std::unique_lock<std::mutex> read_lock(read_mutex_, std::try_to_lock);
  19274. if (!read_lock.owns_lock()) { return; }
  19275. // Use a short timeout to avoid hanging if the peer doesn't respond.
  19276. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  19277. Opcode op;
  19278. std::string resp;
  19279. bool fin;
  19280. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125) ==
  19281. impl::FrameRead::Ok) {
  19282. if (op == Opcode::Close) { break; }
  19283. }
  19284. }
  19285. inline WebSocket::~WebSocket() {
  19286. {
  19287. std::lock_guard<std::mutex> lock(ping_mutex_);
  19288. closed_ = true;
  19289. }
  19290. ping_cv_.notify_all();
  19291. if (ping_thread_.joinable()) { ping_thread_.join(); }
  19292. }
  19293. inline void WebSocket::start_heartbeat() {
  19294. if (ping_interval_sec_ == 0) { return; }
  19295. ping_thread_ = std::thread([this]() {
  19296. std::unique_lock<std::mutex> lock(ping_mutex_);
  19297. while (!closed_) {
  19298. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  19299. if (closed_) { break; }
  19300. // If the peer has failed to respond to the previous pings, give up.
  19301. // RFC 6455 does not define a pong-timeout mechanism; this is an
  19302. // opt-in liveness check controlled by max_missed_pongs_.
  19303. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  19304. lock.unlock();
  19305. close(CloseStatus::GoingAway, "pong timeout");
  19306. return;
  19307. }
  19308. lock.unlock();
  19309. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  19310. lock.lock();
  19311. closed_ = true;
  19312. break;
  19313. }
  19314. lock.lock();
  19315. unacked_pings_++;
  19316. }
  19317. });
  19318. }
  19319. inline const Request &WebSocket::request() const { return req_; }
  19320. inline bool WebSocket::is_open() const { return !closed_; }
  19321. inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
  19322. // 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
  19323. // poll(), where 0 would instead mean "return immediately", so hand it the
  19324. // negative poll uses for an unbounded wait.
  19325. if (sec == 0 && usec == 0) { sec = -1; }
  19326. strm_.set_read_timeout(sec, usec);
  19327. read_timeout_set_ = true;
  19328. }
  19329. // WebSocketClient implementation
  19330. inline WebSocketClient::WebSocketClient(
  19331. const std::string &scheme_host_port_path, const Headers &headers)
  19332. : headers_(headers) {
  19333. detail::UrlComponents uc;
  19334. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  19335. !uc.host.empty() && !uc.path.empty()) {
  19336. auto &scheme = uc.scheme;
  19337. #ifdef CPPHTTPLIB_SSL_ENABLED
  19338. if (scheme != "ws" && scheme != "wss") {
  19339. #else
  19340. if (scheme != "ws") {
  19341. #endif
  19342. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  19343. std::string msg = "'" + scheme + "' scheme is not supported.";
  19344. throw std::invalid_argument(msg);
  19345. #endif
  19346. return;
  19347. }
  19348. auto is_ssl = scheme == "wss";
  19349. host_ = std::move(uc.host);
  19350. port_ = is_ssl ? 443 : 80;
  19351. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  19352. path_ = std::move(uc.path);
  19353. if (!uc.query.empty()) { path_ += uc.query; }
  19354. #ifdef CPPHTTPLIB_SSL_ENABLED
  19355. is_ssl_ = is_ssl;
  19356. if (is_ssl_) {
  19357. // The context lives as long as the client so that CA configuration
  19358. // survives reconnects; sessions are created per connection.
  19359. tls_ctx_ = tls::create_client_context();
  19360. if (!tls_ctx_) { return; }
  19361. }
  19362. #else
  19363. if (is_ssl) { return; }
  19364. #endif
  19365. is_valid_ = true;
  19366. }
  19367. }
  19368. #ifdef CPPHTTPLIB_SSL_ENABLED
  19369. inline WebSocketClient::WebSocketClient(
  19370. const std::string &scheme_host_port_path, const PemMemory &pem,
  19371. const Headers &headers)
  19372. : WebSocketClient(scheme_host_port_path, headers) {
  19373. // For ws:// URLs the client certificate is silently ignored, consistent
  19374. // with the TLS-only setters such as set_ca_cert_path().
  19375. if (is_valid_ && is_ssl_ && pem.cert_pem && pem.key_pem) {
  19376. if (!tls::set_client_cert_pem(tls_ctx_, pem.cert_pem, pem.key_pem,
  19377. pem.private_key_password)) {
  19378. tls::free_context(tls_ctx_);
  19379. tls_ctx_ = nullptr;
  19380. is_valid_ = false;
  19381. }
  19382. }
  19383. }
  19384. #endif
  19385. inline WebSocketClient::~WebSocketClient() {
  19386. shutdown_and_close();
  19387. #ifdef CPPHTTPLIB_SSL_ENABLED
  19388. if (tls_ctx_) {
  19389. tls::free_context(tls_ctx_);
  19390. tls_ctx_ = nullptr;
  19391. }
  19392. #endif
  19393. }
  19394. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  19395. inline void WebSocketClient::shutdown_and_close() {
  19396. // Send the close frame while the TLS session is still alive: ws_ holds an
  19397. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  19398. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  19399. if (ws_ && ws_->is_open()) { ws_->close(); }
  19400. ws_.reset();
  19401. #ifdef CPPHTTPLIB_SSL_ENABLED
  19402. if (is_ssl_) {
  19403. if (tls_session_) {
  19404. tls::shutdown(tls_session_, true);
  19405. tls::free_session(tls_session_);
  19406. tls_session_ = nullptr;
  19407. }
  19408. }
  19409. #endif
  19410. if (sock_ != INVALID_SOCKET) {
  19411. detail::shutdown_socket(sock_);
  19412. detail::close_socket(sock_);
  19413. sock_ = INVALID_SOCKET;
  19414. }
  19415. }
  19416. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm,
  19417. Error &error, int &ssl_error,
  19418. uint64_t &ssl_backend_error) {
  19419. // A read timeout of 0 means "wait forever", the way SO_RCVTIMEO reads it.
  19420. // The streams wait with poll(), where 0 instead means "return immediately",
  19421. // so they are given the negative poll uses for an unbounded wait.
  19422. auto unbounded = read_timeout_sec_ == 0 && read_timeout_usec_ == 0;
  19423. time_t strm_read_sec = unbounded ? -1 : read_timeout_sec_;
  19424. time_t strm_read_usec = unbounded ? 0 : read_timeout_usec_;
  19425. // The handshake belongs to establishing the connection, so an unset read
  19426. // timeout leaves it bounded by the connection timeout instead of forever.
  19427. time_t hs_sec = unbounded ? connection_timeout_sec_ : read_timeout_sec_;
  19428. time_t hs_usec = unbounded ? connection_timeout_usec_ : read_timeout_usec_;
  19429. #ifdef CPPHTTPLIB_SSL_ENABLED
  19430. if (is_ssl_) {
  19431. // A plain flag rather than SSLClient::load_certs()'s call_once: connect()
  19432. // is not safe to call concurrently on one client to begin with, since
  19433. // nothing else here is guarded either.
  19434. if (server_certificate_verification_ && !certs_loaded_) {
  19435. uint64_t backend_error = 0;
  19436. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_,
  19437. ca_cert_dir_path_, custom_ca_loaded_,
  19438. system_ca_mode_, backend_error);
  19439. certs_loaded_ = true;
  19440. }
  19441. detail::ClientTlsSessionOptions options;
  19442. options.server_hostname_verification = server_hostname_verification_;
  19443. detail::ClientTlsSessionError tls_error;
  19444. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  19445. server_certificate_verification_,
  19446. hs_sec, hs_usec, &tls_error,
  19447. options)) {
  19448. error = tls_error.error;
  19449. ssl_error = tls_error.ssl_error;
  19450. ssl_backend_error = tls_error.backend_error;
  19451. return false;
  19452. }
  19453. strm = std::unique_ptr<Stream>(new detail::WebSocketSSLStream(
  19454. sock_, tls_session_, strm_read_sec, strm_read_usec, write_timeout_sec_,
  19455. write_timeout_usec_));
  19456. return true;
  19457. }
  19458. #else
  19459. (void)error;
  19460. (void)ssl_error;
  19461. (void)ssl_backend_error;
  19462. (void)hs_sec;
  19463. (void)hs_usec;
  19464. #endif
  19465. strm = std::unique_ptr<Stream>(
  19466. new detail::SocketStream(sock_, strm_read_sec, strm_read_usec,
  19467. write_timeout_sec_, write_timeout_usec_));
  19468. return true;
  19469. }
  19470. inline void WebSocketClient::prepare_default_headers(Request &req) {
  19471. #ifdef CPPHTTPLIB_SSL_ENABLED
  19472. auto is_ssl = is_ssl_;
  19473. #else
  19474. auto is_ssl = false;
  19475. #endif
  19476. if (!req.has_header("Host")) {
  19477. req.headers.emplace("Host", detail::make_default_host_header_value(
  19478. host_, port_, is_ssl, address_family_));
  19479. }
  19480. detail::add_default_user_agent_header(req);
  19481. }
  19482. inline Result WebSocketClient::connect() {
  19483. if (!is_valid_) { return Result{Error::Connection, -1, Headers{}}; }
  19484. shutdown_and_close();
  19485. // Check is custom IP or hostname specified for host_
  19486. std::string connect_host;
  19487. std::string ip;
  19488. detail::apply_addr_map(addr_map_, host_, connect_host, ip);
  19489. auto error = Error::Success;
  19490. sock_ = detail::create_client_socket(
  19491. connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  19492. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  19493. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  19494. write_timeout_usec_, interface_, error);
  19495. if (sock_ == INVALID_SOCKET) {
  19496. if (error == Error::Success) { error = Error::Connection; }
  19497. return Result{error, -1, Headers{}};
  19498. }
  19499. std::unique_ptr<Stream> strm;
  19500. auto stream_error = Error::SSLConnection;
  19501. int ssl_error = 0;
  19502. uint64_t ssl_backend_error = 0;
  19503. if (!create_stream(strm, stream_error, ssl_error, ssl_backend_error)) {
  19504. shutdown_and_close();
  19505. #ifdef CPPHTTPLIB_SSL_ENABLED
  19506. return Result{stream_error, -1, Headers{}, ssl_error, ssl_backend_error};
  19507. #else
  19508. return Result{stream_error, -1, Headers{}};
  19509. #endif
  19510. }
  19511. Request req;
  19512. req.method = "GET";
  19513. req.path = path_;
  19514. req.headers = headers_;
  19515. prepare_default_headers(req);
  19516. detail::WebSocketUpgradeResponse upgrade;
  19517. if (!detail::perform_websocket_handshake(*strm, req, upgrade)) {
  19518. shutdown_and_close();
  19519. return Result{upgrade.error, upgrade.status, std::move(upgrade.headers)};
  19520. }
  19521. subprotocol_ = std::move(upgrade.selected_subprotocol);
  19522. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  19523. websocket_ping_interval_sec_,
  19524. websocket_max_missed_pongs_));
  19525. // The stream was created with the timeout already; tell the WebSocket
  19526. // whether it came from the caller, so read() knows to report it as Timeout.
  19527. ws_->read_timeout_set_ = read_timeout_set_;
  19528. return Result{Error::Success, upgrade.status, std::move(upgrade.headers)};
  19529. }
  19530. inline ReadResult WebSocketClient::read(std::string &msg) {
  19531. if (!ws_) { return Fail; }
  19532. return ws_->read(msg);
  19533. }
  19534. inline bool WebSocketClient::send(const std::string &data) {
  19535. if (!ws_) { return false; }
  19536. return ws_->send(data);
  19537. }
  19538. inline bool WebSocketClient::send(const char *data, size_t len) {
  19539. if (!ws_) { return false; }
  19540. return ws_->send(data, len);
  19541. }
  19542. inline void WebSocketClient::close(CloseStatus status,
  19543. const std::string &reason) {
  19544. if (ws_) { ws_->close(status, reason); }
  19545. }
  19546. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  19547. inline const std::string &WebSocketClient::subprotocol() const {
  19548. return subprotocol_;
  19549. }
  19550. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  19551. read_timeout_sec_ = sec;
  19552. read_timeout_usec_ = usec;
  19553. read_timeout_set_ = true;
  19554. // The members above only seed the next connect(); read() consults the
  19555. // stream, so an already-open connection has to be told directly.
  19556. if (ws_) { ws_->set_read_timeout(sec, usec); }
  19557. }
  19558. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  19559. write_timeout_sec_ = sec;
  19560. write_timeout_usec_ = usec;
  19561. }
  19562. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  19563. websocket_ping_interval_sec_ = sec;
  19564. }
  19565. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  19566. websocket_max_missed_pongs_ = count;
  19567. }
  19568. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  19569. inline void WebSocketClient::set_address_family(int family) {
  19570. address_family_ = family;
  19571. }
  19572. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  19573. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  19574. socket_options_ = std::move(socket_options);
  19575. }
  19576. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  19577. connection_timeout_sec_ = sec;
  19578. connection_timeout_usec_ = usec;
  19579. }
  19580. inline void WebSocketClient::set_interface(const std::string &intf) {
  19581. interface_ = intf;
  19582. }
  19583. inline void WebSocketClient::set_hostname_addr_map(
  19584. std::map<std::string, std::string> addr_map) {
  19585. addr_map_ = std::move(addr_map);
  19586. }
  19587. #ifdef CPPHTTPLIB_SSL_ENABLED
  19588. inline void
  19589. WebSocketClient::set_ca_cert_path(const std::string &ca_cert_file_path,
  19590. const std::string &ca_cert_dir_path) {
  19591. ca_cert_file_path_ = ca_cert_file_path;
  19592. ca_cert_dir_path_ = ca_cert_dir_path;
  19593. }
  19594. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  19595. if (store && tls_ctx_) {
  19596. // set_ca_store takes ownership of store
  19597. tls::set_ca_store(tls_ctx_, store);
  19598. custom_ca_loaded_ = true;
  19599. } else if (store) {
  19600. tls::free_ca_store(store);
  19601. }
  19602. }
  19603. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  19604. std::size_t size) {
  19605. if (tls_ctx_ && ca_cert && size > 0) {
  19606. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  19607. custom_ca_loaded_ = true;
  19608. }
  19609. }
  19610. inline void
  19611. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  19612. server_certificate_verification_ = enabled;
  19613. }
  19614. inline void WebSocketClient::enable_server_hostname_verification(bool enabled) {
  19615. server_hostname_verification_ = enabled;
  19616. }
  19617. inline void WebSocketClient::enable_system_ca(bool enabled) {
  19618. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  19619. }
  19620. #endif // CPPHTTPLIB_SSL_ENABLED
  19621. } // namespace ws
  19622. // ----------------------------------------------------------------------------
  19623. } // namespace httplib
  19624. #endif // CPPHTTPLIB_HTTPLIB_H