httplib.h 689 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.50.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003201"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. #ifndef CPPHTTPLIB_TCP_NODELAY
  109. #define CPPHTTPLIB_TCP_NODELAY false
  110. #endif
  111. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  112. #define CPPHTTPLIB_IPV6_V6ONLY false
  113. #endif
  114. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  115. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  116. #endif
  117. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  118. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  119. #endif
  120. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  121. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  124. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  125. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  126. ? std::thread::hardware_concurrency() - 1 \
  127. : 0))
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  131. #endif
  132. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  133. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  148. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  149. #endif
  150. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  151. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  152. #endif
  153. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  154. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  155. #endif
  156. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  157. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  158. #endif
  159. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  160. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  161. #endif
  162. /*
  163. * Headers
  164. */
  165. #ifdef _WIN32
  166. #ifndef _CRT_SECURE_NO_WARNINGS
  167. #define _CRT_SECURE_NO_WARNINGS
  168. #endif //_CRT_SECURE_NO_WARNINGS
  169. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  170. #define _CRT_NONSTDC_NO_DEPRECATE
  171. #endif //_CRT_NONSTDC_NO_DEPRECATE
  172. #if defined(_MSC_VER)
  173. #if _MSC_VER < 1900
  174. #error Sorry, Visual Studio versions prior to 2015 are not supported
  175. #endif
  176. #pragma comment(lib, "ws2_32.lib")
  177. #ifndef _SSIZE_T_DEFINED
  178. using ssize_t = __int64;
  179. #define _SSIZE_T_DEFINED
  180. #endif
  181. #endif // _MSC_VER
  182. #ifndef S_ISREG
  183. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  184. #endif // S_ISREG
  185. #ifndef S_ISDIR
  186. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  187. #endif // S_ISDIR
  188. #ifndef NOMINMAX
  189. #define NOMINMAX
  190. #endif // NOMINMAX
  191. #include <io.h>
  192. #include <winsock2.h>
  193. #include <ws2tcpip.h>
  194. #if defined(__has_include)
  195. #if __has_include(<afunix.h>)
  196. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  197. #include <afunix.h>
  198. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  199. #endif
  200. #endif
  201. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  202. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  203. #endif
  204. using nfds_t = unsigned long;
  205. using socket_t = SOCKET;
  206. using socklen_t = int;
  207. #else // not _WIN32
  208. #include <arpa/inet.h>
  209. #if !defined(_AIX) && !defined(__MVS__)
  210. #include <ifaddrs.h>
  211. #endif
  212. #ifdef __MVS__
  213. #include <strings.h>
  214. #ifndef NI_MAXHOST
  215. #define NI_MAXHOST 1025
  216. #endif
  217. #endif
  218. #include <net/if.h>
  219. #include <netdb.h>
  220. #include <netinet/in.h>
  221. #ifdef __linux__
  222. #include <resolv.h>
  223. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  224. #endif
  225. #include <csignal>
  226. #include <netinet/tcp.h>
  227. #include <poll.h>
  228. #include <pthread.h>
  229. #include <sys/mman.h>
  230. #include <sys/socket.h>
  231. #include <sys/un.h>
  232. #include <unistd.h>
  233. using socket_t = int;
  234. #ifndef INVALID_SOCKET
  235. #define INVALID_SOCKET (-1)
  236. #endif
  237. #endif //_WIN32
  238. #if defined(__APPLE__)
  239. #include <TargetConditionals.h>
  240. #endif
  241. #include <algorithm>
  242. #include <array>
  243. #include <atomic>
  244. #include <cassert>
  245. #include <chrono>
  246. #include <climits>
  247. #include <condition_variable>
  248. #include <cstdlib>
  249. #include <cstring>
  250. #include <errno.h>
  251. #include <exception>
  252. #include <fcntl.h>
  253. #include <fstream>
  254. #include <functional>
  255. #include <iomanip>
  256. #include <iostream>
  257. #include <list>
  258. #include <map>
  259. #include <memory>
  260. #include <mutex>
  261. #include <random>
  262. #include <regex>
  263. #include <set>
  264. #include <sstream>
  265. #include <string>
  266. #include <sys/stat.h>
  267. #include <system_error>
  268. #include <thread>
  269. #include <unordered_map>
  270. #include <unordered_set>
  271. #include <utility>
  272. // On macOS with a TLS backend, enable Keychain root certificates by default
  273. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  274. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  275. // only; on those platforms the user must provide a CA bundle explicitly.
  276. #if defined(__APPLE__) && defined(__clang__) && \
  277. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  278. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  279. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  280. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  281. #if TARGET_OS_OSX
  282. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  283. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  284. #endif
  285. #endif
  286. #endif
  287. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  288. defined(__APPLE__) && !TARGET_OS_OSX
  289. #error \
  290. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  291. #endif
  292. // On Windows, enable Schannel certificate verification by default
  293. // unless the user explicitly opts out.
  294. #if defined(_WIN32) && \
  295. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  296. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  297. #endif
  298. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  299. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  300. #if TARGET_OS_MAC && defined(__clang__)
  301. #include <CFNetwork/CFHost.h>
  302. #include <CoreFoundation/CoreFoundation.h>
  303. #endif
  304. #endif
  305. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  306. #ifdef _WIN32
  307. #include <wincrypt.h>
  308. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  309. // used
  310. #undef X509_NAME
  311. #undef X509_CERT_PAIR
  312. #undef X509_EXTENSIONS
  313. #undef PKCS7_SIGNER_INFO
  314. #ifdef _MSC_VER
  315. #pragma comment(lib, "crypt32.lib")
  316. #endif
  317. #endif // _WIN32
  318. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  319. #if TARGET_OS_OSX
  320. #include <Security/Security.h>
  321. #endif
  322. #endif
  323. #include <openssl/err.h>
  324. #include <openssl/evp.h>
  325. #include <openssl/ssl.h>
  326. #include <openssl/x509v3.h>
  327. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  328. #include <openssl/applink.c>
  329. #endif
  330. #include <iostream>
  331. #include <sstream>
  332. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  333. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  334. #error Please use OpenSSL or a current version of BoringSSL
  335. #endif
  336. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  337. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  338. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  339. #endif
  340. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  341. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  342. #include <mbedtls/ctr_drbg.h>
  343. #include <mbedtls/entropy.h>
  344. #include <mbedtls/error.h>
  345. #include <mbedtls/md5.h>
  346. #include <mbedtls/net_sockets.h>
  347. #include <mbedtls/oid.h>
  348. #include <mbedtls/pk.h>
  349. #include <mbedtls/sha1.h>
  350. #include <mbedtls/sha256.h>
  351. #include <mbedtls/sha512.h>
  352. #include <mbedtls/ssl.h>
  353. #include <mbedtls/x509_crt.h>
  354. #ifdef _WIN32
  355. #include <wincrypt.h>
  356. #ifdef _MSC_VER
  357. #pragma comment(lib, "crypt32.lib")
  358. #endif
  359. #endif // _WIN32
  360. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  361. #if TARGET_OS_OSX
  362. #include <Security/Security.h>
  363. #endif
  364. #endif
  365. // Mbed TLS 3.x API compatibility
  366. #if MBEDTLS_VERSION_MAJOR >= 3
  367. #define CPPHTTPLIB_MBEDTLS_V3
  368. #endif
  369. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  370. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  371. #include <wolfssl/options.h>
  372. #include <wolfssl/openssl/x509v3.h>
  373. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  374. #ifndef WOLFSSL_GEN_EMAIL
  375. #define WOLFSSL_GEN_EMAIL 1
  376. #endif
  377. #ifndef WOLFSSL_GEN_DNS
  378. #define WOLFSSL_GEN_DNS 2
  379. #endif
  380. #ifndef WOLFSSL_GEN_URI
  381. #define WOLFSSL_GEN_URI 6
  382. #endif
  383. #ifndef WOLFSSL_GEN_IPADD
  384. #define WOLFSSL_GEN_IPADD 7
  385. #endif
  386. #include <wolfssl/ssl.h>
  387. #include <wolfssl/wolfcrypt/hash.h>
  388. #include <wolfssl/wolfcrypt/md5.h>
  389. #include <wolfssl/wolfcrypt/sha256.h>
  390. #include <wolfssl/wolfcrypt/sha512.h>
  391. #ifdef _WIN32
  392. #include <wincrypt.h>
  393. #ifdef _MSC_VER
  394. #pragma comment(lib, "crypt32.lib")
  395. #endif
  396. #endif // _WIN32
  397. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  398. #if TARGET_OS_OSX
  399. #include <Security/Security.h>
  400. #endif
  401. #endif
  402. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  403. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  404. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  405. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  406. #define CPPHTTPLIB_SSL_ENABLED
  407. #endif
  408. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  409. #include <zlib.h>
  410. #endif
  411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  412. #include <brotli/decode.h>
  413. #include <brotli/encode.h>
  414. #endif
  415. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  416. #include <zstd.h>
  417. #endif
  418. /*
  419. * Declaration
  420. */
  421. namespace httplib {
  422. namespace ws {
  423. class WebSocket;
  424. } // namespace ws
  425. namespace detail {
  426. /*
  427. * Backport std::make_unique from C++14.
  428. *
  429. * NOTE: This code came up with the following stackoverflow post:
  430. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  431. *
  432. */
  433. template <class T, class... Args>
  434. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  435. make_unique(Args &&...args) {
  436. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  437. }
  438. template <class T>
  439. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  440. make_unique(std::size_t n) {
  441. typedef typename std::remove_extent<T>::type RT;
  442. return std::unique_ptr<T>(new RT[n]);
  443. }
  444. // Locale-independent ASCII character classification. The <cctype>
  445. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  446. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  447. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  448. // classified without regard to the locale.
  449. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  450. inline bool is_ascii_alpha(char c) {
  451. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  452. }
  453. inline bool is_ascii_alnum(char c) {
  454. return is_ascii_digit(c) || is_ascii_alpha(c);
  455. }
  456. namespace case_ignore {
  457. inline unsigned char to_lower(int c) {
  458. const static unsigned char table[256] = {
  459. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  460. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  461. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  462. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  463. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  464. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  465. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  466. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  467. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  468. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  469. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  470. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  471. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  472. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  473. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  474. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  475. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  476. 255,
  477. };
  478. return table[(unsigned char)(char)c];
  479. }
  480. inline std::string to_lower(const std::string &s) {
  481. std::string result = s;
  482. std::transform(
  483. result.begin(), result.end(), result.begin(),
  484. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  485. return result;
  486. }
  487. inline bool equal(const std::string &a, const std::string &b) {
  488. return a.size() == b.size() &&
  489. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  490. return to_lower(ca) == to_lower(cb);
  491. });
  492. }
  493. struct equal_to {
  494. bool operator()(const std::string &a, const std::string &b) const {
  495. return equal(a, b);
  496. }
  497. };
  498. struct hash {
  499. size_t operator()(const std::string &key) const {
  500. return hash_core(key.data(), key.size(), 0);
  501. }
  502. size_t hash_core(const char *s, size_t l, size_t h) const {
  503. return (l == 0) ? h
  504. : hash_core(s + 1, l - 1,
  505. // Unsets the 6 high bits of h, therefore no
  506. // overflow happens
  507. (((std::numeric_limits<size_t>::max)() >> 6) &
  508. h * 33) ^
  509. static_cast<unsigned char>(to_lower(*s)));
  510. }
  511. };
  512. template <typename T>
  513. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  514. detail::case_ignore::equal_to>;
  515. } // namespace case_ignore
  516. // This is based on
  517. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  518. struct scope_exit {
  519. explicit scope_exit(std::function<void(void)> &&f)
  520. : exit_function(std::move(f)), execute_on_destruction{true} {}
  521. scope_exit(scope_exit &&rhs) noexcept
  522. : exit_function(std::move(rhs.exit_function)),
  523. execute_on_destruction{rhs.execute_on_destruction} {
  524. rhs.release();
  525. }
  526. ~scope_exit() {
  527. if (execute_on_destruction) { this->exit_function(); }
  528. }
  529. void release() { this->execute_on_destruction = false; }
  530. private:
  531. scope_exit(const scope_exit &) = delete;
  532. void operator=(const scope_exit &) = delete;
  533. scope_exit &operator=(scope_exit &&) = delete;
  534. std::function<void(void)> exit_function;
  535. bool execute_on_destruction;
  536. };
  537. // Simple from_chars implementation for integer and double types (C++17
  538. // substitute)
  539. template <typename T> struct from_chars_result {
  540. const char *ptr;
  541. std::errc ec;
  542. };
  543. template <typename T>
  544. inline from_chars_result<T> from_chars(const char *first, const char *last,
  545. T &value, int base = 10) {
  546. value = 0;
  547. const char *p = first;
  548. bool negative = false;
  549. if (p != last && *p == '-') {
  550. negative = true;
  551. ++p;
  552. }
  553. if (p == last) { return {first, std::errc::invalid_argument}; }
  554. T result = 0;
  555. for (; p != last; ++p) {
  556. char c = *p;
  557. int digit = -1;
  558. if (is_ascii_digit(c)) {
  559. digit = c - '0';
  560. } else if ('a' <= c && c <= 'z') {
  561. digit = c - 'a' + 10;
  562. } else if ('A' <= c && c <= 'Z') {
  563. digit = c - 'A' + 10;
  564. } else {
  565. break;
  566. }
  567. if (digit < 0 || digit >= base) { break; }
  568. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  569. return {p, std::errc::result_out_of_range};
  570. }
  571. result = result * base + digit;
  572. }
  573. if (p == first || (negative && p == first + 1)) {
  574. return {first, std::errc::invalid_argument};
  575. }
  576. value = negative ? -result : result;
  577. return {p, std::errc{}};
  578. }
  579. // from_chars for double (hand-written, locale-independent)
  580. //
  581. // The only double consumed by this library is the HTTP quality value, whose
  582. // grammar is (RFC 9110 12.4.2):
  583. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  584. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  585. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  586. // '.' always the decimal separator (std::strtod would instead read it from the
  587. // global C locale, mis-parsing q-values once an embedder calls
  588. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  589. // the result to [0, 1], so inputs outside that range need not be distinguished
  590. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  591. // cases that exponent and wide-range handling would introduce.
  592. inline from_chars_result<double> from_chars(const char *first, const char *last,
  593. double &value) {
  594. value = 0.0;
  595. const char *p = first;
  596. // Each 1eN is exactly representable, so a single final division by the
  597. // matching entry yields a correctly-rounded result.
  598. static const double powers_of_ten[] = {
  599. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  600. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  601. const int max_frac_digits =
  602. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  603. // Accumulate digits into a 64-bit integer and remember how many were
  604. // fractional. Two independent caps keep this bounded and safe:
  605. // * accumulation saturates before mantissa could overflow uint64_t, and
  606. // * frac_digits is capped at max_frac_digits so it is always a valid index
  607. // into powers_of_ten (without this an input like "0.000...0" would never
  608. // grow mantissa, so the saturation cap alone would not bound it).
  609. // Both caps only drop digits far beyond the precision a q-value needs; any
  610. // value they would change is well outside [0, 1] and rejected by the caller.
  611. uint64_t mantissa = 0;
  612. int frac_digits = 0;
  613. bool seen_digit = false;
  614. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  615. auto accumulate = [&](char c) {
  616. if (mantissa <= limit) {
  617. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  618. return true;
  619. }
  620. return false;
  621. };
  622. for (; p != last && is_ascii_digit(*p); ++p) {
  623. seen_digit = true;
  624. accumulate(*p);
  625. }
  626. if (p != last && *p == '.') {
  627. ++p;
  628. for (; p != last && is_ascii_digit(*p); ++p) {
  629. seen_digit = true;
  630. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  631. }
  632. }
  633. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  634. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  635. return {p, std::errc{}};
  636. }
  637. inline bool parse_port(const char *s, size_t len, int &port) {
  638. int val = 0;
  639. auto r = from_chars(s, s + len, val);
  640. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  641. port = val;
  642. return true;
  643. }
  644. inline bool parse_port(const std::string &s, int &port) {
  645. return parse_port(s.data(), s.size(), port);
  646. }
  647. struct UrlComponents {
  648. std::string scheme;
  649. std::string host;
  650. std::string port;
  651. std::string path;
  652. std::string query;
  653. };
  654. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  655. uc = {};
  656. size_t pos = 0;
  657. auto sep = url.find("://");
  658. if (sep != std::string::npos) {
  659. uc.scheme = url.substr(0, sep);
  660. // Scheme must be [a-z]+ only
  661. if (uc.scheme.empty()) { return false; }
  662. for (auto c : uc.scheme) {
  663. if (c < 'a' || c > 'z') { return false; }
  664. }
  665. pos = sep + 3;
  666. } else if (url.compare(0, 2, "//") == 0) {
  667. pos = 2;
  668. }
  669. auto has_authority_prefix = pos > 0;
  670. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  671. url[0] != '?' && url[0] != '#');
  672. if (has_authority) {
  673. if (pos < url.size() && url[pos] == '[') {
  674. auto close = url.find(']', pos);
  675. if (close == std::string::npos) { return false; }
  676. uc.host = url.substr(pos + 1, close - pos - 1);
  677. // IPv6 host must be [a-fA-F0-9:]+ only
  678. if (uc.host.empty()) { return false; }
  679. for (auto c : uc.host) {
  680. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  681. (c >= 'A' && c <= 'F') || c == ':')) {
  682. return false;
  683. }
  684. }
  685. pos = close + 1;
  686. } else {
  687. auto end = url.find_first_of(":/?#", pos);
  688. if (end == std::string::npos) { end = url.size(); }
  689. uc.host = url.substr(pos, end - pos);
  690. pos = end;
  691. }
  692. if (pos < url.size() && url[pos] == ':') {
  693. ++pos;
  694. auto end = url.find_first_of("/?#", pos);
  695. if (end == std::string::npos) { end = url.size(); }
  696. uc.port = url.substr(pos, end - pos);
  697. pos = end;
  698. }
  699. // Without :// or //, the entire input must be consumed as host[:port].
  700. // If there is leftover (path, query, etc.), this is not a valid
  701. // host[:port] string — clear and reparse as a plain path.
  702. if (!has_authority_prefix && pos < url.size()) {
  703. uc.host.clear();
  704. uc.port.clear();
  705. pos = 0;
  706. }
  707. }
  708. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  709. auto end = url.find_first_of("?#", pos);
  710. if (end == std::string::npos) { end = url.size(); }
  711. uc.path = url.substr(pos, end - pos);
  712. pos = end;
  713. }
  714. if (pos < url.size() && url[pos] == '?') {
  715. auto end = url.find('#', pos);
  716. if (end == std::string::npos) { end = url.size(); }
  717. uc.query = url.substr(pos, end - pos);
  718. }
  719. return true;
  720. }
  721. } // namespace detail
  722. enum class SSLVerifierResponse {
  723. // no decision has been made, use the built-in certificate verifier
  724. NoDecisionMade,
  725. // connection certificate is verified and accepted
  726. CertificateAccepted,
  727. // connection certificate was processed but is rejected
  728. CertificateRejected
  729. };
  730. // System CA loading policy for SSL clients. Auto (the default) loads system
  731. // CA certs only when no custom CA is configured; enable_system_ca() switches
  732. // to an explicit policy.
  733. enum class SystemCAMode { Auto, Enabled, Disabled };
  734. enum StatusCode {
  735. // Information responses
  736. Continue_100 = 100,
  737. SwitchingProtocol_101 = 101,
  738. Processing_102 = 102,
  739. EarlyHints_103 = 103,
  740. // Successful responses
  741. OK_200 = 200,
  742. Created_201 = 201,
  743. Accepted_202 = 202,
  744. NonAuthoritativeInformation_203 = 203,
  745. NoContent_204 = 204,
  746. ResetContent_205 = 205,
  747. PartialContent_206 = 206,
  748. MultiStatus_207 = 207,
  749. AlreadyReported_208 = 208,
  750. IMUsed_226 = 226,
  751. // Redirection messages
  752. MultipleChoices_300 = 300,
  753. MovedPermanently_301 = 301,
  754. Found_302 = 302,
  755. SeeOther_303 = 303,
  756. NotModified_304 = 304,
  757. UseProxy_305 = 305,
  758. unused_306 = 306,
  759. TemporaryRedirect_307 = 307,
  760. PermanentRedirect_308 = 308,
  761. // Client error responses
  762. BadRequest_400 = 400,
  763. Unauthorized_401 = 401,
  764. PaymentRequired_402 = 402,
  765. Forbidden_403 = 403,
  766. NotFound_404 = 404,
  767. MethodNotAllowed_405 = 405,
  768. NotAcceptable_406 = 406,
  769. ProxyAuthenticationRequired_407 = 407,
  770. RequestTimeout_408 = 408,
  771. Conflict_409 = 409,
  772. Gone_410 = 410,
  773. LengthRequired_411 = 411,
  774. PreconditionFailed_412 = 412,
  775. PayloadTooLarge_413 = 413,
  776. UriTooLong_414 = 414,
  777. UnsupportedMediaType_415 = 415,
  778. RangeNotSatisfiable_416 = 416,
  779. ExpectationFailed_417 = 417,
  780. ImATeapot_418 = 418,
  781. MisdirectedRequest_421 = 421,
  782. UnprocessableContent_422 = 422,
  783. Locked_423 = 423,
  784. FailedDependency_424 = 424,
  785. TooEarly_425 = 425,
  786. UpgradeRequired_426 = 426,
  787. PreconditionRequired_428 = 428,
  788. TooManyRequests_429 = 429,
  789. RequestHeaderFieldsTooLarge_431 = 431,
  790. UnavailableForLegalReasons_451 = 451,
  791. // Server error responses
  792. InternalServerError_500 = 500,
  793. NotImplemented_501 = 501,
  794. BadGateway_502 = 502,
  795. ServiceUnavailable_503 = 503,
  796. GatewayTimeout_504 = 504,
  797. HttpVersionNotSupported_505 = 505,
  798. VariantAlsoNegotiates_506 = 506,
  799. InsufficientStorage_507 = 507,
  800. LoopDetected_508 = 508,
  801. NotExtended_510 = 510,
  802. NetworkAuthenticationRequired_511 = 511,
  803. };
  804. using Headers =
  805. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  806. detail::case_ignore::equal_to>;
  807. using Params = std::multimap<std::string, std::string>;
  808. using Match = std::smatch;
  809. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  810. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  811. /*
  812. * detail: type-erased storage used by UserData.
  813. * ABI-stable regardless of C++ standard — always uses this custom
  814. * implementation instead of std::any.
  815. */
  816. namespace detail {
  817. using any_type_id = const void *;
  818. template <typename T> any_type_id any_typeid() noexcept {
  819. static const char id = 0;
  820. return &id;
  821. }
  822. struct any_storage {
  823. virtual ~any_storage() = default;
  824. virtual std::unique_ptr<any_storage> clone() const = 0;
  825. virtual any_type_id type_id() const noexcept = 0;
  826. };
  827. template <typename T> struct any_value final : any_storage {
  828. T value;
  829. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  830. std::unique_ptr<any_storage> clone() const override {
  831. return std::unique_ptr<any_storage>(new any_value<T>(value));
  832. }
  833. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  834. };
  835. } // namespace detail
  836. class UserData {
  837. public:
  838. UserData() = default;
  839. UserData(UserData &&) noexcept = default;
  840. UserData &operator=(UserData &&) noexcept = default;
  841. UserData(const UserData &o) {
  842. for (const auto &e : o.entries_) {
  843. if (e.second) { entries_[e.first] = e.second->clone(); }
  844. }
  845. }
  846. UserData &operator=(const UserData &o) {
  847. if (this != &o) {
  848. entries_.clear();
  849. for (const auto &e : o.entries_) {
  850. if (e.second) { entries_[e.first] = e.second->clone(); }
  851. }
  852. }
  853. return *this;
  854. }
  855. template <typename T> void set(const std::string &key, T &&value) {
  856. using D = typename std::decay<T>::type;
  857. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  858. }
  859. template <typename T> T *get(const std::string &key) noexcept {
  860. auto it = entries_.find(key);
  861. if (it == entries_.end() || !it->second) { return nullptr; }
  862. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  863. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  864. }
  865. template <typename T> const T *get(const std::string &key) const noexcept {
  866. auto it = entries_.find(key);
  867. if (it == entries_.end() || !it->second) { return nullptr; }
  868. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  869. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  870. }
  871. bool has(const std::string &key) const noexcept {
  872. return entries_.find(key) != entries_.end();
  873. }
  874. void erase(const std::string &key) { entries_.erase(key); }
  875. void clear() noexcept { entries_.clear(); }
  876. private:
  877. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  878. entries_;
  879. };
  880. struct Response;
  881. using ResponseHandler = std::function<bool(const Response &response)>;
  882. struct FormData {
  883. std::string name;
  884. std::string content;
  885. std::string filename;
  886. std::string content_type;
  887. Headers headers;
  888. };
  889. struct FormField {
  890. std::string name;
  891. std::string content;
  892. Headers headers;
  893. };
  894. using FormFields = std::multimap<std::string, FormField>;
  895. using FormFiles = std::multimap<std::string, FormData>;
  896. struct MultipartFormData {
  897. FormFields fields; // Text fields from multipart
  898. FormFiles files; // Files from multipart
  899. // Text field access
  900. std::string get_field(const std::string &key, size_t id = 0) const;
  901. std::vector<std::string> get_fields(const std::string &key) const;
  902. bool has_field(const std::string &key) const;
  903. size_t get_field_count(const std::string &key) const;
  904. // File access
  905. FormData get_file(const std::string &key, size_t id = 0) const;
  906. std::vector<FormData> get_files(const std::string &key) const;
  907. bool has_file(const std::string &key) const;
  908. size_t get_file_count(const std::string &key) const;
  909. };
  910. struct UploadFormData {
  911. std::string name;
  912. std::string content;
  913. std::string filename;
  914. std::string content_type;
  915. };
  916. using UploadFormDataItems = std::vector<UploadFormData>;
  917. class DataSink {
  918. public:
  919. DataSink() : os(&sb_), sb_(*this) {}
  920. DataSink(const DataSink &) = delete;
  921. DataSink &operator=(const DataSink &) = delete;
  922. DataSink(DataSink &&) = delete;
  923. DataSink &operator=(DataSink &&) = delete;
  924. std::function<bool(const char *data, size_t data_len)> write;
  925. std::function<bool()> is_writable;
  926. std::function<void()> done;
  927. std::function<void(const Headers &trailer)> done_with_trailer;
  928. std::ostream os;
  929. private:
  930. class data_sink_streambuf final : public std::streambuf {
  931. public:
  932. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  933. protected:
  934. std::streamsize xsputn(const char *s, std::streamsize n) override {
  935. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  936. return 0;
  937. }
  938. private:
  939. DataSink &sink_;
  940. };
  941. data_sink_streambuf sb_;
  942. };
  943. using ContentProvider =
  944. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  945. using ContentProviderWithoutLength =
  946. std::function<bool(size_t offset, DataSink &sink)>;
  947. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  948. struct FormDataProvider {
  949. std::string name;
  950. ContentProviderWithoutLength provider;
  951. std::string filename;
  952. std::string content_type;
  953. };
  954. using FormDataProviderItems = std::vector<FormDataProvider>;
  955. inline FormDataProvider
  956. make_file_provider(const std::string &name, const std::string &filepath,
  957. const std::string &filename = std::string(),
  958. const std::string &content_type = std::string()) {
  959. FormDataProvider fdp;
  960. fdp.name = name;
  961. fdp.filename = filename.empty() ? filepath : filename;
  962. fdp.content_type = content_type;
  963. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  964. std::ifstream f(filepath, std::ios::binary);
  965. if (!f) { return false; }
  966. if (offset > 0) {
  967. f.seekg(static_cast<std::streamoff>(offset));
  968. if (!f.good()) {
  969. sink.done();
  970. return true;
  971. }
  972. }
  973. char buf[8192];
  974. f.read(buf, sizeof(buf));
  975. auto n = static_cast<size_t>(f.gcount());
  976. if (n > 0) { return sink.write(buf, n); }
  977. sink.done(); // EOF
  978. return true;
  979. };
  980. return fdp;
  981. }
  982. inline std::pair<size_t, ContentProvider>
  983. make_file_body(const std::string &filepath) {
  984. size_t size = 0;
  985. {
  986. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  987. if (!f) { return {0, ContentProvider{}}; }
  988. size = static_cast<size_t>(f.tellg());
  989. }
  990. ContentProvider provider = [filepath](size_t offset, size_t length,
  991. DataSink &sink) -> bool {
  992. std::ifstream f(filepath, std::ios::binary);
  993. if (!f) { return false; }
  994. f.seekg(static_cast<std::streamoff>(offset));
  995. if (!f.good()) { return false; }
  996. char buf[8192];
  997. while (length > 0) {
  998. auto to_read = (std::min)(sizeof(buf), length);
  999. f.read(buf, static_cast<std::streamsize>(to_read));
  1000. auto n = static_cast<size_t>(f.gcount());
  1001. if (n == 0) { break; }
  1002. if (!sink.write(buf, n)) { return false; }
  1003. length -= n;
  1004. }
  1005. return true;
  1006. };
  1007. return {size, std::move(provider)};
  1008. }
  1009. using ContentReceiverWithProgress = std::function<bool(
  1010. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1011. using ContentReceiver =
  1012. std::function<bool(const char *data, size_t data_length)>;
  1013. using FormDataHeader = std::function<bool(const FormData &file)>;
  1014. class ContentReader {
  1015. public:
  1016. using Reader = std::function<bool(ContentReceiver receiver)>;
  1017. using FormDataReader =
  1018. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1019. ContentReader(Reader reader, FormDataReader multipart_reader)
  1020. : reader_(std::move(reader)),
  1021. formdata_reader_(std::move(multipart_reader)) {}
  1022. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1023. return formdata_reader_(std::move(header), std::move(receiver));
  1024. }
  1025. bool operator()(ContentReceiver receiver) const {
  1026. return reader_(std::move(receiver));
  1027. }
  1028. Reader reader_;
  1029. FormDataReader formdata_reader_;
  1030. };
  1031. using Range = std::pair<ssize_t, ssize_t>;
  1032. using Ranges = std::vector<Range>;
  1033. #ifdef CPPHTTPLIB_SSL_ENABLED
  1034. // TLS abstraction layer - public type definitions and API
  1035. namespace tls {
  1036. // Opaque handles (defined as void* for abstraction)
  1037. using ctx_t = void *;
  1038. using session_t = void *;
  1039. using const_session_t = const void *; // For read-only session access
  1040. using cert_t = void *;
  1041. using ca_store_t = void *;
  1042. // TLS versions
  1043. enum class Version {
  1044. TLS1_2 = 0x0303,
  1045. TLS1_3 = 0x0304,
  1046. };
  1047. // Subject Alternative Names (SAN) entry types
  1048. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1049. // SAN entry structure
  1050. struct SanEntry {
  1051. SanType type;
  1052. std::string value;
  1053. };
  1054. // Verification context for certificate verification callback
  1055. struct VerifyContext {
  1056. session_t session; // TLS session handle
  1057. cert_t cert; // Current certificate being verified
  1058. int depth; // Certificate chain depth (0 = leaf)
  1059. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1060. long error_code; // Backend-specific error code (0 = no error)
  1061. const char *error_string; // Human-readable error description
  1062. // Certificate introspection methods
  1063. std::string subject_cn() const;
  1064. std::string issuer_name() const;
  1065. bool check_hostname(const char *hostname) const;
  1066. std::vector<SanEntry> sans() const;
  1067. bool validity(time_t &not_before, time_t &not_after) const;
  1068. std::string serial() const;
  1069. };
  1070. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1071. // TlsError codes for TLS operations (backend-independent)
  1072. enum class ErrorCode : int {
  1073. Success = 0,
  1074. WantRead, // Non-blocking: need to wait for read
  1075. WantWrite, // Non-blocking: need to wait for write
  1076. PeerClosed, // Peer closed the connection
  1077. Fatal, // Unrecoverable error
  1078. SyscallError, // System call error (check sys_errno)
  1079. CertVerifyFailed, // Certificate verification failed
  1080. HostnameMismatch, // Hostname verification failed
  1081. };
  1082. // TLS error information
  1083. struct TlsError {
  1084. ErrorCode code = ErrorCode::Fatal;
  1085. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1086. int sys_errno = 0; // errno when SyscallError
  1087. // Convert verification error code to human-readable string
  1088. static std::string verify_error_to_string(long error_code);
  1089. };
  1090. // RAII wrapper for peer certificate
  1091. class PeerCert {
  1092. public:
  1093. PeerCert();
  1094. PeerCert(PeerCert &&other) noexcept;
  1095. PeerCert &operator=(PeerCert &&other) noexcept;
  1096. ~PeerCert();
  1097. PeerCert(const PeerCert &) = delete;
  1098. PeerCert &operator=(const PeerCert &) = delete;
  1099. explicit operator bool() const;
  1100. std::string subject_cn() const;
  1101. std::string issuer_name() const;
  1102. bool check_hostname(const char *hostname) const;
  1103. std::vector<SanEntry> sans() const;
  1104. bool validity(time_t &not_before, time_t &not_after) const;
  1105. std::string serial() const;
  1106. private:
  1107. explicit PeerCert(cert_t cert);
  1108. cert_t cert_ = nullptr;
  1109. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1110. };
  1111. // Callback for TLS context setup (used by SSLServer constructor)
  1112. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1113. } // namespace tls
  1114. #endif
  1115. struct Request {
  1116. std::string method;
  1117. std::string path;
  1118. std::string matched_route;
  1119. Params params;
  1120. Headers headers;
  1121. Headers trailers;
  1122. std::string body;
  1123. std::string remote_addr;
  1124. int remote_port = -1;
  1125. std::string local_addr;
  1126. int local_port = -1;
  1127. // for server
  1128. std::string version;
  1129. std::string target;
  1130. MultipartFormData form;
  1131. Ranges ranges;
  1132. Match matches;
  1133. std::unordered_map<std::string, std::string> path_params;
  1134. std::function<bool()> is_connection_closed = []() { return true; };
  1135. // for client
  1136. std::vector<std::string> accept_content_types;
  1137. ResponseHandler response_handler;
  1138. ContentReceiverWithProgress content_receiver;
  1139. DownloadProgress download_progress;
  1140. UploadProgress upload_progress;
  1141. bool has_header(const std::string &key) const;
  1142. std::string get_header_value(const std::string &key, const char *def = "",
  1143. size_t id = 0) const;
  1144. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1145. size_t id = 0) const;
  1146. size_t get_header_value_count(const std::string &key) const;
  1147. void set_header(const std::string &key, const std::string &val);
  1148. bool has_trailer(const std::string &key) const;
  1149. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1150. size_t get_trailer_value_count(const std::string &key) const;
  1151. bool has_param(const std::string &key) const;
  1152. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1153. std::vector<std::string> get_param_values(const std::string &key) const;
  1154. size_t get_param_value_count(const std::string &key) const;
  1155. bool is_multipart_form_data() const;
  1156. // private members...
  1157. bool body_consumed_ = false;
  1158. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1159. size_t content_length_ = 0;
  1160. ContentProvider content_provider_;
  1161. bool is_chunked_content_provider_ = false;
  1162. size_t authorization_count_ = 0;
  1163. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1164. (std::chrono::steady_clock::time_point::min)();
  1165. #ifdef CPPHTTPLIB_SSL_ENABLED
  1166. tls::const_session_t ssl = nullptr;
  1167. tls::PeerCert peer_cert() const;
  1168. std::string sni() const;
  1169. #endif
  1170. };
  1171. struct Response {
  1172. std::string version;
  1173. int status = -1;
  1174. std::string reason;
  1175. Headers headers;
  1176. Headers trailers;
  1177. std::string body;
  1178. std::string location; // Redirect location
  1179. // User-defined context — set by pre-routing/pre-request handlers and read
  1180. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1181. UserData user_data;
  1182. bool has_header(const std::string &key) const;
  1183. std::string get_header_value(const std::string &key, const char *def = "",
  1184. size_t id = 0) const;
  1185. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1186. size_t id = 0) const;
  1187. size_t get_header_value_count(const std::string &key) const;
  1188. void set_header(const std::string &key, const std::string &val);
  1189. bool has_trailer(const std::string &key) const;
  1190. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1191. size_t get_trailer_value_count(const std::string &key) const;
  1192. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1193. void set_content(const char *s, size_t n, const std::string &content_type);
  1194. void set_content(const std::string &s, const std::string &content_type);
  1195. void set_content(std::string &&s, const std::string &content_type);
  1196. void set_content_provider(
  1197. size_t length, const std::string &content_type, ContentProvider provider,
  1198. ContentProviderResourceReleaser resource_releaser = nullptr);
  1199. void set_content_provider(
  1200. const std::string &content_type, ContentProviderWithoutLength provider,
  1201. ContentProviderResourceReleaser resource_releaser = nullptr);
  1202. void set_chunked_content_provider(
  1203. const std::string &content_type, ContentProviderWithoutLength provider,
  1204. ContentProviderResourceReleaser resource_releaser = nullptr);
  1205. void set_file_content(const std::string &path,
  1206. const std::string &content_type);
  1207. void set_file_content(const std::string &path);
  1208. Response() = default;
  1209. Response(const Response &) = default;
  1210. Response &operator=(const Response &) = default;
  1211. Response(Response &&) = default;
  1212. Response &operator=(Response &&) = default;
  1213. ~Response() {
  1214. if (content_provider_resource_releaser_) {
  1215. content_provider_resource_releaser_(content_provider_success_);
  1216. }
  1217. }
  1218. // private members...
  1219. size_t content_length_ = 0;
  1220. ContentProvider content_provider_;
  1221. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1222. bool is_chunked_content_provider_ = false;
  1223. bool content_provider_success_ = false;
  1224. std::string file_content_path_;
  1225. std::string file_content_content_type_;
  1226. };
  1227. enum class Error {
  1228. Success = 0,
  1229. Unknown,
  1230. Connection,
  1231. BindIPAddress,
  1232. Read,
  1233. Write,
  1234. ExceedRedirectCount,
  1235. Canceled,
  1236. SSLConnection,
  1237. SSLLoadingCerts,
  1238. SSLServerVerification,
  1239. SSLServerHostnameVerification,
  1240. UnsupportedMultipartBoundaryChars,
  1241. Compression,
  1242. ConnectionTimeout,
  1243. ProxyConnection,
  1244. ConnectionClosed,
  1245. Timeout,
  1246. ResourceExhaustion,
  1247. TooManyFormDataFiles,
  1248. ExceedMaxPayloadSize,
  1249. ExceedUriMaxLength,
  1250. ExceedMaxSocketDescriptorCount,
  1251. InvalidRequestLine,
  1252. InvalidHTTPMethod,
  1253. InvalidHTTPVersion,
  1254. InvalidHeaders,
  1255. MultipartParsing,
  1256. OpenFile,
  1257. Listen,
  1258. GetSockName,
  1259. UnsupportedAddressFamily,
  1260. HTTPParsing,
  1261. InvalidRangeHeader,
  1262. // For internal use only
  1263. SSLPeerCouldBeClosed_,
  1264. };
  1265. std::string to_string(Error error);
  1266. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1267. class Stream {
  1268. public:
  1269. virtual ~Stream() = default;
  1270. virtual bool is_readable() const = 0;
  1271. virtual bool wait_readable() const = 0;
  1272. virtual bool wait_writable() const = 0;
  1273. virtual bool is_peer_alive() const { return wait_writable(); }
  1274. virtual ssize_t read(char *ptr, size_t size) = 0;
  1275. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1276. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1277. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1278. virtual socket_t socket() const = 0;
  1279. virtual time_t duration() const = 0;
  1280. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1281. (void)sec;
  1282. (void)usec;
  1283. }
  1284. ssize_t write(const char *ptr);
  1285. ssize_t write(const std::string &s);
  1286. Error get_error() const { return error_; }
  1287. protected:
  1288. Error error_ = Error::Success;
  1289. };
  1290. class TaskQueue {
  1291. public:
  1292. TaskQueue() = default;
  1293. virtual ~TaskQueue() = default;
  1294. virtual bool enqueue(std::function<void()> fn) = 0;
  1295. virtual void shutdown() = 0;
  1296. virtual void on_idle() {}
  1297. };
  1298. class ThreadPool final : public TaskQueue {
  1299. public:
  1300. explicit ThreadPool(
  1301. size_t n, size_t max_n = 0, size_t mqr = 0,
  1302. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1303. ThreadPool(const ThreadPool &) = delete;
  1304. ~ThreadPool() override = default;
  1305. bool enqueue(std::function<void()> fn) override;
  1306. void shutdown() override;
  1307. private:
  1308. void worker(bool is_dynamic);
  1309. void move_to_finished(std::thread::id id);
  1310. void cleanup_finished_threads();
  1311. size_t base_thread_count_;
  1312. size_t max_thread_count_;
  1313. size_t max_queued_requests_;
  1314. time_t idle_timeout_sec_;
  1315. size_t idle_thread_count_;
  1316. bool shutdown_;
  1317. std::list<std::function<void()>> jobs_;
  1318. std::vector<std::thread> threads_; // base threads
  1319. std::list<std::thread> dynamic_threads_; // dynamic threads
  1320. std::vector<std::thread>
  1321. finished_threads_; // exited dynamic threads awaiting join
  1322. std::condition_variable cond_;
  1323. std::mutex mutex_;
  1324. };
  1325. using Logger = std::function<void(const Request &, const Response &)>;
  1326. // Forward declaration for Error type
  1327. enum class Error;
  1328. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1329. using SocketOptions = std::function<void(socket_t sock)>;
  1330. void default_socket_options(socket_t sock);
  1331. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1332. const char *status_message(int status);
  1333. std::string to_string(Error error);
  1334. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1335. std::string get_bearer_token_auth(const Request &req);
  1336. namespace detail {
  1337. class MatcherBase {
  1338. public:
  1339. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1340. virtual ~MatcherBase() = default;
  1341. const std::string &pattern() const { return pattern_; }
  1342. // Match request path and populate its matches and
  1343. virtual bool match(Request &request) const = 0;
  1344. private:
  1345. std::string pattern_;
  1346. };
  1347. /**
  1348. * Captures parameters in request path and stores them in Request::path_params
  1349. *
  1350. * Capture name is a substring of a pattern from : to /.
  1351. * The rest of the pattern is matched against the request path directly
  1352. * Parameters are captured starting from the next character after
  1353. * the end of the last matched static pattern fragment until the next /.
  1354. *
  1355. * Example pattern:
  1356. * "/path/fragments/:capture/more/fragments/:second_capture"
  1357. * Static fragments:
  1358. * "/path/fragments/", "more/fragments/"
  1359. *
  1360. * Given the following request path:
  1361. * "/path/fragments/:1/more/fragments/:2"
  1362. * the resulting capture will be
  1363. * {{"capture", "1"}, {"second_capture", "2"}}
  1364. */
  1365. class PathParamsMatcher final : public MatcherBase {
  1366. public:
  1367. PathParamsMatcher(const std::string &pattern);
  1368. bool match(Request &request) const override;
  1369. private:
  1370. // Treat segment separators as the end of path parameter capture
  1371. // Does not need to handle query parameters as they are parsed before path
  1372. // matching
  1373. static constexpr char separator = '/';
  1374. // Contains static path fragments to match against, excluding the '/' after
  1375. // path params
  1376. // Fragments are separated by path params
  1377. std::vector<std::string> static_fragments_;
  1378. // Stores the names of the path parameters to be used as keys in the
  1379. // Request::path_params map
  1380. std::vector<std::string> param_names_;
  1381. };
  1382. /**
  1383. * Performs std::regex_match on request path
  1384. * and stores the result in Request::matches
  1385. *
  1386. * Note that regex match is performed directly on the whole request.
  1387. * This means that wildcard patterns may match multiple path segments with /:
  1388. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1389. */
  1390. class RegexMatcher final : public MatcherBase {
  1391. public:
  1392. RegexMatcher(const std::string &pattern)
  1393. : MatcherBase(pattern), regex_(pattern) {}
  1394. bool match(Request &request) const override;
  1395. private:
  1396. std::regex regex_;
  1397. };
  1398. int close_socket(socket_t sock) noexcept;
  1399. ssize_t write_headers(Stream &strm, const Headers &headers);
  1400. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1401. time_t usec);
  1402. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1403. const std::string &boundary);
  1404. ContentProvider
  1405. make_multipart_content_provider(const UploadFormDataItems &items,
  1406. const std::string &boundary);
  1407. } // namespace detail
  1408. bool is_valid_multipart_boundary(const std::string &boundary);
  1409. // Serializer for multipart/form-data request bodies. The boundary is owned
  1410. // by the writer so that per-part framing and the final terminator always
  1411. // agree. Field names and filenames are escaped following the WHATWG HTML
  1412. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1413. // in content types.
  1414. class MultipartFormDataWriter {
  1415. public:
  1416. MultipartFormDataWriter();
  1417. // precondition: is_valid_multipart_boundary(boundary)
  1418. explicit MultipartFormDataWriter(std::string boundary);
  1419. const std::string &boundary() const;
  1420. std::string content_type() const;
  1421. // In-memory items -> whole body (known length)
  1422. std::string serialize(const UploadFormDataItems &items) const;
  1423. size_t content_length(const UploadFormDataItems &items) const;
  1424. // Per-part framing for streaming via a content provider
  1425. std::string item_begin(const UploadFormData &item) const;
  1426. static std::string item_end();
  1427. std::string finish() const;
  1428. private:
  1429. std::string boundary_;
  1430. };
  1431. class Server {
  1432. public:
  1433. using Handler = std::function<void(const Request &, Response &)>;
  1434. using ExceptionHandler =
  1435. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1436. enum class HandlerResponse {
  1437. Handled,
  1438. Unhandled,
  1439. };
  1440. using HandlerWithResponse =
  1441. std::function<HandlerResponse(const Request &, Response &)>;
  1442. using HandlerWithContentReader = std::function<void(
  1443. const Request &, Response &, const ContentReader &content_reader)>;
  1444. using Expect100ContinueHandler =
  1445. std::function<int(const Request &, Response &)>;
  1446. using StartHandler = std::function<void()>;
  1447. using WebSocketHandler =
  1448. std::function<void(const Request &, ws::WebSocket &)>;
  1449. using SubProtocolSelector =
  1450. std::function<std::string(const std::vector<std::string> &protocols)>;
  1451. Server();
  1452. virtual ~Server();
  1453. virtual bool is_valid() const;
  1454. Server &Get(const std::string &pattern, Handler handler);
  1455. Server &Post(const std::string &pattern, Handler handler);
  1456. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1457. Server &Put(const std::string &pattern, Handler handler);
  1458. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1459. Server &Patch(const std::string &pattern, Handler handler);
  1460. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1461. Server &Delete(const std::string &pattern, Handler handler);
  1462. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1463. Server &Options(const std::string &pattern, Handler handler);
  1464. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1465. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1466. SubProtocolSelector sub_protocol_selector);
  1467. bool set_base_dir(const std::string &dir,
  1468. const std::string &mount_point = std::string());
  1469. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1470. Headers headers = Headers());
  1471. bool remove_mount_point(const std::string &mount_point);
  1472. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1473. const std::string &mime);
  1474. Server &set_default_file_mimetype(const std::string &mime);
  1475. Server &set_file_request_handler(Handler handler);
  1476. template <class ErrorHandlerFunc>
  1477. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1478. return set_error_handler_core(
  1479. std::forward<ErrorHandlerFunc>(handler),
  1480. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1481. }
  1482. Server &set_exception_handler(ExceptionHandler handler);
  1483. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1484. Server &set_post_routing_handler(Handler handler);
  1485. Server &set_pre_request_handler(HandlerWithResponse handler);
  1486. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1487. Server &set_start_handler(StartHandler handler);
  1488. Server &set_logger(Logger logger);
  1489. Server &set_pre_compression_logger(Logger logger);
  1490. Server &set_error_logger(ErrorLogger error_logger);
  1491. Server &set_address_family(int family);
  1492. Server &set_tcp_nodelay(bool on);
  1493. Server &set_ipv6_v6only(bool on);
  1494. Server &set_socket_options(SocketOptions socket_options);
  1495. Server &set_default_headers(Headers headers);
  1496. Server &
  1497. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1498. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1499. Server &set_keep_alive_max_count(size_t count);
  1500. Server &set_keep_alive_timeout(time_t sec);
  1501. template <class Rep, class Period>
  1502. Server &
  1503. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1504. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1505. template <class Rep, class Period>
  1506. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1507. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1508. template <class Rep, class Period>
  1509. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1510. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1511. template <class Rep, class Period>
  1512. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1513. Server &set_payload_max_length(size_t length);
  1514. Server &set_websocket_ping_interval(time_t sec);
  1515. template <class Rep, class Period>
  1516. Server &set_websocket_ping_interval(
  1517. const std::chrono::duration<Rep, Period> &duration);
  1518. Server &set_websocket_max_missed_pongs(int count);
  1519. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1520. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1521. bool listen_after_bind();
  1522. bool listen(const std::string &host, int port, int socket_flags = 0);
  1523. bool is_running() const;
  1524. void wait_until_ready() const;
  1525. void stop() noexcept;
  1526. void decommission();
  1527. std::function<TaskQueue *(void)> new_task_queue;
  1528. protected:
  1529. bool process_request(Stream &strm, const std::string &remote_addr,
  1530. int remote_port, const std::string &local_addr,
  1531. int local_port, bool close_connection,
  1532. bool &connection_closed,
  1533. const std::function<void(Request &)> &setup_request,
  1534. bool *websocket_upgraded = nullptr);
  1535. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1536. std::vector<std::string> trusted_proxies_;
  1537. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1538. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1539. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1540. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1541. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1542. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1543. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1544. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1545. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1546. time_t websocket_ping_interval_sec_ =
  1547. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1548. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1549. private:
  1550. using Handlers =
  1551. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1552. using HandlersForContentReader =
  1553. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1554. HandlerWithContentReader>>;
  1555. static std::unique_ptr<detail::MatcherBase>
  1556. make_matcher(const std::string &pattern);
  1557. template <typename H>
  1558. Server &add_handler(
  1559. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1560. const std::string &pattern, H handler) {
  1561. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1562. return *this;
  1563. }
  1564. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1565. Server &set_error_handler_core(Handler handler, std::false_type);
  1566. socket_t create_server_socket(const std::string &host, int port,
  1567. int socket_flags,
  1568. SocketOptions socket_options) const;
  1569. int bind_internal(const std::string &host, int port, int socket_flags);
  1570. bool listen_internal();
  1571. bool routing(Request &req, Response &res, Stream &strm);
  1572. bool handle_file_request(Request &req, Response &res);
  1573. bool check_if_not_modified(const Request &req, Response &res,
  1574. const std::string &etag, time_t mtime) const;
  1575. bool check_if_range(Request &req, const std::string &etag,
  1576. time_t mtime) const;
  1577. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1578. Stream &strm);
  1579. bool dispatch_request_for_content_reader(
  1580. Request &req, Response &res, ContentReader content_reader,
  1581. const HandlersForContentReader &handlers) const;
  1582. bool parse_request_line(const char *s, Request &req) const;
  1583. void apply_ranges(const Request &req, Response &res,
  1584. std::string &content_type, std::string &boundary) const;
  1585. bool write_response(Stream &strm, bool close_connection, Request &req,
  1586. Response &res);
  1587. bool write_response_with_content(Stream &strm, bool close_connection,
  1588. const Request &req, Response &res);
  1589. bool write_response_core(Stream &strm, bool close_connection,
  1590. const Request &req, Response &res,
  1591. bool need_apply_ranges);
  1592. bool write_content_with_provider(Stream &strm, const Request &req,
  1593. Response &res, const std::string &boundary,
  1594. const std::string &content_type);
  1595. bool read_content(Stream &strm, Request &req, Response &res);
  1596. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1597. Response &res,
  1598. ContentReceiver receiver,
  1599. FormDataHeader multipart_header,
  1600. ContentReceiver multipart_receiver);
  1601. bool read_content_core(Stream &strm, Request &req, Response &res,
  1602. ContentReceiver receiver,
  1603. FormDataHeader multipart_header,
  1604. ContentReceiver multipart_receiver) const;
  1605. virtual bool process_and_close_socket(socket_t sock);
  1606. void output_log(const Request &req, const Response &res) const;
  1607. void output_pre_compression_log(const Request &req,
  1608. const Response &res) const;
  1609. void output_error_log(const Error &err, const Request *req) const;
  1610. std::atomic<bool> is_running_{false};
  1611. std::atomic<bool> is_decommissioned{false};
  1612. struct MountPointEntry {
  1613. std::string mount_point;
  1614. std::string base_dir;
  1615. std::string resolved_base_dir;
  1616. Headers headers;
  1617. };
  1618. std::vector<MountPointEntry> base_dirs_;
  1619. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1620. std::string default_file_mimetype_ = "application/octet-stream";
  1621. Handler file_request_handler_;
  1622. Handlers get_handlers_;
  1623. Handlers post_handlers_;
  1624. HandlersForContentReader post_handlers_for_content_reader_;
  1625. Handlers put_handlers_;
  1626. HandlersForContentReader put_handlers_for_content_reader_;
  1627. Handlers patch_handlers_;
  1628. HandlersForContentReader patch_handlers_for_content_reader_;
  1629. Handlers delete_handlers_;
  1630. HandlersForContentReader delete_handlers_for_content_reader_;
  1631. Handlers options_handlers_;
  1632. struct WebSocketHandlerEntry {
  1633. std::unique_ptr<detail::MatcherBase> matcher;
  1634. WebSocketHandler handler;
  1635. SubProtocolSelector sub_protocol_selector;
  1636. };
  1637. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1638. WebSocketHandlers websocket_handlers_;
  1639. HandlerWithResponse error_handler_;
  1640. ExceptionHandler exception_handler_;
  1641. HandlerWithResponse pre_routing_handler_;
  1642. Handler post_routing_handler_;
  1643. HandlerWithResponse pre_request_handler_;
  1644. Expect100ContinueHandler expect_100_continue_handler_;
  1645. StartHandler start_handler_;
  1646. mutable std::mutex logger_mutex_;
  1647. Logger logger_;
  1648. Logger pre_compression_logger_;
  1649. ErrorLogger error_logger_;
  1650. int address_family_ = AF_UNSPEC;
  1651. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1652. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1653. SocketOptions socket_options_ = default_socket_options;
  1654. Headers default_headers_;
  1655. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1656. detail::write_headers;
  1657. };
  1658. class Result {
  1659. public:
  1660. Result() = default;
  1661. Result(std::unique_ptr<Response> &&res, Error err,
  1662. Headers &&request_headers = Headers{})
  1663. : res_(std::move(res)), err_(err),
  1664. request_headers_(std::move(request_headers)) {}
  1665. // Response
  1666. operator bool() const { return res_ != nullptr; }
  1667. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1668. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1669. const Response &value() const { return *res_; }
  1670. Response &value() { return *res_; }
  1671. const Response &operator*() const { return *res_; }
  1672. Response &operator*() { return *res_; }
  1673. const Response *operator->() const { return res_.get(); }
  1674. Response *operator->() { return res_.get(); }
  1675. // Error
  1676. Error error() const { return err_; }
  1677. // Request Headers
  1678. bool has_request_header(const std::string &key) const;
  1679. std::string get_request_header_value(const std::string &key,
  1680. const char *def = "",
  1681. size_t id = 0) const;
  1682. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1683. size_t id = 0) const;
  1684. size_t get_request_header_value_count(const std::string &key) const;
  1685. private:
  1686. std::unique_ptr<Response> res_;
  1687. Error err_ = Error::Unknown;
  1688. Headers request_headers_;
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. public:
  1691. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1692. int ssl_error)
  1693. : res_(std::move(res)), err_(err),
  1694. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1695. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1696. int ssl_error, uint64_t ssl_backend_error)
  1697. : res_(std::move(res)), err_(err),
  1698. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1699. ssl_backend_error_(ssl_backend_error) {}
  1700. int ssl_error() const { return ssl_error_; }
  1701. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1702. private:
  1703. int ssl_error_ = 0;
  1704. uint64_t ssl_backend_error_ = 0;
  1705. #endif
  1706. };
  1707. struct ClientConnection {
  1708. socket_t sock = INVALID_SOCKET;
  1709. bool is_open() const { return sock != INVALID_SOCKET; }
  1710. ClientConnection() = default;
  1711. ~ClientConnection();
  1712. ClientConnection(const ClientConnection &) = delete;
  1713. ClientConnection &operator=(const ClientConnection &) = delete;
  1714. ClientConnection(ClientConnection &&other) noexcept
  1715. : sock(other.sock)
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. ,
  1718. session(other.session)
  1719. #endif
  1720. {
  1721. other.sock = INVALID_SOCKET;
  1722. #ifdef CPPHTTPLIB_SSL_ENABLED
  1723. other.session = nullptr;
  1724. #endif
  1725. }
  1726. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1727. if (this != &other) {
  1728. sock = other.sock;
  1729. other.sock = INVALID_SOCKET;
  1730. #ifdef CPPHTTPLIB_SSL_ENABLED
  1731. session = other.session;
  1732. other.session = nullptr;
  1733. #endif
  1734. }
  1735. return *this;
  1736. }
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. tls::session_t session = nullptr;
  1739. #endif
  1740. };
  1741. namespace detail {
  1742. struct ChunkedDecoder;
  1743. struct BodyReader {
  1744. Stream *stream = nullptr;
  1745. bool has_content_length = false;
  1746. size_t content_length = 0;
  1747. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1748. size_t bytes_read = 0;
  1749. bool chunked = false;
  1750. bool eof = false;
  1751. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1752. Error last_error = Error::Success;
  1753. ssize_t read(char *buf, size_t len);
  1754. bool has_error() const { return last_error != Error::Success; }
  1755. };
  1756. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1757. size_t len) {
  1758. (void)stream;
  1759. return br.read(buf, len);
  1760. }
  1761. class decompressor;
  1762. enum class NoProxyKind {
  1763. Wildcard, // "*"
  1764. HostnameSuffix, // "example.com" or ".example.com"
  1765. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1766. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1767. };
  1768. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1769. // Lets one CIDR matcher cover both families.
  1770. using IPBytes = std::array<uint8_t, 16>;
  1771. struct NoProxyEntry {
  1772. NoProxyKind kind = NoProxyKind::Wildcard;
  1773. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1774. IPBytes net{};
  1775. int prefix_bits = 0;
  1776. };
  1777. struct NormalizedTarget {
  1778. std::string hostname; // lowercase; brackets and trailing dot removed
  1779. bool is_ipv4 = false;
  1780. bool is_ipv6 = false;
  1781. IPBytes ip{};
  1782. };
  1783. } // namespace detail
  1784. class ClientImpl {
  1785. public:
  1786. explicit ClientImpl(const std::string &host);
  1787. explicit ClientImpl(const std::string &host, int port);
  1788. explicit ClientImpl(const std::string &host, int port,
  1789. const std::string &client_cert_path,
  1790. const std::string &client_key_path);
  1791. virtual ~ClientImpl();
  1792. virtual bool is_valid() const;
  1793. struct StreamHandle {
  1794. std::unique_ptr<Response> response;
  1795. Error error = Error::Success;
  1796. StreamHandle() = default;
  1797. StreamHandle(const StreamHandle &) = delete;
  1798. StreamHandle &operator=(const StreamHandle &) = delete;
  1799. StreamHandle(StreamHandle &&) = default;
  1800. StreamHandle &operator=(StreamHandle &&) = default;
  1801. ~StreamHandle() = default;
  1802. bool is_valid() const {
  1803. return response != nullptr && error == Error::Success;
  1804. }
  1805. ssize_t read(char *buf, size_t len);
  1806. void parse_trailers_if_needed();
  1807. Error get_read_error() const { return body_reader_.last_error; }
  1808. bool has_read_error() const { return body_reader_.has_error(); }
  1809. bool trailers_parsed_ = false;
  1810. private:
  1811. friend class ClientImpl;
  1812. ssize_t read_with_decompression(char *buf, size_t len);
  1813. std::unique_ptr<ClientConnection> connection_;
  1814. std::unique_ptr<Stream> socket_stream_;
  1815. Stream *stream_ = nullptr;
  1816. detail::BodyReader body_reader_;
  1817. std::unique_ptr<detail::decompressor> decompressor_;
  1818. std::string decompress_buffer_;
  1819. size_t decompress_offset_ = 0;
  1820. size_t decompressed_bytes_read_ = 0;
  1821. };
  1822. // clang-format off
  1823. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1824. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1825. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1826. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1827. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1828. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1829. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1830. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1831. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1832. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1833. Result Head(const std::string &path);
  1834. Result Head(const std::string &path, const Headers &headers);
  1835. Result Post(const std::string &path);
  1836. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1837. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1838. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1839. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1840. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1841. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1842. Result Post(const std::string &path, const Params &params);
  1843. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1844. Result Post(const std::string &path, const Headers &headers);
  1845. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1847. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1848. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1849. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1850. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1851. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1852. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1853. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1854. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1855. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1856. Result Put(const std::string &path);
  1857. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1859. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1861. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1862. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1863. Result Put(const std::string &path, const Params &params);
  1864. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1865. Result Put(const std::string &path, const Headers &headers);
  1866. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1868. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1869. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1870. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1871. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1872. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1873. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1874. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1875. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1876. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1877. Result Patch(const std::string &path);
  1878. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1880. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1882. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1883. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1884. Result Patch(const std::string &path, const Params &params);
  1885. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1886. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1887. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1888. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1889. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1890. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1891. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1892. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1893. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1894. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1895. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1896. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1897. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1898. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1899. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1900. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1901. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1902. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1903. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1904. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1905. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1906. Result Options(const std::string &path);
  1907. Result Options(const std::string &path, const Headers &headers);
  1908. // clang-format on
  1909. // Streaming API: Open a stream for reading response body incrementally
  1910. // Socket ownership is transferred to StreamHandle for true streaming
  1911. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1912. StreamHandle open_stream(const std::string &method, const std::string &path,
  1913. const Params &params = {},
  1914. const Headers &headers = {},
  1915. const std::string &body = {},
  1916. const std::string &content_type = {});
  1917. bool send(Request &req, Response &res, Error &error);
  1918. Result send(const Request &req);
  1919. void stop();
  1920. std::string host() const;
  1921. int port() const;
  1922. size_t is_socket_open() const;
  1923. socket_t socket() const;
  1924. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1925. void set_default_headers(Headers headers);
  1926. void
  1927. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1928. void set_address_family(int family);
  1929. void set_tcp_nodelay(bool on);
  1930. void set_ipv6_v6only(bool on);
  1931. void set_socket_options(SocketOptions socket_options);
  1932. void set_connection_timeout(time_t sec, time_t usec = 0);
  1933. template <class Rep, class Period>
  1934. void
  1935. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1936. void set_read_timeout(time_t sec, time_t usec = 0);
  1937. template <class Rep, class Period>
  1938. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1939. void set_write_timeout(time_t sec, time_t usec = 0);
  1940. template <class Rep, class Period>
  1941. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1942. void set_max_timeout(time_t msec);
  1943. template <class Rep, class Period>
  1944. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1945. void set_basic_auth(const std::string &username, const std::string &password);
  1946. void set_bearer_token_auth(const std::string &token);
  1947. void set_keep_alive(bool on);
  1948. void set_follow_location(bool on);
  1949. void set_path_encode(bool on);
  1950. void set_compress(bool on);
  1951. void set_decompress(bool on);
  1952. void set_payload_max_length(size_t length);
  1953. void set_interface(const std::string &intf);
  1954. void set_proxy(const std::string &host, int port);
  1955. void set_proxy_basic_auth(const std::string &username,
  1956. const std::string &password);
  1957. void set_proxy_bearer_token_auth(const std::string &token);
  1958. void set_no_proxy(const std::vector<std::string> &patterns);
  1959. void set_logger(Logger logger);
  1960. void set_error_logger(ErrorLogger error_logger);
  1961. protected:
  1962. struct Socket {
  1963. socket_t sock = INVALID_SOCKET;
  1964. // For Mbed TLS compatibility: start_time for request timeout tracking
  1965. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1966. bool is_open() const { return sock != INVALID_SOCKET; }
  1967. #ifdef CPPHTTPLIB_SSL_ENABLED
  1968. tls::session_t ssl = nullptr;
  1969. #endif
  1970. };
  1971. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1972. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1973. virtual bool setup_proxy_connection(
  1974. Socket &socket,
  1975. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1976. Response &res, bool &success, Error &error);
  1977. bool is_proxy_enabled_for_host(const std::string &host) const;
  1978. // All of:
  1979. // shutdown_ssl
  1980. // shutdown_socket
  1981. // close_socket
  1982. // disconnect
  1983. // should ONLY be called when socket_mutex_ is locked, and only when
  1984. // no other thread is using the socket.
  1985. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1986. void shutdown_socket(Socket &socket) const;
  1987. void close_socket(Socket &socket);
  1988. void disconnect(bool gracefully);
  1989. bool process_request(Stream &strm, Request &req, Response &res,
  1990. bool close_connection, Error &error);
  1991. bool write_content_with_provider(Stream &strm, const Request &req,
  1992. Error &error) const;
  1993. void copy_settings(const ClientImpl &rhs);
  1994. void output_log(const Request &req, const Response &res) const;
  1995. void output_error_log(const Error &err, const Request *req) const;
  1996. // Socket endpoint information
  1997. const std::string host_;
  1998. const int port_;
  1999. // Current open socket
  2000. Socket socket_;
  2001. mutable std::mutex socket_mutex_;
  2002. std::recursive_mutex request_mutex_;
  2003. // These are all protected under socket_mutex
  2004. size_t socket_requests_in_flight_ = 0;
  2005. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2006. bool socket_should_be_closed_when_request_is_done_ = false;
  2007. // Hostname-IP map
  2008. std::map<std::string, std::string> addr_map_;
  2009. // Default headers
  2010. Headers default_headers_;
  2011. // Header writer
  2012. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2013. detail::write_headers;
  2014. // Settings
  2015. std::string client_cert_path_;
  2016. std::string client_key_path_;
  2017. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2018. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2019. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2020. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2021. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2022. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2023. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2024. std::string basic_auth_username_;
  2025. std::string basic_auth_password_;
  2026. std::string bearer_token_auth_token_;
  2027. bool keep_alive_ = false;
  2028. bool follow_location_ = false;
  2029. bool path_encode_ = true;
  2030. int address_family_ = AF_UNSPEC;
  2031. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2032. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2033. SocketOptions socket_options_ = nullptr;
  2034. bool compress_ = false;
  2035. bool decompress_ = true;
  2036. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2037. bool has_payload_max_length_ = false;
  2038. std::string interface_;
  2039. std::string proxy_host_;
  2040. int proxy_port_ = -1;
  2041. std::string proxy_basic_auth_username_;
  2042. std::string proxy_basic_auth_password_;
  2043. std::string proxy_bearer_token_auth_token_;
  2044. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2045. mutable detail::NormalizedTarget host_normalized_;
  2046. mutable bool host_normalized_valid_ = false;
  2047. mutable std::mutex logger_mutex_;
  2048. Logger logger_;
  2049. ErrorLogger error_logger_;
  2050. private:
  2051. bool send_(Request &req, Response &res, Error &error);
  2052. Result send_(Request &&req);
  2053. socket_t create_client_socket(Error &error) const;
  2054. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2055. bool skip_100_continue = true) const;
  2056. bool write_request(Stream &strm, Request &req, bool close_connection,
  2057. Error &error, bool skip_body = false);
  2058. bool write_request_body(Stream &strm, Request &req, Error &error);
  2059. void prepare_default_headers(Request &r, bool for_stream,
  2060. const std::string &ct);
  2061. bool redirect(Request &req, Response &res, Error &error);
  2062. bool create_redirect_client(const std::string &scheme,
  2063. const std::string &host, int port, Request &req,
  2064. Response &res, const std::string &path,
  2065. const std::string &location, Error &error);
  2066. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2067. bool handle_request(Stream &strm, Request &req, Response &res,
  2068. bool close_connection, Error &error);
  2069. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2070. Request &req, const char *body, size_t content_length,
  2071. ContentProvider content_provider,
  2072. ContentProviderWithoutLength content_provider_without_length,
  2073. const std::string &content_type, ContentReceiver content_receiver,
  2074. Error &error);
  2075. Result send_with_content_provider_and_receiver(
  2076. const std::string &method, const std::string &path,
  2077. const Headers &headers, const char *body, size_t content_length,
  2078. ContentProvider content_provider,
  2079. ContentProviderWithoutLength content_provider_without_length,
  2080. const std::string &content_type, ContentReceiver content_receiver,
  2081. UploadProgress progress);
  2082. ContentProviderWithoutLength get_multipart_content_provider(
  2083. const std::string &boundary, const UploadFormDataItems &items,
  2084. const FormDataProviderItems &provider_items) const;
  2085. virtual bool
  2086. process_socket(const Socket &socket,
  2087. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2088. std::function<bool(Stream &strm)> callback);
  2089. virtual bool is_ssl() const;
  2090. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2091. #ifdef CPPHTTPLIB_SSL_ENABLED
  2092. public:
  2093. void set_digest_auth(const std::string &username,
  2094. const std::string &password);
  2095. void set_proxy_digest_auth(const std::string &username,
  2096. const std::string &password);
  2097. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2098. const std::string &ca_cert_dir_path = std::string());
  2099. void enable_server_certificate_verification(bool enabled);
  2100. void enable_server_hostname_verification(bool enabled);
  2101. void enable_system_ca(bool enabled);
  2102. protected:
  2103. std::string digest_auth_username_;
  2104. std::string digest_auth_password_;
  2105. std::string proxy_digest_auth_username_;
  2106. std::string proxy_digest_auth_password_;
  2107. std::string ca_cert_file_path_;
  2108. std::string ca_cert_dir_path_;
  2109. bool server_certificate_verification_ = true;
  2110. bool server_hostname_verification_ = true;
  2111. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2112. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2113. int last_ssl_error_ = 0;
  2114. uint64_t last_backend_error_ = 0;
  2115. #endif
  2116. };
  2117. class Client {
  2118. public:
  2119. // Universal interface
  2120. explicit Client(const std::string &scheme_host_port);
  2121. explicit Client(const std::string &scheme_host_port,
  2122. const std::string &client_cert_path,
  2123. const std::string &client_key_path);
  2124. // HTTP only interface
  2125. explicit Client(const std::string &host, int port);
  2126. explicit Client(const std::string &host, int port,
  2127. const std::string &client_cert_path,
  2128. const std::string &client_key_path);
  2129. Client(Client &&) = default;
  2130. Client &operator=(Client &&) = default;
  2131. ~Client();
  2132. bool is_valid() const;
  2133. // clang-format off
  2134. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2135. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2136. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2137. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2138. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2139. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2140. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2141. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2142. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2143. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2144. Result Head(const std::string &path);
  2145. Result Head(const std::string &path, const Headers &headers);
  2146. Result Post(const std::string &path);
  2147. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2149. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2150. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2151. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2152. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const Params &params);
  2154. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2155. Result Post(const std::string &path, const Headers &headers);
  2156. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2157. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2158. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2159. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2160. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2161. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2162. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2163. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2164. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2165. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2166. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2167. Result Put(const std::string &path);
  2168. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2171. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2172. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2173. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const Params &params);
  2175. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2176. Result Put(const std::string &path, const Headers &headers);
  2177. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2178. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2179. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2180. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2181. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2182. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2184. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2185. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2186. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2187. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2188. Result Patch(const std::string &path);
  2189. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2192. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2193. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2194. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const Params &params);
  2196. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2197. Result Patch(const std::string &path, const Headers &headers);
  2198. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2199. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2200. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2201. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2202. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2203. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2205. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2206. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2207. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2208. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2209. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2210. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2211. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2212. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2213. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2214. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2215. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2216. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2217. Result Options(const std::string &path);
  2218. Result Options(const std::string &path, const Headers &headers);
  2219. // clang-format on
  2220. // Streaming API: Open a stream for reading response body incrementally
  2221. // Socket ownership is transferred to StreamHandle for true streaming
  2222. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2223. ClientImpl::StreamHandle open_stream(const std::string &method,
  2224. const std::string &path,
  2225. const Params &params = {},
  2226. const Headers &headers = {},
  2227. const std::string &body = {},
  2228. const std::string &content_type = {});
  2229. bool send(Request &req, Response &res, Error &error);
  2230. Result send(const Request &req);
  2231. void stop();
  2232. std::string host() const;
  2233. int port() const;
  2234. size_t is_socket_open() const;
  2235. socket_t socket() const;
  2236. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2237. void set_default_headers(Headers headers);
  2238. void
  2239. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2240. void set_address_family(int family);
  2241. void set_tcp_nodelay(bool on);
  2242. void set_socket_options(SocketOptions socket_options);
  2243. void set_connection_timeout(time_t sec, time_t usec = 0);
  2244. template <class Rep, class Period>
  2245. void
  2246. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2247. void set_read_timeout(time_t sec, time_t usec = 0);
  2248. template <class Rep, class Period>
  2249. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2250. void set_write_timeout(time_t sec, time_t usec = 0);
  2251. template <class Rep, class Period>
  2252. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2253. void set_max_timeout(time_t msec);
  2254. template <class Rep, class Period>
  2255. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2256. void set_basic_auth(const std::string &username, const std::string &password);
  2257. void set_bearer_token_auth(const std::string &token);
  2258. void set_keep_alive(bool on);
  2259. void set_follow_location(bool on);
  2260. void set_path_encode(bool on);
  2261. void set_compress(bool on);
  2262. void set_decompress(bool on);
  2263. void set_payload_max_length(size_t length);
  2264. void set_interface(const std::string &intf);
  2265. void set_proxy(const std::string &host, int port);
  2266. void set_proxy_basic_auth(const std::string &username,
  2267. const std::string &password);
  2268. void set_proxy_bearer_token_auth(const std::string &token);
  2269. void set_no_proxy(const std::vector<std::string> &patterns);
  2270. void set_logger(Logger logger);
  2271. void set_error_logger(ErrorLogger error_logger);
  2272. private:
  2273. std::unique_ptr<ClientImpl> cli_;
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. public:
  2276. void set_digest_auth(const std::string &username,
  2277. const std::string &password);
  2278. void set_proxy_digest_auth(const std::string &username,
  2279. const std::string &password);
  2280. void enable_server_certificate_verification(bool enabled);
  2281. void enable_server_hostname_verification(bool enabled);
  2282. void enable_system_ca(bool enabled);
  2283. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2284. const std::string &ca_cert_dir_path = std::string());
  2285. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2286. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2287. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2288. void set_session_verifier(
  2289. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2290. tls::ctx_t tls_context() const;
  2291. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2292. void enable_windows_certificate_verification(bool enabled);
  2293. #endif
  2294. private:
  2295. bool is_ssl_ = false;
  2296. #endif
  2297. };
  2298. #ifdef CPPHTTPLIB_SSL_ENABLED
  2299. class SSLServer : public Server {
  2300. public:
  2301. SSLServer(const char *cert_path, const char *private_key_path,
  2302. const char *client_ca_cert_file_path = nullptr,
  2303. const char *client_ca_cert_dir_path = nullptr,
  2304. const char *private_key_password = nullptr);
  2305. struct PemMemory {
  2306. const char *cert_pem;
  2307. size_t cert_pem_len;
  2308. const char *key_pem;
  2309. size_t key_pem_len;
  2310. const char *client_ca_pem;
  2311. size_t client_ca_pem_len;
  2312. const char *private_key_password;
  2313. };
  2314. explicit SSLServer(const PemMemory &pem);
  2315. // The callback receives the ctx_t handle which can be cast to the
  2316. // appropriate backend type (SSL_CTX* for OpenSSL,
  2317. // tls::impl::MbedTlsContext* for Mbed TLS)
  2318. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2319. ~SSLServer() override;
  2320. bool is_valid() const override;
  2321. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2322. const char *client_ca_pem = nullptr,
  2323. const char *password = nullptr);
  2324. tls::ctx_t tls_context() const { return ctx_; }
  2325. int ssl_last_error() const { return last_ssl_error_; }
  2326. private:
  2327. bool process_and_close_socket(socket_t sock) override;
  2328. tls::ctx_t ctx_ = nullptr;
  2329. std::mutex ctx_mutex_;
  2330. int last_ssl_error_ = 0;
  2331. };
  2332. class SSLClient final : public ClientImpl {
  2333. public:
  2334. explicit SSLClient(const std::string &host);
  2335. explicit SSLClient(const std::string &host, int port);
  2336. explicit SSLClient(const std::string &host, int port,
  2337. const std::string &client_cert_path,
  2338. const std::string &client_key_path,
  2339. const std::string &private_key_password = std::string());
  2340. struct PemMemory {
  2341. const char *cert_pem;
  2342. size_t cert_pem_len;
  2343. const char *key_pem;
  2344. size_t key_pem_len;
  2345. const char *private_key_password;
  2346. };
  2347. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2348. ~SSLClient() override;
  2349. bool is_valid() const override;
  2350. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2351. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2352. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2353. // Post-handshake session verifier (backend-independent)
  2354. void set_session_verifier(
  2355. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2356. tls::ctx_t tls_context() const { return ctx_; }
  2357. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2358. void enable_windows_certificate_verification(bool enabled);
  2359. #endif
  2360. private:
  2361. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2362. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2363. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2364. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2365. bool
  2366. process_socket(const Socket &socket,
  2367. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2368. std::function<bool(Stream &strm)> callback) override;
  2369. bool is_ssl() const override;
  2370. bool setup_proxy_connection(
  2371. Socket &socket,
  2372. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2373. Response &res, bool &success, Error &error) override;
  2374. bool connect_with_proxy(
  2375. Socket &sock,
  2376. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2377. Response &res, bool &success, Error &error);
  2378. bool initialize_ssl(Socket &socket, Error &error);
  2379. void init_ctx();
  2380. void reset_ctx_on_error();
  2381. bool load_certs();
  2382. tls::ctx_t ctx_ = nullptr;
  2383. std::mutex ctx_mutex_;
  2384. std::once_flag initialize_cert_;
  2385. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2386. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2387. // Used to keep custom CA configuration exclusive with system CA loading.
  2388. bool ca_cert_store_set_ = false;
  2389. long verify_result_ = 0;
  2390. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2391. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2392. bool enable_windows_cert_verification_ = true;
  2393. #endif
  2394. friend class ClientImpl;
  2395. };
  2396. #endif // CPPHTTPLIB_SSL_ENABLED
  2397. namespace detail {
  2398. template <typename T, typename U>
  2399. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2400. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2401. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2402. duration - std::chrono::seconds(sec))
  2403. .count();
  2404. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2405. }
  2406. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2407. return N - 1;
  2408. }
  2409. inline bool is_numeric(const std::string &str) {
  2410. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2411. }
  2412. inline size_t get_header_value_u64(const Headers &headers,
  2413. const std::string &key, size_t def,
  2414. size_t id, bool &is_invalid_value) {
  2415. is_invalid_value = false;
  2416. auto rng = headers.equal_range(key);
  2417. auto it = rng.first;
  2418. std::advance(it, static_cast<ssize_t>(id));
  2419. if (it != rng.second) {
  2420. if (is_numeric(it->second)) {
  2421. // Parse at size_t width so an out-of-range Content-Length is reported
  2422. // rather than silently saturated/truncated (a value above 2^32 would
  2423. // otherwise wrap to a small framing length on 32-bit builds). Flag it
  2424. // and return SIZE_MAX so the existing oversized-value guards reject it.
  2425. size_t val = 0;
  2426. const auto &s = it->second;
  2427. auto r = from_chars(s.data(), s.data() + s.size(), val);
  2428. if (r.ec == std::errc::result_out_of_range) {
  2429. is_invalid_value = true;
  2430. return (std::numeric_limits<size_t>::max)();
  2431. }
  2432. return val;
  2433. } else {
  2434. is_invalid_value = true;
  2435. }
  2436. }
  2437. return def;
  2438. }
  2439. inline size_t get_header_value_u64(const Headers &headers,
  2440. const std::string &key, size_t def,
  2441. size_t id) {
  2442. auto dummy = false;
  2443. return get_header_value_u64(headers, key, def, id, dummy);
  2444. }
  2445. } // namespace detail
  2446. template <class Rep, class Period>
  2447. inline Server &
  2448. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2449. detail::duration_to_sec_and_usec(
  2450. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2451. return *this;
  2452. }
  2453. template <class Rep, class Period>
  2454. inline Server &
  2455. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2456. detail::duration_to_sec_and_usec(
  2457. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2458. return *this;
  2459. }
  2460. template <class Rep, class Period>
  2461. inline Server &
  2462. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2463. detail::duration_to_sec_and_usec(
  2464. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2465. return *this;
  2466. }
  2467. template <class Rep, class Period>
  2468. inline void ClientImpl::set_connection_timeout(
  2469. const std::chrono::duration<Rep, Period> &duration) {
  2470. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2471. set_connection_timeout(sec, usec);
  2472. });
  2473. }
  2474. template <class Rep, class Period>
  2475. inline void ClientImpl::set_read_timeout(
  2476. const std::chrono::duration<Rep, Period> &duration) {
  2477. detail::duration_to_sec_and_usec(
  2478. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2479. }
  2480. template <class Rep, class Period>
  2481. inline void ClientImpl::set_write_timeout(
  2482. const std::chrono::duration<Rep, Period> &duration) {
  2483. detail::duration_to_sec_and_usec(
  2484. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2485. }
  2486. template <class Rep, class Period>
  2487. inline void ClientImpl::set_max_timeout(
  2488. const std::chrono::duration<Rep, Period> &duration) {
  2489. auto msec =
  2490. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2491. set_max_timeout(msec);
  2492. }
  2493. template <class Rep, class Period>
  2494. inline void Client::set_connection_timeout(
  2495. const std::chrono::duration<Rep, Period> &duration) {
  2496. cli_->set_connection_timeout(duration);
  2497. }
  2498. template <class Rep, class Period>
  2499. inline void
  2500. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2501. cli_->set_read_timeout(duration);
  2502. }
  2503. template <class Rep, class Period>
  2504. inline void
  2505. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2506. cli_->set_write_timeout(duration);
  2507. }
  2508. inline void Client::set_max_timeout(time_t msec) {
  2509. cli_->set_max_timeout(msec);
  2510. }
  2511. template <class Rep, class Period>
  2512. inline void
  2513. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2514. cli_->set_max_timeout(duration);
  2515. }
  2516. /*
  2517. * Forward declarations and types that will be part of the .h file if split into
  2518. * .h + .cc.
  2519. */
  2520. std::string hosted_at(const std::string &hostname);
  2521. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2522. // JavaScript-style URL encoding/decoding functions
  2523. std::string encode_uri_component(const std::string &value);
  2524. std::string encode_uri(const std::string &value);
  2525. std::string decode_uri_component(const std::string &value);
  2526. std::string decode_uri(const std::string &value);
  2527. // RFC 3986 compliant URL component encoding/decoding functions
  2528. std::string encode_path_component(const std::string &component);
  2529. std::string decode_path_component(const std::string &component);
  2530. std::string encode_query_component(const std::string &component,
  2531. bool space_as_plus = true);
  2532. std::string decode_query_component(const std::string &component,
  2533. bool plus_as_space = true);
  2534. std::string sanitize_filename(const std::string &filename);
  2535. std::string append_query_params(const std::string &path, const Params &params);
  2536. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2537. std::pair<std::string, std::string>
  2538. make_basic_authentication_header(const std::string &username,
  2539. const std::string &password,
  2540. bool is_proxy = false);
  2541. namespace detail {
  2542. #if defined(_WIN32)
  2543. inline std::wstring u8string_to_wstring(const char *s) {
  2544. if (!s) { return std::wstring(); }
  2545. auto len = static_cast<int>(strlen(s));
  2546. if (!len) { return std::wstring(); }
  2547. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2548. if (!wlen) { return std::wstring(); }
  2549. std::wstring ws;
  2550. ws.resize(wlen);
  2551. wlen = ::MultiByteToWideChar(
  2552. CP_UTF8, 0, s, len,
  2553. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2554. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2555. return ws;
  2556. }
  2557. #endif
  2558. struct FileStat {
  2559. FileStat(const std::string &path);
  2560. bool is_file() const;
  2561. bool is_dir() const;
  2562. time_t mtime() const;
  2563. size_t size() const;
  2564. private:
  2565. #if defined(_WIN32)
  2566. struct _stat st_;
  2567. #else
  2568. struct stat st_;
  2569. #endif
  2570. int ret_ = -1;
  2571. };
  2572. std::string make_host_and_port_string(const std::string &host, int port,
  2573. bool is_ssl);
  2574. std::string trim_copy(const std::string &s);
  2575. void divide(
  2576. const char *data, std::size_t size, char d,
  2577. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2578. fn);
  2579. void divide(
  2580. const std::string &str, char d,
  2581. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2582. fn);
  2583. void split(const char *b, const char *e, char d,
  2584. std::function<void(const char *, const char *)> fn);
  2585. void split(const char *b, const char *e, char d, size_t m,
  2586. std::function<void(const char *, const char *)> fn);
  2587. bool process_client_socket(
  2588. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2589. time_t write_timeout_sec, time_t write_timeout_usec,
  2590. time_t max_timeout_msec,
  2591. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2592. std::function<bool(Stream &)> callback);
  2593. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2594. int port, int address_family, bool tcp_nodelay,
  2595. bool ipv6_v6only, SocketOptions socket_options,
  2596. time_t connection_timeout_sec,
  2597. time_t connection_timeout_usec,
  2598. time_t read_timeout_sec, time_t read_timeout_usec,
  2599. time_t write_timeout_sec,
  2600. time_t write_timeout_usec,
  2601. const std::string &intf, Error &error);
  2602. const char *get_header_value(const Headers &headers, const std::string &key,
  2603. const char *def, size_t id);
  2604. std::string params_to_query_str(const Params &params);
  2605. void parse_query_text(const char *data, std::size_t size, Params &params);
  2606. void parse_query_text(const std::string &s, Params &params);
  2607. bool parse_multipart_boundary(const std::string &content_type,
  2608. std::string &boundary);
  2609. bool parse_range_header(const std::string &s, Ranges &ranges);
  2610. bool parse_accept_header(const std::string &s,
  2611. std::vector<std::string> &content_types);
  2612. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2613. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2614. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2615. EncodingType encoding_type(const Request &req, const Response &res);
  2616. class BufferStream final : public Stream {
  2617. public:
  2618. BufferStream() = default;
  2619. ~BufferStream() override = default;
  2620. bool is_readable() const override;
  2621. bool wait_readable() const override;
  2622. bool wait_writable() const override;
  2623. ssize_t read(char *ptr, size_t size) override;
  2624. ssize_t write(const char *ptr, size_t size) override;
  2625. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2626. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2627. socket_t socket() const override;
  2628. time_t duration() const override;
  2629. const std::string &get_buffer() const;
  2630. private:
  2631. std::string buffer;
  2632. size_t position = 0;
  2633. };
  2634. class compressor {
  2635. public:
  2636. virtual ~compressor() = default;
  2637. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2638. virtual bool compress(const char *data, size_t data_length, bool last,
  2639. Callback callback) = 0;
  2640. };
  2641. class decompressor {
  2642. public:
  2643. virtual ~decompressor() = default;
  2644. virtual bool is_valid() const = 0;
  2645. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2646. virtual bool decompress(const char *data, size_t data_length,
  2647. Callback callback) = 0;
  2648. };
  2649. class nocompressor final : public compressor {
  2650. public:
  2651. ~nocompressor() override = default;
  2652. bool compress(const char *data, size_t data_length, bool /*last*/,
  2653. Callback callback) override;
  2654. };
  2655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2656. class gzip_compressor final : public compressor {
  2657. public:
  2658. gzip_compressor();
  2659. ~gzip_compressor() override;
  2660. bool compress(const char *data, size_t data_length, bool last,
  2661. Callback callback) override;
  2662. private:
  2663. bool is_valid_ = false;
  2664. z_stream strm_;
  2665. };
  2666. class gzip_decompressor final : public decompressor {
  2667. public:
  2668. gzip_decompressor();
  2669. ~gzip_decompressor() override;
  2670. bool is_valid() const override;
  2671. bool decompress(const char *data, size_t data_length,
  2672. Callback callback) override;
  2673. private:
  2674. bool is_valid_ = false;
  2675. z_stream strm_;
  2676. };
  2677. #endif
  2678. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2679. class brotli_compressor final : public compressor {
  2680. public:
  2681. brotli_compressor();
  2682. ~brotli_compressor();
  2683. bool compress(const char *data, size_t data_length, bool last,
  2684. Callback callback) override;
  2685. private:
  2686. BrotliEncoderState *state_ = nullptr;
  2687. };
  2688. class brotli_decompressor final : public decompressor {
  2689. public:
  2690. brotli_decompressor();
  2691. ~brotli_decompressor();
  2692. bool is_valid() const override;
  2693. bool decompress(const char *data, size_t data_length,
  2694. Callback callback) override;
  2695. private:
  2696. BrotliDecoderResult decoder_r;
  2697. BrotliDecoderState *decoder_s = nullptr;
  2698. };
  2699. #endif
  2700. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2701. class zstd_compressor : public compressor {
  2702. public:
  2703. zstd_compressor();
  2704. ~zstd_compressor();
  2705. bool compress(const char *data, size_t data_length, bool last,
  2706. Callback callback) override;
  2707. private:
  2708. ZSTD_CCtx *ctx_ = nullptr;
  2709. };
  2710. class zstd_decompressor : public decompressor {
  2711. public:
  2712. zstd_decompressor();
  2713. ~zstd_decompressor();
  2714. bool is_valid() const override;
  2715. bool decompress(const char *data, size_t data_length,
  2716. Callback callback) override;
  2717. private:
  2718. ZSTD_DCtx *ctx_ = nullptr;
  2719. };
  2720. #endif
  2721. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2722. // to store data. The call can set memory on stack for performance.
  2723. class stream_line_reader {
  2724. public:
  2725. stream_line_reader(Stream &strm, char *fixed_buffer,
  2726. size_t fixed_buffer_size);
  2727. const char *ptr() const;
  2728. size_t size() const;
  2729. bool end_with_crlf() const;
  2730. bool getline();
  2731. private:
  2732. void append(char c);
  2733. Stream &strm_;
  2734. char *fixed_buffer_;
  2735. const size_t fixed_buffer_size_;
  2736. size_t fixed_buffer_used_size_ = 0;
  2737. std::string growable_buffer_;
  2738. };
  2739. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2740. const Headers &src_headers);
  2741. struct ChunkedDecoder {
  2742. Stream &strm;
  2743. size_t chunk_remaining = 0;
  2744. bool finished = false;
  2745. char line_buf[64];
  2746. size_t last_chunk_total = 0;
  2747. size_t last_chunk_offset = 0;
  2748. explicit ChunkedDecoder(Stream &s);
  2749. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2750. size_t &out_chunk_total);
  2751. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2752. };
  2753. class mmap {
  2754. public:
  2755. mmap(const char *path);
  2756. ~mmap();
  2757. bool open(const char *path);
  2758. void close();
  2759. bool is_open() const;
  2760. size_t size() const;
  2761. const char *data() const;
  2762. private:
  2763. #if defined(_WIN32)
  2764. HANDLE hFile_ = NULL;
  2765. HANDLE hMapping_ = NULL;
  2766. #else
  2767. int fd_ = -1;
  2768. #endif
  2769. size_t size_ = 0;
  2770. void *addr_ = nullptr;
  2771. bool is_open_empty_file = false;
  2772. };
  2773. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2774. namespace fields {
  2775. bool is_token_char(char c);
  2776. bool is_token(const std::string &s);
  2777. bool is_field_name(const std::string &s);
  2778. bool is_vchar(char c);
  2779. bool is_obs_text(char c);
  2780. bool is_field_vchar(char c);
  2781. bool is_field_content(const std::string &s);
  2782. bool is_field_value(const std::string &s);
  2783. } // namespace fields
  2784. } // namespace detail
  2785. /*
  2786. * TLS Abstraction Layer Declarations
  2787. */
  2788. #ifdef CPPHTTPLIB_SSL_ENABLED
  2789. // TLS abstraction layer - backend-specific type declarations
  2790. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2791. namespace tls {
  2792. namespace impl {
  2793. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2794. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2795. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2796. struct MbedTlsContext {
  2797. mbedtls_ssl_config conf;
  2798. mbedtls_entropy_context entropy;
  2799. mbedtls_ctr_drbg_context ctr_drbg;
  2800. mbedtls_x509_crt ca_chain;
  2801. mbedtls_x509_crt own_cert;
  2802. mbedtls_pk_context own_key;
  2803. bool is_server = false;
  2804. bool verify_client = false;
  2805. bool has_verify_callback = false;
  2806. MbedTlsContext();
  2807. ~MbedTlsContext();
  2808. MbedTlsContext(const MbedTlsContext &) = delete;
  2809. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2810. };
  2811. } // namespace impl
  2812. } // namespace tls
  2813. #endif
  2814. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2815. namespace tls {
  2816. namespace impl {
  2817. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2818. // This struct is accessible via tls::impl for use in SSL context
  2819. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2820. struct WolfSSLContext {
  2821. WOLFSSL_CTX *ctx = nullptr;
  2822. bool is_server = false;
  2823. bool verify_client = false;
  2824. bool has_verify_callback = false;
  2825. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2826. WolfSSLContext();
  2827. ~WolfSSLContext();
  2828. WolfSSLContext(const WolfSSLContext &) = delete;
  2829. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2830. };
  2831. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2832. struct WolfSSLCAStore {
  2833. std::string pem_data;
  2834. };
  2835. } // namespace impl
  2836. } // namespace tls
  2837. #endif
  2838. #endif // CPPHTTPLIB_SSL_ENABLED
  2839. namespace stream {
  2840. class Result {
  2841. public:
  2842. Result();
  2843. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2844. Result(Result &&other) noexcept;
  2845. Result &operator=(Result &&other) noexcept;
  2846. Result(const Result &) = delete;
  2847. Result &operator=(const Result &) = delete;
  2848. // Response info
  2849. bool is_valid() const;
  2850. explicit operator bool() const;
  2851. int status() const;
  2852. const Headers &headers() const;
  2853. std::string get_header_value(const std::string &key,
  2854. const char *def = "") const;
  2855. bool has_header(const std::string &key) const;
  2856. Error error() const;
  2857. Error read_error() const;
  2858. bool has_read_error() const;
  2859. // Stream reading
  2860. bool next();
  2861. const char *data() const;
  2862. size_t size() const;
  2863. std::string read_all();
  2864. private:
  2865. ClientImpl::StreamHandle handle_;
  2866. std::string buffer_;
  2867. size_t current_size_ = 0;
  2868. size_t chunk_size_;
  2869. bool finished_ = false;
  2870. };
  2871. // GET
  2872. template <typename ClientType>
  2873. inline Result Get(ClientType &cli, const std::string &path,
  2874. size_t chunk_size = 8192) {
  2875. return Result{cli.open_stream("GET", path), chunk_size};
  2876. }
  2877. template <typename ClientType>
  2878. inline Result Get(ClientType &cli, const std::string &path,
  2879. const Headers &headers, size_t chunk_size = 8192) {
  2880. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2881. }
  2882. template <typename ClientType>
  2883. inline Result Get(ClientType &cli, const std::string &path,
  2884. const Params &params, size_t chunk_size = 8192) {
  2885. return Result{cli.open_stream("GET", path, params), chunk_size};
  2886. }
  2887. template <typename ClientType>
  2888. inline Result Get(ClientType &cli, const std::string &path,
  2889. const Params &params, const Headers &headers,
  2890. size_t chunk_size = 8192) {
  2891. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2892. }
  2893. // POST
  2894. template <typename ClientType>
  2895. inline Result Post(ClientType &cli, const std::string &path,
  2896. const std::string &body, const std::string &content_type,
  2897. size_t chunk_size = 8192) {
  2898. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2899. chunk_size};
  2900. }
  2901. template <typename ClientType>
  2902. inline Result Post(ClientType &cli, const std::string &path,
  2903. const Headers &headers, const std::string &body,
  2904. const std::string &content_type, size_t chunk_size = 8192) {
  2905. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2906. chunk_size};
  2907. }
  2908. template <typename ClientType>
  2909. inline Result Post(ClientType &cli, const std::string &path,
  2910. const Params &params, const std::string &body,
  2911. const std::string &content_type, size_t chunk_size = 8192) {
  2912. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2913. chunk_size};
  2914. }
  2915. template <typename ClientType>
  2916. inline Result Post(ClientType &cli, const std::string &path,
  2917. const Params &params, const Headers &headers,
  2918. const std::string &body, const std::string &content_type,
  2919. size_t chunk_size = 8192) {
  2920. return Result{
  2921. cli.open_stream("POST", path, params, headers, body, content_type),
  2922. chunk_size};
  2923. }
  2924. // PUT
  2925. template <typename ClientType>
  2926. inline Result Put(ClientType &cli, const std::string &path,
  2927. const std::string &body, const std::string &content_type,
  2928. size_t chunk_size = 8192) {
  2929. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2930. chunk_size};
  2931. }
  2932. template <typename ClientType>
  2933. inline Result Put(ClientType &cli, const std::string &path,
  2934. const Headers &headers, const std::string &body,
  2935. const std::string &content_type, size_t chunk_size = 8192) {
  2936. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2937. chunk_size};
  2938. }
  2939. template <typename ClientType>
  2940. inline Result Put(ClientType &cli, const std::string &path,
  2941. const Params &params, const std::string &body,
  2942. const std::string &content_type, size_t chunk_size = 8192) {
  2943. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2944. chunk_size};
  2945. }
  2946. template <typename ClientType>
  2947. inline Result Put(ClientType &cli, const std::string &path,
  2948. const Params &params, const Headers &headers,
  2949. const std::string &body, const std::string &content_type,
  2950. size_t chunk_size = 8192) {
  2951. return Result{
  2952. cli.open_stream("PUT", path, params, headers, body, content_type),
  2953. chunk_size};
  2954. }
  2955. // PATCH
  2956. template <typename ClientType>
  2957. inline Result Patch(ClientType &cli, const std::string &path,
  2958. const std::string &body, const std::string &content_type,
  2959. size_t chunk_size = 8192) {
  2960. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2961. chunk_size};
  2962. }
  2963. template <typename ClientType>
  2964. inline Result Patch(ClientType &cli, const std::string &path,
  2965. const Headers &headers, const std::string &body,
  2966. const std::string &content_type, size_t chunk_size = 8192) {
  2967. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2968. chunk_size};
  2969. }
  2970. template <typename ClientType>
  2971. inline Result Patch(ClientType &cli, const std::string &path,
  2972. const Params &params, const std::string &body,
  2973. const std::string &content_type, size_t chunk_size = 8192) {
  2974. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2975. chunk_size};
  2976. }
  2977. template <typename ClientType>
  2978. inline Result Patch(ClientType &cli, const std::string &path,
  2979. const Params &params, const Headers &headers,
  2980. const std::string &body, const std::string &content_type,
  2981. size_t chunk_size = 8192) {
  2982. return Result{
  2983. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2984. chunk_size};
  2985. }
  2986. // DELETE
  2987. template <typename ClientType>
  2988. inline Result Delete(ClientType &cli, const std::string &path,
  2989. size_t chunk_size = 8192) {
  2990. return Result{cli.open_stream("DELETE", path), chunk_size};
  2991. }
  2992. template <typename ClientType>
  2993. inline Result Delete(ClientType &cli, const std::string &path,
  2994. const Headers &headers, size_t chunk_size = 8192) {
  2995. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2996. }
  2997. template <typename ClientType>
  2998. inline Result Delete(ClientType &cli, const std::string &path,
  2999. const std::string &body, const std::string &content_type,
  3000. size_t chunk_size = 8192) {
  3001. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  3002. chunk_size};
  3003. }
  3004. template <typename ClientType>
  3005. inline Result Delete(ClientType &cli, const std::string &path,
  3006. const Headers &headers, const std::string &body,
  3007. const std::string &content_type,
  3008. size_t chunk_size = 8192) {
  3009. return Result{
  3010. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3011. chunk_size};
  3012. }
  3013. template <typename ClientType>
  3014. inline Result Delete(ClientType &cli, const std::string &path,
  3015. const Params &params, size_t chunk_size = 8192) {
  3016. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3017. }
  3018. template <typename ClientType>
  3019. inline Result Delete(ClientType &cli, const std::string &path,
  3020. const Params &params, const Headers &headers,
  3021. size_t chunk_size = 8192) {
  3022. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3023. }
  3024. template <typename ClientType>
  3025. inline Result Delete(ClientType &cli, const std::string &path,
  3026. const Params &params, const std::string &body,
  3027. const std::string &content_type,
  3028. size_t chunk_size = 8192) {
  3029. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3030. chunk_size};
  3031. }
  3032. template <typename ClientType>
  3033. inline Result Delete(ClientType &cli, const std::string &path,
  3034. const Params &params, const Headers &headers,
  3035. const std::string &body, const std::string &content_type,
  3036. size_t chunk_size = 8192) {
  3037. return Result{
  3038. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3039. chunk_size};
  3040. }
  3041. // HEAD
  3042. template <typename ClientType>
  3043. inline Result Head(ClientType &cli, const std::string &path,
  3044. size_t chunk_size = 8192) {
  3045. return Result{cli.open_stream("HEAD", path), chunk_size};
  3046. }
  3047. template <typename ClientType>
  3048. inline Result Head(ClientType &cli, const std::string &path,
  3049. const Headers &headers, size_t chunk_size = 8192) {
  3050. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3051. }
  3052. template <typename ClientType>
  3053. inline Result Head(ClientType &cli, const std::string &path,
  3054. const Params &params, size_t chunk_size = 8192) {
  3055. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3056. }
  3057. template <typename ClientType>
  3058. inline Result Head(ClientType &cli, const std::string &path,
  3059. const Params &params, const Headers &headers,
  3060. size_t chunk_size = 8192) {
  3061. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3062. }
  3063. // OPTIONS
  3064. template <typename ClientType>
  3065. inline Result Options(ClientType &cli, const std::string &path,
  3066. size_t chunk_size = 8192) {
  3067. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3068. }
  3069. template <typename ClientType>
  3070. inline Result Options(ClientType &cli, const std::string &path,
  3071. const Headers &headers, size_t chunk_size = 8192) {
  3072. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3073. }
  3074. template <typename ClientType>
  3075. inline Result Options(ClientType &cli, const std::string &path,
  3076. const Params &params, size_t chunk_size = 8192) {
  3077. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3078. }
  3079. template <typename ClientType>
  3080. inline Result Options(ClientType &cli, const std::string &path,
  3081. const Params &params, const Headers &headers,
  3082. size_t chunk_size = 8192) {
  3083. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3084. }
  3085. } // namespace stream
  3086. namespace sse {
  3087. struct SSEMessage {
  3088. std::string event; // Event type (default: "message")
  3089. std::string data; // Event payload
  3090. std::string id; // Event ID for Last-Event-ID header
  3091. SSEMessage();
  3092. void clear();
  3093. };
  3094. class SSEClient {
  3095. public:
  3096. using MessageHandler = std::function<void(const SSEMessage &)>;
  3097. using ErrorHandler = std::function<void(Error)>;
  3098. using OpenHandler = std::function<void()>;
  3099. SSEClient(Client &client, const std::string &path);
  3100. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3101. ~SSEClient();
  3102. SSEClient(const SSEClient &) = delete;
  3103. SSEClient &operator=(const SSEClient &) = delete;
  3104. // Event handlers
  3105. SSEClient &on_message(MessageHandler handler);
  3106. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3107. SSEClient &on_open(OpenHandler handler);
  3108. SSEClient &on_error(ErrorHandler handler);
  3109. SSEClient &set_reconnect_interval(int ms);
  3110. SSEClient &set_max_reconnect_attempts(int n);
  3111. // Update headers (thread-safe)
  3112. SSEClient &set_headers(const Headers &headers);
  3113. // State accessors
  3114. bool is_connected() const;
  3115. const std::string &last_event_id() const;
  3116. // Blocking start - runs event loop with auto-reconnect
  3117. void start();
  3118. // Non-blocking start - runs in background thread
  3119. void start_async();
  3120. // Stop the client (thread-safe)
  3121. void stop();
  3122. private:
  3123. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3124. void run_event_loop();
  3125. void dispatch_event(const SSEMessage &msg);
  3126. bool should_reconnect(int count) const;
  3127. void wait_for_reconnect();
  3128. // Client and path
  3129. Client &client_;
  3130. std::string path_;
  3131. Headers headers_;
  3132. mutable std::mutex headers_mutex_;
  3133. // Callbacks
  3134. MessageHandler on_message_;
  3135. std::map<std::string, MessageHandler> event_handlers_;
  3136. OpenHandler on_open_;
  3137. ErrorHandler on_error_;
  3138. // Configuration
  3139. int reconnect_interval_ms_ = 3000;
  3140. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3141. // State
  3142. std::atomic<bool> running_{false};
  3143. std::atomic<bool> connected_{false};
  3144. std::string last_event_id_;
  3145. // Async support
  3146. std::thread async_thread_;
  3147. };
  3148. } // namespace sse
  3149. namespace ws {
  3150. enum class Opcode : uint8_t {
  3151. Continuation = 0x0,
  3152. Text = 0x1,
  3153. Binary = 0x2,
  3154. Close = 0x8,
  3155. Ping = 0x9,
  3156. Pong = 0xA,
  3157. };
  3158. enum class CloseStatus : uint16_t {
  3159. Normal = 1000,
  3160. GoingAway = 1001,
  3161. ProtocolError = 1002,
  3162. UnsupportedData = 1003,
  3163. NoStatus = 1005,
  3164. Abnormal = 1006,
  3165. InvalidPayload = 1007,
  3166. PolicyViolation = 1008,
  3167. MessageTooBig = 1009,
  3168. MandatoryExtension = 1010,
  3169. InternalError = 1011,
  3170. };
  3171. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3172. class WebSocket {
  3173. public:
  3174. WebSocket(const WebSocket &) = delete;
  3175. WebSocket &operator=(const WebSocket &) = delete;
  3176. ~WebSocket();
  3177. ReadResult read(std::string &msg);
  3178. bool send(const std::string &data);
  3179. bool send(const char *data, size_t len);
  3180. void close(CloseStatus status = CloseStatus::Normal,
  3181. const std::string &reason = "");
  3182. const Request &request() const;
  3183. bool is_open() const;
  3184. private:
  3185. friend class httplib::Server;
  3186. friend class WebSocketClient;
  3187. WebSocket(
  3188. Stream &strm, const Request &req, bool is_server,
  3189. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3190. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3191. : strm_(strm), req_(req), is_server_(is_server),
  3192. ping_interval_sec_(ping_interval_sec),
  3193. max_missed_pongs_(max_missed_pongs) {
  3194. start_heartbeat();
  3195. }
  3196. WebSocket(
  3197. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3198. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3199. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3200. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3201. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3202. max_missed_pongs_(max_missed_pongs) {
  3203. start_heartbeat();
  3204. }
  3205. void start_heartbeat();
  3206. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3207. Stream &strm_;
  3208. std::unique_ptr<Stream> owned_strm_;
  3209. Request req_;
  3210. bool is_server_;
  3211. time_t ping_interval_sec_;
  3212. int max_missed_pongs_;
  3213. int unacked_pings_ = 0;
  3214. std::atomic<bool> closed_{false};
  3215. std::mutex write_mutex_;
  3216. std::thread ping_thread_;
  3217. std::mutex ping_mutex_;
  3218. std::condition_variable ping_cv_;
  3219. };
  3220. class WebSocketClient {
  3221. public:
  3222. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3223. const Headers &headers = {});
  3224. ~WebSocketClient();
  3225. WebSocketClient(const WebSocketClient &) = delete;
  3226. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3227. bool is_valid() const;
  3228. bool connect();
  3229. ReadResult read(std::string &msg);
  3230. bool send(const std::string &data);
  3231. bool send(const char *data, size_t len);
  3232. void close(CloseStatus status = CloseStatus::Normal,
  3233. const std::string &reason = "");
  3234. bool is_open() const;
  3235. const std::string &subprotocol() const;
  3236. void set_read_timeout(time_t sec, time_t usec = 0);
  3237. void set_write_timeout(time_t sec, time_t usec = 0);
  3238. void set_websocket_ping_interval(time_t sec);
  3239. void set_websocket_max_missed_pongs(int count);
  3240. void set_tcp_nodelay(bool on);
  3241. void set_address_family(int family);
  3242. void set_ipv6_v6only(bool on);
  3243. void set_socket_options(SocketOptions socket_options);
  3244. void set_connection_timeout(time_t sec, time_t usec = 0);
  3245. void set_interface(const std::string &intf);
  3246. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3247. #ifdef CPPHTTPLIB_SSL_ENABLED
  3248. void set_ca_cert_path(const std::string &path);
  3249. void set_ca_cert_store(tls::ca_store_t store);
  3250. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3251. void enable_server_certificate_verification(bool enabled);
  3252. void enable_system_ca(bool enabled);
  3253. #endif
  3254. private:
  3255. void shutdown_and_close();
  3256. bool create_stream(std::unique_ptr<Stream> &strm);
  3257. std::string host_;
  3258. int port_;
  3259. std::string path_;
  3260. Headers headers_;
  3261. std::string subprotocol_;
  3262. bool is_valid_ = false;
  3263. socket_t sock_ = INVALID_SOCKET;
  3264. std::unique_ptr<WebSocket> ws_;
  3265. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3266. time_t read_timeout_usec_ = 0;
  3267. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3268. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3269. time_t websocket_ping_interval_sec_ =
  3270. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3271. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3272. int address_family_ = AF_UNSPEC;
  3273. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3274. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3275. SocketOptions socket_options_ = nullptr;
  3276. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3277. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3278. std::string interface_;
  3279. // Hostname-IP map
  3280. std::map<std::string, std::string> addr_map_;
  3281. #ifdef CPPHTTPLIB_SSL_ENABLED
  3282. bool is_ssl_ = false;
  3283. tls::ctx_t tls_ctx_ = nullptr;
  3284. tls::session_t tls_session_ = nullptr;
  3285. std::string ca_cert_file_path_;
  3286. bool custom_ca_loaded_ = false;
  3287. bool certs_loaded_ = false;
  3288. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3289. bool server_certificate_verification_ = true;
  3290. #endif
  3291. };
  3292. namespace impl {
  3293. bool is_valid_utf8(const std::string &s);
  3294. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3295. bool &fin, bool expect_masked, size_t max_len);
  3296. } // namespace impl
  3297. } // namespace ws
  3298. // ----------------------------------------------------------------------------
  3299. /*
  3300. * Implementation that will be part of the .cc file if split into .h + .cc.
  3301. */
  3302. namespace stream {
  3303. // stream::Result implementations
  3304. inline Result::Result() : chunk_size_(8192) {}
  3305. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3306. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3307. inline Result::Result(Result &&other) noexcept
  3308. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3309. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3310. finished_(other.finished_) {
  3311. other.current_size_ = 0;
  3312. other.finished_ = true;
  3313. }
  3314. inline Result &Result::operator=(Result &&other) noexcept {
  3315. if (this != &other) {
  3316. handle_ = std::move(other.handle_);
  3317. buffer_ = std::move(other.buffer_);
  3318. current_size_ = other.current_size_;
  3319. chunk_size_ = other.chunk_size_;
  3320. finished_ = other.finished_;
  3321. other.current_size_ = 0;
  3322. other.finished_ = true;
  3323. }
  3324. return *this;
  3325. }
  3326. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3327. inline Result::operator bool() const { return is_valid(); }
  3328. inline int Result::status() const {
  3329. return handle_.response ? handle_.response->status : -1;
  3330. }
  3331. inline const Headers &Result::headers() const {
  3332. static const Headers empty_headers;
  3333. return handle_.response ? handle_.response->headers : empty_headers;
  3334. }
  3335. inline std::string Result::get_header_value(const std::string &key,
  3336. const char *def) const {
  3337. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3338. }
  3339. inline bool Result::has_header(const std::string &key) const {
  3340. return handle_.response ? handle_.response->has_header(key) : false;
  3341. }
  3342. inline Error Result::error() const { return handle_.error; }
  3343. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3344. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3345. inline bool Result::next() {
  3346. if (!handle_.is_valid() || finished_) { return false; }
  3347. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3348. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3349. if (n > 0) {
  3350. current_size_ = static_cast<size_t>(n);
  3351. return true;
  3352. }
  3353. current_size_ = 0;
  3354. finished_ = true;
  3355. return false;
  3356. }
  3357. inline const char *Result::data() const { return buffer_.data(); }
  3358. inline size_t Result::size() const { return current_size_; }
  3359. inline std::string Result::read_all() {
  3360. std::string result;
  3361. while (next()) {
  3362. result.append(data(), size());
  3363. }
  3364. return result;
  3365. }
  3366. } // namespace stream
  3367. namespace sse {
  3368. // SSEMessage implementations
  3369. inline SSEMessage::SSEMessage() : event("message") {}
  3370. inline void SSEMessage::clear() {
  3371. event = "message";
  3372. data.clear();
  3373. id.clear();
  3374. }
  3375. // SSEClient implementations
  3376. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3377. : client_(client), path_(path) {}
  3378. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3379. const Headers &headers)
  3380. : client_(client), path_(path), headers_(headers) {}
  3381. inline SSEClient::~SSEClient() { stop(); }
  3382. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3383. on_message_ = std::move(handler);
  3384. return *this;
  3385. }
  3386. inline SSEClient &SSEClient::on_event(const std::string &type,
  3387. MessageHandler handler) {
  3388. event_handlers_[type] = std::move(handler);
  3389. return *this;
  3390. }
  3391. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3392. on_open_ = std::move(handler);
  3393. return *this;
  3394. }
  3395. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3396. on_error_ = std::move(handler);
  3397. return *this;
  3398. }
  3399. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3400. reconnect_interval_ms_ = ms;
  3401. return *this;
  3402. }
  3403. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3404. max_reconnect_attempts_ = n;
  3405. return *this;
  3406. }
  3407. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3408. std::lock_guard<std::mutex> lock(headers_mutex_);
  3409. headers_ = headers;
  3410. return *this;
  3411. }
  3412. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3413. inline const std::string &SSEClient::last_event_id() const {
  3414. return last_event_id_;
  3415. }
  3416. inline void SSEClient::start() {
  3417. running_.store(true);
  3418. run_event_loop();
  3419. }
  3420. inline void SSEClient::start_async() {
  3421. running_.store(true);
  3422. async_thread_ = std::thread([this]() { run_event_loop(); });
  3423. }
  3424. inline void SSEClient::stop() {
  3425. running_.store(false);
  3426. client_.stop(); // Cancel any pending operations
  3427. if (async_thread_.joinable()) { async_thread_.join(); }
  3428. }
  3429. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3430. int &retry_ms) {
  3431. // Blank line signals end of event
  3432. if (line.empty() || line == "\r") { return true; }
  3433. // Lines starting with ':' are comments (ignored)
  3434. if (!line.empty() && line[0] == ':') { return false; }
  3435. // Find the colon separator
  3436. auto colon_pos = line.find(':');
  3437. if (colon_pos == std::string::npos) {
  3438. // Line with no colon is treated as field name with empty value
  3439. return false;
  3440. }
  3441. auto field = line.substr(0, colon_pos);
  3442. std::string value;
  3443. // Value starts after colon, skip optional single space
  3444. if (colon_pos + 1 < line.size()) {
  3445. auto value_start = colon_pos + 1;
  3446. if (line[value_start] == ' ') { value_start++; }
  3447. value = line.substr(value_start);
  3448. // Remove trailing \r if present
  3449. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3450. }
  3451. // Handle known fields
  3452. if (field == "event") {
  3453. msg.event = value;
  3454. } else if (field == "data") {
  3455. // Multiple data lines are concatenated with newlines
  3456. if (!msg.data.empty()) { msg.data += "\n"; }
  3457. msg.data += value;
  3458. } else if (field == "id") {
  3459. // Empty id is valid (clears the last event ID)
  3460. msg.id = value;
  3461. } else if (field == "retry") {
  3462. // Parse retry interval in milliseconds
  3463. {
  3464. int v = 0;
  3465. auto res =
  3466. detail::from_chars(value.data(), value.data() + value.size(), v);
  3467. if (res.ec == std::errc{}) { retry_ms = v; }
  3468. }
  3469. }
  3470. // Unknown fields are ignored per SSE spec
  3471. return false;
  3472. }
  3473. inline void SSEClient::run_event_loop() {
  3474. auto reconnect_count = 0;
  3475. while (running_.load()) {
  3476. // Build headers, including Last-Event-ID if we have one
  3477. Headers request_headers;
  3478. {
  3479. std::lock_guard<std::mutex> lock(headers_mutex_);
  3480. request_headers = headers_;
  3481. }
  3482. if (!last_event_id_.empty()) {
  3483. request_headers.emplace("Last-Event-ID", last_event_id_);
  3484. }
  3485. // Open streaming connection
  3486. auto result = stream::Get(client_, path_, request_headers);
  3487. // Connection error handling
  3488. if (!result) {
  3489. connected_.store(false);
  3490. if (on_error_) { on_error_(result.error()); }
  3491. if (!should_reconnect(reconnect_count)) { break; }
  3492. wait_for_reconnect();
  3493. reconnect_count++;
  3494. continue;
  3495. }
  3496. if (result.status() != StatusCode::OK_200) {
  3497. connected_.store(false);
  3498. if (on_error_) { on_error_(Error::Connection); }
  3499. // For certain errors, don't reconnect.
  3500. // Note: 401 is intentionally absent so that handlers can refresh
  3501. // credentials via set_headers() and let the client reconnect.
  3502. if (result.status() == StatusCode::NoContent_204 ||
  3503. result.status() == StatusCode::NotFound_404 ||
  3504. result.status() == StatusCode::Forbidden_403) {
  3505. break;
  3506. }
  3507. if (!should_reconnect(reconnect_count)) { break; }
  3508. wait_for_reconnect();
  3509. reconnect_count++;
  3510. continue;
  3511. }
  3512. // Connection successful
  3513. connected_.store(true);
  3514. reconnect_count = 0;
  3515. if (on_open_) { on_open_(); }
  3516. // Event receiving loop
  3517. std::string buffer;
  3518. SSEMessage current_msg;
  3519. while (running_.load() && result.next()) {
  3520. buffer.append(result.data(), result.size());
  3521. // Process complete lines in the buffer
  3522. size_t line_start = 0;
  3523. size_t newline_pos;
  3524. while ((newline_pos = buffer.find('\n', line_start)) !=
  3525. std::string::npos) {
  3526. auto line = buffer.substr(line_start, newline_pos - line_start);
  3527. line_start = newline_pos + 1;
  3528. // Parse the line and check if event is complete
  3529. auto event_complete =
  3530. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3531. if (event_complete && !current_msg.data.empty()) {
  3532. // Update last_event_id for reconnection
  3533. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3534. // Dispatch event to appropriate handler
  3535. dispatch_event(current_msg);
  3536. current_msg.clear();
  3537. }
  3538. }
  3539. // Keep unprocessed data in buffer
  3540. buffer.erase(0, line_start);
  3541. }
  3542. // Connection ended
  3543. connected_.store(false);
  3544. if (!running_.load()) { break; }
  3545. // Check for read errors
  3546. if (result.has_read_error()) {
  3547. if (on_error_) { on_error_(result.read_error()); }
  3548. }
  3549. if (!should_reconnect(reconnect_count)) { break; }
  3550. wait_for_reconnect();
  3551. reconnect_count++;
  3552. }
  3553. connected_.store(false);
  3554. }
  3555. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3556. // Check for specific event type handler first
  3557. auto it = event_handlers_.find(msg.event);
  3558. if (it != event_handlers_.end()) {
  3559. it->second(msg);
  3560. return;
  3561. }
  3562. // Fall back to generic message handler
  3563. if (on_message_) { on_message_(msg); }
  3564. }
  3565. inline bool SSEClient::should_reconnect(int count) const {
  3566. if (!running_.load()) { return false; }
  3567. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3568. return count < max_reconnect_attempts_;
  3569. }
  3570. inline void SSEClient::wait_for_reconnect() {
  3571. // Use small increments to check running_ flag frequently
  3572. auto waited = 0;
  3573. while (running_.load() && waited < reconnect_interval_ms_) {
  3574. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3575. waited += 100;
  3576. }
  3577. }
  3578. } // namespace sse
  3579. #ifdef CPPHTTPLIB_SSL_ENABLED
  3580. /*
  3581. * TLS abstraction layer - internal function declarations
  3582. * These are implementation details and not part of the public API.
  3583. */
  3584. namespace tls {
  3585. // Client context
  3586. ctx_t create_client_context();
  3587. void free_context(ctx_t ctx);
  3588. bool set_min_version(ctx_t ctx, Version version);
  3589. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3590. bool load_ca_file(ctx_t ctx, const char *file_path);
  3591. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3592. bool load_system_certs(ctx_t ctx);
  3593. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3594. const char *password);
  3595. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3596. const char *key_path, const char *password);
  3597. // Server context
  3598. ctx_t create_server_context();
  3599. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3600. const char *password);
  3601. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3602. const char *key_path, const char *password);
  3603. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3604. void set_verify_client(ctx_t ctx, bool require);
  3605. // Session management
  3606. session_t create_session(ctx_t ctx, socket_t sock);
  3607. void free_session(session_t session);
  3608. bool set_sni(session_t session, const char *hostname);
  3609. bool set_hostname(session_t session, const char *hostname);
  3610. // Handshake (non-blocking capable)
  3611. TlsError connect(session_t session);
  3612. TlsError accept(session_t session);
  3613. // Handshake with timeout (blocking until timeout)
  3614. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3615. time_t timeout_usec, TlsError *err);
  3616. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3617. time_t timeout_usec, TlsError *err);
  3618. // I/O (non-blocking capable)
  3619. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3620. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3621. int pending(const_session_t session);
  3622. void shutdown(session_t session, bool graceful);
  3623. // Connection state
  3624. bool is_peer_closed(session_t session, socket_t sock);
  3625. // Certificate verification
  3626. cert_t get_peer_cert(const_session_t session);
  3627. void free_cert(cert_t cert);
  3628. bool verify_hostname(cert_t cert, const char *hostname);
  3629. uint64_t hostname_mismatch_code();
  3630. long get_verify_result(const_session_t session);
  3631. // Certificate introspection
  3632. std::string get_cert_subject_cn(cert_t cert);
  3633. std::string get_cert_issuer_name(cert_t cert);
  3634. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3635. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3636. std::string get_cert_serial(cert_t cert);
  3637. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3638. const char *get_sni(const_session_t session);
  3639. // CA store management
  3640. ca_store_t create_ca_store(const char *pem, size_t len);
  3641. void free_ca_store(ca_store_t store);
  3642. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3643. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3644. std::vector<std::string> get_ca_names(ctx_t ctx);
  3645. // Dynamic certificate update (for servers)
  3646. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3647. const char *password);
  3648. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3649. // Certificate verification callback
  3650. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3651. long get_verify_error(const_session_t session);
  3652. std::string verify_error_string(long error_code);
  3653. // TlsError information
  3654. uint64_t peek_error();
  3655. uint64_t get_error();
  3656. std::string error_string(uint64_t code);
  3657. } // namespace tls
  3658. #endif // CPPHTTPLIB_SSL_ENABLED
  3659. /*
  3660. * Group 1: detail namespace - Non-SSL utilities
  3661. */
  3662. namespace detail {
  3663. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3664. const void *optval, socklen_t optlen) {
  3665. return setsockopt(sock, level, optname,
  3666. #ifdef _WIN32
  3667. reinterpret_cast<const char *>(optval),
  3668. #else
  3669. optval,
  3670. #endif
  3671. optlen) == 0;
  3672. }
  3673. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3674. time_t sec, time_t usec) {
  3675. #ifdef _WIN32
  3676. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3677. #else
  3678. timeval timeout;
  3679. timeout.tv_sec = static_cast<long>(sec);
  3680. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3681. #endif
  3682. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3683. }
  3684. inline bool is_hex(char c, int &v) {
  3685. if (is_ascii_digit(c)) {
  3686. v = c - '0';
  3687. return true;
  3688. } else if ('A' <= c && c <= 'F') {
  3689. v = c - 'A' + 10;
  3690. return true;
  3691. } else if ('a' <= c && c <= 'f') {
  3692. v = c - 'a' + 10;
  3693. return true;
  3694. }
  3695. return false;
  3696. }
  3697. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3698. int &val) {
  3699. if (i >= s.size()) { return false; }
  3700. val = 0;
  3701. for (; cnt; i++, cnt--) {
  3702. if (!s[i]) { return false; }
  3703. auto v = 0;
  3704. if (is_hex(s[i], v)) {
  3705. val = val * 16 + v;
  3706. } else {
  3707. return false;
  3708. }
  3709. }
  3710. return true;
  3711. }
  3712. inline std::string from_i_to_hex(size_t n) {
  3713. static const auto charset = "0123456789abcdef";
  3714. std::string ret;
  3715. do {
  3716. ret = charset[n & 15] + ret;
  3717. n >>= 4;
  3718. } while (n > 0);
  3719. return ret;
  3720. }
  3721. inline std::string compute_etag(const FileStat &fs) {
  3722. if (!fs.is_file()) { return std::string(); }
  3723. // If mtime cannot be determined (negative value indicates an error
  3724. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3725. // value like 0 could collide with a real file that legitimately has
  3726. // mtime == 0 (epoch) and lead to misleading validators.
  3727. auto mtime_raw = fs.mtime();
  3728. if (mtime_raw < 0) { return std::string(); }
  3729. auto mtime = static_cast<size_t>(mtime_raw);
  3730. auto size = fs.size();
  3731. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3732. from_i_to_hex(size) + "\"";
  3733. }
  3734. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3735. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3736. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3737. inline std::string file_mtime_to_http_date(time_t mtime) {
  3738. if (mtime < 0) { return std::string(); }
  3739. struct tm tm_buf;
  3740. #ifdef _WIN32
  3741. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3742. #else
  3743. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3744. #endif
  3745. char buf[64];
  3746. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3747. return std::string();
  3748. }
  3749. return std::string(buf);
  3750. }
  3751. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3752. inline time_t parse_http_date(const std::string &date_str) {
  3753. struct tm tm_buf;
  3754. // Create a classic locale object once for all parsing attempts
  3755. const std::locale classic_locale = std::locale::classic();
  3756. // Try to parse using std::get_time (C++11, cross-platform)
  3757. auto try_parse = [&](const char *fmt) -> bool {
  3758. std::istringstream ss(date_str);
  3759. ss.imbue(classic_locale);
  3760. memset(&tm_buf, 0, sizeof(tm_buf));
  3761. ss >> std::get_time(&tm_buf, fmt);
  3762. return !ss.fail();
  3763. };
  3764. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3765. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3766. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3767. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3768. // asctime format: "Sun Nov 6 08:49:37 1994"
  3769. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3770. return static_cast<time_t>(-1);
  3771. }
  3772. }
  3773. }
  3774. #ifdef _WIN32
  3775. return _mkgmtime(&tm_buf);
  3776. #elif defined _AIX
  3777. return mktime(&tm_buf);
  3778. #else
  3779. return timegm(&tm_buf);
  3780. #endif
  3781. }
  3782. inline bool is_weak_etag(const std::string &s) {
  3783. // Check if the string is a weak ETag (starts with 'W/"')
  3784. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3785. }
  3786. inline bool is_strong_etag(const std::string &s) {
  3787. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3788. // chars)
  3789. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3790. }
  3791. inline size_t to_utf8(int code, char *buff) {
  3792. if (code < 0x0080) {
  3793. buff[0] = static_cast<char>(code & 0x7F);
  3794. return 1;
  3795. } else if (code < 0x0800) {
  3796. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3797. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3798. return 2;
  3799. } else if (code < 0xD800) {
  3800. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3801. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3802. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3803. return 3;
  3804. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3805. return 0;
  3806. } else if (code < 0x10000) {
  3807. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3808. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3809. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3810. return 3;
  3811. } else if (code < 0x110000) {
  3812. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3813. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3814. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3815. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3816. return 4;
  3817. }
  3818. // NOTREACHED
  3819. return 0;
  3820. }
  3821. } // namespace detail
  3822. namespace ws {
  3823. namespace impl {
  3824. inline bool is_valid_utf8(const std::string &s) {
  3825. size_t i = 0;
  3826. auto n = s.size();
  3827. while (i < n) {
  3828. auto c = static_cast<unsigned char>(s[i]);
  3829. size_t len;
  3830. uint32_t cp;
  3831. if (c < 0x80) {
  3832. i++;
  3833. continue;
  3834. } else if ((c & 0xE0) == 0xC0) {
  3835. len = 2;
  3836. cp = c & 0x1F;
  3837. } else if ((c & 0xF0) == 0xE0) {
  3838. len = 3;
  3839. cp = c & 0x0F;
  3840. } else if ((c & 0xF8) == 0xF0) {
  3841. len = 4;
  3842. cp = c & 0x07;
  3843. } else {
  3844. return false;
  3845. }
  3846. if (i + len > n) { return false; }
  3847. for (size_t j = 1; j < len; j++) {
  3848. auto b = static_cast<unsigned char>(s[i + j]);
  3849. if ((b & 0xC0) != 0x80) { return false; }
  3850. cp = (cp << 6) | (b & 0x3F);
  3851. }
  3852. // Overlong encoding check
  3853. if (len == 2 && cp < 0x80) { return false; }
  3854. if (len == 3 && cp < 0x800) { return false; }
  3855. if (len == 4 && cp < 0x10000) { return false; }
  3856. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3857. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3858. if (cp > 0x10FFFF) { return false; }
  3859. i += len;
  3860. }
  3861. return true;
  3862. }
  3863. } // namespace impl
  3864. } // namespace ws
  3865. namespace detail {
  3866. // NOTE: This code came up with the following stackoverflow post:
  3867. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3868. inline std::string base64_encode(const std::string &in) {
  3869. static const auto lookup =
  3870. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3871. std::string out;
  3872. out.reserve(in.size());
  3873. // Unsigned: the accumulator is never masked, so with a signed int the
  3874. // `val << 8` below overflows once enough bytes are folded in (undefined
  3875. // behaviour before C++20). Only the low bits are ever emitted, so the
  3876. // wrap-around of an unsigned accumulator does not affect the output.
  3877. uint32_t val = 0;
  3878. auto valb = -6;
  3879. for (auto c : in) {
  3880. val = (val << 8) + static_cast<uint8_t>(c);
  3881. valb += 8;
  3882. while (valb >= 0) {
  3883. out.push_back(lookup[(val >> valb) & 0x3F]);
  3884. valb -= 6;
  3885. }
  3886. }
  3887. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3888. while (out.size() % 4) {
  3889. out.push_back('=');
  3890. }
  3891. return out;
  3892. }
  3893. inline std::string sha1(const std::string &input) {
  3894. // RFC 3174 SHA-1 implementation
  3895. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3896. return (x << n) | (x >> (32 - n));
  3897. };
  3898. uint32_t h0 = 0x67452301;
  3899. uint32_t h1 = 0xEFCDAB89;
  3900. uint32_t h2 = 0x98BADCFE;
  3901. uint32_t h3 = 0x10325476;
  3902. uint32_t h4 = 0xC3D2E1F0;
  3903. // Pre-processing: adding padding bits
  3904. std::string msg = input;
  3905. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3906. msg.push_back(static_cast<char>(0x80u));
  3907. while (msg.size() % 64 != 56) {
  3908. msg.push_back(0);
  3909. }
  3910. // Append original length in bits as 64-bit big-endian
  3911. for (int i = 56; i >= 0; i -= 8) {
  3912. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3913. }
  3914. // Process each 512-bit chunk
  3915. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3916. uint32_t w[80];
  3917. for (size_t i = 0; i < 16; i++) {
  3918. w[i] =
  3919. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3920. << 24) |
  3921. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3922. << 16) |
  3923. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3924. << 8) |
  3925. (static_cast<uint32_t>(
  3926. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3927. }
  3928. for (int i = 16; i < 80; i++) {
  3929. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3930. }
  3931. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3932. for (int i = 0; i < 80; i++) {
  3933. uint32_t f, k;
  3934. if (i < 20) {
  3935. f = (b & c) | ((~b) & d);
  3936. k = 0x5A827999;
  3937. } else if (i < 40) {
  3938. f = b ^ c ^ d;
  3939. k = 0x6ED9EBA1;
  3940. } else if (i < 60) {
  3941. f = (b & c) | (b & d) | (c & d);
  3942. k = 0x8F1BBCDC;
  3943. } else {
  3944. f = b ^ c ^ d;
  3945. k = 0xCA62C1D6;
  3946. }
  3947. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3948. e = d;
  3949. d = c;
  3950. c = left_rotate(b, 30);
  3951. b = a;
  3952. a = temp;
  3953. }
  3954. h0 += a;
  3955. h1 += b;
  3956. h2 += c;
  3957. h3 += d;
  3958. h4 += e;
  3959. }
  3960. // Produce the final hash as a 20-byte binary string
  3961. std::string hash(20, '\0');
  3962. for (size_t i = 0; i < 4; i++) {
  3963. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3964. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3965. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3966. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3967. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3968. }
  3969. return hash;
  3970. }
  3971. inline std::string websocket_accept_key(const std::string &client_key) {
  3972. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3973. return base64_encode(sha1(client_key + magic));
  3974. }
  3975. inline bool is_websocket_upgrade(const Request &req) {
  3976. if (req.method != "GET") { return false; }
  3977. // Check Upgrade: websocket (case-insensitive)
  3978. auto upgrade_it = req.headers.find("Upgrade");
  3979. if (upgrade_it == req.headers.end()) { return false; }
  3980. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3981. if (upgrade_val != "websocket") { return false; }
  3982. // Check Connection header contains "Upgrade"
  3983. auto connection_it = req.headers.find("Connection");
  3984. if (connection_it == req.headers.end()) { return false; }
  3985. auto connection_val = case_ignore::to_lower(connection_it->second);
  3986. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3987. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3988. // RFC 6455 Section 4.2.1
  3989. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3990. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3991. return false;
  3992. }
  3993. static const std::string b64chars =
  3994. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3995. for (size_t i = 0; i < 22; i++) {
  3996. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3997. }
  3998. // Check Sec-WebSocket-Version: 13
  3999. auto version = req.get_header_value("Sec-WebSocket-Version");
  4000. if (version != "13") { return false; }
  4001. return true;
  4002. }
  4003. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  4004. const char *data, size_t len, bool fin,
  4005. bool mask) {
  4006. // First byte: FIN + opcode
  4007. uint8_t header[2];
  4008. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  4009. (static_cast<uint8_t>(opcode) & 0x0F));
  4010. // Second byte: MASK + payload length
  4011. if (len < 126) {
  4012. header[1] = static_cast<uint8_t>(len);
  4013. if (mask) { header[1] |= 0x80; }
  4014. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4015. } else if (len <= 0xFFFF) {
  4016. header[1] = 126;
  4017. if (mask) { header[1] |= 0x80; }
  4018. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4019. uint8_t ext[2];
  4020. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4021. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4022. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4023. } else {
  4024. header[1] = 127;
  4025. if (mask) { header[1] |= 0x80; }
  4026. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4027. uint8_t ext[8];
  4028. for (int i = 7; i >= 0; i--) {
  4029. ext[7 - i] =
  4030. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4031. }
  4032. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4033. }
  4034. if (mask) {
  4035. // Generate random mask key
  4036. thread_local std::mt19937 rng(std::random_device{}());
  4037. uint8_t mask_key[4];
  4038. auto r = rng();
  4039. std::memcpy(mask_key, &r, 4);
  4040. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4041. // Write masked payload in chunks
  4042. const size_t chunk_size = 4096;
  4043. std::vector<char> buf((std::min)(len, chunk_size));
  4044. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4045. size_t n = (std::min)(chunk_size, len - offset);
  4046. for (size_t i = 0; i < n; i++) {
  4047. buf[i] =
  4048. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4049. }
  4050. if (strm.write(buf.data(), n) < 0) { return false; }
  4051. }
  4052. } else {
  4053. if (len > 0) {
  4054. if (strm.write(data, len) < 0) { return false; }
  4055. }
  4056. }
  4057. return true;
  4058. }
  4059. } // namespace detail
  4060. namespace ws {
  4061. namespace impl {
  4062. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4063. std::string &payload, bool &fin,
  4064. bool expect_masked, size_t max_len) {
  4065. // Read first 2 bytes
  4066. uint8_t header[2];
  4067. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4068. fin = (header[0] & 0x80) != 0;
  4069. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4070. if (header[0] & 0x70) { return false; }
  4071. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4072. bool masked = (header[1] & 0x80) != 0;
  4073. uint64_t payload_len = header[1] & 0x7F;
  4074. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4075. // MUST have a payload length of 125 bytes or less
  4076. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4077. if (is_control) {
  4078. if (!fin) { return false; }
  4079. if (payload_len > 125) { return false; }
  4080. }
  4081. if (masked != expect_masked) { return false; }
  4082. // Extended payload length
  4083. if (payload_len == 126) {
  4084. uint8_t ext[2];
  4085. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4086. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4087. } else if (payload_len == 127) {
  4088. uint8_t ext[8];
  4089. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4090. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4091. if (ext[0] & 0x80) { return false; }
  4092. payload_len = 0;
  4093. for (int i = 0; i < 8; i++) {
  4094. payload_len = (payload_len << 8) | ext[i];
  4095. }
  4096. }
  4097. if (payload_len > max_len) { return false; }
  4098. // Read mask key if present
  4099. uint8_t mask_key[4] = {0};
  4100. if (masked) {
  4101. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4102. }
  4103. // Read payload
  4104. payload.resize(static_cast<size_t>(payload_len));
  4105. if (payload_len > 0) {
  4106. size_t total_read = 0;
  4107. while (total_read < payload_len) {
  4108. auto n = strm.read(&payload[total_read],
  4109. static_cast<size_t>(payload_len - total_read));
  4110. if (n <= 0) { return false; }
  4111. total_read += static_cast<size_t>(n);
  4112. }
  4113. }
  4114. // Unmask if needed
  4115. if (masked) {
  4116. for (size_t i = 0; i < payload.size(); i++) {
  4117. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4118. }
  4119. }
  4120. return true;
  4121. }
  4122. } // namespace impl
  4123. } // namespace ws
  4124. namespace detail {
  4125. inline bool is_valid_path(const std::string &path) {
  4126. size_t level = 0;
  4127. size_t i = 0;
  4128. // Skip slash
  4129. while (i < path.size() && path[i] == '/') {
  4130. i++;
  4131. }
  4132. while (i < path.size()) {
  4133. // Read component
  4134. auto beg = i;
  4135. while (i < path.size() && path[i] != '/') {
  4136. if (path[i] == '\0') {
  4137. return false;
  4138. } else if (path[i] == '\\') {
  4139. return false;
  4140. }
  4141. i++;
  4142. }
  4143. auto len = i - beg;
  4144. assert(len > 0);
  4145. if (!path.compare(beg, len, ".")) {
  4146. ;
  4147. } else if (!path.compare(beg, len, "..")) {
  4148. if (level == 0) { return false; }
  4149. level--;
  4150. } else {
  4151. level++;
  4152. }
  4153. // Skip slash
  4154. while (i < path.size() && path[i] == '/') {
  4155. i++;
  4156. }
  4157. }
  4158. return true;
  4159. }
  4160. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4161. #if defined(_WIN32)
  4162. char buf[_MAX_PATH];
  4163. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4164. resolved = buf;
  4165. #elif defined(PATH_MAX)
  4166. char buf[PATH_MAX];
  4167. if (realpath(path, buf) == nullptr) { return false; }
  4168. resolved = buf;
  4169. #else
  4170. auto buf = realpath(path, nullptr);
  4171. auto guard = scope_exit([&]() { std::free(buf); });
  4172. if (buf == nullptr) { return false; }
  4173. resolved = buf;
  4174. #endif
  4175. return true;
  4176. }
  4177. inline bool is_path_within_base(const std::string &resolved_path,
  4178. const std::string &resolved_base) {
  4179. #if defined(_WIN32)
  4180. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4181. resolved_base.size()) == 0;
  4182. #else
  4183. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4184. resolved_base.size()) == 0;
  4185. #endif
  4186. }
  4187. inline FileStat::FileStat(const std::string &path) {
  4188. #if defined(_WIN32)
  4189. auto wpath = u8string_to_wstring(path.c_str());
  4190. ret_ = _wstat(wpath.c_str(), &st_);
  4191. #else
  4192. ret_ = stat(path.c_str(), &st_);
  4193. #endif
  4194. }
  4195. inline bool FileStat::is_file() const {
  4196. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4197. }
  4198. inline bool FileStat::is_dir() const {
  4199. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4200. }
  4201. inline time_t FileStat::mtime() const {
  4202. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4203. : static_cast<time_t>(-1);
  4204. }
  4205. inline size_t FileStat::size() const {
  4206. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4207. }
  4208. inline std::string encode_path(const std::string &s) {
  4209. std::string result;
  4210. result.reserve(s.size());
  4211. for (size_t i = 0; s[i]; i++) {
  4212. switch (s[i]) {
  4213. case ' ': result += "%20"; break;
  4214. case '+': result += "%2B"; break;
  4215. case '\r': result += "%0D"; break;
  4216. case '\n': result += "%0A"; break;
  4217. case '\'': result += "%27"; break;
  4218. case ',': result += "%2C"; break;
  4219. // case ':': result += "%3A"; break; // ok? probably...
  4220. case ';': result += "%3B"; break;
  4221. default:
  4222. auto c = static_cast<uint8_t>(s[i]);
  4223. if (c >= 0x80) {
  4224. result += '%';
  4225. char hex[4];
  4226. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4227. assert(len == 2);
  4228. result.append(hex, static_cast<size_t>(len));
  4229. } else {
  4230. result += s[i];
  4231. }
  4232. break;
  4233. }
  4234. }
  4235. return result;
  4236. }
  4237. inline std::string file_extension(const std::string &path) {
  4238. std::smatch m;
  4239. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4240. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4241. return std::string();
  4242. }
  4243. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4244. template <typename T>
  4245. inline bool parse_header(const char *beg, const char *end, T fn);
  4246. template <typename T>
  4247. inline bool parse_header(const char *beg, const char *end, T fn) {
  4248. // Skip trailing spaces and tabs.
  4249. while (beg < end && is_space_or_tab(end[-1])) {
  4250. end--;
  4251. }
  4252. auto p = beg;
  4253. while (p < end && *p != ':') {
  4254. p++;
  4255. }
  4256. auto name = std::string(beg, p);
  4257. if (!detail::fields::is_field_name(name)) { return false; }
  4258. if (p == end) { return false; }
  4259. auto key_end = p;
  4260. if (*p++ != ':') { return false; }
  4261. while (p < end && is_space_or_tab(*p)) {
  4262. p++;
  4263. }
  4264. if (p <= end) {
  4265. auto key_len = key_end - beg;
  4266. if (!key_len) { return false; }
  4267. auto key = std::string(beg, key_end);
  4268. auto val = std::string(p, end);
  4269. if (!detail::fields::is_field_value(val)) { return false; }
  4270. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4271. // percent-decoded by the recipient. Applications that need to interpret a
  4272. // value as a URI component should call httplib::decode_uri_component()
  4273. // (or decode_path_component()) explicitly.
  4274. fn(key, val);
  4275. return true;
  4276. }
  4277. return false;
  4278. }
  4279. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4280. const Headers &src_headers) {
  4281. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4282. // transfer coding is complete when a chunk with a chunk-size of zero is
  4283. // received, possibly followed by a trailer section, and finally terminated by
  4284. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4285. //
  4286. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4287. // doesn't care for the existence of the final CRLF. In other words, it seems
  4288. // to be ok whether the final CRLF exists or not in the chunked data.
  4289. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4290. //
  4291. // According to the reference code in RFC 9112, cpp-httplib now allows
  4292. // chunked transfer coding data without the final CRLF.
  4293. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4294. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4295. "transfer-encoding",
  4296. "content-length",
  4297. "host",
  4298. "authorization",
  4299. "www-authenticate",
  4300. "proxy-authenticate",
  4301. "proxy-authorization",
  4302. "cookie",
  4303. "set-cookie",
  4304. "cache-control",
  4305. "expect",
  4306. "max-forwards",
  4307. "pragma",
  4308. "range",
  4309. "te",
  4310. "age",
  4311. "expires",
  4312. "date",
  4313. "location",
  4314. "retry-after",
  4315. "vary",
  4316. "warning",
  4317. "content-encoding",
  4318. "content-type",
  4319. "content-range",
  4320. "trailer"};
  4321. case_ignore::unordered_set<std::string> declared_trailers;
  4322. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4323. if (trailer_header && std::strlen(trailer_header)) {
  4324. auto len = std::strlen(trailer_header);
  4325. split(trailer_header, trailer_header + len, ',',
  4326. [&](const char *b, const char *e) {
  4327. const char *kbeg = b;
  4328. const char *kend = e;
  4329. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4330. ++kbeg;
  4331. }
  4332. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4333. --kend;
  4334. }
  4335. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4336. if (!key.empty() &&
  4337. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4338. declared_trailers.insert(key);
  4339. }
  4340. });
  4341. }
  4342. size_t trailer_header_count = 0;
  4343. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4344. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4345. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4346. constexpr auto line_terminator_len = 2;
  4347. auto line_beg = line_reader.ptr();
  4348. auto line_end =
  4349. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4350. if (!parse_header(line_beg, line_end,
  4351. [&](const std::string &key, const std::string &val) {
  4352. if (declared_trailers.find(key) !=
  4353. declared_trailers.end()) {
  4354. dest.emplace(key, val);
  4355. trailer_header_count++;
  4356. }
  4357. })) {
  4358. return false;
  4359. }
  4360. if (!line_reader.getline()) { return false; }
  4361. }
  4362. return true;
  4363. }
  4364. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4365. size_t right) {
  4366. while (b + left < e && is_space_or_tab(b[left])) {
  4367. left++;
  4368. }
  4369. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4370. right--;
  4371. }
  4372. return std::make_pair(left, right);
  4373. }
  4374. inline std::string trim_copy(const std::string &s) {
  4375. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4376. return s.substr(r.first, r.second - r.first);
  4377. }
  4378. inline std::string trim_double_quotes_copy(const std::string &s) {
  4379. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4380. return s.substr(1, s.size() - 2);
  4381. }
  4382. return s;
  4383. }
  4384. inline void
  4385. divide(const char *data, std::size_t size, char d,
  4386. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4387. fn) {
  4388. const auto it = std::find(data, data + size, d);
  4389. const auto found = static_cast<std::size_t>(it != data + size);
  4390. const auto lhs_data = data;
  4391. const auto lhs_size = static_cast<std::size_t>(it - data);
  4392. const auto rhs_data = it + found;
  4393. const auto rhs_size = size - lhs_size - found;
  4394. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4395. }
  4396. inline void
  4397. divide(const std::string &str, char d,
  4398. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4399. fn) {
  4400. divide(str.data(), str.size(), d, std::move(fn));
  4401. }
  4402. inline void split(const char *b, const char *e, char d,
  4403. std::function<void(const char *, const char *)> fn) {
  4404. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4405. }
  4406. inline void split(const char *b, const char *e, char d, size_t m,
  4407. std::function<void(const char *, const char *)> fn) {
  4408. size_t i = 0;
  4409. size_t beg = 0;
  4410. size_t count = 1;
  4411. while (e ? (b + i < e) : (b[i] != '\0')) {
  4412. if (b[i] == d && count < m) {
  4413. auto r = trim(b, e, beg, i);
  4414. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4415. beg = i + 1;
  4416. count++;
  4417. }
  4418. i++;
  4419. }
  4420. if (i) {
  4421. auto r = trim(b, e, beg, i);
  4422. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4423. }
  4424. }
  4425. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4426. std::function<bool(const char *, const char *)> fn) {
  4427. size_t i = 0;
  4428. size_t beg = 0;
  4429. size_t count = 1;
  4430. while (e ? (b + i < e) : (b[i] != '\0')) {
  4431. if (b[i] == d && count < m) {
  4432. auto r = trim(b, e, beg, i);
  4433. if (r.first < r.second) {
  4434. auto found = fn(&b[r.first], &b[r.second]);
  4435. if (found) { return true; }
  4436. }
  4437. beg = i + 1;
  4438. count++;
  4439. }
  4440. i++;
  4441. }
  4442. if (i) {
  4443. auto r = trim(b, e, beg, i);
  4444. if (r.first < r.second) {
  4445. auto found = fn(&b[r.first], &b[r.second]);
  4446. if (found) { return true; }
  4447. }
  4448. }
  4449. return false;
  4450. }
  4451. inline bool split_find(const char *b, const char *e, char d,
  4452. std::function<bool(const char *, const char *)> fn) {
  4453. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4454. std::move(fn));
  4455. }
  4456. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4457. size_t fixed_buffer_size)
  4458. : strm_(strm), fixed_buffer_(fixed_buffer),
  4459. fixed_buffer_size_(fixed_buffer_size) {}
  4460. inline const char *stream_line_reader::ptr() const {
  4461. if (growable_buffer_.empty()) {
  4462. return fixed_buffer_;
  4463. } else {
  4464. return growable_buffer_.data();
  4465. }
  4466. }
  4467. inline size_t stream_line_reader::size() const {
  4468. if (growable_buffer_.empty()) {
  4469. return fixed_buffer_used_size_;
  4470. } else {
  4471. return growable_buffer_.size();
  4472. }
  4473. }
  4474. inline bool stream_line_reader::end_with_crlf() const {
  4475. auto end = ptr() + size();
  4476. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4477. }
  4478. inline bool stream_line_reader::getline() {
  4479. fixed_buffer_used_size_ = 0;
  4480. growable_buffer_.clear();
  4481. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4482. char prev_byte = 0;
  4483. #endif
  4484. for (size_t i = 0;; i++) {
  4485. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4486. // Treat exceptionally long lines as an error to
  4487. // prevent infinite loops/memory exhaustion
  4488. return false;
  4489. }
  4490. char byte;
  4491. auto n = strm_.read(&byte, 1);
  4492. if (n < 0) {
  4493. return false;
  4494. } else if (n == 0) {
  4495. if (i == 0) {
  4496. return false;
  4497. } else {
  4498. break;
  4499. }
  4500. }
  4501. append(byte);
  4502. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4503. if (byte == '\n') { break; }
  4504. #else
  4505. if (prev_byte == '\r' && byte == '\n') { break; }
  4506. prev_byte = byte;
  4507. #endif
  4508. }
  4509. return true;
  4510. }
  4511. inline void stream_line_reader::append(char c) {
  4512. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4513. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4514. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4515. } else {
  4516. if (growable_buffer_.empty()) {
  4517. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4518. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4519. }
  4520. growable_buffer_ += c;
  4521. }
  4522. }
  4523. inline mmap::mmap(const char *path) { open(path); }
  4524. inline mmap::~mmap() { close(); }
  4525. inline bool mmap::open(const char *path) {
  4526. close();
  4527. #if defined(_WIN32)
  4528. auto wpath = u8string_to_wstring(path);
  4529. if (wpath.empty()) { return false; }
  4530. hFile_ =
  4531. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4532. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4533. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4534. LARGE_INTEGER size{};
  4535. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4536. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4537. // See:
  4538. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4539. if (static_cast<ULONGLONG>(size.QuadPart) >
  4540. (std::numeric_limits<decltype(size_)>::max)()) {
  4541. // `size_t` might be 32-bits, on 32-bits Windows.
  4542. return false;
  4543. }
  4544. size_ = static_cast<size_t>(size.QuadPart);
  4545. hMapping_ =
  4546. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4547. // Special treatment for an empty file...
  4548. if (hMapping_ == NULL && size_ == 0) {
  4549. close();
  4550. is_open_empty_file = true;
  4551. return true;
  4552. }
  4553. if (hMapping_ == NULL) {
  4554. close();
  4555. return false;
  4556. }
  4557. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4558. if (addr_ == nullptr) {
  4559. close();
  4560. return false;
  4561. }
  4562. #else
  4563. fd_ = ::open(path, O_RDONLY);
  4564. if (fd_ == -1) { return false; }
  4565. struct stat sb;
  4566. if (fstat(fd_, &sb) == -1) {
  4567. close();
  4568. return false;
  4569. }
  4570. size_ = static_cast<size_t>(sb.st_size);
  4571. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4572. // Special treatment for an empty file...
  4573. if (addr_ == MAP_FAILED && size_ == 0) {
  4574. close();
  4575. is_open_empty_file = true;
  4576. return false;
  4577. }
  4578. #endif
  4579. return true;
  4580. }
  4581. inline bool mmap::is_open() const {
  4582. return is_open_empty_file ? true : addr_ != nullptr;
  4583. }
  4584. inline size_t mmap::size() const { return size_; }
  4585. inline const char *mmap::data() const {
  4586. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4587. }
  4588. inline void mmap::close() {
  4589. #if defined(_WIN32)
  4590. if (addr_) {
  4591. ::UnmapViewOfFile(addr_);
  4592. addr_ = nullptr;
  4593. }
  4594. if (hMapping_) {
  4595. ::CloseHandle(hMapping_);
  4596. hMapping_ = NULL;
  4597. }
  4598. if (hFile_ != INVALID_HANDLE_VALUE) {
  4599. ::CloseHandle(hFile_);
  4600. hFile_ = INVALID_HANDLE_VALUE;
  4601. }
  4602. is_open_empty_file = false;
  4603. #else
  4604. if (addr_ != nullptr) {
  4605. munmap(addr_, size_);
  4606. addr_ = nullptr;
  4607. }
  4608. if (fd_ != -1) {
  4609. ::close(fd_);
  4610. fd_ = -1;
  4611. }
  4612. #endif
  4613. size_ = 0;
  4614. }
  4615. inline int close_socket(socket_t sock) noexcept {
  4616. #ifdef _WIN32
  4617. return closesocket(sock);
  4618. #else
  4619. return close(sock);
  4620. #endif
  4621. }
  4622. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4623. ssize_t res = 0;
  4624. while (true) {
  4625. res = fn();
  4626. if (res < 0 && errno == EINTR) {
  4627. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4628. continue;
  4629. }
  4630. break;
  4631. }
  4632. return res;
  4633. }
  4634. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4635. return handle_EINTR([&]() {
  4636. return recv(sock,
  4637. #ifdef _WIN32
  4638. static_cast<char *>(ptr), static_cast<int>(size),
  4639. #else
  4640. ptr, size,
  4641. #endif
  4642. flags);
  4643. });
  4644. }
  4645. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4646. int flags) {
  4647. return handle_EINTR([&]() {
  4648. return send(sock,
  4649. #ifdef _WIN32
  4650. static_cast<const char *>(ptr), static_cast<int>(size),
  4651. #else
  4652. ptr, size,
  4653. #endif
  4654. flags);
  4655. });
  4656. }
  4657. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4658. #ifdef _WIN32
  4659. return ::WSAPoll(fds, nfds, timeout);
  4660. #else
  4661. return ::poll(fds, nfds, timeout);
  4662. #endif
  4663. }
  4664. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4665. time_t usec) {
  4666. struct pollfd pfd;
  4667. pfd.fd = sock;
  4668. pfd.events = events;
  4669. pfd.revents = 0;
  4670. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4671. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4672. }
  4673. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4674. return select_impl(sock, POLLIN, sec, usec);
  4675. }
  4676. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4677. return select_impl(sock, POLLOUT, sec, usec);
  4678. }
  4679. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4680. time_t usec) {
  4681. struct pollfd pfd_read;
  4682. pfd_read.fd = sock;
  4683. pfd_read.events = POLLIN | POLLOUT;
  4684. pfd_read.revents = 0;
  4685. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4686. auto poll_res =
  4687. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4688. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4689. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4690. auto error = 0;
  4691. socklen_t len = sizeof(error);
  4692. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4693. reinterpret_cast<char *>(&error), &len);
  4694. auto successful = res >= 0 && !error;
  4695. return successful ? Error::Success : Error::Connection;
  4696. }
  4697. return Error::Connection;
  4698. }
  4699. inline bool is_socket_alive(socket_t sock) {
  4700. const auto val = detail::select_read(sock, 0, 0);
  4701. if (val == 0) {
  4702. return true;
  4703. } else if (val < 0 && errno == EBADF) {
  4704. return false;
  4705. }
  4706. char buf[1];
  4707. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4708. }
  4709. class SocketStream final : public Stream {
  4710. public:
  4711. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4712. time_t write_timeout_sec, time_t write_timeout_usec,
  4713. time_t max_timeout_msec = 0,
  4714. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4715. (std::chrono::steady_clock::time_point::min)());
  4716. ~SocketStream() override;
  4717. bool is_readable() const override;
  4718. bool wait_readable() const override;
  4719. bool wait_writable() const override;
  4720. bool is_peer_alive() const override;
  4721. ssize_t read(char *ptr, size_t size) override;
  4722. ssize_t write(const char *ptr, size_t size) override;
  4723. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4724. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4725. socket_t socket() const override;
  4726. time_t duration() const override;
  4727. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4728. private:
  4729. socket_t sock_;
  4730. time_t read_timeout_sec_;
  4731. time_t read_timeout_usec_;
  4732. time_t write_timeout_sec_;
  4733. time_t write_timeout_usec_;
  4734. time_t max_timeout_msec_;
  4735. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4736. std::vector<char> read_buff_;
  4737. size_t read_buff_off_ = 0;
  4738. size_t read_buff_content_size_ = 0;
  4739. static const size_t read_buff_size_ = 1024l * 4;
  4740. };
  4741. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4742. time_t keep_alive_timeout_sec) {
  4743. using namespace std::chrono;
  4744. const auto interval_usec =
  4745. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4746. // Avoid expensive `steady_clock::now()` call for the first time
  4747. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4748. const auto start = steady_clock::now() - microseconds{interval_usec};
  4749. const auto timeout = seconds{keep_alive_timeout_sec};
  4750. while (true) {
  4751. if (svr_sock == INVALID_SOCKET) {
  4752. break; // Server socket is closed
  4753. }
  4754. auto val = select_read(sock, 0, interval_usec);
  4755. if (val < 0) {
  4756. break; // Ssocket error
  4757. } else if (val == 0) {
  4758. if (steady_clock::now() - start > timeout) {
  4759. break; // Timeout
  4760. }
  4761. } else {
  4762. return true; // Ready for read
  4763. }
  4764. }
  4765. return false;
  4766. }
  4767. template <typename T>
  4768. inline bool
  4769. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4770. size_t keep_alive_max_count,
  4771. time_t keep_alive_timeout_sec, T callback) {
  4772. assert(keep_alive_max_count > 0);
  4773. auto ret = false;
  4774. auto count = keep_alive_max_count;
  4775. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4776. auto close_connection = count == 1;
  4777. auto connection_closed = false;
  4778. ret = callback(close_connection, connection_closed);
  4779. if (!ret || connection_closed) { break; }
  4780. count--;
  4781. }
  4782. return ret;
  4783. }
  4784. template <typename T>
  4785. inline bool
  4786. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4787. size_t keep_alive_max_count,
  4788. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4789. time_t read_timeout_usec, time_t write_timeout_sec,
  4790. time_t write_timeout_usec, T callback) {
  4791. return process_server_socket_core(
  4792. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4793. [&](bool close_connection, bool &connection_closed) {
  4794. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4795. write_timeout_sec, write_timeout_usec);
  4796. return callback(strm, close_connection, connection_closed);
  4797. });
  4798. }
  4799. inline bool process_client_socket(
  4800. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4801. time_t write_timeout_sec, time_t write_timeout_usec,
  4802. time_t max_timeout_msec,
  4803. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4804. std::function<bool(Stream &)> callback) {
  4805. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4806. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4807. start_time);
  4808. return callback(strm);
  4809. }
  4810. inline int shutdown_socket(socket_t sock) noexcept {
  4811. #ifdef _WIN32
  4812. return shutdown(sock, SD_BOTH);
  4813. #else
  4814. return shutdown(sock, SHUT_RDWR);
  4815. #endif
  4816. }
  4817. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4818. if (s.size() > 1 && s[0] == '\0') {
  4819. auto ret = s;
  4820. ret[0] = '@';
  4821. return ret;
  4822. }
  4823. return s;
  4824. }
  4825. inline std::string
  4826. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4827. if (s.size() > 1 && s[0] == '@') {
  4828. auto ret = s;
  4829. ret[0] = '\0';
  4830. return ret;
  4831. }
  4832. return s;
  4833. }
  4834. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4835. const struct addrinfo *hints,
  4836. struct addrinfo **res, time_t timeout_sec) {
  4837. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4838. if (timeout_sec <= 0) {
  4839. // No timeout specified, use standard getaddrinfo
  4840. return getaddrinfo(node, service, hints, res);
  4841. }
  4842. #ifdef _WIN32
  4843. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4844. OVERLAPPED overlapped = {};
  4845. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4846. if (!event) { return EAI_FAIL; }
  4847. overlapped.hEvent = event;
  4848. PADDRINFOEXW result_addrinfo = nullptr;
  4849. HANDLE cancel_handle = nullptr;
  4850. ADDRINFOEXW hints_ex = {};
  4851. if (hints) {
  4852. hints_ex.ai_flags = hints->ai_flags;
  4853. hints_ex.ai_family = hints->ai_family;
  4854. hints_ex.ai_socktype = hints->ai_socktype;
  4855. hints_ex.ai_protocol = hints->ai_protocol;
  4856. }
  4857. auto wnode = u8string_to_wstring(node);
  4858. auto wservice = u8string_to_wstring(service);
  4859. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4860. hints ? &hints_ex : nullptr, &result_addrinfo,
  4861. nullptr, &overlapped, nullptr, &cancel_handle);
  4862. if (ret == WSA_IO_PENDING) {
  4863. auto wait_result =
  4864. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4865. if (wait_result == WAIT_TIMEOUT) {
  4866. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4867. ::CloseHandle(event);
  4868. return EAI_AGAIN;
  4869. }
  4870. DWORD bytes_returned;
  4871. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4872. &bytes_returned, FALSE)) {
  4873. ::CloseHandle(event);
  4874. return ::WSAGetLastError();
  4875. }
  4876. }
  4877. ::CloseHandle(event);
  4878. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4879. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4880. return 0;
  4881. }
  4882. return ret;
  4883. #elif TARGET_OS_MAC && defined(__clang__)
  4884. if (!node) { return EAI_NONAME; }
  4885. // macOS implementation using CFHost API for asynchronous DNS resolution
  4886. CFStringRef hostname_ref = CFStringCreateWithCString(
  4887. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4888. if (!hostname_ref) { return EAI_MEMORY; }
  4889. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4890. CFRelease(hostname_ref);
  4891. if (!host_ref) { return EAI_MEMORY; }
  4892. // Set up context for callback
  4893. struct CFHostContext {
  4894. bool completed = false;
  4895. bool success = false;
  4896. CFArrayRef addresses = nullptr;
  4897. std::mutex mutex;
  4898. std::condition_variable cv;
  4899. } context;
  4900. CFHostClientContext client_context;
  4901. memset(&client_context, 0, sizeof(client_context));
  4902. client_context.info = &context;
  4903. // Set callback
  4904. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4905. const CFStreamError *error, void *info) {
  4906. auto ctx = static_cast<CFHostContext *>(info);
  4907. std::lock_guard<std::mutex> lock(ctx->mutex);
  4908. if (error && error->error != 0) {
  4909. ctx->success = false;
  4910. } else {
  4911. Boolean hasBeenResolved;
  4912. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4913. if (ctx->addresses && hasBeenResolved) {
  4914. CFRetain(ctx->addresses);
  4915. ctx->success = true;
  4916. } else {
  4917. ctx->success = false;
  4918. }
  4919. }
  4920. ctx->completed = true;
  4921. ctx->cv.notify_one();
  4922. };
  4923. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4924. CFRelease(host_ref);
  4925. return EAI_SYSTEM;
  4926. }
  4927. // Schedule on run loop
  4928. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4929. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4930. // Start resolution
  4931. CFStreamError stream_error;
  4932. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4933. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4934. CFRelease(host_ref);
  4935. return EAI_FAIL;
  4936. }
  4937. // Wait for completion with timeout
  4938. auto timeout_time =
  4939. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4940. bool timed_out = false;
  4941. {
  4942. std::unique_lock<std::mutex> lock(context.mutex);
  4943. while (!context.completed) {
  4944. auto now = std::chrono::steady_clock::now();
  4945. if (now >= timeout_time) {
  4946. timed_out = true;
  4947. break;
  4948. }
  4949. // Run the runloop for a short time
  4950. lock.unlock();
  4951. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4952. lock.lock();
  4953. }
  4954. }
  4955. // Clean up
  4956. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4957. CFHostSetClient(host_ref, nullptr, nullptr);
  4958. if (timed_out || !context.completed) {
  4959. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4960. CFRelease(host_ref);
  4961. return EAI_AGAIN;
  4962. }
  4963. if (!context.success || !context.addresses) {
  4964. CFRelease(host_ref);
  4965. return EAI_NODATA;
  4966. }
  4967. // Convert CFArray to addrinfo
  4968. CFIndex count = CFArrayGetCount(context.addresses);
  4969. if (count == 0) {
  4970. CFRelease(context.addresses);
  4971. CFRelease(host_ref);
  4972. return EAI_NODATA;
  4973. }
  4974. struct addrinfo *result_addrinfo = nullptr;
  4975. struct addrinfo **current = &result_addrinfo;
  4976. for (CFIndex i = 0; i < count; i++) {
  4977. CFDataRef addr_data =
  4978. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4979. if (!addr_data) continue;
  4980. const struct sockaddr *sockaddr_ptr =
  4981. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4982. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4983. // Allocate addrinfo structure
  4984. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4985. if (!*current) {
  4986. freeaddrinfo(result_addrinfo);
  4987. CFRelease(context.addresses);
  4988. CFRelease(host_ref);
  4989. return EAI_MEMORY;
  4990. }
  4991. memset(*current, 0, sizeof(struct addrinfo));
  4992. // Set up addrinfo fields
  4993. (*current)->ai_family = sockaddr_ptr->sa_family;
  4994. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4995. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4996. (*current)->ai_addrlen = sockaddr_len;
  4997. // Copy sockaddr
  4998. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4999. if (!(*current)->ai_addr) {
  5000. freeaddrinfo(result_addrinfo);
  5001. CFRelease(context.addresses);
  5002. CFRelease(host_ref);
  5003. return EAI_MEMORY;
  5004. }
  5005. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  5006. // Set port if service is specified
  5007. if (service && *service) {
  5008. int port = 0;
  5009. if (parse_port(service, strlen(service), port)) {
  5010. if (sockaddr_ptr->sa_family == AF_INET) {
  5011. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5012. ->sin_port = htons(static_cast<uint16_t>(port));
  5013. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5014. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5015. ->sin6_port = htons(static_cast<uint16_t>(port));
  5016. }
  5017. }
  5018. }
  5019. current = &((*current)->ai_next);
  5020. }
  5021. CFRelease(context.addresses);
  5022. CFRelease(host_ref);
  5023. *res = result_addrinfo;
  5024. return 0;
  5025. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5026. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5027. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5028. // the resolver worker still references the stack-local gaicb. The cancel
  5029. // path therefore waits (gai_suspend with no timeout) for the worker to
  5030. // actually finish before letting the stack frame go. The trade-off is that
  5031. // a wedged DNS server can hold this thread for the system resolver timeout
  5032. // (~30s by default) past the caller's connection timeout.
  5033. struct gaicb request {};
  5034. struct gaicb *requests[1] = {&request};
  5035. struct sigevent sevp {};
  5036. struct timespec timeout {
  5037. timeout_sec, 0
  5038. };
  5039. request.ar_name = node;
  5040. request.ar_service = service;
  5041. request.ar_request = hints;
  5042. sevp.sigev_notify = SIGEV_NONE;
  5043. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5044. if (rc != 0) { return rc; }
  5045. auto cleanup = scope_exit([&] {
  5046. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5047. });
  5048. int wait_result = gai_suspend(requests, 1, &timeout);
  5049. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5050. int gai_result = gai_error(&request);
  5051. if (gai_result == 0) {
  5052. *res = request.ar_result;
  5053. request.ar_result = nullptr;
  5054. return 0;
  5055. }
  5056. return gai_result;
  5057. }
  5058. gai_cancel(&request);
  5059. while (gai_error(&request) == EAI_INPROGRESS) {
  5060. gai_suspend(requests, 1, nullptr);
  5061. }
  5062. return wait_result;
  5063. #else
  5064. // Fallback implementation using thread-based timeout for other Unix systems.
  5065. struct GetAddrInfoState {
  5066. ~GetAddrInfoState() {
  5067. if (info) { freeaddrinfo(info); }
  5068. }
  5069. std::mutex mutex;
  5070. std::condition_variable result_cv;
  5071. bool completed = false;
  5072. int result = EAI_SYSTEM;
  5073. std::string node;
  5074. std::string service;
  5075. struct addrinfo hints;
  5076. struct addrinfo *info = nullptr;
  5077. };
  5078. // Allocate on the heap, so the resolver thread can keep using the data.
  5079. auto state = std::make_shared<GetAddrInfoState>();
  5080. if (node) { state->node = node; }
  5081. state->service = service;
  5082. state->hints = *hints;
  5083. std::thread resolve_thread([state]() {
  5084. auto thread_result =
  5085. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5086. &state->info);
  5087. std::lock_guard<std::mutex> lock(state->mutex);
  5088. state->result = thread_result;
  5089. state->completed = true;
  5090. state->result_cv.notify_one();
  5091. });
  5092. // Wait for completion or timeout
  5093. std::unique_lock<std::mutex> lock(state->mutex);
  5094. auto finished =
  5095. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5096. [&] { return state->completed; });
  5097. if (finished) {
  5098. // Operation completed within timeout
  5099. resolve_thread.join();
  5100. *res = state->info;
  5101. state->info = nullptr; // Pass ownership to caller
  5102. return state->result;
  5103. } else {
  5104. // Timeout occurred
  5105. resolve_thread.detach(); // Let the thread finish in background
  5106. return EAI_AGAIN; // Return timeout error
  5107. }
  5108. #endif
  5109. #else
  5110. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5111. return getaddrinfo(node, service, hints, res);
  5112. #endif
  5113. }
  5114. template <typename BindOrConnect>
  5115. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5116. int address_family, int socket_flags, bool tcp_nodelay,
  5117. bool ipv6_v6only, SocketOptions socket_options,
  5118. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5119. // Get address info
  5120. const char *node = nullptr;
  5121. struct addrinfo hints;
  5122. struct addrinfo *result;
  5123. memset(&hints, 0, sizeof(struct addrinfo));
  5124. hints.ai_socktype = SOCK_STREAM;
  5125. hints.ai_protocol = IPPROTO_IP;
  5126. if (!ip.empty()) {
  5127. node = ip.c_str();
  5128. // Ask getaddrinfo to convert IP in c-string to address
  5129. hints.ai_family = AF_UNSPEC;
  5130. hints.ai_flags = AI_NUMERICHOST;
  5131. } else {
  5132. if (!host.empty()) { node = host.c_str(); }
  5133. hints.ai_family = address_family;
  5134. hints.ai_flags = socket_flags;
  5135. }
  5136. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5137. if (hints.ai_family == AF_UNIX) {
  5138. const auto addrlen = host.length();
  5139. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5140. #ifdef SOCK_CLOEXEC
  5141. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5142. hints.ai_protocol);
  5143. #else
  5144. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5145. #endif
  5146. if (sock != INVALID_SOCKET) {
  5147. sockaddr_un addr{};
  5148. addr.sun_family = AF_UNIX;
  5149. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5150. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5151. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5152. hints.ai_addrlen = static_cast<socklen_t>(
  5153. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5154. #ifndef SOCK_CLOEXEC
  5155. #ifndef _WIN32
  5156. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5157. #endif
  5158. #endif
  5159. if (socket_options) { socket_options(sock); }
  5160. #ifdef _WIN32
  5161. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5162. // remove the option.
  5163. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5164. #endif
  5165. bool dummy;
  5166. if (!bind_or_connect(sock, hints, dummy)) {
  5167. close_socket(sock);
  5168. sock = INVALID_SOCKET;
  5169. }
  5170. }
  5171. return sock;
  5172. }
  5173. #endif
  5174. auto service = std::to_string(port);
  5175. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5176. timeout_sec)) {
  5177. #if defined __linux__ && !defined __ANDROID__
  5178. res_init();
  5179. #endif
  5180. return INVALID_SOCKET;
  5181. }
  5182. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5183. for (auto rp = result; rp; rp = rp->ai_next) {
  5184. // Create a socket
  5185. #ifdef _WIN32
  5186. auto sock =
  5187. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5188. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5189. /**
  5190. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5191. * and above the socket creation fails on older Windows Systems.
  5192. *
  5193. * Let's try to create a socket the old way in this case.
  5194. *
  5195. * Reference:
  5196. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5197. *
  5198. * WSA_FLAG_NO_HANDLE_INHERIT:
  5199. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5200. * SP1, and later
  5201. *
  5202. */
  5203. if (sock == INVALID_SOCKET) {
  5204. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5205. }
  5206. #else
  5207. #ifdef SOCK_CLOEXEC
  5208. auto sock =
  5209. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5210. #else
  5211. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5212. #endif
  5213. #endif
  5214. if (sock == INVALID_SOCKET) { continue; }
  5215. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5216. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5217. close_socket(sock);
  5218. continue;
  5219. }
  5220. #endif
  5221. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5222. if (rp->ai_family == AF_INET6) {
  5223. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5224. }
  5225. if (socket_options) { socket_options(sock); }
  5226. // bind or connect
  5227. auto quit = false;
  5228. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5229. close_socket(sock);
  5230. if (quit) { break; }
  5231. }
  5232. return INVALID_SOCKET;
  5233. }
  5234. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5235. #ifdef _WIN32
  5236. auto flags = nonblocking ? 1UL : 0UL;
  5237. ioctlsocket(sock, FIONBIO, &flags);
  5238. #else
  5239. auto flags = fcntl(sock, F_GETFL, 0);
  5240. fcntl(sock, F_SETFL,
  5241. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5242. #endif
  5243. }
  5244. inline bool is_connection_error() {
  5245. #ifdef _WIN32
  5246. return WSAGetLastError() != WSAEWOULDBLOCK;
  5247. #else
  5248. return errno != EINPROGRESS;
  5249. #endif
  5250. }
  5251. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5252. struct addrinfo hints;
  5253. struct addrinfo *result;
  5254. memset(&hints, 0, sizeof(struct addrinfo));
  5255. hints.ai_family = AF_UNSPEC;
  5256. hints.ai_socktype = SOCK_STREAM;
  5257. hints.ai_protocol = 0;
  5258. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5259. return false;
  5260. }
  5261. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5262. auto ret = false;
  5263. for (auto rp = result; rp; rp = rp->ai_next) {
  5264. const auto &ai = *rp;
  5265. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5266. ret = true;
  5267. break;
  5268. }
  5269. }
  5270. return ret;
  5271. }
  5272. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5273. #define USE_IF2IP
  5274. #endif
  5275. #ifdef USE_IF2IP
  5276. inline std::string if2ip(int address_family, const std::string &ifn) {
  5277. struct ifaddrs *ifap;
  5278. getifaddrs(&ifap);
  5279. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5280. std::string addr_candidate;
  5281. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5282. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5283. (AF_UNSPEC == address_family ||
  5284. ifa->ifa_addr->sa_family == address_family)) {
  5285. if (ifa->ifa_addr->sa_family == AF_INET) {
  5286. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5287. char buf[INET_ADDRSTRLEN];
  5288. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5289. return std::string(buf, INET_ADDRSTRLEN);
  5290. }
  5291. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5292. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5293. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5294. char buf[INET6_ADDRSTRLEN] = {};
  5295. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5296. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5297. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5298. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5299. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5300. } else {
  5301. return std::string(buf, INET6_ADDRSTRLEN);
  5302. }
  5303. }
  5304. }
  5305. }
  5306. }
  5307. }
  5308. return addr_candidate;
  5309. }
  5310. #endif
  5311. inline socket_t create_client_socket(
  5312. const std::string &host, const std::string &ip, int port,
  5313. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5314. SocketOptions socket_options, time_t connection_timeout_sec,
  5315. time_t connection_timeout_usec, time_t read_timeout_sec,
  5316. time_t read_timeout_usec, time_t write_timeout_sec,
  5317. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5318. auto sock = create_socket(
  5319. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5320. std::move(socket_options),
  5321. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5322. if (!intf.empty()) {
  5323. #ifdef USE_IF2IP
  5324. auto ip_from_if = if2ip(address_family, intf);
  5325. if (ip_from_if.empty()) { ip_from_if = intf; }
  5326. if (!bind_ip_address(sock2, ip_from_if)) {
  5327. error = Error::BindIPAddress;
  5328. return false;
  5329. }
  5330. #endif
  5331. }
  5332. set_nonblocking(sock2, true);
  5333. auto ret =
  5334. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5335. if (ret < 0) {
  5336. if (is_connection_error()) {
  5337. error = Error::Connection;
  5338. return false;
  5339. }
  5340. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5341. connection_timeout_usec);
  5342. if (error != Error::Success) {
  5343. if (error == Error::ConnectionTimeout) { quit = true; }
  5344. return false;
  5345. }
  5346. }
  5347. set_nonblocking(sock2, false);
  5348. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5349. read_timeout_usec);
  5350. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5351. write_timeout_usec);
  5352. error = Error::Success;
  5353. return true;
  5354. },
  5355. connection_timeout_sec); // Pass DNS timeout
  5356. if (sock != INVALID_SOCKET) {
  5357. error = Error::Success;
  5358. } else {
  5359. if (error == Error::Success) { error = Error::Connection; }
  5360. }
  5361. return sock;
  5362. }
  5363. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5364. socklen_t addr_len, std::string &ip, int &port) {
  5365. if (addr.ss_family == AF_INET) {
  5366. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5367. } else if (addr.ss_family == AF_INET6) {
  5368. port =
  5369. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5370. } else {
  5371. return false;
  5372. }
  5373. std::array<char, NI_MAXHOST> ipstr{};
  5374. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5375. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5376. 0, NI_NUMERICHOST)) {
  5377. return false;
  5378. }
  5379. ip = ipstr.data();
  5380. return true;
  5381. }
  5382. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5383. struct sockaddr_storage addr;
  5384. socklen_t addr_len = sizeof(addr);
  5385. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5386. &addr_len)) {
  5387. get_ip_and_port(addr, addr_len, ip, port);
  5388. }
  5389. }
  5390. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5391. struct sockaddr_storage addr;
  5392. socklen_t addr_len = sizeof(addr);
  5393. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5394. &addr_len)) {
  5395. #ifndef _WIN32
  5396. if (addr.ss_family == AF_UNIX) {
  5397. #if defined(__linux__)
  5398. struct ucred ucred;
  5399. socklen_t len = sizeof(ucred);
  5400. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5401. port = ucred.pid;
  5402. }
  5403. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5404. pid_t pid;
  5405. socklen_t len = sizeof(pid);
  5406. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5407. port = pid;
  5408. }
  5409. #endif
  5410. return;
  5411. }
  5412. #endif
  5413. get_ip_and_port(addr, addr_len, ip, port);
  5414. }
  5415. }
  5416. // Recursive form retained so operator""_t below can compute hashes for
  5417. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5418. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5419. // instead, which is iterative and stack-safe.
  5420. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5421. unsigned int h) {
  5422. return (l == 0)
  5423. ? h
  5424. : str2tag_core(
  5425. s + 1, l - 1,
  5426. // Unsets the 6 high bits of h, therefore no overflow happens
  5427. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5428. h * 33) ^
  5429. static_cast<unsigned char>(*s));
  5430. }
  5431. inline unsigned int str2tag(const std::string &s) {
  5432. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5433. // for compile-time UDL evaluation of short string literals, but at runtime
  5434. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5435. // would blow the stack with one frame per character.
  5436. unsigned int h = 0;
  5437. for (auto c : s) {
  5438. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5439. static_cast<unsigned char>(c);
  5440. }
  5441. return h;
  5442. }
  5443. namespace udl {
  5444. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5445. return str2tag_core(s, l, 0);
  5446. }
  5447. } // namespace udl
  5448. inline std::string
  5449. find_content_type(const std::string &path,
  5450. const std::map<std::string, std::string> &user_data,
  5451. const std::string &default_content_type) {
  5452. auto ext = file_extension(path);
  5453. auto it = user_data.find(ext);
  5454. if (it != user_data.end()) { return it->second; }
  5455. using udl::operator""_t;
  5456. switch (str2tag(ext)) {
  5457. default: return default_content_type;
  5458. case "css"_t: return "text/css";
  5459. case "csv"_t: return "text/csv";
  5460. case "htm"_t:
  5461. case "html"_t: return "text/html";
  5462. case "js"_t:
  5463. case "mjs"_t: return "text/javascript";
  5464. case "txt"_t: return "text/plain";
  5465. case "vtt"_t: return "text/vtt";
  5466. case "apng"_t: return "image/apng";
  5467. case "avif"_t: return "image/avif";
  5468. case "bmp"_t: return "image/bmp";
  5469. case "gif"_t: return "image/gif";
  5470. case "png"_t: return "image/png";
  5471. case "svg"_t: return "image/svg+xml";
  5472. case "webp"_t: return "image/webp";
  5473. case "ico"_t: return "image/x-icon";
  5474. case "tif"_t: return "image/tiff";
  5475. case "tiff"_t: return "image/tiff";
  5476. case "jpg"_t:
  5477. case "jpeg"_t: return "image/jpeg";
  5478. case "mp4"_t: return "video/mp4";
  5479. case "mpeg"_t: return "video/mpeg";
  5480. case "webm"_t: return "video/webm";
  5481. case "mp3"_t: return "audio/mp3";
  5482. case "mpga"_t: return "audio/mpeg";
  5483. case "weba"_t: return "audio/webm";
  5484. case "wav"_t: return "audio/wave";
  5485. case "otf"_t: return "font/otf";
  5486. case "ttf"_t: return "font/ttf";
  5487. case "woff"_t: return "font/woff";
  5488. case "woff2"_t: return "font/woff2";
  5489. case "7z"_t: return "application/x-7z-compressed";
  5490. case "atom"_t: return "application/atom+xml";
  5491. case "pdf"_t: return "application/pdf";
  5492. case "json"_t: return "application/json";
  5493. case "rss"_t: return "application/rss+xml";
  5494. case "tar"_t: return "application/x-tar";
  5495. case "xht"_t:
  5496. case "xhtml"_t: return "application/xhtml+xml";
  5497. case "xslt"_t: return "application/xslt+xml";
  5498. case "xml"_t: return "application/xml";
  5499. case "gz"_t: return "application/gzip";
  5500. case "zip"_t: return "application/zip";
  5501. case "wasm"_t: return "application/wasm";
  5502. }
  5503. }
  5504. inline std::string
  5505. extract_media_type(const std::string &content_type,
  5506. std::map<std::string, std::string> *params = nullptr) {
  5507. // Extract type/subtype from Content-Type value (RFC 2045)
  5508. // e.g. "application/json; charset=utf-8" -> "application/json"
  5509. auto media_type = content_type;
  5510. auto semicolon_pos = media_type.find(';');
  5511. if (semicolon_pos != std::string::npos) {
  5512. auto param_str = media_type.substr(semicolon_pos + 1);
  5513. media_type = media_type.substr(0, semicolon_pos);
  5514. if (params) {
  5515. // Parse parameters: key=value pairs separated by ';'
  5516. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5517. [&](const char *b, const char *e) {
  5518. std::string key;
  5519. std::string val;
  5520. split(b, e, '=', [&](const char *b2, const char *e2) {
  5521. if (key.empty()) {
  5522. key.assign(b2, e2);
  5523. } else {
  5524. val.assign(b2, e2);
  5525. }
  5526. });
  5527. if (!key.empty()) {
  5528. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5529. }
  5530. });
  5531. }
  5532. }
  5533. // Trim whitespace from media type
  5534. return trim_copy(media_type);
  5535. }
  5536. inline bool can_compress_content_type(const std::string &content_type) {
  5537. using udl::operator""_t;
  5538. auto mime_type = extract_media_type(content_type);
  5539. auto tag = str2tag(mime_type);
  5540. switch (tag) {
  5541. case "image/svg+xml"_t:
  5542. case "application/javascript"_t:
  5543. case "application/x-javascript"_t:
  5544. case "application/json"_t:
  5545. case "application/ld+json"_t:
  5546. case "application/xml"_t:
  5547. case "application/xhtml+xml"_t:
  5548. case "application/rss+xml"_t:
  5549. case "application/atom+xml"_t:
  5550. case "application/xslt+xml"_t:
  5551. case "application/protobuf"_t: return true;
  5552. case "text/event-stream"_t: return false;
  5553. default: return !mime_type.rfind("text/", 0);
  5554. }
  5555. }
  5556. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5557. double &quality) {
  5558. quality = 1.0;
  5559. token.clear();
  5560. // Split on first ';': left = token name, right = parameters
  5561. const char *params_b = nullptr;
  5562. std::size_t params_len = 0;
  5563. divide(
  5564. b, static_cast<std::size_t>(e - b), ';',
  5565. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5566. auto r = trim(lb, lb + llen, 0, llen);
  5567. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5568. params_b = rb;
  5569. params_len = rlen;
  5570. });
  5571. if (token.empty()) { return false; }
  5572. if (params_len == 0) { return true; }
  5573. // Scan parameters for q= (stops on first match)
  5574. bool invalid = false;
  5575. split_find(params_b, params_b + params_len, ';',
  5576. (std::numeric_limits<size_t>::max)(),
  5577. [&](const char *pb, const char *pe) -> bool {
  5578. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5579. auto len = static_cast<size_t>(pe - pb);
  5580. if (len < 2) { return false; }
  5581. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5582. return false;
  5583. }
  5584. // Trim the value portion
  5585. auto r = trim(pb, pe, 2, len);
  5586. if (r.first >= r.second) {
  5587. invalid = true;
  5588. return true;
  5589. }
  5590. double v = 0.0;
  5591. auto res = from_chars(pb + r.first, pb + r.second, v);
  5592. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5593. invalid = true;
  5594. return true;
  5595. }
  5596. quality = v;
  5597. return true;
  5598. });
  5599. return !invalid;
  5600. }
  5601. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5602. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5603. return EncodingType::None;
  5604. }
  5605. const auto &s = req.get_header_value("Accept-Encoding");
  5606. if (s.empty()) { return EncodingType::None; }
  5607. // Single-pass: iterate tokens and track the best supported encoding.
  5608. // Server preference breaks ties (br > gzip > zstd).
  5609. EncodingType best = EncodingType::None;
  5610. double best_q = 0.0; // q=0 means "not acceptable"
  5611. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5612. auto priority = [](EncodingType t) -> int {
  5613. switch (t) {
  5614. case EncodingType::Brotli: return 0;
  5615. case EncodingType::Gzip: return 1;
  5616. case EncodingType::Zstd: return 2;
  5617. default: return 3;
  5618. }
  5619. };
  5620. std::string name;
  5621. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5622. double quality = 1.0;
  5623. if (!parse_quality(b, e, name, quality)) { return; }
  5624. if (quality <= 0.0) { return; }
  5625. EncodingType type = EncodingType::None;
  5626. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5627. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5628. #endif
  5629. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5630. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5631. type = EncodingType::Gzip;
  5632. }
  5633. #endif
  5634. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5635. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5636. type = EncodingType::Zstd;
  5637. }
  5638. #endif
  5639. if (type == EncodingType::None) { return; }
  5640. // Higher q-value wins; for equal q, server preference breaks ties
  5641. if (quality > best_q ||
  5642. (quality == best_q && priority(type) < priority(best))) {
  5643. best_q = quality;
  5644. best = type;
  5645. }
  5646. });
  5647. return best;
  5648. }
  5649. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5650. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5651. if (type == EncodingType::Gzip) {
  5652. return detail::make_unique<gzip_compressor>();
  5653. }
  5654. #endif
  5655. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5656. if (type == EncodingType::Brotli) {
  5657. return detail::make_unique<brotli_compressor>();
  5658. }
  5659. #endif
  5660. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5661. if (type == EncodingType::Zstd) {
  5662. return detail::make_unique<zstd_compressor>();
  5663. }
  5664. #endif
  5665. (void)type;
  5666. return nullptr;
  5667. }
  5668. inline const char *encoding_name(EncodingType type) {
  5669. switch (type) {
  5670. case EncodingType::Gzip: return "gzip";
  5671. case EncodingType::Brotli: return "br";
  5672. case EncodingType::Zstd: return "zstd";
  5673. default: return "";
  5674. }
  5675. }
  5676. inline bool nocompressor::compress(const char *data, size_t data_length,
  5677. bool /*last*/, Callback callback) {
  5678. if (!data_length) { return true; }
  5679. return callback(data, data_length);
  5680. }
  5681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5682. inline gzip_compressor::gzip_compressor() {
  5683. std::memset(&strm_, 0, sizeof(strm_));
  5684. strm_.zalloc = Z_NULL;
  5685. strm_.zfree = Z_NULL;
  5686. strm_.opaque = Z_NULL;
  5687. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5688. Z_DEFAULT_STRATEGY) == Z_OK;
  5689. }
  5690. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5691. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5692. bool last, Callback callback) {
  5693. assert(is_valid_);
  5694. do {
  5695. constexpr size_t max_avail_in =
  5696. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5697. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5698. (std::min)(data_length, max_avail_in));
  5699. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5700. data_length -= strm_.avail_in;
  5701. data += strm_.avail_in;
  5702. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5703. auto ret = Z_OK;
  5704. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5705. do {
  5706. strm_.avail_out = static_cast<uInt>(buff.size());
  5707. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5708. ret = deflate(&strm_, flush);
  5709. if (ret == Z_STREAM_ERROR) { return false; }
  5710. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5711. return false;
  5712. }
  5713. } while (strm_.avail_out == 0);
  5714. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5715. (flush == Z_NO_FLUSH && ret == Z_OK));
  5716. assert(strm_.avail_in == 0);
  5717. } while (data_length > 0);
  5718. return true;
  5719. }
  5720. inline gzip_decompressor::gzip_decompressor() {
  5721. std::memset(&strm_, 0, sizeof(strm_));
  5722. strm_.zalloc = Z_NULL;
  5723. strm_.zfree = Z_NULL;
  5724. strm_.opaque = Z_NULL;
  5725. // 15 is the value of wbits, which should be at the maximum possible value
  5726. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5727. // that the stream type should be automatically detected either gzip or
  5728. // deflate.
  5729. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5730. }
  5731. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5732. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5733. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5734. Callback callback) {
  5735. assert(is_valid_);
  5736. auto ret = Z_OK;
  5737. do {
  5738. constexpr size_t max_avail_in =
  5739. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5740. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5741. (std::min)(data_length, max_avail_in));
  5742. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5743. data_length -= strm_.avail_in;
  5744. data += strm_.avail_in;
  5745. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5746. while (strm_.avail_in > 0 && ret == Z_OK) {
  5747. strm_.avail_out = static_cast<uInt>(buff.size());
  5748. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5749. ret = inflate(&strm_, Z_NO_FLUSH);
  5750. assert(ret != Z_STREAM_ERROR);
  5751. switch (ret) {
  5752. case Z_NEED_DICT:
  5753. case Z_DATA_ERROR:
  5754. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5755. }
  5756. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5757. return false;
  5758. }
  5759. }
  5760. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5761. } while (data_length > 0);
  5762. return true;
  5763. }
  5764. #endif
  5765. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5766. inline brotli_compressor::brotli_compressor() {
  5767. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5768. }
  5769. inline brotli_compressor::~brotli_compressor() {
  5770. BrotliEncoderDestroyInstance(state_);
  5771. }
  5772. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5773. bool last, Callback callback) {
  5774. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5775. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5776. auto available_in = data_length;
  5777. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5778. for (;;) {
  5779. if (last) {
  5780. if (BrotliEncoderIsFinished(state_)) { break; }
  5781. } else {
  5782. if (!available_in) { break; }
  5783. }
  5784. auto available_out = buff.size();
  5785. auto next_out = buff.data();
  5786. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5787. &available_out, &next_out, nullptr)) {
  5788. return false;
  5789. }
  5790. auto output_bytes = buff.size() - available_out;
  5791. if (output_bytes) {
  5792. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5793. }
  5794. }
  5795. return true;
  5796. }
  5797. inline brotli_decompressor::brotli_decompressor() {
  5798. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5799. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5800. : BROTLI_DECODER_RESULT_ERROR;
  5801. }
  5802. inline brotli_decompressor::~brotli_decompressor() {
  5803. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5804. }
  5805. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5806. inline bool brotli_decompressor::decompress(const char *data,
  5807. size_t data_length,
  5808. Callback callback) {
  5809. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5810. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5811. return 0;
  5812. }
  5813. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5814. size_t avail_in = data_length;
  5815. size_t total_out;
  5816. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5817. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5818. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5819. char *next_out = buff.data();
  5820. size_t avail_out = buff.size();
  5821. decoder_r = BrotliDecoderDecompressStream(
  5822. decoder_s, &avail_in, &next_in, &avail_out,
  5823. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5824. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5825. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5826. }
  5827. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5828. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5829. }
  5830. #endif
  5831. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5832. inline zstd_compressor::zstd_compressor() {
  5833. ctx_ = ZSTD_createCCtx();
  5834. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5835. }
  5836. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5837. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5838. bool last, Callback callback) {
  5839. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5840. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5841. ZSTD_inBuffer input = {data, data_length, 0};
  5842. bool finished;
  5843. do {
  5844. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5845. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5846. if (ZSTD_isError(remaining)) { return false; }
  5847. if (!callback(buff.data(), output.pos)) { return false; }
  5848. finished = last ? (remaining == 0) : (input.pos == input.size);
  5849. } while (!finished);
  5850. return true;
  5851. }
  5852. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5853. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5854. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5855. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5856. Callback callback) {
  5857. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5858. ZSTD_inBuffer input = {data, data_length, 0};
  5859. while (input.pos < input.size) {
  5860. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5861. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5862. if (ZSTD_isError(remaining)) { return false; }
  5863. if (!callback(buff.data(), output.pos)) { return false; }
  5864. }
  5865. return true;
  5866. }
  5867. #endif
  5868. inline std::unique_ptr<decompressor>
  5869. create_decompressor(const std::string &encoding) {
  5870. std::unique_ptr<decompressor> decompressor;
  5871. if (encoding == "gzip" || encoding == "deflate") {
  5872. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5873. decompressor = detail::make_unique<gzip_decompressor>();
  5874. #endif
  5875. } else if (encoding.find("br") != std::string::npos) {
  5876. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5877. decompressor = detail::make_unique<brotli_decompressor>();
  5878. #endif
  5879. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5880. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5881. decompressor = detail::make_unique<zstd_decompressor>();
  5882. #endif
  5883. }
  5884. return decompressor;
  5885. }
  5886. // Returns the best available compressor and its Content-Encoding name.
  5887. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5888. inline std::pair<std::unique_ptr<compressor>, const char *>
  5889. create_compressor() {
  5890. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5891. return {detail::make_unique<brotli_compressor>(), "br"};
  5892. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5893. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5894. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5895. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5896. #else
  5897. return {nullptr, nullptr};
  5898. #endif
  5899. }
  5900. inline bool is_prohibited_header_name(const std::string &name) {
  5901. using udl::operator""_t;
  5902. switch (str2tag(name)) {
  5903. case "REMOTE_ADDR"_t:
  5904. case "REMOTE_PORT"_t:
  5905. case "LOCAL_ADDR"_t:
  5906. case "LOCAL_PORT"_t: return true;
  5907. default: return false;
  5908. }
  5909. }
  5910. inline bool has_header(const Headers &headers, const std::string &key) {
  5911. if (is_prohibited_header_name(key)) { return false; }
  5912. return headers.find(key) != headers.end();
  5913. }
  5914. inline const char *get_header_value(const Headers &headers,
  5915. const std::string &key, const char *def,
  5916. size_t id) {
  5917. if (is_prohibited_header_name(key)) {
  5918. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5919. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5920. throw std::invalid_argument(msg);
  5921. #else
  5922. return "";
  5923. #endif
  5924. }
  5925. auto rng = headers.equal_range(key);
  5926. auto it = rng.first;
  5927. std::advance(it, static_cast<ssize_t>(id));
  5928. if (it != rng.second) { return it->second.c_str(); }
  5929. return def;
  5930. }
  5931. inline size_t get_header_value_count(const Headers &headers,
  5932. const std::string &key) {
  5933. auto r = headers.equal_range(key);
  5934. return static_cast<size_t>(std::distance(r.first, r.second));
  5935. }
  5936. template <typename Map>
  5937. inline typename Map::mapped_type
  5938. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5939. auto rng = m.equal_range(key);
  5940. auto it = rng.first;
  5941. std::advance(it, static_cast<ssize_t>(id));
  5942. if (it != rng.second) { return it->second; }
  5943. return typename Map::mapped_type();
  5944. }
  5945. inline void set_header(Headers &headers, const std::string &key,
  5946. const std::string &val) {
  5947. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5948. headers.emplace(key, val);
  5949. }
  5950. }
  5951. inline bool read_headers(Stream &strm, Headers &headers) {
  5952. const auto bufsiz = 2048;
  5953. char buf[bufsiz];
  5954. stream_line_reader line_reader(strm, buf, bufsiz);
  5955. size_t header_count = 0;
  5956. for (;;) {
  5957. if (!line_reader.getline()) { return false; }
  5958. // Check if the line ends with CRLF.
  5959. auto line_terminator_len = 2;
  5960. if (line_reader.end_with_crlf()) {
  5961. // Blank line indicates end of headers.
  5962. if (line_reader.size() == 2) { break; }
  5963. } else {
  5964. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5965. // Blank line indicates end of headers.
  5966. if (line_reader.size() == 1) { break; }
  5967. line_terminator_len = 1;
  5968. #else
  5969. continue; // Skip invalid line.
  5970. #endif
  5971. }
  5972. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5973. // Check header count limit
  5974. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5975. // Exclude line terminator
  5976. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5977. if (!parse_header(line_reader.ptr(), end,
  5978. [&](const std::string &key, const std::string &val) {
  5979. headers.emplace(key, val);
  5980. })) {
  5981. return false;
  5982. }
  5983. header_count++;
  5984. }
  5985. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5986. // headers that have different values to prevent request smuggling.
  5987. auto cl_range = headers.equal_range("Content-Length");
  5988. if (cl_range.first != cl_range.second) {
  5989. const auto &first_val = cl_range.first->second;
  5990. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5991. if (it->second != first_val) { return false; }
  5992. }
  5993. }
  5994. return true;
  5995. }
  5996. inline bool read_websocket_upgrade_response(Stream &strm,
  5997. const std::string &expected_accept,
  5998. std::string &selected_subprotocol) {
  5999. // Read status line
  6000. const auto bufsiz = 2048;
  6001. char buf[bufsiz];
  6002. stream_line_reader line_reader(strm, buf, bufsiz);
  6003. if (!line_reader.getline()) { return false; }
  6004. // Check for "HTTP/1.1 101"
  6005. auto line = std::string(line_reader.ptr(), line_reader.size());
  6006. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  6007. // Parse headers using existing read_headers
  6008. Headers headers;
  6009. if (!read_headers(strm, headers)) { return false; }
  6010. // Verify Upgrade: websocket (case-insensitive)
  6011. auto upgrade_it = headers.find("Upgrade");
  6012. if (upgrade_it == headers.end()) { return false; }
  6013. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  6014. if (upgrade_val != "websocket") { return false; }
  6015. // Verify Connection header contains "Upgrade" (case-insensitive)
  6016. auto connection_it = headers.find("Connection");
  6017. if (connection_it == headers.end()) { return false; }
  6018. auto connection_val = case_ignore::to_lower(connection_it->second);
  6019. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  6020. // Verify Sec-WebSocket-Accept header value
  6021. auto it = headers.find("Sec-WebSocket-Accept");
  6022. if (it == headers.end() || it->second != expected_accept) { return false; }
  6023. // Extract negotiated subprotocol
  6024. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6025. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6026. return true;
  6027. }
  6028. enum class ReadContentResult {
  6029. Success, // Successfully read the content
  6030. PayloadTooLarge, // The content exceeds the specified payload limit
  6031. Error // An error occurred while reading the content
  6032. };
  6033. inline ReadContentResult read_content_with_length(
  6034. Stream &strm, size_t len, DownloadProgress progress,
  6035. ContentReceiverWithProgress out,
  6036. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6037. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6038. detail::BodyReader br;
  6039. br.stream = &strm;
  6040. br.has_content_length = true;
  6041. br.content_length = len;
  6042. br.payload_max_length = payload_max_length;
  6043. br.chunked = false;
  6044. br.bytes_read = 0;
  6045. br.last_error = Error::Success;
  6046. size_t r = 0;
  6047. while (r < len) {
  6048. auto read_len = static_cast<size_t>(len - r);
  6049. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6050. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6051. if (n <= 0) {
  6052. // Check if it was a payload size error
  6053. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6054. return ReadContentResult::PayloadTooLarge;
  6055. }
  6056. return ReadContentResult::Error;
  6057. }
  6058. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6059. return ReadContentResult::Error;
  6060. }
  6061. r += static_cast<size_t>(n);
  6062. if (progress) {
  6063. if (!progress(r, len)) { return ReadContentResult::Error; }
  6064. }
  6065. }
  6066. return ReadContentResult::Success;
  6067. }
  6068. inline ReadContentResult
  6069. read_content_without_length(Stream &strm, size_t payload_max_length,
  6070. ContentReceiverWithProgress out) {
  6071. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6072. size_t r = 0;
  6073. for (;;) {
  6074. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6075. if (n == 0) { return ReadContentResult::Success; }
  6076. if (n < 0) { return ReadContentResult::Error; }
  6077. // Check if adding this data would exceed the payload limit
  6078. if (r > payload_max_length ||
  6079. payload_max_length - r < static_cast<size_t>(n)) {
  6080. return ReadContentResult::PayloadTooLarge;
  6081. }
  6082. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6083. return ReadContentResult::Error;
  6084. }
  6085. r += static_cast<size_t>(n);
  6086. }
  6087. return ReadContentResult::Success;
  6088. }
  6089. template <typename T>
  6090. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6091. size_t payload_max_length,
  6092. ContentReceiverWithProgress out) {
  6093. detail::ChunkedDecoder dec(strm);
  6094. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6095. size_t total_len = 0;
  6096. for (;;) {
  6097. size_t chunk_offset = 0;
  6098. size_t chunk_total = 0;
  6099. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6100. if (n < 0) { return ReadContentResult::Error; }
  6101. if (n == 0) {
  6102. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6103. return ReadContentResult::Error;
  6104. }
  6105. return ReadContentResult::Success;
  6106. }
  6107. if (total_len > payload_max_length ||
  6108. payload_max_length - total_len < static_cast<size_t>(n)) {
  6109. return ReadContentResult::PayloadTooLarge;
  6110. }
  6111. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6112. return ReadContentResult::Error;
  6113. }
  6114. total_len += static_cast<size_t>(n);
  6115. }
  6116. }
  6117. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6118. // RFC 9112 6.1: a message is framed with the chunked coding when "chunked"
  6119. // is the final transfer coding. A single field value may list several
  6120. // codings ("gzip, chunked"), and the list may be split across multiple
  6121. // Transfer-Encoding header lines (RFC 9110 5.3). Match the last coding token
  6122. // case-insensitively rather than comparing the whole value against "chunked".
  6123. //
  6124. // Security: reading a chunked message as unframed leaves its body in the
  6125. // socket, where a keep-alive connection parses it as a smuggled request.
  6126. // Headers is an unordered_multimap whose iteration order for duplicate keys
  6127. // is not portable, so when there is more than one Transfer-Encoding line we
  6128. // cannot tell which coding is truly final. In that ambiguous case we fail
  6129. // safe by treating the message as chunked (a mis-parse just closes the
  6130. // connection, whereas the opposite error enables smuggling).
  6131. auto rng = headers.equal_range("Transfer-Encoding");
  6132. size_t line_count = 0;
  6133. bool chunked_present = false;
  6134. bool last_line_ends_with_chunked = false;
  6135. for (auto it = rng.first; it != rng.second; ++it) {
  6136. line_count++;
  6137. const auto &value = it->second;
  6138. std::string last_coding;
  6139. bool line_has_chunked = false;
  6140. split(value.data(), value.data() + value.size(), ',',
  6141. [&](const char *b, const char *e) {
  6142. last_coding.assign(b, e);
  6143. if (case_ignore::equal(last_coding, "chunked")) {
  6144. line_has_chunked = true;
  6145. }
  6146. });
  6147. if (line_has_chunked) { chunked_present = true; }
  6148. last_line_ends_with_chunked = case_ignore::equal(last_coding, "chunked");
  6149. }
  6150. if (line_count == 0) { return false; }
  6151. if (line_count == 1) { return last_line_ends_with_chunked; }
  6152. return chunked_present;
  6153. }
  6154. template <typename T, typename U>
  6155. bool prepare_content_receiver(T &x, int &status,
  6156. ContentReceiverWithProgress receiver,
  6157. bool decompress, size_t payload_max_length,
  6158. bool &exceed_payload_max_length, U callback) {
  6159. if (decompress) {
  6160. std::string encoding = x.get_header_value("Content-Encoding");
  6161. std::unique_ptr<decompressor> decompressor;
  6162. if (!encoding.empty()) {
  6163. decompressor = detail::create_decompressor(encoding);
  6164. if (!decompressor) {
  6165. // Unsupported encoding or no support compiled in
  6166. status = StatusCode::UnsupportedMediaType_415;
  6167. return false;
  6168. }
  6169. }
  6170. if (decompressor) {
  6171. if (decompressor->is_valid()) {
  6172. size_t decompressed_size = 0;
  6173. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6174. size_t off, size_t len) {
  6175. return decompressor->decompress(
  6176. buf, n, [&](const char *buf2, size_t n2) {
  6177. // Guard against zip-bomb: check
  6178. // decompressed size against limit.
  6179. if (payload_max_length > 0 &&
  6180. (decompressed_size >= payload_max_length ||
  6181. n2 > payload_max_length - decompressed_size)) {
  6182. exceed_payload_max_length = true;
  6183. return false;
  6184. }
  6185. decompressed_size += n2;
  6186. return receiver(buf2, n2, off, len);
  6187. });
  6188. };
  6189. return callback(std::move(out));
  6190. } else {
  6191. status = StatusCode::InternalServerError_500;
  6192. return false;
  6193. }
  6194. }
  6195. }
  6196. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6197. size_t len) {
  6198. return receiver(buf, n, off, len);
  6199. };
  6200. return callback(std::move(out));
  6201. }
  6202. template <typename T>
  6203. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6204. DownloadProgress progress,
  6205. ContentReceiverWithProgress receiver, bool decompress) {
  6206. bool exceed_payload_max_length = false;
  6207. return prepare_content_receiver(
  6208. x, status, std::move(receiver), decompress, payload_max_length,
  6209. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6210. auto ret = true;
  6211. // Note: exceed_payload_max_length may also be set by the decompressor
  6212. // wrapper in prepare_content_receiver when the decompressed payload
  6213. // size exceeds the limit.
  6214. if (is_chunked_transfer_encoding(x.headers)) {
  6215. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6216. if (result == ReadContentResult::Success) {
  6217. ret = true;
  6218. } else if (result == ReadContentResult::PayloadTooLarge) {
  6219. exceed_payload_max_length = true;
  6220. ret = false;
  6221. } else {
  6222. ret = false;
  6223. }
  6224. } else if (!has_header(x.headers, "Content-Length")) {
  6225. auto result =
  6226. read_content_without_length(strm, payload_max_length, out);
  6227. if (result == ReadContentResult::Success) {
  6228. ret = true;
  6229. } else if (result == ReadContentResult::PayloadTooLarge) {
  6230. exceed_payload_max_length = true;
  6231. ret = false;
  6232. } else {
  6233. ret = false;
  6234. }
  6235. } else {
  6236. auto is_invalid_value = false;
  6237. auto len = get_header_value_u64(x.headers, "Content-Length",
  6238. (std::numeric_limits<size_t>::max)(),
  6239. 0, is_invalid_value);
  6240. if (is_invalid_value) {
  6241. ret = false;
  6242. } else if (len > 0) {
  6243. auto result = read_content_with_length(
  6244. strm, len, std::move(progress), out, payload_max_length);
  6245. ret = (result == ReadContentResult::Success);
  6246. if (result == ReadContentResult::PayloadTooLarge) {
  6247. exceed_payload_max_length = true;
  6248. }
  6249. }
  6250. }
  6251. if (!ret) {
  6252. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6253. : StatusCode::BadRequest_400;
  6254. }
  6255. return ret;
  6256. });
  6257. }
  6258. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6259. const std::string &path) {
  6260. // A request target must not carry CR/LF (or other control octets); otherwise
  6261. // a value smuggled into it splits the request line and injects headers or a
  6262. // whole request. The same field-value check already guards header values in
  6263. // check_and_write_headers and the request target in
  6264. // perform_websocket_handshake; apply it here too.
  6265. if (!fields::is_field_value(path)) { return -1; }
  6266. std::string s = method;
  6267. s += ' ';
  6268. s += path;
  6269. s += " HTTP/1.1\r\n";
  6270. return strm.write(s.data(), s.size());
  6271. }
  6272. inline ssize_t write_response_line(Stream &strm, int status) {
  6273. std::string s = "HTTP/1.1 ";
  6274. s += std::to_string(status);
  6275. s += ' ';
  6276. s += httplib::status_message(status);
  6277. s += "\r\n";
  6278. return strm.write(s.data(), s.size());
  6279. }
  6280. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6281. ssize_t write_len = 0;
  6282. for (const auto &x : headers) {
  6283. std::string s;
  6284. s = x.first;
  6285. s += ": ";
  6286. s += x.second;
  6287. s += "\r\n";
  6288. auto len = strm.write(s.data(), s.size());
  6289. if (len < 0) { return len; }
  6290. write_len += len;
  6291. }
  6292. auto len = strm.write("\r\n");
  6293. if (len < 0) { return len; }
  6294. write_len += len;
  6295. return write_len;
  6296. }
  6297. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6298. size_t offset = 0;
  6299. while (offset < l) {
  6300. auto length = strm.write(d + offset, l - offset);
  6301. if (length < 0) { return false; }
  6302. offset += static_cast<size_t>(length);
  6303. }
  6304. return true;
  6305. }
  6306. template <typename T>
  6307. inline bool write_content_with_progress(Stream &strm,
  6308. const ContentProvider &content_provider,
  6309. size_t offset, size_t length,
  6310. T is_shutting_down,
  6311. const UploadProgress &upload_progress,
  6312. Error &error) {
  6313. size_t end_offset = offset + length;
  6314. size_t start_offset = offset;
  6315. auto ok = true;
  6316. DataSink data_sink;
  6317. data_sink.write = [&](const char *d, size_t l) -> bool {
  6318. if (ok) {
  6319. if (write_data(strm, d, l)) {
  6320. offset += l;
  6321. if (upload_progress && length > 0) {
  6322. size_t current_written = offset - start_offset;
  6323. if (!upload_progress(current_written, length)) {
  6324. ok = false;
  6325. return false;
  6326. }
  6327. }
  6328. } else {
  6329. ok = false;
  6330. }
  6331. }
  6332. return ok;
  6333. };
  6334. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6335. while (offset < end_offset && !is_shutting_down()) {
  6336. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6337. error = Error::Write;
  6338. return false;
  6339. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6340. error = Error::Canceled;
  6341. return false;
  6342. } else if (!ok) {
  6343. error = Error::Write;
  6344. return false;
  6345. }
  6346. }
  6347. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6348. error = Error::Write;
  6349. return false;
  6350. }
  6351. error = Error::Success;
  6352. return true;
  6353. }
  6354. template <typename T>
  6355. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6356. size_t offset, size_t length, T is_shutting_down,
  6357. Error &error) {
  6358. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6359. is_shutting_down, nullptr, error);
  6360. }
  6361. template <typename T>
  6362. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6363. size_t offset, size_t length,
  6364. const T &is_shutting_down) {
  6365. auto error = Error::Success;
  6366. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6367. error);
  6368. }
  6369. template <typename T>
  6370. inline bool
  6371. write_content_without_length(Stream &strm,
  6372. const ContentProvider &content_provider,
  6373. const T &is_shutting_down) {
  6374. size_t offset = 0;
  6375. auto data_available = true;
  6376. auto ok = true;
  6377. DataSink data_sink;
  6378. data_sink.write = [&](const char *d, size_t l) -> bool {
  6379. if (ok) {
  6380. offset += l;
  6381. if (!write_data(strm, d, l)) { ok = false; }
  6382. }
  6383. return ok;
  6384. };
  6385. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6386. data_sink.done = [&](void) { data_available = false; };
  6387. while (data_available && !is_shutting_down()) {
  6388. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6389. return false;
  6390. } else if (!content_provider(offset, 0, data_sink)) {
  6391. return false;
  6392. } else if (!ok) {
  6393. return false;
  6394. }
  6395. }
  6396. return !data_available; // true only if done() was called, false if shutting
  6397. // down
  6398. }
  6399. template <typename T, typename U>
  6400. inline bool
  6401. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6402. const T &is_shutting_down, U &compressor, Error &error) {
  6403. size_t offset = 0;
  6404. auto data_available = true;
  6405. auto ok = true;
  6406. DataSink data_sink;
  6407. data_sink.write = [&](const char *d, size_t l) -> bool {
  6408. if (ok) {
  6409. data_available = l > 0;
  6410. offset += l;
  6411. std::string payload;
  6412. if (compressor.compress(d, l, false,
  6413. [&](const char *data, size_t data_len) {
  6414. payload.append(data, data_len);
  6415. return true;
  6416. })) {
  6417. if (!payload.empty()) {
  6418. // Emit chunked response header and footer for each chunk
  6419. auto chunk =
  6420. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6421. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6422. }
  6423. } else {
  6424. ok = false;
  6425. }
  6426. }
  6427. return ok;
  6428. };
  6429. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6430. auto done_with_trailer = [&](const Headers *trailer) {
  6431. if (!ok) { return; }
  6432. data_available = false;
  6433. std::string payload;
  6434. if (!compressor.compress(nullptr, 0, true,
  6435. [&](const char *data, size_t data_len) {
  6436. payload.append(data, data_len);
  6437. return true;
  6438. })) {
  6439. ok = false;
  6440. return;
  6441. }
  6442. if (!payload.empty()) {
  6443. // Emit chunked response header and footer for each chunk
  6444. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6445. if (!write_data(strm, chunk.data(), chunk.size())) {
  6446. ok = false;
  6447. return;
  6448. }
  6449. }
  6450. constexpr const char done_marker[] = "0\r\n";
  6451. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6452. // Trailer
  6453. if (trailer) {
  6454. for (const auto &kv : *trailer) {
  6455. // Skip fields with invalid names or values to prevent response
  6456. // splitting via CR/LF injection, matching set_header().
  6457. if (!fields::is_field_name(kv.first) ||
  6458. !fields::is_field_value(kv.second)) {
  6459. continue;
  6460. }
  6461. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6462. if (!write_data(strm, field_line.data(), field_line.size())) {
  6463. ok = false;
  6464. }
  6465. }
  6466. }
  6467. constexpr const char crlf[] = "\r\n";
  6468. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6469. };
  6470. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6471. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6472. done_with_trailer(&trailer);
  6473. };
  6474. while (data_available && !is_shutting_down()) {
  6475. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6476. error = Error::Write;
  6477. return false;
  6478. } else if (!content_provider(offset, 0, data_sink)) {
  6479. error = Error::Canceled;
  6480. return false;
  6481. } else if (!ok) {
  6482. error = Error::Write;
  6483. return false;
  6484. }
  6485. }
  6486. if (data_available) { // exited due to is_shutting_down(), not done()
  6487. error = Error::Write;
  6488. return false;
  6489. }
  6490. error = Error::Success;
  6491. return true;
  6492. }
  6493. template <typename T, typename U>
  6494. inline bool write_content_chunked(Stream &strm,
  6495. const ContentProvider &content_provider,
  6496. const T &is_shutting_down, U &compressor) {
  6497. auto error = Error::Success;
  6498. return write_content_chunked(strm, content_provider, is_shutting_down,
  6499. compressor, error);
  6500. }
  6501. template <typename T>
  6502. inline bool redirect(T &cli, Request &req, Response &res,
  6503. const std::string &path, const std::string &location,
  6504. Error &error) {
  6505. Request new_req = req;
  6506. new_req.path = path;
  6507. new_req.redirect_count_ -= 1;
  6508. if (res.status == StatusCode::SeeOther_303 &&
  6509. (req.method != "GET" && req.method != "HEAD")) {
  6510. new_req.method = "GET";
  6511. new_req.body.clear();
  6512. new_req.headers.clear();
  6513. }
  6514. Response new_res;
  6515. auto ret = cli.send(new_req, new_res, error);
  6516. if (ret) {
  6517. req = std::move(new_req);
  6518. res = std::move(new_res);
  6519. if (res.location.empty()) { res.location = location; }
  6520. }
  6521. return ret;
  6522. }
  6523. inline std::string params_to_query_str(const Params &params) {
  6524. std::string query;
  6525. for (auto it = params.begin(); it != params.end(); ++it) {
  6526. if (it != params.begin()) { query += '&'; }
  6527. query += encode_query_component(it->first);
  6528. query += '=';
  6529. query += encode_query_component(it->second);
  6530. }
  6531. return query;
  6532. }
  6533. inline void parse_query_text(const char *data, std::size_t size,
  6534. Params &params) {
  6535. std::set<std::string> cache;
  6536. split(data, data + size, '&', [&](const char *b, const char *e) {
  6537. std::string kv(b, e);
  6538. if (cache.find(kv) != cache.end()) { return; }
  6539. cache.insert(std::move(kv));
  6540. std::string key;
  6541. std::string val;
  6542. divide(b, static_cast<std::size_t>(e - b), '=',
  6543. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6544. std::size_t rhs_size) {
  6545. key.assign(lhs_data, lhs_size);
  6546. val.assign(rhs_data, rhs_size);
  6547. });
  6548. if (!key.empty()) {
  6549. params.emplace(decode_query_component(key), decode_query_component(val));
  6550. }
  6551. });
  6552. }
  6553. inline void parse_query_text(const std::string &s, Params &params) {
  6554. parse_query_text(s.data(), s.size(), params);
  6555. }
  6556. // Normalize a query string by decoding and re-encoding each key/value pair
  6557. // while preserving the original parameter order. This avoids double-encoding
  6558. // and ensures consistent encoding without reordering (unlike Params which
  6559. // uses std::multimap and sorts keys).
  6560. inline std::string normalize_query_string(const std::string &query) {
  6561. std::string result;
  6562. split(query.data(), query.data() + query.size(), '&',
  6563. [&](const char *b, const char *e) {
  6564. std::string key;
  6565. std::string val;
  6566. divide(b, static_cast<std::size_t>(e - b), '=',
  6567. [&](const char *lhs_data, std::size_t lhs_size,
  6568. const char *rhs_data, std::size_t rhs_size) {
  6569. key.assign(lhs_data, lhs_size);
  6570. val.assign(rhs_data, rhs_size);
  6571. });
  6572. if (!key.empty()) {
  6573. auto dec_key = decode_query_component(key);
  6574. auto dec_val = decode_query_component(val);
  6575. if (!result.empty()) { result += '&'; }
  6576. result += encode_query_component(dec_key);
  6577. if (!val.empty() || std::find(b, e, '=') != e) {
  6578. result += '=';
  6579. result += encode_query_component(dec_val);
  6580. }
  6581. }
  6582. });
  6583. return result;
  6584. }
  6585. inline bool parse_multipart_boundary(const std::string &content_type,
  6586. std::string &boundary) {
  6587. std::map<std::string, std::string> params;
  6588. extract_media_type(content_type, &params);
  6589. auto it = params.find("boundary");
  6590. if (it == params.end()) { return false; }
  6591. boundary = it->second;
  6592. return !boundary.empty();
  6593. }
  6594. inline void parse_disposition_params(const std::string &s, Params &params) {
  6595. std::set<std::string> cache;
  6596. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6597. std::string kv(b, e);
  6598. if (cache.find(kv) != cache.end()) { return; }
  6599. cache.insert(kv);
  6600. std::string key;
  6601. std::string val;
  6602. split(b, e, '=', [&](const char *b2, const char *e2) {
  6603. if (key.empty()) {
  6604. key.assign(b2, e2);
  6605. } else {
  6606. val.assign(b2, e2);
  6607. }
  6608. });
  6609. if (!key.empty()) {
  6610. params.emplace(trim_double_quotes_copy((key)),
  6611. trim_double_quotes_copy((val)));
  6612. }
  6613. });
  6614. }
  6615. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6616. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6617. #else
  6618. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6619. #endif
  6620. auto is_valid = [](const std::string &str) {
  6621. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6622. };
  6623. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6624. const auto pos = static_cast<size_t>(6);
  6625. const auto len = static_cast<size_t>(s.size() - 6);
  6626. auto all_valid_ranges = true;
  6627. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6628. if (!all_valid_ranges) { return; }
  6629. const auto it = std::find(b, e, '-');
  6630. if (it == e) {
  6631. all_valid_ranges = false;
  6632. return;
  6633. }
  6634. const auto lhs = std::string(b, it);
  6635. const auto rhs = std::string(it + 1, e);
  6636. if (!is_valid(lhs) || !is_valid(rhs)) {
  6637. all_valid_ranges = false;
  6638. return;
  6639. }
  6640. ssize_t first = -1;
  6641. if (!lhs.empty()) {
  6642. ssize_t v;
  6643. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6644. if (res.ec == std::errc{}) { first = v; }
  6645. }
  6646. ssize_t last = -1;
  6647. if (!rhs.empty()) {
  6648. ssize_t v;
  6649. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6650. if (res.ec == std::errc{}) { last = v; }
  6651. }
  6652. if ((first == -1 && last == -1) ||
  6653. (first != -1 && last != -1 && first > last)) {
  6654. all_valid_ranges = false;
  6655. return;
  6656. }
  6657. ranges.emplace_back(first, last);
  6658. });
  6659. return all_valid_ranges && !ranges.empty();
  6660. }
  6661. return false;
  6662. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6663. }
  6664. #else
  6665. } catch (...) { return false; }
  6666. #endif
  6667. inline bool parse_accept_header(const std::string &s,
  6668. std::vector<std::string> &content_types) {
  6669. content_types.clear();
  6670. // Empty string is considered valid (no preference)
  6671. if (s.empty()) { return true; }
  6672. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6673. if (s.front() == ',' || s.back() == ',' ||
  6674. s.find(",,") != std::string::npos) {
  6675. return false;
  6676. }
  6677. struct AcceptEntry {
  6678. std::string media_type;
  6679. double quality;
  6680. int order;
  6681. };
  6682. std::vector<AcceptEntry> entries;
  6683. int order = 0;
  6684. bool has_invalid_entry = false;
  6685. // Split by comma and parse each entry
  6686. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6687. std::string entry(b, e);
  6688. entry = trim_copy(entry);
  6689. if (entry.empty()) {
  6690. has_invalid_entry = true;
  6691. return;
  6692. }
  6693. AcceptEntry accept_entry;
  6694. accept_entry.order = order++;
  6695. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6696. accept_entry.media_type, accept_entry.quality)) {
  6697. has_invalid_entry = true;
  6698. return;
  6699. }
  6700. // Remove additional parameters from media type
  6701. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6702. // Basic validation of media type format
  6703. if (accept_entry.media_type.empty()) {
  6704. has_invalid_entry = true;
  6705. return;
  6706. }
  6707. // Check for basic media type format (should contain '/' or be '*')
  6708. if (accept_entry.media_type != "*" &&
  6709. accept_entry.media_type.find('/') == std::string::npos) {
  6710. has_invalid_entry = true;
  6711. return;
  6712. }
  6713. entries.push_back(std::move(accept_entry));
  6714. });
  6715. // Return false if any invalid entry was found
  6716. if (has_invalid_entry) { return false; }
  6717. // Sort by quality (descending), then by original order (ascending)
  6718. std::sort(entries.begin(), entries.end(),
  6719. [](const AcceptEntry &a, const AcceptEntry &b) {
  6720. if (a.quality != b.quality) {
  6721. return a.quality > b.quality; // Higher quality first
  6722. }
  6723. return a.order < b.order; // Earlier order first for same quality
  6724. });
  6725. // Extract sorted media types
  6726. content_types.reserve(entries.size());
  6727. for (auto &entry : entries) {
  6728. content_types.push_back(std::move(entry.media_type));
  6729. }
  6730. return true;
  6731. }
  6732. class FormDataParser {
  6733. public:
  6734. FormDataParser() = default;
  6735. void set_boundary(std::string &&boundary) {
  6736. boundary_ = std::move(boundary);
  6737. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6738. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6739. }
  6740. bool is_valid() const { return is_valid_; }
  6741. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6742. const ContentReceiver &content_callback) {
  6743. buf_append(buf, n);
  6744. while (buf_size() > 0) {
  6745. switch (state_) {
  6746. case 0: { // Initial boundary
  6747. auto pos = buf_find(dash_boundary_crlf_);
  6748. if (pos == buf_size()) { return true; }
  6749. buf_erase(pos + dash_boundary_crlf_.size());
  6750. state_ = 1;
  6751. break;
  6752. }
  6753. case 1: { // New entry
  6754. clear_file_info();
  6755. state_ = 2;
  6756. break;
  6757. }
  6758. case 2: { // Headers
  6759. auto pos = buf_find(crlf_);
  6760. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6761. while (pos < buf_size()) {
  6762. // Empty line
  6763. if (pos == 0) {
  6764. if (!header_callback(file_)) {
  6765. is_valid_ = false;
  6766. return false;
  6767. }
  6768. buf_erase(crlf_.size());
  6769. state_ = 3;
  6770. break;
  6771. }
  6772. const auto header = buf_head(pos);
  6773. if (!parse_header(header.data(), header.data() + header.size(),
  6774. [&](const std::string &, const std::string &) {})) {
  6775. is_valid_ = false;
  6776. return false;
  6777. }
  6778. // Parse and emplace space trimmed headers into a map
  6779. if (!parse_header(
  6780. header.data(), header.data() + header.size(),
  6781. [&](const std::string &key, const std::string &val) {
  6782. file_.headers.emplace(key, val);
  6783. })) {
  6784. is_valid_ = false;
  6785. return false;
  6786. }
  6787. constexpr const char header_content_type[] = "Content-Type:";
  6788. if (start_with_case_ignore(header, header_content_type)) {
  6789. file_.content_type =
  6790. trim_copy(header.substr(str_len(header_content_type)));
  6791. } else {
  6792. std::string disposition_params;
  6793. if (parse_content_disposition(header, disposition_params)) {
  6794. Params params;
  6795. parse_disposition_params(disposition_params, params);
  6796. auto it = params.find("name");
  6797. if (it != params.end()) {
  6798. file_.name = it->second;
  6799. } else {
  6800. is_valid_ = false;
  6801. return false;
  6802. }
  6803. it = params.find("filename");
  6804. if (it != params.end()) { file_.filename = it->second; }
  6805. it = params.find("filename*");
  6806. if (it != params.end()) {
  6807. // RFC 5987: only UTF-8 encoding is allowed
  6808. const auto &val = it->second;
  6809. constexpr const char utf8_prefix[] = "UTF-8''";
  6810. constexpr size_t prefix_len = str_len(utf8_prefix);
  6811. if (val.size() > prefix_len &&
  6812. start_with_case_ignore(val, utf8_prefix)) {
  6813. file_.filename = decode_path_component(
  6814. val.substr(prefix_len)); // override...
  6815. } else {
  6816. is_valid_ = false;
  6817. return false;
  6818. }
  6819. }
  6820. }
  6821. }
  6822. buf_erase(pos + crlf_.size());
  6823. pos = buf_find(crlf_);
  6824. }
  6825. if (state_ != 3) { return true; }
  6826. break;
  6827. }
  6828. case 3: { // Body
  6829. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6830. auto pos = buf_find(crlf_dash_boundary_);
  6831. if (pos < buf_size()) {
  6832. if (!content_callback(buf_data(), pos)) {
  6833. is_valid_ = false;
  6834. return false;
  6835. }
  6836. buf_erase(pos + crlf_dash_boundary_.size());
  6837. state_ = 4;
  6838. } else {
  6839. auto len = buf_size() - crlf_dash_boundary_.size();
  6840. if (len > 0) {
  6841. if (!content_callback(buf_data(), len)) {
  6842. is_valid_ = false;
  6843. return false;
  6844. }
  6845. buf_erase(len);
  6846. }
  6847. return true;
  6848. }
  6849. break;
  6850. }
  6851. case 4: { // Boundary
  6852. if (crlf_.size() > buf_size()) { return true; }
  6853. if (buf_start_with(crlf_)) {
  6854. buf_erase(crlf_.size());
  6855. state_ = 1;
  6856. } else {
  6857. if (dash_.size() > buf_size()) { return true; }
  6858. if (buf_start_with(dash_)) {
  6859. buf_erase(dash_.size());
  6860. is_valid_ = true;
  6861. buf_erase(buf_size()); // Remove epilogue
  6862. } else {
  6863. return true;
  6864. }
  6865. }
  6866. break;
  6867. }
  6868. }
  6869. }
  6870. return true;
  6871. }
  6872. private:
  6873. void clear_file_info() {
  6874. file_.name.clear();
  6875. file_.filename.clear();
  6876. file_.content_type.clear();
  6877. file_.headers.clear();
  6878. }
  6879. bool start_with_case_ignore(const std::string &a, const char *b,
  6880. size_t offset = 0) const {
  6881. const auto b_len = strlen(b);
  6882. if (a.size() < offset + b_len) { return false; }
  6883. for (size_t i = 0; i < b_len; i++) {
  6884. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6885. return false;
  6886. }
  6887. }
  6888. return true;
  6889. }
  6890. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6891. // Returns true if header matches, with the params portion in `params_out`.
  6892. bool parse_content_disposition(const std::string &header,
  6893. std::string &params_out) const {
  6894. constexpr const char prefix[] = "Content-Disposition:";
  6895. constexpr size_t prefix_len = str_len(prefix);
  6896. if (!start_with_case_ignore(header, prefix)) { return false; }
  6897. // Skip whitespace after "Content-Disposition:"
  6898. auto pos = prefix_len;
  6899. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6900. pos++;
  6901. }
  6902. // Match "form-data;" (case-insensitive)
  6903. constexpr const char form_data[] = "form-data;";
  6904. constexpr size_t form_data_len = str_len(form_data);
  6905. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6906. pos += form_data_len;
  6907. // Skip whitespace after "form-data;"
  6908. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6909. pos++;
  6910. }
  6911. params_out = header.substr(pos);
  6912. return true;
  6913. }
  6914. const std::string dash_ = "--";
  6915. const std::string crlf_ = "\r\n";
  6916. std::string boundary_;
  6917. std::string dash_boundary_crlf_;
  6918. std::string crlf_dash_boundary_;
  6919. size_t state_ = 0;
  6920. bool is_valid_ = false;
  6921. FormData file_;
  6922. // Buffer
  6923. bool start_with(const std::string &a, size_t spos, size_t epos,
  6924. const std::string &b) const {
  6925. if (epos - spos < b.size()) { return false; }
  6926. for (size_t i = 0; i < b.size(); i++) {
  6927. if (a[i + spos] != b[i]) { return false; }
  6928. }
  6929. return true;
  6930. }
  6931. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6932. const char *buf_data() const { return &buf_[buf_spos_]; }
  6933. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6934. bool buf_start_with(const std::string &s) const {
  6935. return start_with(buf_, buf_spos_, buf_epos_, s);
  6936. }
  6937. size_t buf_find(const std::string &s) const {
  6938. auto c = s.front();
  6939. size_t off = buf_spos_;
  6940. while (off < buf_epos_) {
  6941. auto pos = off;
  6942. while (true) {
  6943. if (pos == buf_epos_) { return buf_size(); }
  6944. if (buf_[pos] == c) { break; }
  6945. pos++;
  6946. }
  6947. auto remaining_size = buf_epos_ - pos;
  6948. if (s.size() > remaining_size) { return buf_size(); }
  6949. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6950. off = pos + 1;
  6951. }
  6952. return buf_size();
  6953. }
  6954. void buf_append(const char *data, size_t n) {
  6955. auto remaining_size = buf_size();
  6956. if (remaining_size > 0 && buf_spos_ > 0) {
  6957. for (size_t i = 0; i < remaining_size; i++) {
  6958. buf_[i] = buf_[buf_spos_ + i];
  6959. }
  6960. }
  6961. buf_spos_ = 0;
  6962. buf_epos_ = remaining_size;
  6963. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6964. for (size_t i = 0; i < n; i++) {
  6965. buf_[buf_epos_ + i] = data[i];
  6966. }
  6967. buf_epos_ += n;
  6968. }
  6969. void buf_erase(size_t size) { buf_spos_ += size; }
  6970. std::string buf_;
  6971. size_t buf_spos_ = 0;
  6972. size_t buf_epos_ = 0;
  6973. };
  6974. inline std::string random_string(size_t length) {
  6975. constexpr const char data[] =
  6976. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6977. thread_local auto engine([]() {
  6978. // std::random_device might actually be deterministic on some
  6979. // platforms, but due to lack of support in the c++ standard library,
  6980. // doing better requires either some ugly hacks or breaking portability.
  6981. std::random_device seed_gen;
  6982. // Request 128 bits of entropy for initialization
  6983. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6984. return std::mt19937(seed_sequence);
  6985. }());
  6986. std::string result;
  6987. for (size_t i = 0; i < length; i++) {
  6988. result += data[engine() % (sizeof(data) - 1)];
  6989. }
  6990. return result;
  6991. }
  6992. inline std::string make_multipart_data_boundary() {
  6993. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6994. }
  6995. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6996. auto valid = true;
  6997. for (size_t i = 0; i < boundary.size(); i++) {
  6998. auto c = boundary[i];
  6999. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  7000. valid = false;
  7001. break;
  7002. }
  7003. }
  7004. return valid;
  7005. }
  7006. // Escape a multipart field name/filename following the WHATWG HTML standard
  7007. // ("escape a multipart form-data name"), which is what browsers send:
  7008. // '"' -> %22, CR -> %0D, LF -> %0A
  7009. // With escape_quote = false, only CR and LF are escaped; this is for header
  7010. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  7011. inline std::string escape_multipart_field(const std::string &s,
  7012. bool escape_quote = true) {
  7013. std::string result;
  7014. result.reserve(s.size());
  7015. for (auto c : s) {
  7016. switch (c) {
  7017. case '"':
  7018. if (escape_quote) {
  7019. result += "%22";
  7020. } else {
  7021. result += c;
  7022. }
  7023. break;
  7024. case '\r': result += "%0D"; break;
  7025. case '\n': result += "%0A"; break;
  7026. default: result += c; break;
  7027. }
  7028. }
  7029. return result;
  7030. }
  7031. template <typename T>
  7032. inline std::string
  7033. serialize_multipart_formdata_item_begin(const T &item,
  7034. const std::string &boundary) {
  7035. std::string body = "--" + boundary + "\r\n";
  7036. body += "Content-Disposition: form-data; name=\"" +
  7037. escape_multipart_field(item.name) + "\"";
  7038. if (!item.filename.empty()) {
  7039. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  7040. }
  7041. body += "\r\n";
  7042. if (!item.content_type.empty()) {
  7043. body +=
  7044. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  7045. "\r\n";
  7046. }
  7047. body += "\r\n";
  7048. return body;
  7049. }
  7050. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  7051. inline std::string
  7052. serialize_multipart_formdata_finish(const std::string &boundary) {
  7053. return "--" + boundary + "--\r\n";
  7054. }
  7055. inline std::string
  7056. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7057. return "multipart/form-data; boundary=" + boundary;
  7058. }
  7059. inline std::string
  7060. serialize_multipart_formdata(const UploadFormDataItems &items,
  7061. const std::string &boundary, bool finish = true) {
  7062. std::string body;
  7063. for (const auto &item : items) {
  7064. body += serialize_multipart_formdata_item_begin(item, boundary);
  7065. body += item.content + serialize_multipart_formdata_item_end();
  7066. }
  7067. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7068. return body;
  7069. }
  7070. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7071. const std::string &boundary) {
  7072. size_t total = 0;
  7073. for (const auto &item : items) {
  7074. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7075. total += item.content.size();
  7076. total += serialize_multipart_formdata_item_end().size();
  7077. }
  7078. total += serialize_multipart_formdata_finish(boundary).size();
  7079. return total;
  7080. }
  7081. struct MultipartSegment {
  7082. const char *data;
  7083. size_t size;
  7084. };
  7085. // NOTE: items must outlive the returned ContentProvider
  7086. // (safe for synchronous use inside Post/Put/Patch)
  7087. inline ContentProvider
  7088. make_multipart_content_provider(const UploadFormDataItems &items,
  7089. const std::string &boundary) {
  7090. // Own the per-item header strings and the finish string
  7091. std::vector<std::string> owned;
  7092. owned.reserve(items.size() + 1);
  7093. for (const auto &item : items)
  7094. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7095. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7096. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7097. std::vector<MultipartSegment> segs;
  7098. segs.reserve(items.size() * 3 + 1);
  7099. static const char crlf[] = "\r\n";
  7100. for (size_t i = 0; i < items.size(); i++) {
  7101. segs.push_back({owned[i].data(), owned[i].size()});
  7102. segs.push_back({items[i].content.data(), items[i].content.size()});
  7103. segs.push_back({crlf, 2});
  7104. }
  7105. segs.push_back({owned.back().data(), owned.back().size()});
  7106. struct MultipartState {
  7107. std::vector<std::string> owned;
  7108. std::vector<MultipartSegment> segs;
  7109. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7110. };
  7111. auto state = std::make_shared<MultipartState>();
  7112. state->owned = std::move(owned);
  7113. // `segs` holds raw pointers into owned strings; std::string move preserves
  7114. // the data pointer, so these pointers remain valid after the move above.
  7115. state->segs = std::move(segs);
  7116. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7117. // Buffer multiple small segments into fewer, larger writes to avoid
  7118. // excessive TCP packets when there are many form data items (#2410)
  7119. auto &buf = state->buf;
  7120. auto buf_size = buf.size();
  7121. size_t buf_len = 0;
  7122. size_t remaining = length;
  7123. // Find the first segment containing 'offset'
  7124. size_t pos = 0;
  7125. size_t seg_idx = 0;
  7126. for (; seg_idx < state->segs.size(); seg_idx++) {
  7127. const auto &seg = state->segs[seg_idx];
  7128. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7129. pos += seg.size;
  7130. }
  7131. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7132. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7133. const auto &seg = state->segs[seg_idx];
  7134. size_t available = seg.size - seg_offset;
  7135. size_t to_copy = (std::min)(available, remaining);
  7136. const char *src = seg.data + seg_offset;
  7137. seg_offset = 0; // only the first segment has a non-zero offset
  7138. while (to_copy > 0) {
  7139. size_t space = buf_size - buf_len;
  7140. size_t chunk = (std::min)(to_copy, space);
  7141. std::memcpy(buf.data() + buf_len, src, chunk);
  7142. buf_len += chunk;
  7143. src += chunk;
  7144. to_copy -= chunk;
  7145. remaining -= chunk;
  7146. if (buf_len == buf_size) {
  7147. if (!sink.write(buf.data(), buf_len)) { return false; }
  7148. buf_len = 0;
  7149. }
  7150. }
  7151. }
  7152. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7153. return true;
  7154. };
  7155. }
  7156. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7157. if (ranges.size() <= 1) return;
  7158. // Sort ranges by start position
  7159. std::sort(ranges.begin(), ranges.end(),
  7160. [](const Range &a, const Range &b) { return a.first < b.first; });
  7161. Ranges coalesced;
  7162. coalesced.reserve(ranges.size());
  7163. for (auto &r : ranges) {
  7164. auto first_pos = r.first;
  7165. auto last_pos = r.second;
  7166. // Handle special cases like in range_error
  7167. if (first_pos == -1 && last_pos == -1) {
  7168. first_pos = 0;
  7169. last_pos = static_cast<ssize_t>(content_length);
  7170. }
  7171. if (first_pos == -1) {
  7172. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7173. last_pos = static_cast<ssize_t>(content_length) - 1;
  7174. }
  7175. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7176. last_pos = static_cast<ssize_t>(content_length) - 1;
  7177. }
  7178. // Skip invalid ranges
  7179. if (!(0 <= first_pos && first_pos <= last_pos &&
  7180. last_pos < static_cast<ssize_t>(content_length))) {
  7181. continue;
  7182. }
  7183. // Coalesce with previous range if overlapping or adjacent (but not
  7184. // identical)
  7185. if (!coalesced.empty()) {
  7186. auto &prev = coalesced.back();
  7187. // Check if current range overlaps or is adjacent to previous range
  7188. // but don't coalesce identical ranges (allow duplicates)
  7189. if (first_pos <= prev.second + 1 &&
  7190. !(first_pos == prev.first && last_pos == prev.second)) {
  7191. // Extend the previous range
  7192. prev.second = (std::max)(prev.second, last_pos);
  7193. continue;
  7194. }
  7195. }
  7196. // Add new range
  7197. coalesced.emplace_back(first_pos, last_pos);
  7198. }
  7199. ranges = std::move(coalesced);
  7200. }
  7201. inline bool range_error(Request &req, Response &res) {
  7202. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7203. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7204. req.ranges.clear();
  7205. if (res.status == StatusCode::PartialContent_206) {
  7206. res.status = StatusCode::OK_200;
  7207. }
  7208. return false;
  7209. }
  7210. ssize_t content_len = static_cast<ssize_t>(
  7211. res.content_length_ ? res.content_length_ : res.body.size());
  7212. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7213. size_t overwrapping_count = 0;
  7214. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7215. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7216. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7217. // Too many ranges
  7218. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7219. for (auto &r : req.ranges) {
  7220. auto &first_pos = r.first;
  7221. auto &last_pos = r.second;
  7222. if (first_pos == -1 && last_pos == -1) {
  7223. first_pos = 0;
  7224. last_pos = content_len;
  7225. }
  7226. if (first_pos == -1) {
  7227. first_pos = content_len - last_pos;
  7228. last_pos = content_len - 1;
  7229. }
  7230. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7231. // A client can limit the number of bytes requested without knowing the
  7232. // size of the selected representation. If the last-pos value is absent,
  7233. // or if the value is greater than or equal to the current length of the
  7234. // representation data, the byte range is interpreted as the remainder of
  7235. // the representation (i.e., the server replaces the value of last-pos
  7236. // with a value that is one less than the current length of the selected
  7237. // representation).
  7238. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7239. if (last_pos == -1 || last_pos >= content_len) {
  7240. last_pos = content_len - 1;
  7241. }
  7242. // Range must be within content length
  7243. if (!(0 <= first_pos && first_pos <= last_pos &&
  7244. last_pos <= content_len - 1)) {
  7245. return true;
  7246. }
  7247. // Request must not have more than two overlapping ranges
  7248. for (const auto &processed_range : processed_ranges) {
  7249. if (!(last_pos < processed_range.first ||
  7250. first_pos > processed_range.second)) {
  7251. overwrapping_count++;
  7252. if (overwrapping_count > 2) { return true; }
  7253. break; // Only count once per range
  7254. }
  7255. }
  7256. processed_ranges.emplace_back(first_pos, last_pos);
  7257. }
  7258. // After validation, coalesce overlapping ranges as per RFC 9110
  7259. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7260. }
  7261. return false;
  7262. }
  7263. inline std::pair<size_t, size_t>
  7264. get_range_offset_and_length(Range r, size_t content_length) {
  7265. assert(r.first != -1 && r.second != -1);
  7266. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7267. assert(r.first <= r.second &&
  7268. r.second < static_cast<ssize_t>(content_length));
  7269. (void)(content_length);
  7270. return std::make_pair(static_cast<size_t>(r.first),
  7271. static_cast<size_t>(r.second - r.first) + 1);
  7272. }
  7273. inline std::string make_content_range_header_field(
  7274. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7275. auto st = offset_and_length.first;
  7276. auto ed = st + offset_and_length.second - 1;
  7277. std::string field = "bytes ";
  7278. field += std::to_string(st);
  7279. field += '-';
  7280. field += std::to_string(ed);
  7281. field += '/';
  7282. field += std::to_string(content_length);
  7283. return field;
  7284. }
  7285. template <typename SToken, typename CToken, typename Content>
  7286. bool process_multipart_ranges_data(const Request &req,
  7287. const std::string &boundary,
  7288. const std::string &content_type,
  7289. size_t content_length, SToken stoken,
  7290. CToken ctoken, Content content) {
  7291. for (size_t i = 0; i < req.ranges.size(); i++) {
  7292. ctoken("--");
  7293. stoken(boundary);
  7294. ctoken("\r\n");
  7295. if (!content_type.empty()) {
  7296. ctoken("Content-Type: ");
  7297. stoken(content_type);
  7298. ctoken("\r\n");
  7299. }
  7300. auto offset_and_length =
  7301. get_range_offset_and_length(req.ranges[i], content_length);
  7302. ctoken("Content-Range: ");
  7303. stoken(make_content_range_header_field(offset_and_length, content_length));
  7304. ctoken("\r\n");
  7305. ctoken("\r\n");
  7306. if (!content(offset_and_length.first, offset_and_length.second)) {
  7307. return false;
  7308. }
  7309. ctoken("\r\n");
  7310. }
  7311. ctoken("--");
  7312. stoken(boundary);
  7313. ctoken("--");
  7314. return true;
  7315. }
  7316. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7317. const std::string &boundary,
  7318. const std::string &content_type,
  7319. size_t content_length,
  7320. std::string &data) {
  7321. process_multipart_ranges_data(
  7322. req, boundary, content_type, content_length,
  7323. [&](const std::string &token) { data += token; },
  7324. [&](const std::string &token) { data += token; },
  7325. [&](size_t offset, size_t length) {
  7326. assert(offset + length <= content_length);
  7327. data += res.body.substr(offset, length);
  7328. return true;
  7329. });
  7330. }
  7331. inline size_t get_multipart_ranges_data_length(const Request &req,
  7332. const std::string &boundary,
  7333. const std::string &content_type,
  7334. size_t content_length) {
  7335. size_t data_length = 0;
  7336. process_multipart_ranges_data(
  7337. req, boundary, content_type, content_length,
  7338. [&](const std::string &token) { data_length += token.size(); },
  7339. [&](const std::string &token) { data_length += token.size(); },
  7340. [&](size_t /*offset*/, size_t length) {
  7341. data_length += length;
  7342. return true;
  7343. });
  7344. return data_length;
  7345. }
  7346. template <typename T>
  7347. inline bool
  7348. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7349. const std::string &boundary,
  7350. const std::string &content_type,
  7351. size_t content_length, const T &is_shutting_down) {
  7352. return process_multipart_ranges_data(
  7353. req, boundary, content_type, content_length,
  7354. [&](const std::string &token) { strm.write(token); },
  7355. [&](const std::string &token) { strm.write(token); },
  7356. [&](size_t offset, size_t length) {
  7357. return write_content(strm, res.content_provider_, offset, length,
  7358. is_shutting_down);
  7359. });
  7360. }
  7361. inline bool has_framed_body(const Request &req) {
  7362. return is_chunked_transfer_encoding(req.headers) ||
  7363. req.get_header_value_u64("Content-Length") > 0;
  7364. }
  7365. inline bool is_connection_persistent(const Request &req) {
  7366. auto conn = req.get_header_value("Connection");
  7367. if (conn == "close") { return false; }
  7368. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7369. return true;
  7370. }
  7371. inline bool expect_content(const Request &req) {
  7372. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7373. req.method == "DELETE") {
  7374. return true;
  7375. }
  7376. return has_framed_body(req);
  7377. }
  7378. #ifdef _WIN32
  7379. class WSInit {
  7380. public:
  7381. WSInit() {
  7382. WSADATA wsaData;
  7383. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7384. }
  7385. ~WSInit() {
  7386. if (is_valid_) WSACleanup();
  7387. }
  7388. bool is_valid_ = false;
  7389. };
  7390. static WSInit wsinit_;
  7391. #endif
  7392. inline bool parse_www_authenticate(const Response &res,
  7393. std::map<std::string, std::string> &auth,
  7394. bool is_proxy) {
  7395. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7396. if (res.has_header(auth_key)) {
  7397. thread_local auto re =
  7398. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7399. auto s = res.get_header_value(auth_key);
  7400. auto pos = s.find(' ');
  7401. if (pos != std::string::npos) {
  7402. auto type = s.substr(0, pos);
  7403. if (type == "Basic") {
  7404. return false;
  7405. } else if (type == "Digest") {
  7406. s = s.substr(pos + 1);
  7407. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7408. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7409. const auto &m = *i;
  7410. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7411. static_cast<size_t>(m.length(1)));
  7412. auto val = m.length(2) > 0
  7413. ? s.substr(static_cast<size_t>(m.position(2)),
  7414. static_cast<size_t>(m.length(2)))
  7415. : s.substr(static_cast<size_t>(m.position(3)),
  7416. static_cast<size_t>(m.length(3)));
  7417. auth[std::move(key)] = std::move(val);
  7418. }
  7419. return true;
  7420. }
  7421. }
  7422. }
  7423. return false;
  7424. }
  7425. class ContentProviderAdapter {
  7426. public:
  7427. explicit ContentProviderAdapter(
  7428. ContentProviderWithoutLength &&content_provider)
  7429. : content_provider_(std::move(content_provider)) {}
  7430. bool operator()(size_t offset, size_t, DataSink &sink) {
  7431. return content_provider_(offset, sink);
  7432. }
  7433. private:
  7434. ContentProviderWithoutLength content_provider_;
  7435. };
  7436. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7437. namespace fields {
  7438. inline bool is_token_char(char c) {
  7439. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7440. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7441. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7442. }
  7443. inline bool is_token(const std::string &s) {
  7444. if (s.empty()) { return false; }
  7445. for (auto c : s) {
  7446. if (!is_token_char(c)) { return false; }
  7447. }
  7448. return true;
  7449. }
  7450. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7451. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7452. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7453. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7454. inline bool is_field_content(const std::string &s) {
  7455. if (s.empty()) { return true; }
  7456. if (s.size() == 1) {
  7457. return is_field_vchar(s[0]);
  7458. } else if (s.size() == 2) {
  7459. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7460. } else {
  7461. size_t i = 0;
  7462. if (!is_field_vchar(s[i])) { return false; }
  7463. i++;
  7464. while (i < s.size() - 1) {
  7465. auto c = s[i++];
  7466. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7467. } else {
  7468. return false;
  7469. }
  7470. }
  7471. return is_field_vchar(s[i]);
  7472. }
  7473. }
  7474. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7475. } // namespace fields
  7476. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7477. int port, bool is_ssl,
  7478. const std::string &path,
  7479. const Headers &headers,
  7480. std::string &selected_subprotocol) {
  7481. // Validate path and host
  7482. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7483. return false;
  7484. }
  7485. // Validate user-provided headers
  7486. for (const auto &h : headers) {
  7487. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7488. return false;
  7489. }
  7490. }
  7491. // Generate random Sec-WebSocket-Key
  7492. thread_local std::mt19937 rng(std::random_device{}());
  7493. std::string key_bytes(16, '\0');
  7494. for (size_t i = 0; i < 16; i += 4) {
  7495. auto r = rng();
  7496. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7497. }
  7498. auto client_key = base64_encode(key_bytes);
  7499. // Build upgrade request
  7500. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7501. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7502. req_str += "Upgrade: websocket\r\n";
  7503. req_str += "Connection: Upgrade\r\n";
  7504. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7505. req_str += "Sec-WebSocket-Version: 13\r\n";
  7506. for (const auto &h : headers) {
  7507. req_str += h.first + ": " + h.second + "\r\n";
  7508. }
  7509. req_str += "\r\n";
  7510. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7511. // Verify 101 response and Sec-WebSocket-Accept header
  7512. auto expected_accept = websocket_accept_key(client_key);
  7513. return read_websocket_upgrade_response(strm, expected_accept,
  7514. selected_subprotocol);
  7515. }
  7516. } // namespace detail
  7517. /*
  7518. * Group 2: detail namespace - SSL common utilities
  7519. */
  7520. #ifdef CPPHTTPLIB_SSL_ENABLED
  7521. namespace detail {
  7522. class SSLSocketStream final : public Stream {
  7523. public:
  7524. SSLSocketStream(
  7525. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7526. time_t read_timeout_usec, time_t write_timeout_sec,
  7527. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7528. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7529. (std::chrono::steady_clock::time_point::min)());
  7530. ~SSLSocketStream() override;
  7531. bool is_readable() const override;
  7532. bool wait_readable() const override;
  7533. bool wait_writable() const override;
  7534. bool is_peer_alive() const override;
  7535. ssize_t read(char *ptr, size_t size) override;
  7536. ssize_t write(const char *ptr, size_t size) override;
  7537. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7538. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7539. socket_t socket() const override;
  7540. time_t duration() const override;
  7541. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7542. private:
  7543. socket_t sock_;
  7544. tls::session_t session_;
  7545. time_t read_timeout_sec_;
  7546. time_t read_timeout_usec_;
  7547. time_t write_timeout_sec_;
  7548. time_t write_timeout_usec_;
  7549. time_t max_timeout_msec_;
  7550. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7551. };
  7552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7553. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7554. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7555. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7556. unsigned int hash_length = 0;
  7557. unsigned char hash[EVP_MAX_MD_SIZE];
  7558. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7559. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7560. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7561. std::stringstream ss;
  7562. for (auto i = 0u; i < hash_length; ++i) {
  7563. ss << std::hex << std::setw(2) << std::setfill('0')
  7564. << static_cast<unsigned int>(hash[i]);
  7565. }
  7566. return ss.str();
  7567. }
  7568. inline std::string MD5(const std::string &s) {
  7569. return message_digest(s, EVP_md5());
  7570. }
  7571. inline std::string SHA_256(const std::string &s) {
  7572. return message_digest(s, EVP_sha256());
  7573. }
  7574. inline std::string SHA_512(const std::string &s) {
  7575. return message_digest(s, EVP_sha512());
  7576. }
  7577. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7578. namespace {
  7579. template <size_t N>
  7580. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7581. std::stringstream ss;
  7582. for (size_t i = 0; i < N; ++i) {
  7583. ss << std::hex << std::setw(2) << std::setfill('0')
  7584. << static_cast<unsigned int>(hash[i]);
  7585. }
  7586. return ss.str();
  7587. }
  7588. } // namespace
  7589. inline std::string MD5(const std::string &s) {
  7590. unsigned char hash[16];
  7591. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7592. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7593. hash);
  7594. #else
  7595. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7596. hash);
  7597. #endif
  7598. return hash_to_hex(hash);
  7599. }
  7600. inline std::string SHA_256(const std::string &s) {
  7601. unsigned char hash[32];
  7602. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7603. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7604. hash, 0);
  7605. #else
  7606. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7607. s.size(), hash, 0);
  7608. #endif
  7609. return hash_to_hex(hash);
  7610. }
  7611. inline std::string SHA_512(const std::string &s) {
  7612. unsigned char hash[64];
  7613. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7614. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7615. hash, 0);
  7616. #else
  7617. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7618. s.size(), hash, 0);
  7619. #endif
  7620. return hash_to_hex(hash);
  7621. }
  7622. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7623. namespace {
  7624. template <size_t N>
  7625. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7626. std::stringstream ss;
  7627. for (size_t i = 0; i < N; ++i) {
  7628. ss << std::hex << std::setw(2) << std::setfill('0')
  7629. << static_cast<unsigned int>(hash[i]);
  7630. }
  7631. return ss.str();
  7632. }
  7633. } // namespace
  7634. inline std::string MD5(const std::string &s) {
  7635. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7636. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7637. static_cast<word32>(s.size()), hash);
  7638. return hash_to_hex(hash);
  7639. }
  7640. inline std::string SHA_256(const std::string &s) {
  7641. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7642. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7643. static_cast<word32>(s.size()), hash);
  7644. return hash_to_hex(hash);
  7645. }
  7646. inline std::string SHA_512(const std::string &s) {
  7647. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7648. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7649. static_cast<word32>(s.size()), hash);
  7650. return hash_to_hex(hash);
  7651. }
  7652. #endif
  7653. inline bool is_ip_address(const std::string &host) {
  7654. struct in_addr addr4;
  7655. struct in6_addr addr6;
  7656. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7657. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7658. }
  7659. template <typename T>
  7660. inline bool process_server_socket_ssl(
  7661. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7662. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7663. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7664. time_t write_timeout_usec, T callback) {
  7665. return process_server_socket_core(
  7666. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7667. [&](bool close_connection, bool &connection_closed) {
  7668. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7669. write_timeout_sec, write_timeout_usec);
  7670. return callback(strm, close_connection, connection_closed);
  7671. });
  7672. }
  7673. template <typename T>
  7674. inline bool process_client_socket_ssl(
  7675. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7676. time_t read_timeout_usec, time_t write_timeout_sec,
  7677. time_t write_timeout_usec, time_t max_timeout_msec,
  7678. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7679. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7680. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7681. start_time);
  7682. return callback(strm);
  7683. }
  7684. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7685. const Request &req, const std::map<std::string, std::string> &auth,
  7686. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7687. const std::string &password, bool is_proxy = false) {
  7688. std::string nc;
  7689. {
  7690. std::stringstream ss;
  7691. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7692. nc = ss.str();
  7693. }
  7694. std::string qop;
  7695. if (auth.find("qop") != auth.end()) {
  7696. qop = auth.at("qop");
  7697. if (qop.find("auth-int") != std::string::npos) {
  7698. qop = "auth-int";
  7699. } else if (qop.find("auth") != std::string::npos) {
  7700. qop = "auth";
  7701. } else {
  7702. qop.clear();
  7703. }
  7704. }
  7705. std::string algo = "MD5";
  7706. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7707. std::string response;
  7708. {
  7709. auto H = algo == "SHA-256" ? detail::SHA_256
  7710. : algo == "SHA-512" ? detail::SHA_512
  7711. : detail::MD5;
  7712. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7713. auto A2 = req.method + ":" + req.path;
  7714. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7715. if (qop.empty()) {
  7716. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7717. } else {
  7718. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7719. ":" + qop + ":" + H(A2));
  7720. }
  7721. }
  7722. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7723. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7724. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7725. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7726. (qop.empty() ? ", response=\""
  7727. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7728. cnonce + "\", response=\"") +
  7729. response + "\"" +
  7730. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7731. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7732. return std::make_pair(key, field);
  7733. }
  7734. inline bool match_hostname(const std::string &pattern,
  7735. const std::string &hostname) {
  7736. // Exact match (case-insensitive)
  7737. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7738. // Split both pattern and hostname into components by '.'
  7739. std::vector<std::string> pattern_components;
  7740. if (!pattern.empty()) {
  7741. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7742. [&](const char *b, const char *e) {
  7743. pattern_components.emplace_back(b, e);
  7744. });
  7745. }
  7746. std::vector<std::string> host_components;
  7747. if (!hostname.empty()) {
  7748. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7749. [&](const char *b, const char *e) {
  7750. host_components.emplace_back(b, e);
  7751. });
  7752. }
  7753. // Component count must match
  7754. if (host_components.size() != pattern_components.size()) { return false; }
  7755. // Compare each component with wildcard support
  7756. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7757. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7758. auto itr = pattern_components.begin();
  7759. for (const auto &h : host_components) {
  7760. auto &p = *itr;
  7761. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7762. bool partial_match = false;
  7763. if (!p.empty() && p[p.size() - 1] == '*') {
  7764. const auto prefix_length = p.size() - 1;
  7765. if (prefix_length == 0) {
  7766. partial_match = true;
  7767. } else if (h.size() >= prefix_length) {
  7768. partial_match =
  7769. std::equal(p.begin(),
  7770. p.begin() + static_cast<std::string::difference_type>(
  7771. prefix_length),
  7772. h.begin(), [](const char ca, const char cb) {
  7773. return detail::case_ignore::to_lower(ca) ==
  7774. detail::case_ignore::to_lower(cb);
  7775. });
  7776. }
  7777. }
  7778. if (!partial_match) { return false; }
  7779. }
  7780. ++itr;
  7781. }
  7782. return true;
  7783. }
  7784. #ifdef _WIN32
  7785. // Verify certificate using Windows CertGetCertificateChain API.
  7786. // This provides real-time certificate validation with Windows Update
  7787. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7788. inline bool
  7789. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7790. const std::string &hostname,
  7791. bool verify_hostname, uint64_t &out_error) {
  7792. if (der_cert.empty()) { return false; }
  7793. out_error = 0;
  7794. // Create Windows certificate context from DER data
  7795. auto cert_context = CertCreateCertificateContext(
  7796. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7797. static_cast<DWORD>(der_cert.size()));
  7798. if (!cert_context) {
  7799. out_error = GetLastError();
  7800. return false;
  7801. }
  7802. auto cert_guard =
  7803. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7804. // Setup chain parameters
  7805. CERT_CHAIN_PARA chain_para = {};
  7806. chain_para.cbSize = sizeof(chain_para);
  7807. // Build certificate chain with revocation checking
  7808. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7809. auto chain_result = CertGetCertificateChain(
  7810. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7811. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7812. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7813. nullptr, &chain_context);
  7814. if (!chain_result || !chain_context) {
  7815. out_error = GetLastError();
  7816. return false;
  7817. }
  7818. auto chain_guard =
  7819. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7820. // Check if chain has errors
  7821. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7822. out_error = chain_context->TrustStatus.dwErrorStatus;
  7823. return false;
  7824. }
  7825. // Verify SSL policy
  7826. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7827. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7828. #ifdef AUTHTYPE_SERVER
  7829. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7830. #endif
  7831. std::wstring whost;
  7832. if (verify_hostname) {
  7833. whost = u8string_to_wstring(hostname.c_str());
  7834. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7835. }
  7836. CERT_CHAIN_POLICY_PARA policy_para = {};
  7837. policy_para.cbSize = sizeof(policy_para);
  7838. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7839. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7840. #else
  7841. policy_para.dwFlags = 0;
  7842. #endif
  7843. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7844. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7845. policy_status.cbSize = sizeof(policy_status);
  7846. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7847. &policy_para, &policy_status)) {
  7848. out_error = GetLastError();
  7849. return false;
  7850. }
  7851. if (policy_status.dwError != 0) {
  7852. out_error = policy_status.dwError;
  7853. return false;
  7854. }
  7855. return true;
  7856. }
  7857. #endif // _WIN32
  7858. // Loads CA file/dir configuration and applies the system CA policy to a
  7859. // client TLS context. PEM data and native stores are applied to the context
  7860. // directly at set time; has_custom_store reflects them for the Auto policy
  7861. // decision.
  7862. inline bool load_client_ca_config(tls::ctx_t ctx,
  7863. const std::string &ca_cert_file_path,
  7864. const std::string &ca_cert_dir_path,
  7865. bool has_custom_store, SystemCAMode mode,
  7866. uint64_t &backend_error) {
  7867. auto ret = true;
  7868. if (!ca_cert_file_path.empty()) {
  7869. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7870. backend_error = tls::get_error();
  7871. ret = false;
  7872. }
  7873. } else if (!ca_cert_dir_path.empty()) {
  7874. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7875. backend_error = tls::get_error();
  7876. ret = false;
  7877. }
  7878. }
  7879. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7880. !ca_cert_dir_path.empty() || has_custom_store;
  7881. if (mode == SystemCAMode::Enabled ||
  7882. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7883. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7884. }
  7885. return ret;
  7886. }
  7887. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7888. tls::session_t &session, socket_t sock,
  7889. bool server_certificate_verification,
  7890. time_t timeout_sec, time_t timeout_usec) {
  7891. using namespace tls;
  7892. if (!ctx) { return false; }
  7893. bool is_ip = is_ip_address(host);
  7894. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7895. // Chain verification happens during the handshake even for IP hosts; the
  7896. // certificate identity is verified post-handshake via verify_hostname()
  7897. set_verify_client(ctx, server_certificate_verification);
  7898. #endif
  7899. session = create_session(ctx, sock);
  7900. if (!session) { return false; }
  7901. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7902. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7903. // their identity is checked post-handshake below instead.
  7904. if (!is_ip) {
  7905. if (server_certificate_verification) {
  7906. set_hostname(session, host.c_str());
  7907. } else {
  7908. set_sni(session, host.c_str());
  7909. }
  7910. }
  7911. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7912. return false;
  7913. }
  7914. if (server_certificate_verification) {
  7915. if (get_verify_result(session) != 0) { return false; }
  7916. // Identity check against the peer certificate, post-handshake for all
  7917. // backends (same as SSLClient). For IP hosts this is the only identity
  7918. // verification since no hostname is bound during the handshake.
  7919. auto server_cert = get_peer_cert(session);
  7920. if (!server_cert) { return false; }
  7921. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7922. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7923. }
  7924. return true;
  7925. }
  7926. } // namespace detail
  7927. #endif // CPPHTTPLIB_SSL_ENABLED
  7928. /*
  7929. * Group 3: httplib namespace - Non-SSL public API implementations
  7930. */
  7931. inline void default_socket_options(socket_t sock) {
  7932. set_socket_opt(sock, SOL_SOCKET,
  7933. #ifdef SO_REUSEPORT
  7934. SO_REUSEPORT,
  7935. #else
  7936. SO_REUSEADDR,
  7937. #endif
  7938. 1);
  7939. }
  7940. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7941. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7942. sizeof(optval));
  7943. }
  7944. inline std::string get_bearer_token_auth(const Request &req) {
  7945. if (req.has_header("Authorization")) {
  7946. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7947. return req.get_header_value("Authorization")
  7948. .substr(bearer_header_prefix_len);
  7949. }
  7950. return "";
  7951. }
  7952. inline const char *status_message(int status) {
  7953. switch (status) {
  7954. case StatusCode::Continue_100: return "Continue";
  7955. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7956. case StatusCode::Processing_102: return "Processing";
  7957. case StatusCode::EarlyHints_103: return "Early Hints";
  7958. case StatusCode::OK_200: return "OK";
  7959. case StatusCode::Created_201: return "Created";
  7960. case StatusCode::Accepted_202: return "Accepted";
  7961. case StatusCode::NonAuthoritativeInformation_203:
  7962. return "Non-Authoritative Information";
  7963. case StatusCode::NoContent_204: return "No Content";
  7964. case StatusCode::ResetContent_205: return "Reset Content";
  7965. case StatusCode::PartialContent_206: return "Partial Content";
  7966. case StatusCode::MultiStatus_207: return "Multi-Status";
  7967. case StatusCode::AlreadyReported_208: return "Already Reported";
  7968. case StatusCode::IMUsed_226: return "IM Used";
  7969. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7970. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7971. case StatusCode::Found_302: return "Found";
  7972. case StatusCode::SeeOther_303: return "See Other";
  7973. case StatusCode::NotModified_304: return "Not Modified";
  7974. case StatusCode::UseProxy_305: return "Use Proxy";
  7975. case StatusCode::unused_306: return "unused";
  7976. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7977. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7978. case StatusCode::BadRequest_400: return "Bad Request";
  7979. case StatusCode::Unauthorized_401: return "Unauthorized";
  7980. case StatusCode::PaymentRequired_402: return "Payment Required";
  7981. case StatusCode::Forbidden_403: return "Forbidden";
  7982. case StatusCode::NotFound_404: return "Not Found";
  7983. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7984. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7985. case StatusCode::ProxyAuthenticationRequired_407:
  7986. return "Proxy Authentication Required";
  7987. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7988. case StatusCode::Conflict_409: return "Conflict";
  7989. case StatusCode::Gone_410: return "Gone";
  7990. case StatusCode::LengthRequired_411: return "Length Required";
  7991. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7992. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7993. case StatusCode::UriTooLong_414: return "URI Too Long";
  7994. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7995. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7996. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7997. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7998. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7999. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  8000. case StatusCode::Locked_423: return "Locked";
  8001. case StatusCode::FailedDependency_424: return "Failed Dependency";
  8002. case StatusCode::TooEarly_425: return "Too Early";
  8003. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  8004. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  8005. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  8006. case StatusCode::RequestHeaderFieldsTooLarge_431:
  8007. return "Request Header Fields Too Large";
  8008. case StatusCode::UnavailableForLegalReasons_451:
  8009. return "Unavailable For Legal Reasons";
  8010. case StatusCode::NotImplemented_501: return "Not Implemented";
  8011. case StatusCode::BadGateway_502: return "Bad Gateway";
  8012. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  8013. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  8014. case StatusCode::HttpVersionNotSupported_505:
  8015. return "HTTP Version Not Supported";
  8016. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  8017. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  8018. case StatusCode::LoopDetected_508: return "Loop Detected";
  8019. case StatusCode::NotExtended_510: return "Not Extended";
  8020. case StatusCode::NetworkAuthenticationRequired_511:
  8021. return "Network Authentication Required";
  8022. default:
  8023. case StatusCode::InternalServerError_500: return "Internal Server Error";
  8024. }
  8025. }
  8026. inline std::string to_string(const Error error) {
  8027. switch (error) {
  8028. case Error::Success: return "Success (no error)";
  8029. case Error::Unknown: return "Unknown";
  8030. case Error::Connection: return "Could not establish connection";
  8031. case Error::BindIPAddress: return "Failed to bind IP address";
  8032. case Error::Read: return "Failed to read connection";
  8033. case Error::Write: return "Failed to write connection";
  8034. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  8035. case Error::Canceled: return "Connection handling canceled";
  8036. case Error::SSLConnection: return "SSL connection failed";
  8037. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  8038. case Error::SSLServerVerification: return "SSL server verification failed";
  8039. case Error::SSLServerHostnameVerification:
  8040. return "SSL server hostname verification failed";
  8041. case Error::UnsupportedMultipartBoundaryChars:
  8042. return "Unsupported HTTP multipart boundary characters";
  8043. case Error::Compression: return "Compression failed";
  8044. case Error::ConnectionTimeout: return "Connection timed out";
  8045. case Error::ProxyConnection: return "Proxy connection failed";
  8046. case Error::ConnectionClosed: return "Connection closed by server";
  8047. case Error::Timeout: return "Read timeout";
  8048. case Error::ResourceExhaustion: return "Resource exhaustion";
  8049. case Error::TooManyFormDataFiles: return "Too many form data files";
  8050. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  8051. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  8052. case Error::ExceedMaxSocketDescriptorCount:
  8053. return "Exceeded maximum socket descriptor count";
  8054. case Error::InvalidRequestLine: return "Invalid request line";
  8055. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8056. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8057. case Error::InvalidHeaders: return "Invalid headers";
  8058. case Error::MultipartParsing: return "Multipart parsing failed";
  8059. case Error::OpenFile: return "Failed to open file";
  8060. case Error::Listen: return "Failed to listen on socket";
  8061. case Error::GetSockName: return "Failed to get socket name";
  8062. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8063. case Error::HTTPParsing: return "HTTP parsing failed";
  8064. case Error::InvalidRangeHeader: return "Invalid Range header";
  8065. default: break;
  8066. }
  8067. return "Invalid";
  8068. }
  8069. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8070. os << to_string(obj);
  8071. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8072. return os;
  8073. }
  8074. inline std::string hosted_at(const std::string &hostname) {
  8075. std::vector<std::string> addrs;
  8076. hosted_at(hostname, addrs);
  8077. if (addrs.empty()) { return std::string(); }
  8078. return addrs[0];
  8079. }
  8080. inline void hosted_at(const std::string &hostname,
  8081. std::vector<std::string> &addrs) {
  8082. struct addrinfo hints;
  8083. struct addrinfo *result;
  8084. memset(&hints, 0, sizeof(struct addrinfo));
  8085. hints.ai_family = AF_UNSPEC;
  8086. hints.ai_socktype = SOCK_STREAM;
  8087. hints.ai_protocol = 0;
  8088. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8089. &result, 0)) {
  8090. #if defined __linux__ && !defined __ANDROID__
  8091. res_init();
  8092. #endif
  8093. return;
  8094. }
  8095. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8096. for (auto rp = result; rp; rp = rp->ai_next) {
  8097. const auto &addr =
  8098. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8099. std::string ip;
  8100. auto dummy = -1;
  8101. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8102. dummy)) {
  8103. addrs.emplace_back(std::move(ip));
  8104. }
  8105. }
  8106. }
  8107. inline std::string encode_uri_component(const std::string &value) {
  8108. std::ostringstream escaped;
  8109. escaped.fill('0');
  8110. escaped << std::hex;
  8111. for (auto c : value) {
  8112. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8113. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8114. escaped << c;
  8115. } else {
  8116. escaped << std::uppercase;
  8117. escaped << '%' << std::setw(2)
  8118. << static_cast<int>(static_cast<unsigned char>(c));
  8119. escaped << std::nouppercase;
  8120. }
  8121. }
  8122. return escaped.str();
  8123. }
  8124. inline std::string encode_uri(const std::string &value) {
  8125. std::ostringstream escaped;
  8126. escaped.fill('0');
  8127. escaped << std::hex;
  8128. for (auto c : value) {
  8129. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8130. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8131. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8132. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8133. escaped << c;
  8134. } else {
  8135. escaped << std::uppercase;
  8136. escaped << '%' << std::setw(2)
  8137. << static_cast<int>(static_cast<unsigned char>(c));
  8138. escaped << std::nouppercase;
  8139. }
  8140. }
  8141. return escaped.str();
  8142. }
  8143. inline std::string decode_uri_component(const std::string &value) {
  8144. std::string result;
  8145. for (size_t i = 0; i < value.size(); i++) {
  8146. if (value[i] == '%' && i + 2 < value.size()) {
  8147. auto val = 0;
  8148. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8149. result += static_cast<char>(val);
  8150. i += 2;
  8151. } else {
  8152. result += value[i];
  8153. }
  8154. } else {
  8155. result += value[i];
  8156. }
  8157. }
  8158. return result;
  8159. }
  8160. inline std::string decode_uri(const std::string &value) {
  8161. std::string result;
  8162. for (size_t i = 0; i < value.size(); i++) {
  8163. if (value[i] == '%' && i + 2 < value.size()) {
  8164. auto val = 0;
  8165. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8166. result += static_cast<char>(val);
  8167. i += 2;
  8168. } else {
  8169. result += value[i];
  8170. }
  8171. } else {
  8172. result += value[i];
  8173. }
  8174. }
  8175. return result;
  8176. }
  8177. inline std::string encode_path_component(const std::string &component) {
  8178. std::string result;
  8179. result.reserve(component.size() * 3);
  8180. for (size_t i = 0; i < component.size(); i++) {
  8181. auto c = static_cast<unsigned char>(component[i]);
  8182. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8183. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8184. c == '_' || c == '~') {
  8185. result += static_cast<char>(c);
  8186. }
  8187. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8188. // "," / ";" / "="
  8189. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8190. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8191. c == '=') {
  8192. result += static_cast<char>(c);
  8193. }
  8194. // Colon is allowed in path segments except first segment
  8195. else if (c == ':') {
  8196. result += static_cast<char>(c);
  8197. }
  8198. // @ is allowed in path
  8199. else if (c == '@') {
  8200. result += static_cast<char>(c);
  8201. } else {
  8202. result += '%';
  8203. char hex[3];
  8204. snprintf(hex, sizeof(hex), "%02X", c);
  8205. result.append(hex, 2);
  8206. }
  8207. }
  8208. return result;
  8209. }
  8210. inline std::string decode_path_component(const std::string &component) {
  8211. std::string result;
  8212. result.reserve(component.size());
  8213. for (size_t i = 0; i < component.size(); i++) {
  8214. if (component[i] == '%' && i + 1 < component.size()) {
  8215. if (component[i + 1] == 'u') {
  8216. // Unicode %uXXXX encoding
  8217. auto val = 0;
  8218. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8219. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8220. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8221. char buff[4];
  8222. size_t len = detail::to_utf8(val, buff);
  8223. if (len > 0) { result.append(buff, len); }
  8224. i += 5; // 'u0000'
  8225. } else {
  8226. result += component[i];
  8227. }
  8228. } else {
  8229. // Standard %XX encoding
  8230. auto val = 0;
  8231. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8232. // 2 digits hex codes
  8233. result += static_cast<char>(val);
  8234. i += 2; // 'XX'
  8235. } else {
  8236. result += component[i];
  8237. }
  8238. }
  8239. } else {
  8240. result += component[i];
  8241. }
  8242. }
  8243. return result;
  8244. }
  8245. inline std::string encode_query_component(const std::string &component,
  8246. bool space_as_plus) {
  8247. std::string result;
  8248. result.reserve(component.size() * 3);
  8249. for (size_t i = 0; i < component.size(); i++) {
  8250. auto c = static_cast<unsigned char>(component[i]);
  8251. // Unreserved characters per RFC 3986
  8252. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8253. c == '_' || c == '~') {
  8254. result += static_cast<char>(c);
  8255. }
  8256. // Space handling
  8257. else if (c == ' ') {
  8258. if (space_as_plus) {
  8259. result += '+';
  8260. } else {
  8261. result += "%20";
  8262. }
  8263. }
  8264. // Plus sign handling
  8265. else if (c == '+') {
  8266. if (space_as_plus) {
  8267. result += "%2B";
  8268. } else {
  8269. result += static_cast<char>(c);
  8270. }
  8271. }
  8272. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8273. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8274. c == '*' || c == ',' || c == ';') {
  8275. result += static_cast<char>(c);
  8276. }
  8277. // Colon and @ are allowed in query
  8278. else if (c == ':' || c == '@') {
  8279. result += static_cast<char>(c);
  8280. }
  8281. // Forward slash is allowed in query values
  8282. else if (c == '/') {
  8283. result += static_cast<char>(c);
  8284. }
  8285. // Question mark is allowed in query values (after first ?)
  8286. else if (c == '?') {
  8287. result += static_cast<char>(c);
  8288. } else {
  8289. result += '%';
  8290. char hex[3];
  8291. snprintf(hex, sizeof(hex), "%02X", c);
  8292. result.append(hex, 2);
  8293. }
  8294. }
  8295. return result;
  8296. }
  8297. inline std::string decode_query_component(const std::string &component,
  8298. bool plus_as_space) {
  8299. std::string result;
  8300. result.reserve(component.size());
  8301. for (size_t i = 0; i < component.size(); i++) {
  8302. if (component[i] == '%' && i + 2 < component.size()) {
  8303. auto val = 0;
  8304. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8305. result += static_cast<char>(val);
  8306. i += 2;
  8307. } else {
  8308. result += component[i];
  8309. }
  8310. } else if (component[i] == '+' && plus_as_space) {
  8311. result += ' '; // + becomes space in form-urlencoded
  8312. } else {
  8313. result += component[i];
  8314. }
  8315. }
  8316. return result;
  8317. }
  8318. inline std::string sanitize_filename(const std::string &filename) {
  8319. // Extract basename: find the last path separator (/ or \)
  8320. auto pos = filename.find_last_of("/\\");
  8321. auto result =
  8322. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8323. // Strip null bytes
  8324. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8325. // Trim whitespace
  8326. {
  8327. auto start = result.find_first_not_of(" \t");
  8328. auto end = result.find_last_not_of(" \t");
  8329. result = (start == std::string::npos)
  8330. ? ""
  8331. : result.substr(start, end - start + 1);
  8332. }
  8333. // Reject . and ..
  8334. if (result == "." || result == "..") { return ""; }
  8335. return result;
  8336. }
  8337. inline std::string append_query_params(const std::string &path,
  8338. const Params &params) {
  8339. std::string path_with_query = path;
  8340. thread_local const std::regex re("[^?]+\\?.*");
  8341. auto delm = std::regex_match(path, re) ? '&' : '?';
  8342. path_with_query += delm + detail::params_to_query_str(params);
  8343. return path_with_query;
  8344. }
  8345. // Header utilities
  8346. inline std::pair<std::string, std::string>
  8347. make_range_header(const Ranges &ranges) {
  8348. std::string field = "bytes=";
  8349. auto i = 0;
  8350. for (const auto &r : ranges) {
  8351. if (i != 0) { field += ", "; }
  8352. if (r.first != -1) { field += std::to_string(r.first); }
  8353. field += '-';
  8354. if (r.second != -1) { field += std::to_string(r.second); }
  8355. i++;
  8356. }
  8357. return std::make_pair("Range", std::move(field));
  8358. }
  8359. inline std::pair<std::string, std::string>
  8360. make_basic_authentication_header(const std::string &username,
  8361. const std::string &password, bool is_proxy) {
  8362. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8363. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8364. return std::make_pair(key, std::move(field));
  8365. }
  8366. inline std::pair<std::string, std::string>
  8367. make_bearer_token_authentication_header(const std::string &token,
  8368. bool is_proxy = false) {
  8369. auto field = "Bearer " + token;
  8370. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8371. return std::make_pair(key, std::move(field));
  8372. }
  8373. // Request implementation
  8374. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8375. size_t id) const {
  8376. return detail::get_header_value_u64(headers, key, def, id);
  8377. }
  8378. inline bool Request::has_header(const std::string &key) const {
  8379. return detail::has_header(headers, key);
  8380. }
  8381. inline std::string Request::get_header_value(const std::string &key,
  8382. const char *def, size_t id) const {
  8383. return detail::get_header_value(headers, key, def, id);
  8384. }
  8385. inline size_t Request::get_header_value_count(const std::string &key) const {
  8386. return detail::get_header_value_count(headers, key);
  8387. }
  8388. inline void Request::set_header(const std::string &key,
  8389. const std::string &val) {
  8390. detail::set_header(headers, key, val);
  8391. }
  8392. inline bool Request::has_trailer(const std::string &key) const {
  8393. return trailers.find(key) != trailers.end();
  8394. }
  8395. inline std::string Request::get_trailer_value(const std::string &key,
  8396. size_t id) const {
  8397. return detail::get_multimap_value(trailers, key, id);
  8398. }
  8399. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8400. auto r = trailers.equal_range(key);
  8401. return static_cast<size_t>(std::distance(r.first, r.second));
  8402. }
  8403. inline bool Request::has_param(const std::string &key) const {
  8404. return params.find(key) != params.end();
  8405. }
  8406. inline std::string Request::get_param_value(const std::string &key,
  8407. size_t id) const {
  8408. return detail::get_multimap_value(params, key, id);
  8409. }
  8410. inline std::vector<std::string>
  8411. Request::get_param_values(const std::string &key) const {
  8412. auto rng = params.equal_range(key);
  8413. std::vector<std::string> values;
  8414. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8415. for (auto it = rng.first; it != rng.second; ++it) {
  8416. values.push_back(it->second);
  8417. }
  8418. return values;
  8419. }
  8420. inline size_t Request::get_param_value_count(const std::string &key) const {
  8421. auto r = params.equal_range(key);
  8422. return static_cast<size_t>(std::distance(r.first, r.second));
  8423. }
  8424. inline bool Request::is_multipart_form_data() const {
  8425. const auto &content_type = get_header_value("Content-Type");
  8426. return detail::extract_media_type(content_type) == "multipart/form-data";
  8427. }
  8428. // Multipart FormData implementation
  8429. inline std::string MultipartFormData::get_field(const std::string &key,
  8430. size_t id) const {
  8431. auto rng = fields.equal_range(key);
  8432. auto it = rng.first;
  8433. std::advance(it, static_cast<ssize_t>(id));
  8434. if (it != rng.second) { return it->second.content; }
  8435. return std::string();
  8436. }
  8437. inline std::vector<std::string>
  8438. MultipartFormData::get_fields(const std::string &key) const {
  8439. std::vector<std::string> values;
  8440. auto rng = fields.equal_range(key);
  8441. for (auto it = rng.first; it != rng.second; it++) {
  8442. values.push_back(it->second.content);
  8443. }
  8444. return values;
  8445. }
  8446. inline bool MultipartFormData::has_field(const std::string &key) const {
  8447. return fields.find(key) != fields.end();
  8448. }
  8449. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8450. auto r = fields.equal_range(key);
  8451. return static_cast<size_t>(std::distance(r.first, r.second));
  8452. }
  8453. inline FormData MultipartFormData::get_file(const std::string &key,
  8454. size_t id) const {
  8455. return detail::get_multimap_value(files, key, id);
  8456. }
  8457. inline std::vector<FormData>
  8458. MultipartFormData::get_files(const std::string &key) const {
  8459. std::vector<FormData> values;
  8460. auto rng = files.equal_range(key);
  8461. for (auto it = rng.first; it != rng.second; it++) {
  8462. values.push_back(it->second);
  8463. }
  8464. return values;
  8465. }
  8466. inline bool MultipartFormData::has_file(const std::string &key) const {
  8467. return files.find(key) != files.end();
  8468. }
  8469. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8470. auto r = files.equal_range(key);
  8471. return static_cast<size_t>(std::distance(r.first, r.second));
  8472. }
  8473. // Multipart FormData writer implementation
  8474. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8475. return detail::is_multipart_boundary_chars_valid(boundary);
  8476. }
  8477. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8478. : boundary_(detail::make_multipart_data_boundary()) {}
  8479. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8480. : boundary_(std::move(boundary)) {}
  8481. inline const std::string &MultipartFormDataWriter::boundary() const {
  8482. return boundary_;
  8483. }
  8484. inline std::string MultipartFormDataWriter::content_type() const {
  8485. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8486. }
  8487. inline std::string
  8488. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8489. return detail::serialize_multipart_formdata(items, boundary_);
  8490. }
  8491. inline size_t MultipartFormDataWriter::content_length(
  8492. const UploadFormDataItems &items) const {
  8493. return detail::get_multipart_content_length(items, boundary_);
  8494. }
  8495. inline std::string
  8496. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8497. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8498. }
  8499. inline std::string MultipartFormDataWriter::item_end() {
  8500. return detail::serialize_multipart_formdata_item_end();
  8501. }
  8502. inline std::string MultipartFormDataWriter::finish() const {
  8503. return detail::serialize_multipart_formdata_finish(boundary_);
  8504. }
  8505. // Response implementation
  8506. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8507. size_t id) const {
  8508. return detail::get_header_value_u64(headers, key, def, id);
  8509. }
  8510. inline bool Response::has_header(const std::string &key) const {
  8511. return headers.find(key) != headers.end();
  8512. }
  8513. inline std::string Response::get_header_value(const std::string &key,
  8514. const char *def,
  8515. size_t id) const {
  8516. return detail::get_header_value(headers, key, def, id);
  8517. }
  8518. inline size_t Response::get_header_value_count(const std::string &key) const {
  8519. return detail::get_header_value_count(headers, key);
  8520. }
  8521. inline void Response::set_header(const std::string &key,
  8522. const std::string &val) {
  8523. detail::set_header(headers, key, val);
  8524. }
  8525. inline bool Response::has_trailer(const std::string &key) const {
  8526. return trailers.find(key) != trailers.end();
  8527. }
  8528. inline std::string Response::get_trailer_value(const std::string &key,
  8529. size_t id) const {
  8530. return detail::get_multimap_value(trailers, key, id);
  8531. }
  8532. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8533. auto r = trailers.equal_range(key);
  8534. return static_cast<size_t>(std::distance(r.first, r.second));
  8535. }
  8536. inline void Response::set_redirect(const std::string &url, int stat) {
  8537. if (detail::fields::is_field_value(url)) {
  8538. set_header("Location", url);
  8539. if (300 <= stat && stat < 400) {
  8540. this->status = stat;
  8541. } else {
  8542. this->status = StatusCode::Found_302;
  8543. }
  8544. }
  8545. }
  8546. inline void Response::set_content(const char *s, size_t n,
  8547. const std::string &content_type) {
  8548. body.assign(s, n);
  8549. auto rng = headers.equal_range("Content-Type");
  8550. headers.erase(rng.first, rng.second);
  8551. set_header("Content-Type", content_type);
  8552. }
  8553. inline void Response::set_content(const std::string &s,
  8554. const std::string &content_type) {
  8555. set_content(s.data(), s.size(), content_type);
  8556. }
  8557. inline void Response::set_content(std::string &&s,
  8558. const std::string &content_type) {
  8559. body = std::move(s);
  8560. auto rng = headers.equal_range("Content-Type");
  8561. headers.erase(rng.first, rng.second);
  8562. set_header("Content-Type", content_type);
  8563. }
  8564. inline void Response::set_content_provider(
  8565. size_t in_length, const std::string &content_type, ContentProvider provider,
  8566. ContentProviderResourceReleaser resource_releaser) {
  8567. set_header("Content-Type", content_type);
  8568. content_length_ = in_length;
  8569. if (in_length > 0) { content_provider_ = std::move(provider); }
  8570. content_provider_resource_releaser_ = std::move(resource_releaser);
  8571. is_chunked_content_provider_ = false;
  8572. }
  8573. inline void Response::set_content_provider(
  8574. const std::string &content_type, ContentProviderWithoutLength provider,
  8575. ContentProviderResourceReleaser resource_releaser) {
  8576. set_header("Content-Type", content_type);
  8577. content_length_ = 0;
  8578. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8579. content_provider_resource_releaser_ = std::move(resource_releaser);
  8580. is_chunked_content_provider_ = false;
  8581. }
  8582. inline void Response::set_chunked_content_provider(
  8583. const std::string &content_type, ContentProviderWithoutLength provider,
  8584. ContentProviderResourceReleaser resource_releaser) {
  8585. set_header("Content-Type", content_type);
  8586. content_length_ = 0;
  8587. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8588. content_provider_resource_releaser_ = std::move(resource_releaser);
  8589. is_chunked_content_provider_ = true;
  8590. }
  8591. inline void Response::set_file_content(const std::string &path,
  8592. const std::string &content_type) {
  8593. file_content_path_ = path;
  8594. file_content_content_type_ = content_type;
  8595. }
  8596. inline void Response::set_file_content(const std::string &path) {
  8597. file_content_path_ = path;
  8598. }
  8599. // Result implementation
  8600. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8601. size_t def,
  8602. size_t id) const {
  8603. return detail::get_header_value_u64(request_headers_, key, def, id);
  8604. }
  8605. inline bool Result::has_request_header(const std::string &key) const {
  8606. return request_headers_.find(key) != request_headers_.end();
  8607. }
  8608. inline std::string Result::get_request_header_value(const std::string &key,
  8609. const char *def,
  8610. size_t id) const {
  8611. return detail::get_header_value(request_headers_, key, def, id);
  8612. }
  8613. inline size_t
  8614. Result::get_request_header_value_count(const std::string &key) const {
  8615. auto r = request_headers_.equal_range(key);
  8616. return static_cast<size_t>(std::distance(r.first, r.second));
  8617. }
  8618. // Stream implementation
  8619. inline ssize_t Stream::write(const char *ptr) {
  8620. return write(ptr, strlen(ptr));
  8621. }
  8622. inline ssize_t Stream::write(const std::string &s) {
  8623. return write(s.data(), s.size());
  8624. }
  8625. // BodyReader implementation
  8626. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8627. if (!stream) {
  8628. last_error = Error::Connection;
  8629. return -1;
  8630. }
  8631. if (eof) { return 0; }
  8632. if (!chunked) {
  8633. // Content-Length based reading
  8634. if (has_content_length && bytes_read >= content_length) {
  8635. eof = true;
  8636. return 0;
  8637. }
  8638. auto to_read = len;
  8639. if (has_content_length) {
  8640. auto remaining = content_length - bytes_read;
  8641. to_read = (std::min)(len, remaining);
  8642. }
  8643. auto n = stream->read(buf, to_read);
  8644. if (n < 0) {
  8645. last_error = stream->get_error();
  8646. if (last_error == Error::Success) { last_error = Error::Read; }
  8647. eof = true;
  8648. return n;
  8649. }
  8650. if (n == 0) {
  8651. // Unexpected EOF before content_length
  8652. last_error = stream->get_error();
  8653. if (last_error == Error::Success) { last_error = Error::Read; }
  8654. eof = true;
  8655. return 0;
  8656. }
  8657. bytes_read += static_cast<size_t>(n);
  8658. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8659. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8660. last_error = Error::ExceedMaxPayloadSize;
  8661. eof = true;
  8662. return -1;
  8663. }
  8664. return n;
  8665. }
  8666. // Chunked transfer encoding: delegate to shared decoder instance.
  8667. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8668. size_t chunk_offset = 0;
  8669. size_t chunk_total = 0;
  8670. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8671. if (n < 0) {
  8672. last_error = stream->get_error();
  8673. if (last_error == Error::Success) { last_error = Error::Read; }
  8674. eof = true;
  8675. return n;
  8676. }
  8677. if (n == 0) {
  8678. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8679. eof = true;
  8680. return 0;
  8681. }
  8682. bytes_read += static_cast<size_t>(n);
  8683. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8684. last_error = Error::ExceedMaxPayloadSize;
  8685. eof = true;
  8686. return -1;
  8687. }
  8688. return n;
  8689. }
  8690. // ThreadPool implementation
  8691. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8692. time_t idle_timeout_sec)
  8693. : base_thread_count_(n), max_queued_requests_(mqr),
  8694. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8695. shutdown_(false) {
  8696. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8697. if (max_n != 0 && max_n < n) {
  8698. std::string msg = "max_threads must be >= base_threads";
  8699. throw std::invalid_argument(msg);
  8700. }
  8701. #endif
  8702. max_thread_count_ = max_n == 0 ? n : max_n;
  8703. threads_.reserve(base_thread_count_);
  8704. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8705. try {
  8706. #endif
  8707. for (size_t i = 0; i < base_thread_count_; i++) {
  8708. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8709. }
  8710. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8711. } catch (...) {
  8712. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8713. // signal the workers we already spawned to exit and join them so the
  8714. // vector destructor does not see joinable threads (which would call
  8715. // std::terminate). Then rethrow so the caller learns of the failure.
  8716. {
  8717. std::unique_lock<std::mutex> lock(mutex_);
  8718. shutdown_ = true;
  8719. }
  8720. cond_.notify_all();
  8721. for (auto &t : threads_) {
  8722. if (t.joinable()) { t.join(); }
  8723. }
  8724. throw;
  8725. }
  8726. #endif
  8727. }
  8728. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8729. {
  8730. std::unique_lock<std::mutex> lock(mutex_);
  8731. if (shutdown_) { return false; }
  8732. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8733. return false;
  8734. }
  8735. jobs_.push_back(std::move(fn));
  8736. // Spawn a dynamic thread if no idle threads and under max
  8737. if (idle_thread_count_ == 0 &&
  8738. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8739. cleanup_finished_threads();
  8740. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8741. }
  8742. }
  8743. cond_.notify_one();
  8744. return true;
  8745. }
  8746. inline void ThreadPool::shutdown() {
  8747. {
  8748. std::unique_lock<std::mutex> lock(mutex_);
  8749. shutdown_ = true;
  8750. }
  8751. cond_.notify_all();
  8752. for (auto &t : threads_) {
  8753. if (t.joinable()) { t.join(); }
  8754. }
  8755. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8756. // with worker threads that call move_to_finished() concurrently.
  8757. std::list<std::thread> remaining_dynamic;
  8758. {
  8759. std::unique_lock<std::mutex> lock(mutex_);
  8760. remaining_dynamic = std::move(dynamic_threads_);
  8761. }
  8762. for (auto &t : remaining_dynamic) {
  8763. if (t.joinable()) { t.join(); }
  8764. }
  8765. std::unique_lock<std::mutex> lock(mutex_);
  8766. cleanup_finished_threads();
  8767. }
  8768. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8769. // Must be called with mutex_ held
  8770. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8771. if (it->get_id() == id) {
  8772. finished_threads_.push_back(std::move(*it));
  8773. dynamic_threads_.erase(it);
  8774. return;
  8775. }
  8776. }
  8777. }
  8778. inline void ThreadPool::cleanup_finished_threads() {
  8779. // Must be called with mutex_ held
  8780. for (auto &t : finished_threads_) {
  8781. if (t.joinable()) { t.join(); }
  8782. }
  8783. finished_threads_.clear();
  8784. }
  8785. inline void ThreadPool::worker(bool is_dynamic) {
  8786. for (;;) {
  8787. std::function<void()> fn;
  8788. {
  8789. std::unique_lock<std::mutex> lock(mutex_);
  8790. idle_thread_count_++;
  8791. if (is_dynamic) {
  8792. auto has_work =
  8793. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8794. [&] { return !jobs_.empty() || shutdown_; });
  8795. if (!has_work) {
  8796. // Timed out with no work - exit this dynamic thread
  8797. idle_thread_count_--;
  8798. move_to_finished(std::this_thread::get_id());
  8799. break;
  8800. }
  8801. } else {
  8802. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8803. }
  8804. idle_thread_count_--;
  8805. if (shutdown_ && jobs_.empty()) { break; }
  8806. fn = std::move(jobs_.front());
  8807. jobs_.pop_front();
  8808. }
  8809. assert(true == static_cast<bool>(fn));
  8810. fn();
  8811. }
  8812. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8813. !defined(LIBRESSL_VERSION_NUMBER)
  8814. OPENSSL_thread_stop();
  8815. #endif
  8816. }
  8817. /*
  8818. * Group 1 (continued): detail namespace - Stream implementations
  8819. */
  8820. namespace detail {
  8821. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8822. time_t timeout_sec, time_t timeout_usec,
  8823. time_t &actual_timeout_sec,
  8824. time_t &actual_timeout_usec) {
  8825. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8826. auto actual_timeout_msec =
  8827. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8828. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8829. actual_timeout_sec = actual_timeout_msec / 1000;
  8830. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8831. }
  8832. // Socket stream implementation
  8833. inline SocketStream::SocketStream(
  8834. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8835. time_t write_timeout_sec, time_t write_timeout_usec,
  8836. time_t max_timeout_msec,
  8837. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8838. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8839. read_timeout_usec_(read_timeout_usec),
  8840. write_timeout_sec_(write_timeout_sec),
  8841. write_timeout_usec_(write_timeout_usec),
  8842. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8843. read_buff_(read_buff_size_, 0) {}
  8844. inline SocketStream::~SocketStream() = default;
  8845. inline bool SocketStream::is_readable() const {
  8846. return read_buff_off_ < read_buff_content_size_;
  8847. }
  8848. inline bool SocketStream::wait_readable() const {
  8849. if (max_timeout_msec_ <= 0) {
  8850. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8851. }
  8852. time_t read_timeout_sec;
  8853. time_t read_timeout_usec;
  8854. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8855. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8856. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8857. }
  8858. inline bool SocketStream::wait_writable() const {
  8859. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8860. }
  8861. inline bool SocketStream::is_peer_alive() const {
  8862. return detail::is_socket_alive(sock_);
  8863. }
  8864. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8865. #ifdef _WIN32
  8866. size =
  8867. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8868. #else
  8869. size = (std::min)(size,
  8870. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8871. #endif
  8872. if (read_buff_off_ < read_buff_content_size_) {
  8873. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8874. if (size <= remaining_size) {
  8875. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8876. read_buff_off_ += size;
  8877. return static_cast<ssize_t>(size);
  8878. } else {
  8879. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8880. read_buff_off_ += remaining_size;
  8881. return static_cast<ssize_t>(remaining_size);
  8882. }
  8883. }
  8884. if (!wait_readable()) {
  8885. error_ = Error::Timeout;
  8886. return -1;
  8887. }
  8888. read_buff_off_ = 0;
  8889. read_buff_content_size_ = 0;
  8890. if (size < read_buff_size_) {
  8891. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8892. CPPHTTPLIB_RECV_FLAGS);
  8893. if (n <= 0) {
  8894. if (n == 0) {
  8895. error_ = Error::ConnectionClosed;
  8896. } else {
  8897. error_ = Error::Read;
  8898. }
  8899. return n;
  8900. } else if (n <= static_cast<ssize_t>(size)) {
  8901. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8902. return n;
  8903. } else {
  8904. memcpy(ptr, read_buff_.data(), size);
  8905. read_buff_off_ = size;
  8906. read_buff_content_size_ = static_cast<size_t>(n);
  8907. return static_cast<ssize_t>(size);
  8908. }
  8909. } else {
  8910. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8911. if (n <= 0) {
  8912. if (n == 0) {
  8913. error_ = Error::ConnectionClosed;
  8914. } else {
  8915. error_ = Error::Read;
  8916. }
  8917. }
  8918. return n;
  8919. }
  8920. }
  8921. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8922. if (!wait_writable()) { return -1; }
  8923. #if defined(_WIN32) && !defined(_WIN64)
  8924. size =
  8925. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8926. #endif
  8927. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8928. }
  8929. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8930. int &port) const {
  8931. return detail::get_remote_ip_and_port(sock_, ip, port);
  8932. }
  8933. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8934. int &port) const {
  8935. return detail::get_local_ip_and_port(sock_, ip, port);
  8936. }
  8937. inline socket_t SocketStream::socket() const { return sock_; }
  8938. inline time_t SocketStream::duration() const {
  8939. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8940. std::chrono::steady_clock::now() - start_time_)
  8941. .count();
  8942. }
  8943. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8944. read_timeout_sec_ = sec;
  8945. read_timeout_usec_ = usec;
  8946. }
  8947. // Buffer stream implementation
  8948. inline bool BufferStream::is_readable() const { return true; }
  8949. inline bool BufferStream::wait_readable() const { return true; }
  8950. inline bool BufferStream::wait_writable() const { return true; }
  8951. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8952. #if defined(_MSC_VER) && _MSC_VER < 1910
  8953. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8954. #else
  8955. auto len_read = buffer.copy(ptr, size, position);
  8956. #endif
  8957. position += static_cast<size_t>(len_read);
  8958. return static_cast<ssize_t>(len_read);
  8959. }
  8960. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8961. buffer.append(ptr, size);
  8962. return static_cast<ssize_t>(size);
  8963. }
  8964. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8965. int & /*port*/) const {}
  8966. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8967. int & /*port*/) const {}
  8968. inline socket_t BufferStream::socket() const { return 0; }
  8969. inline time_t BufferStream::duration() const { return 0; }
  8970. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8971. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8972. : MatcherBase(pattern) {
  8973. constexpr const char marker[] = "/:";
  8974. // One past the last ending position of a path param substring
  8975. std::size_t last_param_end = 0;
  8976. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8977. // Needed to ensure that parameter names are unique during matcher
  8978. // construction
  8979. // If exceptions are disabled, only last duplicate path
  8980. // parameter will be set
  8981. std::unordered_set<std::string> param_name_set;
  8982. #endif
  8983. while (true) {
  8984. const auto marker_pos = pattern.find(
  8985. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8986. if (marker_pos == std::string::npos) { break; }
  8987. static_fragments_.push_back(
  8988. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8989. const auto param_name_start = marker_pos + str_len(marker);
  8990. auto sep_pos = pattern.find(separator, param_name_start);
  8991. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8992. auto param_name =
  8993. pattern.substr(param_name_start, sep_pos - param_name_start);
  8994. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8995. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8996. std::string msg = "Encountered path parameter '" + param_name +
  8997. "' multiple times in route pattern '" + pattern + "'.";
  8998. throw std::invalid_argument(msg);
  8999. }
  9000. #endif
  9001. param_names_.push_back(std::move(param_name));
  9002. last_param_end = sep_pos + 1;
  9003. }
  9004. if (last_param_end < pattern.length()) {
  9005. static_fragments_.push_back(pattern.substr(last_param_end));
  9006. }
  9007. }
  9008. inline bool PathParamsMatcher::match(Request &request) const {
  9009. request.matches = std::smatch();
  9010. request.path_params.clear();
  9011. request.path_params.reserve(param_names_.size());
  9012. // One past the position at which the path matched the pattern last time
  9013. std::size_t starting_pos = 0;
  9014. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  9015. const auto &fragment = static_fragments_[i];
  9016. if (starting_pos + fragment.length() > request.path.length()) {
  9017. return false;
  9018. }
  9019. // Avoid unnecessary allocation by using strncmp instead of substr +
  9020. // comparison
  9021. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  9022. fragment.length()) != 0) {
  9023. return false;
  9024. }
  9025. starting_pos += fragment.length();
  9026. // Should only happen when we have a static fragment after a param
  9027. // Example: '/users/:id/subscriptions'
  9028. // The 'subscriptions' fragment here does not have a corresponding param
  9029. if (i >= param_names_.size()) { continue; }
  9030. auto sep_pos = request.path.find(separator, starting_pos);
  9031. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  9032. const auto &param_name = param_names_[i];
  9033. request.path_params.emplace(
  9034. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  9035. // Mark everything up to '/' as matched
  9036. starting_pos = sep_pos + 1;
  9037. }
  9038. // Returns false if the path is longer than the pattern
  9039. return starting_pos >= request.path.length();
  9040. }
  9041. inline bool RegexMatcher::match(Request &request) const {
  9042. request.path_params.clear();
  9043. return std::regex_match(request.path, request.matches, regex_);
  9044. }
  9045. // Enclose IPv6 address in brackets if needed
  9046. inline std::string prepare_host_string(const std::string &host) {
  9047. // Enclose IPv6 address in brackets (but not if already enclosed)
  9048. if (host.find(':') == std::string::npos ||
  9049. (!host.empty() && host[0] == '[')) {
  9050. // IPv4, hostname, or already bracketed IPv6
  9051. return host;
  9052. } else {
  9053. // IPv6 address without brackets
  9054. return "[" + host + "]";
  9055. }
  9056. }
  9057. inline std::string make_host_and_port_string(const std::string &host, int port,
  9058. bool is_ssl) {
  9059. auto result = prepare_host_string(host);
  9060. // Append port if not default
  9061. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9062. ; // do nothing
  9063. } else {
  9064. result += ":" + std::to_string(port);
  9065. }
  9066. return result;
  9067. }
  9068. // Create "host:port" string always including port number (for CONNECT method)
  9069. inline std::string
  9070. make_host_and_port_string_always_port(const std::string &host, int port) {
  9071. return prepare_host_string(host) + ":" + std::to_string(port);
  9072. }
  9073. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9074. NormalizedTarget normalize_target(const std::string &host);
  9075. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9076. bool host_matches_no_proxy(const NormalizedTarget &target,
  9077. const std::vector<NoProxyEntry> &entries);
  9078. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9079. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9080. if (prefix_bits == 0) { return true; }
  9081. int full_bytes = prefix_bits / 8;
  9082. int rem_bits = prefix_bits % 8;
  9083. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9084. static_cast<size_t>(full_bytes)) != 0) {
  9085. return false;
  9086. }
  9087. if (rem_bits == 0) { return true; }
  9088. auto i = static_cast<size_t>(full_bytes);
  9089. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9090. return (ip[i] & mask) == (net[i] & mask);
  9091. }
  9092. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9093. if (token.empty()) { return false; }
  9094. if (token == "*") {
  9095. out.kind = NoProxyKind::Wildcard;
  9096. return true;
  9097. }
  9098. auto slash = token.find('/');
  9099. std::string addr_part =
  9100. (slash == std::string::npos) ? token : token.substr(0, slash);
  9101. std::string prefix_part =
  9102. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9103. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9104. // don't silently treat it as a /32 (or /128).
  9105. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9106. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9107. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9108. // when brackets are present.
  9109. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9110. addr_part.back() == ']';
  9111. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9112. if (!bracketed) {
  9113. struct in_addr v4;
  9114. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9115. int prefix = 32;
  9116. if (!prefix_part.empty()) {
  9117. auto r = from_chars(prefix_part.data(),
  9118. prefix_part.data() + prefix_part.size(), prefix);
  9119. if (r.ec != std::errc{} ||
  9120. r.ptr != prefix_part.data() + prefix_part.size()) {
  9121. return false;
  9122. }
  9123. if (prefix < 0 || prefix > 32) { return false; }
  9124. }
  9125. out.kind = NoProxyKind::IPv4Cidr;
  9126. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9127. out.prefix_bits = prefix;
  9128. return true;
  9129. }
  9130. }
  9131. struct in6_addr v6;
  9132. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9133. int prefix = 128;
  9134. if (!prefix_part.empty()) {
  9135. auto r = from_chars(prefix_part.data(),
  9136. prefix_part.data() + prefix_part.size(), prefix);
  9137. if (r.ec != std::errc{} ||
  9138. r.ptr != prefix_part.data() + prefix_part.size()) {
  9139. return false;
  9140. }
  9141. if (prefix < 0 || prefix > 128) { return false; }
  9142. }
  9143. out.kind = NoProxyKind::IPv6Cidr;
  9144. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9145. out.prefix_bits = prefix;
  9146. return true;
  9147. }
  9148. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9149. // the entry is malformed — don't fall through to the hostname branch.
  9150. if (bracketed) { return false; }
  9151. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9152. if (slash != std::string::npos) { return false; }
  9153. // Port-specific entries (host:port) are not supported.
  9154. if (token.find(':') != std::string::npos) { return false; }
  9155. std::string hostname = case_ignore::to_lower(token);
  9156. while (!hostname.empty() && hostname.front() == '.') {
  9157. hostname.erase(hostname.begin());
  9158. }
  9159. while (!hostname.empty() && hostname.back() == '.') {
  9160. hostname.pop_back();
  9161. }
  9162. if (hostname.empty()) { return false; }
  9163. out.kind = NoProxyKind::HostnameSuffix;
  9164. out.hostname_pattern = std::move(hostname);
  9165. return true;
  9166. }
  9167. inline NormalizedTarget normalize_target(const std::string &host) {
  9168. NormalizedTarget t;
  9169. std::string h = host;
  9170. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9171. h = h.substr(1, h.size() - 2);
  9172. }
  9173. // Strip a single trailing dot so "example.com." canonicalizes to
  9174. // "example.com".
  9175. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9176. t.hostname = case_ignore::to_lower(h);
  9177. if (!t.hostname.empty()) {
  9178. struct in_addr v4;
  9179. struct in6_addr v6;
  9180. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9181. t.is_ipv4 = true;
  9182. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9183. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9184. t.is_ipv6 = true;
  9185. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9186. }
  9187. }
  9188. return t;
  9189. }
  9190. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9191. const std::vector<NoProxyEntry> &entries) {
  9192. if (target.hostname.empty()) { return false; }
  9193. for (const auto &e : entries) {
  9194. switch (e.kind) {
  9195. case NoProxyKind::Wildcard: return true;
  9196. case NoProxyKind::IPv4Cidr:
  9197. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9198. return true;
  9199. }
  9200. break;
  9201. case NoProxyKind::IPv6Cidr:
  9202. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9203. return true;
  9204. }
  9205. break;
  9206. case NoProxyKind::HostnameSuffix:
  9207. if (target.is_ipv4 || target.is_ipv6) { break; }
  9208. if (target.hostname == e.hostname_pattern) { return true; }
  9209. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9210. // an entry of "example.com".
  9211. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9212. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9213. if (target.hostname[offset - 1] == '.' &&
  9214. target.hostname.compare(offset, e.hostname_pattern.size(),
  9215. e.hostname_pattern) == 0) {
  9216. return true;
  9217. }
  9218. }
  9219. break;
  9220. }
  9221. }
  9222. return false;
  9223. }
  9224. template <typename T>
  9225. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9226. T header_writer, Error &error) {
  9227. for (const auto &h : headers) {
  9228. if (!detail::fields::is_field_name(h.first) ||
  9229. !detail::fields::is_field_value(h.second)) {
  9230. error = Error::InvalidHeaders;
  9231. return false;
  9232. }
  9233. }
  9234. if (header_writer(strm, headers) <= 0) {
  9235. error = Error::Write;
  9236. return false;
  9237. }
  9238. return true;
  9239. }
  9240. } // namespace detail
  9241. /*
  9242. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9243. */
  9244. #ifdef CPPHTTPLIB_SSL_ENABLED
  9245. namespace detail {
  9246. // SSL socket stream implementation
  9247. inline SSLSocketStream::SSLSocketStream(
  9248. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9249. time_t read_timeout_usec, time_t write_timeout_sec,
  9250. time_t write_timeout_usec, time_t max_timeout_msec,
  9251. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9252. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9253. read_timeout_usec_(read_timeout_usec),
  9254. write_timeout_sec_(write_timeout_sec),
  9255. write_timeout_usec_(write_timeout_usec),
  9256. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9258. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9259. // Note: create_session() also clears this, but SSLClient currently
  9260. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9261. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9262. // SSL session was created.
  9263. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9264. #endif
  9265. }
  9266. inline SSLSocketStream::~SSLSocketStream() = default;
  9267. inline bool SSLSocketStream::is_readable() const {
  9268. return tls::pending(session_) > 0;
  9269. }
  9270. inline bool SSLSocketStream::wait_readable() const {
  9271. if (max_timeout_msec_ <= 0) {
  9272. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9273. }
  9274. time_t read_timeout_sec;
  9275. time_t read_timeout_usec;
  9276. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9277. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9278. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9279. }
  9280. inline bool SSLSocketStream::wait_writable() const {
  9281. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9282. !tls::is_peer_closed(session_, sock_);
  9283. }
  9284. inline bool SSLSocketStream::is_peer_alive() const {
  9285. return !tls::is_peer_closed(session_, sock_);
  9286. }
  9287. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9288. if (tls::pending(session_) > 0) {
  9289. tls::TlsError err;
  9290. auto ret = tls::read(session_, ptr, size, err);
  9291. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9292. error_ = Error::ConnectionClosed;
  9293. }
  9294. return ret;
  9295. } else if (wait_readable()) {
  9296. tls::TlsError err;
  9297. auto ret = tls::read(session_, ptr, size, err);
  9298. if (ret < 0) {
  9299. auto n = 1000;
  9300. #ifdef _WIN32
  9301. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9302. (err.code == tls::ErrorCode::SyscallError &&
  9303. WSAGetLastError() == WSAETIMEDOUT))) {
  9304. #else
  9305. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9306. #endif
  9307. if (tls::pending(session_) > 0) {
  9308. return tls::read(session_, ptr, size, err);
  9309. } else if (wait_readable()) {
  9310. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9311. ret = tls::read(session_, ptr, size, err);
  9312. if (ret >= 0) { return ret; }
  9313. } else {
  9314. break;
  9315. }
  9316. }
  9317. assert(ret < 0);
  9318. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9319. error_ = Error::ConnectionClosed;
  9320. }
  9321. return ret;
  9322. } else {
  9323. error_ = Error::Timeout;
  9324. return -1;
  9325. }
  9326. }
  9327. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9328. if (wait_writable()) {
  9329. auto handle_size =
  9330. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9331. tls::TlsError err;
  9332. auto ret = tls::write(session_, ptr, handle_size, err);
  9333. if (ret < 0) {
  9334. auto n = 1000;
  9335. #ifdef _WIN32
  9336. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9337. (err.code == tls::ErrorCode::SyscallError &&
  9338. WSAGetLastError() == WSAETIMEDOUT))) {
  9339. #else
  9340. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9341. #endif
  9342. if (wait_writable()) {
  9343. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9344. ret = tls::write(session_, ptr, handle_size, err);
  9345. if (ret >= 0) { return ret; }
  9346. } else {
  9347. break;
  9348. }
  9349. }
  9350. assert(ret < 0);
  9351. }
  9352. return ret;
  9353. }
  9354. return -1;
  9355. }
  9356. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9357. int &port) const {
  9358. detail::get_remote_ip_and_port(sock_, ip, port);
  9359. }
  9360. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9361. int &port) const {
  9362. detail::get_local_ip_and_port(sock_, ip, port);
  9363. }
  9364. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9365. inline time_t SSLSocketStream::duration() const {
  9366. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9367. std::chrono::steady_clock::now() - start_time_)
  9368. .count();
  9369. }
  9370. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9371. read_timeout_sec_ = sec;
  9372. read_timeout_usec_ = usec;
  9373. }
  9374. } // namespace detail
  9375. #endif // CPPHTTPLIB_SSL_ENABLED
  9376. /*
  9377. * Group 4: Server implementation
  9378. */
  9379. // HTTP server implementation
  9380. inline Server::Server()
  9381. : new_task_queue([] {
  9382. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9383. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9384. }) {
  9385. #ifndef _WIN32
  9386. signal(SIGPIPE, SIG_IGN);
  9387. #endif
  9388. }
  9389. inline Server::~Server() = default;
  9390. inline std::unique_ptr<detail::MatcherBase>
  9391. Server::make_matcher(const std::string &pattern) {
  9392. if (pattern.find("/:") != std::string::npos) {
  9393. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9394. } else {
  9395. return detail::make_unique<detail::RegexMatcher>(pattern);
  9396. }
  9397. }
  9398. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9399. return add_handler(get_handlers_, pattern, std::move(handler));
  9400. }
  9401. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9402. return add_handler(post_handlers_, pattern, std::move(handler));
  9403. }
  9404. inline Server &Server::Post(const std::string &pattern,
  9405. HandlerWithContentReader handler) {
  9406. return add_handler(post_handlers_for_content_reader_, pattern,
  9407. std::move(handler));
  9408. }
  9409. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9410. return add_handler(put_handlers_, pattern, std::move(handler));
  9411. }
  9412. inline Server &Server::Put(const std::string &pattern,
  9413. HandlerWithContentReader handler) {
  9414. return add_handler(put_handlers_for_content_reader_, pattern,
  9415. std::move(handler));
  9416. }
  9417. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9418. return add_handler(patch_handlers_, pattern, std::move(handler));
  9419. }
  9420. inline Server &Server::Patch(const std::string &pattern,
  9421. HandlerWithContentReader handler) {
  9422. return add_handler(patch_handlers_for_content_reader_, pattern,
  9423. std::move(handler));
  9424. }
  9425. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9426. return add_handler(delete_handlers_, pattern, std::move(handler));
  9427. }
  9428. inline Server &Server::Delete(const std::string &pattern,
  9429. HandlerWithContentReader handler) {
  9430. return add_handler(delete_handlers_for_content_reader_, pattern,
  9431. std::move(handler));
  9432. }
  9433. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9434. return add_handler(options_handlers_, pattern, std::move(handler));
  9435. }
  9436. inline Server &Server::WebSocket(const std::string &pattern,
  9437. WebSocketHandler handler) {
  9438. websocket_handlers_.push_back(
  9439. {make_matcher(pattern), std::move(handler), nullptr});
  9440. return *this;
  9441. }
  9442. inline Server &Server::WebSocket(const std::string &pattern,
  9443. WebSocketHandler handler,
  9444. SubProtocolSelector sub_protocol_selector) {
  9445. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9446. std::move(sub_protocol_selector)});
  9447. return *this;
  9448. }
  9449. inline bool Server::set_base_dir(const std::string &dir,
  9450. const std::string &mount_point) {
  9451. return set_mount_point(mount_point, dir);
  9452. }
  9453. inline bool Server::set_mount_point(const std::string &mount_point,
  9454. const std::string &dir, Headers headers) {
  9455. detail::FileStat stat(dir);
  9456. if (stat.is_dir()) {
  9457. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9458. if (!mnt.empty() && mnt[0] == '/') {
  9459. std::string resolved_base;
  9460. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9461. #if defined(_WIN32)
  9462. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9463. resolved_base += '\\';
  9464. }
  9465. #else
  9466. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9467. #endif
  9468. }
  9469. base_dirs_.push_back(
  9470. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9471. return true;
  9472. }
  9473. }
  9474. return false;
  9475. }
  9476. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9477. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9478. if (it->mount_point == mount_point) {
  9479. base_dirs_.erase(it);
  9480. return true;
  9481. }
  9482. }
  9483. return false;
  9484. }
  9485. inline Server &
  9486. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9487. const std::string &mime) {
  9488. file_extension_and_mimetype_map_[ext] = mime;
  9489. return *this;
  9490. }
  9491. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9492. default_file_mimetype_ = mime;
  9493. return *this;
  9494. }
  9495. inline Server &Server::set_file_request_handler(Handler handler) {
  9496. file_request_handler_ = std::move(handler);
  9497. return *this;
  9498. }
  9499. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9500. std::true_type) {
  9501. error_handler_ = std::move(handler);
  9502. return *this;
  9503. }
  9504. inline Server &Server::set_error_handler_core(Handler handler,
  9505. std::false_type) {
  9506. error_handler_ = [handler](const Request &req, Response &res) {
  9507. handler(req, res);
  9508. return HandlerResponse::Handled;
  9509. };
  9510. return *this;
  9511. }
  9512. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9513. exception_handler_ = std::move(handler);
  9514. return *this;
  9515. }
  9516. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9517. pre_routing_handler_ = std::move(handler);
  9518. return *this;
  9519. }
  9520. inline Server &Server::set_post_routing_handler(Handler handler) {
  9521. post_routing_handler_ = std::move(handler);
  9522. return *this;
  9523. }
  9524. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9525. pre_request_handler_ = std::move(handler);
  9526. return *this;
  9527. }
  9528. inline Server &Server::set_logger(Logger logger) {
  9529. logger_ = std::move(logger);
  9530. return *this;
  9531. }
  9532. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9533. error_logger_ = std::move(error_logger);
  9534. return *this;
  9535. }
  9536. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9537. pre_compression_logger_ = std::move(logger);
  9538. return *this;
  9539. }
  9540. inline Server &
  9541. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9542. expect_100_continue_handler_ = std::move(handler);
  9543. return *this;
  9544. }
  9545. inline Server &Server::set_start_handler(StartHandler handler) {
  9546. start_handler_ = std::move(handler);
  9547. return *this;
  9548. }
  9549. inline Server &Server::set_address_family(int family) {
  9550. address_family_ = family;
  9551. return *this;
  9552. }
  9553. inline Server &Server::set_tcp_nodelay(bool on) {
  9554. tcp_nodelay_ = on;
  9555. return *this;
  9556. }
  9557. inline Server &Server::set_ipv6_v6only(bool on) {
  9558. ipv6_v6only_ = on;
  9559. return *this;
  9560. }
  9561. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9562. socket_options_ = std::move(socket_options);
  9563. return *this;
  9564. }
  9565. inline Server &Server::set_default_headers(Headers headers) {
  9566. default_headers_ = std::move(headers);
  9567. return *this;
  9568. }
  9569. inline Server &Server::set_header_writer(
  9570. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9571. header_writer_ = writer;
  9572. return *this;
  9573. }
  9574. inline Server &
  9575. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9576. trusted_proxies_ = proxies;
  9577. return *this;
  9578. }
  9579. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9580. keep_alive_max_count_ = count;
  9581. return *this;
  9582. }
  9583. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9584. keep_alive_timeout_sec_ = sec;
  9585. return *this;
  9586. }
  9587. template <class Rep, class Period>
  9588. inline Server &Server::set_keep_alive_timeout(
  9589. const std::chrono::duration<Rep, Period> &duration) {
  9590. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9591. set_keep_alive_timeout(sec);
  9592. });
  9593. return *this;
  9594. }
  9595. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9596. read_timeout_sec_ = sec;
  9597. read_timeout_usec_ = usec;
  9598. return *this;
  9599. }
  9600. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9601. write_timeout_sec_ = sec;
  9602. write_timeout_usec_ = usec;
  9603. return *this;
  9604. }
  9605. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9606. idle_interval_sec_ = sec;
  9607. idle_interval_usec_ = usec;
  9608. return *this;
  9609. }
  9610. inline Server &Server::set_payload_max_length(size_t length) {
  9611. payload_max_length_ = length;
  9612. return *this;
  9613. }
  9614. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9615. websocket_max_missed_pongs_ = count;
  9616. return *this;
  9617. }
  9618. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9619. websocket_ping_interval_sec_ = sec;
  9620. return *this;
  9621. }
  9622. template <class Rep, class Period>
  9623. inline Server &Server::set_websocket_ping_interval(
  9624. const std::chrono::duration<Rep, Period> &duration) {
  9625. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9626. set_websocket_ping_interval(sec);
  9627. });
  9628. return *this;
  9629. }
  9630. inline bool Server::bind_to_port(const std::string &host, int port,
  9631. int socket_flags) {
  9632. auto ret = bind_internal(host, port, socket_flags);
  9633. if (ret == -1) { is_decommissioned = true; }
  9634. return ret >= 0;
  9635. }
  9636. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9637. auto ret = bind_internal(host, 0, socket_flags);
  9638. if (ret == -1) { is_decommissioned = true; }
  9639. return ret;
  9640. }
  9641. inline bool Server::listen_after_bind() { return listen_internal(); }
  9642. inline bool Server::listen(const std::string &host, int port,
  9643. int socket_flags) {
  9644. return bind_to_port(host, port, socket_flags) && listen_internal();
  9645. }
  9646. inline bool Server::is_running() const { return is_running_; }
  9647. inline void Server::wait_until_ready() const {
  9648. while (!is_running_ && !is_decommissioned) {
  9649. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9650. }
  9651. }
  9652. inline void Server::stop() noexcept {
  9653. if (is_running_) {
  9654. assert(svr_sock_ != INVALID_SOCKET);
  9655. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9656. detail::shutdown_socket(sock);
  9657. detail::close_socket(sock);
  9658. }
  9659. is_decommissioned = false;
  9660. }
  9661. inline void Server::decommission() { is_decommissioned = true; }
  9662. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9663. auto len = strlen(s);
  9664. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9665. len -= 2;
  9666. {
  9667. size_t count = 0;
  9668. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9669. switch (count) {
  9670. case 0: req.method = std::string(b, e); break;
  9671. case 1: req.target = std::string(b, e); break;
  9672. case 2: req.version = std::string(b, e); break;
  9673. default: break;
  9674. }
  9675. count++;
  9676. });
  9677. if (count != 3) { return false; }
  9678. }
  9679. thread_local const std::set<std::string> methods{
  9680. "GET", "HEAD", "POST", "PUT", "DELETE",
  9681. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9682. if (methods.find(req.method) == methods.end()) {
  9683. output_error_log(Error::InvalidHTTPMethod, &req);
  9684. return false;
  9685. }
  9686. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9687. output_error_log(Error::InvalidHTTPVersion, &req);
  9688. return false;
  9689. }
  9690. {
  9691. // Skip URL fragment
  9692. for (size_t i = 0; i < req.target.size(); i++) {
  9693. if (req.target[i] == '#') {
  9694. req.target.erase(i);
  9695. break;
  9696. }
  9697. }
  9698. detail::divide(req.target, '?',
  9699. [&](const char *lhs_data, std::size_t lhs_size,
  9700. const char *rhs_data, std::size_t rhs_size) {
  9701. req.path =
  9702. decode_path_component(std::string(lhs_data, lhs_size));
  9703. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9704. });
  9705. }
  9706. return true;
  9707. }
  9708. inline bool Server::write_response(Stream &strm, bool close_connection,
  9709. Request &req, Response &res) {
  9710. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9711. // incorrectly to the error content.
  9712. req.ranges.clear();
  9713. return write_response_core(strm, close_connection, req, res, false);
  9714. }
  9715. inline bool Server::write_response_with_content(Stream &strm,
  9716. bool close_connection,
  9717. const Request &req,
  9718. Response &res) {
  9719. return write_response_core(strm, close_connection, req, res, true);
  9720. }
  9721. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9722. const Request &req, Response &res,
  9723. bool need_apply_ranges) {
  9724. assert(res.status != -1);
  9725. if (400 <= res.status && error_handler_ &&
  9726. error_handler_(req, res) == HandlerResponse::Handled) {
  9727. need_apply_ranges = true;
  9728. }
  9729. std::string content_type;
  9730. std::string boundary;
  9731. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9732. // Prepare additional headers
  9733. if (close_connection || req.get_header_value("Connection") == "close" ||
  9734. 400 <= res.status) { // Don't leave connections open after errors
  9735. res.set_header("Connection", "close");
  9736. } else {
  9737. std::string s = "timeout=";
  9738. s += std::to_string(keep_alive_timeout_sec_);
  9739. s += ", max=";
  9740. s += std::to_string(keep_alive_max_count_);
  9741. res.set_header("Keep-Alive", s);
  9742. }
  9743. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9744. !res.has_header("Content-Type")) {
  9745. res.set_header("Content-Type", "text/plain");
  9746. }
  9747. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9748. !res.has_header("Content-Length")) {
  9749. res.set_header("Content-Length", "0");
  9750. }
  9751. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9752. res.set_header("Accept-Ranges", "bytes");
  9753. }
  9754. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9755. // Response line and headers
  9756. detail::BufferStream bstrm;
  9757. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9758. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9759. // Combine small body with headers to reduce write syscalls
  9760. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9761. bstrm.write(res.body.data(), res.body.size());
  9762. }
  9763. // Log before writing to avoid race condition with client-side code that
  9764. // accesses logger-captured data immediately after receiving the response.
  9765. output_log(req, res);
  9766. // Flush buffer
  9767. auto &data = bstrm.get_buffer();
  9768. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9769. // Streaming body
  9770. auto ret = true;
  9771. if (req.method != "HEAD" && res.content_provider_) {
  9772. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9773. res.content_provider_success_ = true;
  9774. } else {
  9775. ret = false;
  9776. }
  9777. }
  9778. return ret;
  9779. }
  9780. inline bool
  9781. Server::write_content_with_provider(Stream &strm, const Request &req,
  9782. Response &res, const std::string &boundary,
  9783. const std::string &content_type) {
  9784. auto is_shutting_down = [this]() {
  9785. return this->svr_sock_ == INVALID_SOCKET;
  9786. };
  9787. if (res.content_length_ > 0) {
  9788. if (req.ranges.empty()) {
  9789. return detail::write_content(strm, res.content_provider_, 0,
  9790. res.content_length_, is_shutting_down);
  9791. } else if (req.ranges.size() == 1) {
  9792. auto offset_and_length = detail::get_range_offset_and_length(
  9793. req.ranges[0], res.content_length_);
  9794. return detail::write_content(strm, res.content_provider_,
  9795. offset_and_length.first,
  9796. offset_and_length.second, is_shutting_down);
  9797. } else {
  9798. return detail::write_multipart_ranges_data(
  9799. strm, req, res, boundary, content_type, res.content_length_,
  9800. is_shutting_down);
  9801. }
  9802. } else {
  9803. if (res.is_chunked_content_provider_) {
  9804. auto type = detail::encoding_type(req, res);
  9805. auto compressor = detail::make_compressor(type);
  9806. if (!compressor) {
  9807. compressor = detail::make_unique<detail::nocompressor>();
  9808. }
  9809. return detail::write_content_chunked(strm, res.content_provider_,
  9810. is_shutting_down, *compressor);
  9811. } else {
  9812. return detail::write_content_without_length(strm, res.content_provider_,
  9813. is_shutting_down);
  9814. }
  9815. }
  9816. }
  9817. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9818. FormFields::iterator cur_field;
  9819. FormFiles::iterator cur_file;
  9820. auto is_text_field = false;
  9821. size_t count = 0;
  9822. if (read_content_core(
  9823. strm, req, res,
  9824. // Regular
  9825. [&](const char *buf, size_t n) {
  9826. // Prevent arithmetic overflow when checking sizes.
  9827. // Avoid computing (req.body.size() + n) directly because
  9828. // adding two unsigned `size_t` values can wrap around and
  9829. // produce a small result instead of indicating overflow.
  9830. // Instead, check using subtraction: ensure `n` does not
  9831. // exceed the remaining capacity `max_size() - size()`.
  9832. if (req.body.size() >= req.body.max_size() ||
  9833. n > req.body.max_size() - req.body.size()) {
  9834. return false;
  9835. }
  9836. // Limit decompressed body size to payload_max_length_ to protect
  9837. // against "zip bomb" attacks where a small compressed payload
  9838. // decompresses to a massive size.
  9839. if (payload_max_length_ > 0 &&
  9840. (req.body.size() >= payload_max_length_ ||
  9841. n > payload_max_length_ - req.body.size())) {
  9842. return false;
  9843. }
  9844. req.body.append(buf, n);
  9845. return true;
  9846. },
  9847. // Multipart FormData
  9848. [&](const FormData &file) {
  9849. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9850. output_error_log(Error::TooManyFormDataFiles, &req);
  9851. return false;
  9852. }
  9853. if (file.filename.empty()) {
  9854. cur_field = req.form.fields.emplace(
  9855. file.name, FormField{file.name, file.content, file.headers});
  9856. is_text_field = true;
  9857. } else {
  9858. cur_file = req.form.files.emplace(file.name, file);
  9859. is_text_field = false;
  9860. }
  9861. return true;
  9862. },
  9863. [&](const char *buf, size_t n) {
  9864. if (is_text_field) {
  9865. auto &content = cur_field->second.content;
  9866. if (content.size() + n > content.max_size()) { return false; }
  9867. content.append(buf, n);
  9868. } else {
  9869. auto &content = cur_file->second.content;
  9870. if (content.size() + n > content.max_size()) { return false; }
  9871. content.append(buf, n);
  9872. }
  9873. return true;
  9874. })) {
  9875. const auto &content_type = req.get_header_value("Content-Type");
  9876. if (detail::extract_media_type(content_type) ==
  9877. "application/x-www-form-urlencoded") {
  9878. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9879. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9880. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9881. return false;
  9882. }
  9883. detail::parse_query_text(req.body, req.params);
  9884. }
  9885. return true;
  9886. }
  9887. return false;
  9888. }
  9889. inline bool Server::read_content_with_content_receiver(
  9890. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9891. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9892. return read_content_core(strm, req, res, std::move(receiver),
  9893. std::move(multipart_header),
  9894. std::move(multipart_receiver));
  9895. }
  9896. inline bool Server::read_content_core(
  9897. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9898. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9899. detail::FormDataParser multipart_form_data_parser;
  9900. ContentReceiverWithProgress out;
  9901. if (req.is_multipart_form_data()) {
  9902. const auto &content_type = req.get_header_value("Content-Type");
  9903. std::string boundary;
  9904. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9905. res.status = StatusCode::BadRequest_400;
  9906. output_error_log(Error::MultipartParsing, &req);
  9907. return false;
  9908. }
  9909. multipart_form_data_parser.set_boundary(std::move(boundary));
  9910. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9911. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9912. multipart_receiver);
  9913. };
  9914. } else {
  9915. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9916. size_t /*len*/) { return receiver(buf, n); };
  9917. }
  9918. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9919. // For non-SSL builds we still scan non-persistent connections for stray
  9920. // body bytes so the payload limit is enforced (413). On keep-alive,
  9921. // pending bytes may be the next request (issue #2450), so skip.
  9922. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9923. if (!req.has_header("Content-Length") &&
  9924. !detail::is_chunked_transfer_encoding(req.headers)) {
  9925. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9926. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9927. auto has_data = strm.is_readable();
  9928. if (!has_data) {
  9929. auto s = strm.socket();
  9930. if (s != INVALID_SOCKET) {
  9931. has_data = detail::select_read(s, 0, 0) > 0;
  9932. }
  9933. }
  9934. if (has_data) {
  9935. auto result =
  9936. detail::read_content_without_length(strm, payload_max_length_, out);
  9937. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9938. res.status = StatusCode::PayloadTooLarge_413;
  9939. return false;
  9940. } else if (result != detail::ReadContentResult::Success) {
  9941. return false;
  9942. }
  9943. return true;
  9944. }
  9945. }
  9946. return true;
  9947. }
  9948. #else
  9949. if (!req.has_header("Content-Length") &&
  9950. !detail::is_chunked_transfer_encoding(req.headers)) {
  9951. return true;
  9952. }
  9953. #endif
  9954. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9955. out, true)) {
  9956. return false;
  9957. }
  9958. req.body_consumed_ = true;
  9959. if (req.is_multipart_form_data()) {
  9960. if (!multipart_form_data_parser.is_valid()) {
  9961. res.status = StatusCode::BadRequest_400;
  9962. output_error_log(Error::MultipartParsing, &req);
  9963. return false;
  9964. }
  9965. }
  9966. return true;
  9967. }
  9968. inline bool Server::handle_file_request(Request &req, Response &res) {
  9969. for (const auto &entry : base_dirs_) {
  9970. // Prefix match
  9971. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9972. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9973. if (detail::is_valid_path(sub_path)) {
  9974. auto path = entry.base_dir + sub_path;
  9975. if (path.back() == '/') { path += "index.html"; }
  9976. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9977. // but symlinks/junctions can still escape the base directory.
  9978. if (!entry.resolved_base_dir.empty()) {
  9979. std::string resolved_path;
  9980. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9981. !detail::is_path_within_base(resolved_path,
  9982. entry.resolved_base_dir)) {
  9983. res.status = StatusCode::Forbidden_403;
  9984. return true;
  9985. }
  9986. }
  9987. detail::FileStat stat(path);
  9988. if (stat.is_dir()) {
  9989. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9990. return true;
  9991. }
  9992. if (stat.is_file()) {
  9993. for (const auto &kv : entry.headers) {
  9994. res.set_header(kv.first, kv.second);
  9995. }
  9996. auto etag = detail::compute_etag(stat);
  9997. if (!etag.empty()) { res.set_header("ETag", etag); }
  9998. auto mtime = stat.mtime();
  9999. auto last_modified = detail::file_mtime_to_http_date(mtime);
  10000. if (!last_modified.empty()) {
  10001. res.set_header("Last-Modified", last_modified);
  10002. }
  10003. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  10004. check_if_range(req, etag, mtime);
  10005. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10006. if (!mm->is_open()) {
  10007. output_error_log(Error::OpenFile, &req);
  10008. return false;
  10009. }
  10010. res.set_content_provider(
  10011. mm->size(),
  10012. detail::find_content_type(path, file_extension_and_mimetype_map_,
  10013. default_file_mimetype_),
  10014. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10015. sink.write(mm->data() + offset, length);
  10016. return true;
  10017. });
  10018. if (req.method != "HEAD" && file_request_handler_) {
  10019. file_request_handler_(req, res);
  10020. }
  10021. return true;
  10022. } else {
  10023. output_error_log(Error::OpenFile, &req);
  10024. }
  10025. }
  10026. }
  10027. }
  10028. return false;
  10029. }
  10030. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  10031. const std::string &etag,
  10032. time_t mtime) const {
  10033. // Handle conditional GET:
  10034. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  10035. // 2. If-Modified-Since is checked only when If-None-Match is absent
  10036. if (req.has_header("If-None-Match")) {
  10037. if (!etag.empty()) {
  10038. auto val = req.get_header_value("If-None-Match");
  10039. // NOTE: We use exact string matching here. This works correctly
  10040. // because our server always generates weak ETags (W/"..."), and
  10041. // clients typically send back the same ETag they received.
  10042. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  10043. // If-None-Match, where W/"x" and "x" would match, but this
  10044. // simplified implementation requires exact matches.
  10045. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  10046. [&](const char *b, const char *e) {
  10047. auto seg_len = static_cast<size_t>(e - b);
  10048. return (seg_len == 1 && *b == '*') ||
  10049. (seg_len == etag.size() &&
  10050. std::equal(b, e, etag.begin()));
  10051. });
  10052. if (ret) {
  10053. res.status = StatusCode::NotModified_304;
  10054. return true;
  10055. }
  10056. }
  10057. } else if (req.has_header("If-Modified-Since")) {
  10058. auto val = req.get_header_value("If-Modified-Since");
  10059. auto t = detail::parse_http_date(val);
  10060. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10061. res.status = StatusCode::NotModified_304;
  10062. return true;
  10063. }
  10064. }
  10065. return false;
  10066. }
  10067. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10068. time_t mtime) const {
  10069. // Handle If-Range for partial content requests (RFC 9110
  10070. // Section 13.1.5). If-Range is only evaluated when Range header is
  10071. // present. If the validator matches, serve partial content; otherwise
  10072. // serve full content.
  10073. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10074. auto val = req.get_header_value("If-Range");
  10075. auto is_valid_range = [&]() {
  10076. if (detail::is_strong_etag(val)) {
  10077. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10078. // comparison.
  10079. return (!etag.empty() && val == etag);
  10080. } else if (detail::is_weak_etag(val)) {
  10081. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10082. return false;
  10083. } else {
  10084. // HTTP-date comparison
  10085. auto t = detail::parse_http_date(val);
  10086. return (t != static_cast<time_t>(-1) && mtime <= t);
  10087. }
  10088. };
  10089. if (!is_valid_range()) {
  10090. // Validator doesn't match: ignore Range and serve full content
  10091. req.ranges.clear();
  10092. return false;
  10093. }
  10094. }
  10095. return true;
  10096. }
  10097. inline socket_t
  10098. Server::create_server_socket(const std::string &host, int port,
  10099. int socket_flags,
  10100. SocketOptions socket_options) const {
  10101. return detail::create_socket(
  10102. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10103. ipv6_v6only_, std::move(socket_options),
  10104. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10105. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10106. output_error_log(Error::BindIPAddress, nullptr);
  10107. return false;
  10108. }
  10109. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10110. output_error_log(Error::Listen, nullptr);
  10111. return false;
  10112. }
  10113. return true;
  10114. });
  10115. }
  10116. inline int Server::bind_internal(const std::string &host, int port,
  10117. int socket_flags) {
  10118. if (is_decommissioned) { return -1; }
  10119. if (!is_valid()) { return -1; }
  10120. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10121. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10122. if (port == 0) {
  10123. struct sockaddr_storage addr;
  10124. socklen_t addr_len = sizeof(addr);
  10125. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10126. &addr_len) == -1) {
  10127. output_error_log(Error::GetSockName, nullptr);
  10128. return -1;
  10129. }
  10130. if (addr.ss_family == AF_INET) {
  10131. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10132. } else if (addr.ss_family == AF_INET6) {
  10133. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10134. } else {
  10135. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10136. return -1;
  10137. }
  10138. } else {
  10139. return port;
  10140. }
  10141. }
  10142. inline bool Server::listen_internal() {
  10143. if (is_decommissioned) { return false; }
  10144. auto ret = true;
  10145. is_running_ = true;
  10146. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10147. if (start_handler_) { start_handler_(); }
  10148. {
  10149. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10150. while (svr_sock_ != INVALID_SOCKET) {
  10151. #ifndef _WIN32
  10152. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10153. #endif
  10154. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10155. idle_interval_usec_);
  10156. if (val == 0) { // Timeout
  10157. task_queue->on_idle();
  10158. continue;
  10159. }
  10160. #ifndef _WIN32
  10161. }
  10162. #endif
  10163. #if defined _WIN32
  10164. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10165. // OVERLAPPED
  10166. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10167. #elif defined SOCK_CLOEXEC
  10168. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10169. #else
  10170. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10171. #endif
  10172. if (sock == INVALID_SOCKET) {
  10173. if (errno == EMFILE) {
  10174. // The per-process limit of open file descriptors has been reached.
  10175. // Try to accept new connections after a short sleep.
  10176. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10177. continue;
  10178. } else if (errno == EINTR || errno == EAGAIN) {
  10179. continue;
  10180. }
  10181. if (svr_sock_ != INVALID_SOCKET) {
  10182. detail::close_socket(svr_sock_);
  10183. ret = false;
  10184. output_error_log(Error::Connection, nullptr);
  10185. } else {
  10186. ; // The server socket was closed by user.
  10187. }
  10188. break;
  10189. }
  10190. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10191. read_timeout_sec_, read_timeout_usec_);
  10192. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10193. write_timeout_sec_, write_timeout_usec_);
  10194. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10195. if (!task_queue->enqueue(
  10196. [this, sock]() { process_and_close_socket(sock); })) {
  10197. output_error_log(Error::ResourceExhaustion, nullptr);
  10198. detail::shutdown_socket(sock);
  10199. detail::close_socket(sock);
  10200. }
  10201. }
  10202. task_queue->shutdown();
  10203. }
  10204. is_decommissioned = !ret;
  10205. return ret;
  10206. }
  10207. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10208. if (pre_routing_handler_ &&
  10209. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10210. return true;
  10211. }
  10212. // File handler
  10213. if ((req.method == "GET" || req.method == "HEAD") &&
  10214. handle_file_request(req, res)) {
  10215. return true;
  10216. }
  10217. if (detail::expect_content(req)) {
  10218. // Content reader handler
  10219. {
  10220. // Track whether the ContentReader was aborted due to the decompressed
  10221. // payload exceeding `payload_max_length_`.
  10222. // The user handler runs after the lambda returns, so we must restore the
  10223. // 413 status if the handler overwrites it.
  10224. bool content_reader_payload_too_large = false;
  10225. ContentReader reader(
  10226. [&](ContentReceiver receiver) {
  10227. auto result = read_content_with_content_receiver(
  10228. strm, req, res, std::move(receiver), nullptr, nullptr);
  10229. if (!result) {
  10230. output_error_log(Error::Read, &req);
  10231. if (res.status == StatusCode::PayloadTooLarge_413) {
  10232. content_reader_payload_too_large = true;
  10233. }
  10234. }
  10235. return result;
  10236. },
  10237. [&](FormDataHeader header, ContentReceiver receiver) {
  10238. auto result = read_content_with_content_receiver(
  10239. strm, req, res, nullptr, std::move(header),
  10240. std::move(receiver));
  10241. if (!result) {
  10242. output_error_log(Error::Read, &req);
  10243. if (res.status == StatusCode::PayloadTooLarge_413) {
  10244. content_reader_payload_too_large = true;
  10245. }
  10246. }
  10247. return result;
  10248. });
  10249. bool dispatched = false;
  10250. if (req.method == "POST") {
  10251. dispatched = dispatch_request_for_content_reader(
  10252. req, res, std::move(reader), post_handlers_for_content_reader_);
  10253. } else if (req.method == "PUT") {
  10254. dispatched = dispatch_request_for_content_reader(
  10255. req, res, std::move(reader), put_handlers_for_content_reader_);
  10256. } else if (req.method == "PATCH") {
  10257. dispatched = dispatch_request_for_content_reader(
  10258. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10259. } else if (req.method == "DELETE") {
  10260. dispatched = dispatch_request_for_content_reader(
  10261. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10262. }
  10263. if (dispatched) {
  10264. if (content_reader_payload_too_large) {
  10265. // Enforce the limit: override any status the handler may have set
  10266. // and return false so the error path sends a plain 413 response.
  10267. res.status = StatusCode::PayloadTooLarge_413;
  10268. res.body.clear();
  10269. res.content_length_ = 0;
  10270. res.content_provider_ = nullptr;
  10271. return false;
  10272. }
  10273. return true;
  10274. }
  10275. }
  10276. // NOTE: `req.body` is not read here. For a regular handler the body is
  10277. // read inside dispatch_request(), after the route has matched and the
  10278. // pre-request handler has approved the request, so that a rejected
  10279. // request (e.g. failed authentication) never forces us to buffer a
  10280. // potentially large body.
  10281. }
  10282. // Regular handler
  10283. if (req.method == "GET" || req.method == "HEAD") {
  10284. return dispatch_request(req, res, get_handlers_, strm);
  10285. } else if (req.method == "POST") {
  10286. return dispatch_request(req, res, post_handlers_, strm);
  10287. } else if (req.method == "PUT") {
  10288. return dispatch_request(req, res, put_handlers_, strm);
  10289. } else if (req.method == "DELETE") {
  10290. return dispatch_request(req, res, delete_handlers_, strm);
  10291. } else if (req.method == "OPTIONS") {
  10292. return dispatch_request(req, res, options_handlers_, strm);
  10293. } else if (req.method == "PATCH") {
  10294. return dispatch_request(req, res, patch_handlers_, strm);
  10295. }
  10296. res.status = StatusCode::BadRequest_400;
  10297. return false;
  10298. }
  10299. inline bool Server::dispatch_request(Request &req, Response &res,
  10300. const Handlers &handlers, Stream &strm) {
  10301. for (const auto &x : handlers) {
  10302. const auto &matcher = x.first;
  10303. const auto &handler = x.second;
  10304. if (matcher->match(req)) {
  10305. req.matched_route = matcher->pattern();
  10306. // Run the pre-request handler before reading the body so a rejected
  10307. // request (e.g. failed authentication) never forces us to buffer a
  10308. // potentially large body. `req.matched_route` is available here.
  10309. if (pre_request_handler_ &&
  10310. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10311. return true;
  10312. }
  10313. // The route matched and the request was approved; read the body now.
  10314. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10315. output_error_log(Error::Read, &req);
  10316. return false;
  10317. }
  10318. handler(req, res);
  10319. return true;
  10320. }
  10321. }
  10322. return false;
  10323. }
  10324. inline void Server::apply_ranges(const Request &req, Response &res,
  10325. std::string &content_type,
  10326. std::string &boundary) const {
  10327. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10328. auto it = res.headers.find("Content-Type");
  10329. if (it != res.headers.end()) {
  10330. content_type = it->second;
  10331. res.headers.erase(it);
  10332. }
  10333. boundary = detail::make_multipart_data_boundary();
  10334. res.set_header("Content-Type",
  10335. "multipart/byteranges; boundary=" + boundary);
  10336. }
  10337. auto type = detail::encoding_type(req, res);
  10338. if (res.body.empty()) {
  10339. if (res.content_length_ > 0) {
  10340. size_t length = 0;
  10341. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10342. length = res.content_length_;
  10343. } else if (req.ranges.size() == 1) {
  10344. auto offset_and_length = detail::get_range_offset_and_length(
  10345. req.ranges[0], res.content_length_);
  10346. length = offset_and_length.second;
  10347. auto content_range = detail::make_content_range_header_field(
  10348. offset_and_length, res.content_length_);
  10349. res.set_header("Content-Range", content_range);
  10350. } else {
  10351. length = detail::get_multipart_ranges_data_length(
  10352. req, boundary, content_type, res.content_length_);
  10353. }
  10354. res.set_header("Content-Length", std::to_string(length));
  10355. } else {
  10356. if (res.content_provider_) {
  10357. if (res.is_chunked_content_provider_) {
  10358. res.set_header("Transfer-Encoding", "chunked");
  10359. if (type != detail::EncodingType::None) {
  10360. res.set_header("Content-Encoding", detail::encoding_name(type));
  10361. res.set_header("Vary", "Accept-Encoding");
  10362. }
  10363. }
  10364. }
  10365. }
  10366. } else {
  10367. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10368. ;
  10369. } else if (req.ranges.size() == 1) {
  10370. auto offset_and_length =
  10371. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10372. auto offset = offset_and_length.first;
  10373. auto length = offset_and_length.second;
  10374. auto content_range = detail::make_content_range_header_field(
  10375. offset_and_length, res.body.size());
  10376. res.set_header("Content-Range", content_range);
  10377. assert(offset + length <= res.body.size());
  10378. res.body = res.body.substr(offset, length);
  10379. } else {
  10380. std::string data;
  10381. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10382. res.body.size(), data);
  10383. res.body.swap(data);
  10384. }
  10385. if (type != detail::EncodingType::None) {
  10386. output_pre_compression_log(req, res);
  10387. if (auto compressor = detail::make_compressor(type)) {
  10388. std::string compressed;
  10389. if (compressor->compress(res.body.data(), res.body.size(), true,
  10390. [&](const char *data, size_t data_len) {
  10391. compressed.append(data, data_len);
  10392. return true;
  10393. })) {
  10394. res.body.swap(compressed);
  10395. res.set_header("Content-Encoding", detail::encoding_name(type));
  10396. res.set_header("Vary", "Accept-Encoding");
  10397. }
  10398. }
  10399. }
  10400. res.content_length_ = res.body.size();
  10401. res.set_header("Content-Length", std::to_string(res.content_length_));
  10402. }
  10403. }
  10404. inline bool Server::dispatch_request_for_content_reader(
  10405. Request &req, Response &res, ContentReader content_reader,
  10406. const HandlersForContentReader &handlers) const {
  10407. for (const auto &x : handlers) {
  10408. const auto &matcher = x.first;
  10409. const auto &handler = x.second;
  10410. if (matcher->match(req)) {
  10411. req.matched_route = matcher->pattern();
  10412. if (!pre_request_handler_ ||
  10413. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10414. handler(req, res, content_reader);
  10415. }
  10416. return true;
  10417. }
  10418. }
  10419. return false;
  10420. }
  10421. inline std::string
  10422. get_client_ip(const std::string &x_forwarded_for,
  10423. const std::vector<std::string> &trusted_proxies) {
  10424. // X-Forwarded-For is a comma-separated list per RFC 7239
  10425. std::vector<std::string> ip_list;
  10426. detail::split(x_forwarded_for.data(),
  10427. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10428. [&](const char *b, const char *e) {
  10429. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10430. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10431. });
  10432. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10433. // no segments. Signal "no client IP derived" with an empty string so the
  10434. // caller can fall back to the connection-level remote address.
  10435. if (ip_list.empty()) { return std::string(); }
  10436. for (size_t i = 0; i < ip_list.size(); ++i) {
  10437. auto ip = ip_list[i];
  10438. auto is_trusted_proxy =
  10439. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10440. [&](const std::string &proxy) { return ip == proxy; });
  10441. if (is_trusted_proxy) {
  10442. if (i == 0) {
  10443. // If the trusted proxy is the first IP, there's no preceding client IP
  10444. return ip;
  10445. } else {
  10446. // Return the IP immediately before the trusted proxy
  10447. return ip_list[i - 1];
  10448. }
  10449. }
  10450. }
  10451. // If no trusted proxy is found, return the first IP in the list
  10452. return ip_list.front();
  10453. }
  10454. inline bool
  10455. Server::process_request(Stream &strm, const std::string &remote_addr,
  10456. int remote_port, const std::string &local_addr,
  10457. int local_port, bool close_connection,
  10458. bool &connection_closed,
  10459. const std::function<void(Request &)> &setup_request,
  10460. bool *websocket_upgraded) {
  10461. std::array<char, 2048> buf{};
  10462. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10463. // Connection has been closed on client
  10464. if (!line_reader.getline()) { return false; }
  10465. Request req;
  10466. req.start_time_ = std::chrono::steady_clock::now();
  10467. req.remote_addr = remote_addr;
  10468. req.remote_port = remote_port;
  10469. req.local_addr = local_addr;
  10470. req.local_port = local_port;
  10471. Response res;
  10472. res.version = "HTTP/1.1";
  10473. res.headers = default_headers_;
  10474. // Request line and headers
  10475. if (!parse_request_line(line_reader.ptr(), req)) {
  10476. res.status = StatusCode::BadRequest_400;
  10477. output_error_log(Error::InvalidRequestLine, &req);
  10478. return write_response(strm, close_connection, req, res);
  10479. }
  10480. // Request headers
  10481. if (!detail::read_headers(strm, req.headers)) {
  10482. res.status = StatusCode::BadRequest_400;
  10483. output_error_log(Error::InvalidHeaders, &req);
  10484. return write_response(strm, close_connection, req, res);
  10485. }
  10486. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10487. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10488. // tolerated for compatibility with existing clients.
  10489. if (req.get_header_value_u64("Content-Length") > 0 &&
  10490. req.has_header("Transfer-Encoding")) {
  10491. connection_closed = true;
  10492. res.status = StatusCode::BadRequest_400;
  10493. return write_response(strm, close_connection, req, res);
  10494. }
  10495. // Check if the request URI doesn't exceed the limit
  10496. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10497. connection_closed = true;
  10498. res.status = StatusCode::UriTooLong_414;
  10499. output_error_log(Error::ExceedUriMaxLength, &req);
  10500. return write_response(strm, close_connection, req, res);
  10501. }
  10502. if (req.get_header_value("Connection") == "close") {
  10503. connection_closed = true;
  10504. }
  10505. if (req.version == "HTTP/1.0" &&
  10506. req.get_header_value("Connection") != "Keep-Alive") {
  10507. connection_closed = true;
  10508. }
  10509. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10510. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10511. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10512. req.remote_addr = derived.empty() ? remote_addr : derived;
  10513. } else {
  10514. req.remote_addr = remote_addr;
  10515. }
  10516. req.remote_port = remote_port;
  10517. req.local_addr = local_addr;
  10518. req.local_port = local_port;
  10519. if (req.has_header("Accept")) {
  10520. const auto &accept_header = req.get_header_value("Accept");
  10521. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10522. connection_closed = true;
  10523. res.status = StatusCode::BadRequest_400;
  10524. output_error_log(Error::HTTPParsing, &req);
  10525. return write_response(strm, close_connection, req, res);
  10526. }
  10527. }
  10528. if (req.has_header("Range")) {
  10529. const auto &range_header_value = req.get_header_value("Range");
  10530. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10531. connection_closed = true;
  10532. res.status = StatusCode::RangeNotSatisfiable_416;
  10533. output_error_log(Error::InvalidRangeHeader, &req);
  10534. return write_response(strm, close_connection, req, res);
  10535. }
  10536. }
  10537. if (setup_request) { setup_request(req); }
  10538. if (req.get_header_value("Expect") == "100-continue") {
  10539. int status = StatusCode::Continue_100;
  10540. if (expect_100_continue_handler_) {
  10541. status = expect_100_continue_handler_(req, res);
  10542. }
  10543. switch (status) {
  10544. case StatusCode::Continue_100:
  10545. case StatusCode::ExpectationFailed_417:
  10546. detail::write_response_line(strm, status);
  10547. strm.write("\r\n");
  10548. break;
  10549. default:
  10550. connection_closed = true;
  10551. return write_response(strm, true, req, res);
  10552. }
  10553. }
  10554. // Setup `is_connection_closed` method
  10555. auto sock = strm.socket();
  10556. req.is_connection_closed = [sock]() {
  10557. return !detail::is_socket_alive(sock);
  10558. };
  10559. // WebSocket upgrade
  10560. // Check pre_routing_handler_ before upgrading so that authentication
  10561. // and other middleware can reject the request with an HTTP response
  10562. // (e.g., 401) before the protocol switches.
  10563. if (detail::is_websocket_upgrade(req)) {
  10564. if (pre_routing_handler_ &&
  10565. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10566. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10567. return write_response(strm, close_connection, req, res);
  10568. }
  10569. // Find matching WebSocket handler
  10570. for (const auto &entry : websocket_handlers_) {
  10571. if (entry.matcher->match(req)) {
  10572. // Compute accept key
  10573. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10574. auto accept_key = detail::websocket_accept_key(client_key);
  10575. // Negotiate subprotocol
  10576. std::string selected_subprotocol;
  10577. if (entry.sub_protocol_selector) {
  10578. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10579. if (!protocol_header.empty()) {
  10580. std::vector<std::string> protocols;
  10581. std::istringstream iss(protocol_header);
  10582. std::string token;
  10583. while (std::getline(iss, token, ',')) {
  10584. // Trim whitespace
  10585. auto start = token.find_first_not_of(' ');
  10586. auto end = token.find_last_not_of(' ');
  10587. if (start != std::string::npos) {
  10588. protocols.push_back(token.substr(start, end - start + 1));
  10589. }
  10590. }
  10591. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10592. }
  10593. }
  10594. // Send 101 Switching Protocols
  10595. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10596. "Upgrade: websocket\r\n"
  10597. "Connection: Upgrade\r\n"
  10598. "Sec-WebSocket-Accept: " +
  10599. accept_key + "\r\n";
  10600. if (!selected_subprotocol.empty()) {
  10601. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10602. return false;
  10603. }
  10604. handshake_response +=
  10605. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10606. }
  10607. handshake_response += "\r\n";
  10608. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10609. 0) {
  10610. return false;
  10611. }
  10612. connection_closed = true;
  10613. if (websocket_upgraded) { *websocket_upgraded = true; }
  10614. {
  10615. // Use WebSocket-specific read timeout instead of HTTP timeout
  10616. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10617. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10618. websocket_max_missed_pongs_);
  10619. entry.handler(req, ws);
  10620. }
  10621. return true;
  10622. }
  10623. }
  10624. // No matching handler - fall through to 404
  10625. }
  10626. // Routing
  10627. auto routed = false;
  10628. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10629. routed = routing(req, res, strm);
  10630. #else
  10631. try {
  10632. routed = routing(req, res, strm);
  10633. } catch (std::exception &) {
  10634. if (exception_handler_) {
  10635. auto ep = std::current_exception();
  10636. exception_handler_(req, res, ep);
  10637. routed = true;
  10638. } else {
  10639. res.status = StatusCode::InternalServerError_500;
  10640. }
  10641. } catch (...) {
  10642. if (exception_handler_) {
  10643. auto ep = std::current_exception();
  10644. exception_handler_(req, res, ep);
  10645. routed = true;
  10646. } else {
  10647. res.status = StatusCode::InternalServerError_500;
  10648. }
  10649. }
  10650. #endif
  10651. auto ret = false;
  10652. if (routed) {
  10653. if (res.status == -1) {
  10654. res.status = req.ranges.empty() ? StatusCode::OK_200
  10655. : StatusCode::PartialContent_206;
  10656. }
  10657. // Serve file content by using a content provider
  10658. auto file_open_error = false;
  10659. if (!res.file_content_path_.empty()) {
  10660. const auto &path = res.file_content_path_;
  10661. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10662. if (!mm->is_open()) {
  10663. res.body.clear();
  10664. res.content_length_ = 0;
  10665. res.content_provider_ = nullptr;
  10666. res.status = StatusCode::NotFound_404;
  10667. output_error_log(Error::OpenFile, &req);
  10668. file_open_error = true;
  10669. } else {
  10670. auto content_type = res.file_content_content_type_;
  10671. if (content_type.empty()) {
  10672. content_type = detail::find_content_type(
  10673. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10674. }
  10675. res.set_content_provider(
  10676. mm->size(), content_type,
  10677. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10678. sink.write(mm->data() + offset, length);
  10679. return true;
  10680. });
  10681. }
  10682. }
  10683. if (file_open_error) {
  10684. ret = write_response(strm, close_connection, req, res);
  10685. } else if (detail::range_error(req, res)) {
  10686. res.body.clear();
  10687. res.content_length_ = 0;
  10688. res.content_provider_ = nullptr;
  10689. res.status = StatusCode::RangeNotSatisfiable_416;
  10690. ret = write_response(strm, close_connection, req, res);
  10691. } else {
  10692. ret = write_response_with_content(strm, close_connection, req, res);
  10693. }
  10694. } else {
  10695. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10696. ret = write_response(strm, close_connection, req, res);
  10697. }
  10698. // Drain any unconsumed framed body to prevent request smuggling on
  10699. // keep-alive. Without framing there is no body to drain — reading would
  10700. // consume the next request (issue #2450).
  10701. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10702. int dummy_status;
  10703. if (!detail::read_content(
  10704. strm, req, payload_max_length_, dummy_status, nullptr,
  10705. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10706. connection_closed = true;
  10707. }
  10708. }
  10709. return ret;
  10710. }
  10711. inline bool Server::is_valid() const { return true; }
  10712. inline bool Server::process_and_close_socket(socket_t sock) {
  10713. std::string remote_addr;
  10714. int remote_port = 0;
  10715. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10716. std::string local_addr;
  10717. int local_port = 0;
  10718. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10719. bool websocket_upgraded = false;
  10720. auto ret = detail::process_server_socket(
  10721. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10722. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10723. write_timeout_usec_,
  10724. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10725. return process_request(strm, remote_addr, remote_port, local_addr,
  10726. local_port, close_connection, connection_closed,
  10727. nullptr, &websocket_upgraded);
  10728. });
  10729. detail::shutdown_socket(sock);
  10730. detail::close_socket(sock);
  10731. return ret;
  10732. }
  10733. inline void Server::output_log(const Request &req, const Response &res) const {
  10734. if (logger_) {
  10735. std::lock_guard<std::mutex> guard(logger_mutex_);
  10736. logger_(req, res);
  10737. }
  10738. }
  10739. inline void Server::output_pre_compression_log(const Request &req,
  10740. const Response &res) const {
  10741. if (pre_compression_logger_) {
  10742. std::lock_guard<std::mutex> guard(logger_mutex_);
  10743. pre_compression_logger_(req, res);
  10744. }
  10745. }
  10746. inline void Server::output_error_log(const Error &err,
  10747. const Request *req) const {
  10748. if (error_logger_) {
  10749. std::lock_guard<std::mutex> guard(logger_mutex_);
  10750. error_logger_(err, req);
  10751. }
  10752. }
  10753. /*
  10754. * Group 5: ClientImpl and Client (Universal) implementation
  10755. */
  10756. // HTTP client implementation
  10757. inline ClientImpl::ClientImpl(const std::string &host)
  10758. : ClientImpl(host, 80, std::string(), std::string()) {}
  10759. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10760. : ClientImpl(host, port, std::string(), std::string()) {}
  10761. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10762. const std::string &client_cert_path,
  10763. const std::string &client_key_path)
  10764. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10765. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10766. inline ClientImpl::~ClientImpl() {
  10767. // Wait until all the requests in flight are handled.
  10768. size_t retry_count = 10;
  10769. while (retry_count-- > 0) {
  10770. {
  10771. std::lock_guard<std::mutex> guard(socket_mutex_);
  10772. if (socket_requests_in_flight_ == 0) { break; }
  10773. }
  10774. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10775. }
  10776. std::lock_guard<std::mutex> guard(socket_mutex_);
  10777. shutdown_socket(socket_);
  10778. close_socket(socket_);
  10779. }
  10780. inline bool ClientImpl::is_valid() const { return true; }
  10781. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10782. client_cert_path_ = rhs.client_cert_path_;
  10783. client_key_path_ = rhs.client_key_path_;
  10784. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10785. read_timeout_sec_ = rhs.read_timeout_sec_;
  10786. read_timeout_usec_ = rhs.read_timeout_usec_;
  10787. write_timeout_sec_ = rhs.write_timeout_sec_;
  10788. write_timeout_usec_ = rhs.write_timeout_usec_;
  10789. max_timeout_msec_ = rhs.max_timeout_msec_;
  10790. basic_auth_username_ = rhs.basic_auth_username_;
  10791. basic_auth_password_ = rhs.basic_auth_password_;
  10792. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10793. keep_alive_ = rhs.keep_alive_;
  10794. follow_location_ = rhs.follow_location_;
  10795. path_encode_ = rhs.path_encode_;
  10796. address_family_ = rhs.address_family_;
  10797. tcp_nodelay_ = rhs.tcp_nodelay_;
  10798. ipv6_v6only_ = rhs.ipv6_v6only_;
  10799. socket_options_ = rhs.socket_options_;
  10800. compress_ = rhs.compress_;
  10801. decompress_ = rhs.decompress_;
  10802. payload_max_length_ = rhs.payload_max_length_;
  10803. has_payload_max_length_ = rhs.has_payload_max_length_;
  10804. interface_ = rhs.interface_;
  10805. proxy_host_ = rhs.proxy_host_;
  10806. proxy_port_ = rhs.proxy_port_;
  10807. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10808. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10809. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10810. no_proxy_entries_ = rhs.no_proxy_entries_;
  10811. logger_ = rhs.logger_;
  10812. error_logger_ = rhs.error_logger_;
  10813. #ifdef CPPHTTPLIB_SSL_ENABLED
  10814. digest_auth_username_ = rhs.digest_auth_username_;
  10815. digest_auth_password_ = rhs.digest_auth_password_;
  10816. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10817. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10818. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10819. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10820. server_certificate_verification_ = rhs.server_certificate_verification_;
  10821. server_hostname_verification_ = rhs.server_hostname_verification_;
  10822. system_ca_mode_ = rhs.system_ca_mode_;
  10823. #endif
  10824. }
  10825. inline bool
  10826. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10827. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10828. if (no_proxy_entries_.empty()) { return true; }
  10829. // host_ is const so its normalized form is invariant; cache it. The
  10830. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10831. if (host == host_) {
  10832. if (!host_normalized_valid_) {
  10833. host_normalized_ = detail::normalize_target(host_);
  10834. host_normalized_valid_ = true;
  10835. }
  10836. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10837. }
  10838. auto target = detail::normalize_target(host);
  10839. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10840. }
  10841. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10842. if (is_proxy_enabled_for_host(host_)) {
  10843. return detail::create_client_socket(
  10844. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10845. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10846. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10847. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10848. }
  10849. // Check is custom IP specified for host_
  10850. std::string ip;
  10851. auto it = addr_map_.find(host_);
  10852. if (it != addr_map_.end()) { ip = it->second; }
  10853. return detail::create_client_socket(
  10854. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10855. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10856. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10857. write_timeout_usec_, interface_, error);
  10858. }
  10859. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10860. Error &error) {
  10861. auto sock = create_client_socket(error);
  10862. if (sock == INVALID_SOCKET) { return false; }
  10863. socket.sock = sock;
  10864. return true;
  10865. }
  10866. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10867. return create_and_connect_socket(socket, error);
  10868. }
  10869. inline bool ClientImpl::setup_proxy_connection(
  10870. Socket & /*socket*/,
  10871. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10872. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10873. return true;
  10874. }
  10875. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10876. bool /*shutdown_gracefully*/) {
  10877. // If there are any requests in flight from threads other than us, then it's
  10878. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10879. assert(socket_requests_in_flight_ == 0 ||
  10880. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10881. }
  10882. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10883. if (socket.sock == INVALID_SOCKET) { return; }
  10884. detail::shutdown_socket(socket.sock);
  10885. }
  10886. inline void ClientImpl::close_socket(Socket &socket) {
  10887. // If there are requests in flight in another thread, usually closing
  10888. // the socket will be fine and they will simply receive an error when
  10889. // using the closed socket, but it is still a bug since rarely the OS
  10890. // may reassign the socket id to be used for a new socket, and then
  10891. // suddenly they will be operating on a live socket that is different
  10892. // than the one they intended!
  10893. assert(socket_requests_in_flight_ == 0 ||
  10894. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10895. // It is also a bug if this happens while SSL is still active
  10896. #ifdef CPPHTTPLIB_SSL_ENABLED
  10897. assert(socket.ssl == nullptr);
  10898. #endif
  10899. if (socket.sock == INVALID_SOCKET) { return; }
  10900. detail::close_socket(socket.sock);
  10901. socket.sock = INVALID_SOCKET;
  10902. }
  10903. inline void ClientImpl::disconnect(bool gracefully) {
  10904. shutdown_ssl(socket_, gracefully);
  10905. shutdown_socket(socket_);
  10906. close_socket(socket_);
  10907. }
  10908. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10909. Response &res,
  10910. bool skip_100_continue) const {
  10911. std::array<char, 2048> buf{};
  10912. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10913. if (!line_reader.getline()) { return false; }
  10914. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10915. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10916. #else
  10917. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10918. #endif
  10919. std::cmatch m;
  10920. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10921. return req.method == "CONNECT";
  10922. }
  10923. res.version = std::string(m[1]);
  10924. res.status = std::stoi(std::string(m[2]));
  10925. res.reason = std::string(m[3]);
  10926. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10927. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10928. if (!line_reader.getline()) { return false; } // CRLF
  10929. if (!line_reader.getline()) { return false; } // next response line
  10930. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10931. res.version = std::string(m[1]);
  10932. res.status = std::stoi(std::string(m[2]));
  10933. res.reason = std::string(m[3]);
  10934. }
  10935. return true;
  10936. }
  10937. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10938. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10939. auto ret = send_(req, res, error);
  10940. if (error == Error::SSLPeerCouldBeClosed_) {
  10941. assert(!ret);
  10942. ret = send_(req, res, error);
  10943. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10944. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10945. }
  10946. return ret;
  10947. }
  10948. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10949. {
  10950. std::lock_guard<std::mutex> guard(socket_mutex_);
  10951. // Set this to false immediately - if it ever gets set to true by the end
  10952. // of the request, we know another thread instructed us to close the
  10953. // socket.
  10954. socket_should_be_closed_when_request_is_done_ = false;
  10955. auto is_alive = false;
  10956. if (socket_.is_open()) {
  10957. is_alive = detail::is_socket_alive(socket_.sock);
  10958. #ifdef CPPHTTPLIB_SSL_ENABLED
  10959. if (is_alive && is_ssl()) {
  10960. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10961. is_alive = false;
  10962. }
  10963. }
  10964. #endif
  10965. if (!is_alive) {
  10966. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10967. disconnect(/*gracefully=*/false);
  10968. }
  10969. }
  10970. if (!is_alive) {
  10971. if (!ensure_socket_connection(socket_, error)) {
  10972. output_error_log(error, &req);
  10973. return false;
  10974. }
  10975. {
  10976. auto success = true;
  10977. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10978. error)) {
  10979. if (!success) { output_error_log(error, &req); }
  10980. return success;
  10981. }
  10982. }
  10983. }
  10984. // Mark the current socket as being in use so that it cannot be closed by
  10985. // anyone else while this request is ongoing, even though we will be
  10986. // releasing the mutex.
  10987. if (socket_requests_in_flight_ > 1) {
  10988. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10989. }
  10990. socket_requests_in_flight_ += 1;
  10991. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10992. }
  10993. for (const auto &header : default_headers_) {
  10994. if (req.headers.find(header.first) == req.headers.end()) {
  10995. req.headers.insert(header);
  10996. }
  10997. }
  10998. auto ret = false;
  10999. auto close_connection = !keep_alive_;
  11000. auto se = detail::scope_exit([&]() {
  11001. // Briefly lock mutex in order to mark that a request is no longer ongoing
  11002. std::lock_guard<std::mutex> guard(socket_mutex_);
  11003. socket_requests_in_flight_ -= 1;
  11004. if (socket_requests_in_flight_ <= 0) {
  11005. assert(socket_requests_in_flight_ == 0);
  11006. socket_requests_are_from_thread_ = std::thread::id();
  11007. }
  11008. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  11009. !ret) {
  11010. disconnect(/*gracefully=*/true);
  11011. }
  11012. });
  11013. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  11014. return handle_request(strm, req, res, close_connection, error);
  11015. });
  11016. if (!ret) {
  11017. if (error == Error::Success) {
  11018. error = Error::Unknown;
  11019. output_error_log(error, &req);
  11020. }
  11021. }
  11022. return ret;
  11023. }
  11024. inline Result ClientImpl::send(const Request &req) {
  11025. auto req2 = req;
  11026. return send_(std::move(req2));
  11027. }
  11028. inline Result ClientImpl::send_(Request &&req) {
  11029. auto res = detail::make_unique<Response>();
  11030. auto error = Error::Success;
  11031. auto ret = send(req, *res, error);
  11032. #ifdef CPPHTTPLIB_SSL_ENABLED
  11033. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  11034. last_ssl_error_, last_backend_error_};
  11035. #else
  11036. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  11037. #endif
  11038. }
  11039. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  11040. const std::string &ct) {
  11041. (void)for_stream;
  11042. for (const auto &header : default_headers_) {
  11043. if (!r.has_header(header.first)) { r.headers.insert(header); }
  11044. }
  11045. if (!r.has_header("Host")) {
  11046. if (address_family_ == AF_UNIX) {
  11047. r.headers.emplace("Host", "localhost");
  11048. } else {
  11049. r.headers.emplace(
  11050. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  11051. }
  11052. }
  11053. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  11054. if (!r.content_receiver) {
  11055. if (!r.has_header("Accept-Encoding")) {
  11056. std::string accept_encoding;
  11057. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11058. accept_encoding = "br";
  11059. #endif
  11060. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11061. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11062. accept_encoding += "gzip, deflate";
  11063. #endif
  11064. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11065. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11066. accept_encoding += "zstd";
  11067. #endif
  11068. r.set_header("Accept-Encoding", accept_encoding);
  11069. }
  11070. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11071. if (!r.has_header("User-Agent")) {
  11072. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11073. r.set_header("User-Agent", agent);
  11074. }
  11075. #endif
  11076. }
  11077. if (!r.body.empty()) {
  11078. if (!ct.empty() && !r.has_header("Content-Type")) {
  11079. r.headers.emplace("Content-Type", ct);
  11080. }
  11081. if (!r.has_header("Content-Length")) {
  11082. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11083. }
  11084. }
  11085. }
  11086. inline ClientImpl::StreamHandle
  11087. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11088. const Params &params, const Headers &headers,
  11089. const std::string &body,
  11090. const std::string &content_type) {
  11091. StreamHandle handle;
  11092. handle.response = detail::make_unique<Response>();
  11093. handle.error = Error::Success;
  11094. auto query_path = params.empty() ? path : append_query_params(path, params);
  11095. handle.connection_ = detail::make_unique<ClientConnection>();
  11096. {
  11097. std::lock_guard<std::mutex> guard(socket_mutex_);
  11098. auto is_alive = false;
  11099. if (socket_.is_open()) {
  11100. is_alive = detail::is_socket_alive(socket_.sock);
  11101. #ifdef CPPHTTPLIB_SSL_ENABLED
  11102. if (is_alive && is_ssl()) {
  11103. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11104. is_alive = false;
  11105. }
  11106. }
  11107. #endif
  11108. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11109. }
  11110. if (!is_alive) {
  11111. if (!ensure_socket_connection(socket_, handle.error)) {
  11112. handle.response.reset();
  11113. return handle;
  11114. }
  11115. {
  11116. auto success = true;
  11117. auto start_time = std::chrono::steady_clock::now();
  11118. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11119. success, handle.error)) {
  11120. if (!success) { handle.response.reset(); }
  11121. return handle;
  11122. }
  11123. }
  11124. }
  11125. transfer_socket_ownership_to_handle(handle);
  11126. }
  11127. #ifdef CPPHTTPLIB_SSL_ENABLED
  11128. if (is_ssl() && handle.connection_->session) {
  11129. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11130. handle.connection_->sock, handle.connection_->session,
  11131. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11132. write_timeout_usec_);
  11133. } else {
  11134. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11135. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11136. write_timeout_sec_, write_timeout_usec_);
  11137. }
  11138. #else
  11139. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11140. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11141. write_timeout_sec_, write_timeout_usec_);
  11142. #endif
  11143. handle.stream_ = handle.socket_stream_.get();
  11144. Request req;
  11145. req.method = method;
  11146. req.path = query_path;
  11147. req.headers = headers;
  11148. req.body = body;
  11149. prepare_default_headers(req, true, content_type);
  11150. auto &strm = *handle.stream_;
  11151. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11152. handle.error = Error::Write;
  11153. handle.response.reset();
  11154. return handle;
  11155. }
  11156. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11157. handle.error)) {
  11158. handle.response.reset();
  11159. return handle;
  11160. }
  11161. if (!body.empty()) {
  11162. if (strm.write(body.data(), body.size()) < 0) {
  11163. handle.error = Error::Write;
  11164. handle.response.reset();
  11165. return handle;
  11166. }
  11167. }
  11168. if (!read_response_line(strm, req, *handle.response) ||
  11169. !detail::read_headers(strm, handle.response->headers)) {
  11170. handle.error = Error::Read;
  11171. handle.response.reset();
  11172. return handle;
  11173. }
  11174. handle.body_reader_.stream = handle.stream_;
  11175. handle.body_reader_.payload_max_length = payload_max_length_;
  11176. if (handle.response->has_header("Content-Length")) {
  11177. bool is_invalid = false;
  11178. auto content_length = detail::get_header_value_u64(
  11179. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11180. if (is_invalid) {
  11181. handle.error = Error::Read;
  11182. handle.response.reset();
  11183. return handle;
  11184. }
  11185. handle.body_reader_.has_content_length = true;
  11186. handle.body_reader_.content_length = content_length;
  11187. }
  11188. handle.body_reader_.chunked =
  11189. detail::is_chunked_transfer_encoding(handle.response->headers);
  11190. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11191. if (!content_encoding.empty()) {
  11192. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11193. }
  11194. return handle;
  11195. }
  11196. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11197. if (!is_valid() || !response) { return -1; }
  11198. if (decompressor_) { return read_with_decompression(buf, len); }
  11199. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11200. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11201. trailers_parsed_ = true;
  11202. if (body_reader_.chunked_decoder) {
  11203. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11204. response->trailers, response->headers)) {
  11205. return n;
  11206. }
  11207. } else {
  11208. detail::ChunkedDecoder dec(*stream_);
  11209. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11210. return n;
  11211. }
  11212. }
  11213. }
  11214. return n;
  11215. }
  11216. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11217. size_t len) {
  11218. if (decompress_offset_ < decompress_buffer_.size()) {
  11219. auto available = decompress_buffer_.size() - decompress_offset_;
  11220. auto to_copy = (std::min)(len, available);
  11221. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11222. decompress_offset_ += to_copy;
  11223. decompressed_bytes_read_ += to_copy;
  11224. return static_cast<ssize_t>(to_copy);
  11225. }
  11226. decompress_buffer_.clear();
  11227. decompress_offset_ = 0;
  11228. constexpr size_t kDecompressionBufferSize = 8192;
  11229. char compressed_buf[kDecompressionBufferSize];
  11230. while (true) {
  11231. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11232. sizeof(compressed_buf));
  11233. if (n <= 0) { return n; }
  11234. bool decompress_ok = decompressor_->decompress(
  11235. compressed_buf, static_cast<size_t>(n),
  11236. [this](const char *data, size_t data_len) {
  11237. decompress_buffer_.append(data, data_len);
  11238. auto limit = body_reader_.payload_max_length;
  11239. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11240. return false;
  11241. }
  11242. return true;
  11243. });
  11244. if (!decompress_ok) {
  11245. body_reader_.last_error = Error::Read;
  11246. return -1;
  11247. }
  11248. if (!decompress_buffer_.empty()) { break; }
  11249. }
  11250. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11251. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11252. decompress_offset_ = to_copy;
  11253. decompressed_bytes_read_ += to_copy;
  11254. return static_cast<ssize_t>(to_copy);
  11255. }
  11256. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11257. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11258. return;
  11259. }
  11260. trailers_parsed_ = true;
  11261. const auto bufsiz = 128;
  11262. char line_buf[bufsiz];
  11263. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11264. if (!line_reader.getline()) { return; }
  11265. if (!detail::parse_trailers(line_reader, response->trailers,
  11266. response->headers)) {
  11267. return;
  11268. }
  11269. }
  11270. namespace detail {
  11271. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11272. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11273. size_t &out_chunk_offset,
  11274. size_t &out_chunk_total) {
  11275. if (finished) { return 0; }
  11276. if (chunk_remaining == 0) {
  11277. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11278. if (!lr.getline()) { return -1; }
  11279. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11280. const char *p = lr.ptr();
  11281. int v = 0;
  11282. if (!is_hex(*p, v)) { return -1; }
  11283. size_t chunk_len = 0;
  11284. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11285. for (; is_hex(*p, v); ++p) {
  11286. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11287. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11288. }
  11289. while (is_space_or_tab(*p)) {
  11290. ++p;
  11291. }
  11292. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11293. if (chunk_len == 0) {
  11294. chunk_remaining = 0;
  11295. finished = true;
  11296. out_chunk_offset = 0;
  11297. out_chunk_total = 0;
  11298. return 0;
  11299. }
  11300. chunk_remaining = chunk_len;
  11301. last_chunk_total = chunk_remaining;
  11302. last_chunk_offset = 0;
  11303. }
  11304. auto to_read = (std::min)(chunk_remaining, len);
  11305. auto n = strm.read(buf, to_read);
  11306. if (n <= 0) { return -1; }
  11307. auto offset_before = last_chunk_offset;
  11308. last_chunk_offset += static_cast<size_t>(n);
  11309. chunk_remaining -= static_cast<size_t>(n);
  11310. out_chunk_offset = offset_before;
  11311. out_chunk_total = last_chunk_total;
  11312. if (chunk_remaining == 0) {
  11313. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11314. if (!lr.getline()) { return -1; }
  11315. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11316. }
  11317. return n;
  11318. }
  11319. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11320. const Headers &src_headers) {
  11321. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11322. if (!lr.getline()) { return false; }
  11323. return parse_trailers(lr, dest, src_headers);
  11324. }
  11325. } // namespace detail
  11326. inline void
  11327. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11328. handle.connection_->sock = socket_.sock;
  11329. #ifdef CPPHTTPLIB_SSL_ENABLED
  11330. handle.connection_->session = socket_.ssl;
  11331. socket_.ssl = nullptr;
  11332. #endif
  11333. socket_.sock = INVALID_SOCKET;
  11334. }
  11335. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11336. Response &res, bool close_connection,
  11337. Error &error) {
  11338. if (req.path.empty()) {
  11339. error = Error::Connection;
  11340. output_error_log(error, &req);
  11341. return false;
  11342. }
  11343. auto req_save = req;
  11344. bool ret;
  11345. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11346. auto req2 = req;
  11347. req2.path = "http://" +
  11348. detail::make_host_and_port_string(host_, port_, false) +
  11349. req.path;
  11350. ret = process_request(strm, req2, res, close_connection, error);
  11351. req = std::move(req2);
  11352. req.path = req_save.path;
  11353. } else {
  11354. ret = process_request(strm, req, res, close_connection, error);
  11355. }
  11356. if (!ret) { return false; }
  11357. if (res.get_header_value("Connection") == "close" ||
  11358. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11359. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11360. // for this to be safe.
  11361. // This is safe to call because handle_request is only called by send_
  11362. // which locks the request mutex during the process. It would be a bug
  11363. // to call it from a different thread since it's a thread-safety issue
  11364. // to do these things to the socket if another thread is using the socket.
  11365. std::lock_guard<std::mutex> guard(socket_mutex_);
  11366. disconnect(/*gracefully=*/true);
  11367. }
  11368. if (300 < res.status && res.status < 400 && follow_location_) {
  11369. req = std::move(req_save);
  11370. ret = redirect(req, res, error);
  11371. }
  11372. #ifdef CPPHTTPLIB_SSL_ENABLED
  11373. if ((res.status == StatusCode::Unauthorized_401 ||
  11374. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11375. req.authorization_count_ < 5) {
  11376. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11377. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11378. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11379. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11380. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11381. return ret;
  11382. }
  11383. const auto &username =
  11384. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11385. const auto &password =
  11386. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11387. if (!username.empty() && !password.empty()) {
  11388. std::map<std::string, std::string> auth;
  11389. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11390. Request new_req = req;
  11391. new_req.authorization_count_ += 1;
  11392. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11393. : "Authorization");
  11394. new_req.headers.insert(detail::make_digest_authentication_header(
  11395. req, auth, new_req.authorization_count_, detail::random_string(10),
  11396. username, password, is_proxy));
  11397. Response new_res;
  11398. ret = send(new_req, new_res, error);
  11399. if (ret) { res = std::move(new_res); }
  11400. }
  11401. }
  11402. }
  11403. #endif
  11404. return ret;
  11405. }
  11406. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11407. if (req.redirect_count_ == 0) {
  11408. error = Error::ExceedRedirectCount;
  11409. output_error_log(error, &req);
  11410. return false;
  11411. }
  11412. auto location = res.get_header_value("location");
  11413. if (location.empty()) { return false; }
  11414. detail::UrlComponents uc;
  11415. if (!detail::parse_url(location, uc)) { return false; }
  11416. // Only follow http/https redirects
  11417. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11418. return false;
  11419. }
  11420. auto scheme = is_ssl() ? "https" : "http";
  11421. auto next_scheme = std::move(uc.scheme);
  11422. auto next_host = std::move(uc.host);
  11423. auto port_str = std::move(uc.port);
  11424. auto next_path = std::move(uc.path);
  11425. auto next_query = std::move(uc.query);
  11426. auto next_port = port_;
  11427. if (!port_str.empty()) {
  11428. if (!detail::parse_port(port_str, next_port)) { return false; }
  11429. } else if (!next_scheme.empty()) {
  11430. next_port = next_scheme == "https" ? 443 : 80;
  11431. }
  11432. if (next_scheme.empty()) { next_scheme = scheme; }
  11433. if (next_host.empty()) { next_host = host_; }
  11434. if (next_path.empty()) { next_path = "/"; }
  11435. auto path = decode_path_component(next_path) + next_query;
  11436. // Same host redirect - use current client
  11437. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11438. return detail::redirect(*this, req, res, path, location, error);
  11439. }
  11440. // Cross-host/scheme redirect - create new client with robust setup
  11441. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11442. path, location, error);
  11443. }
  11444. // New method for robust redirect client creation
  11445. inline bool ClientImpl::create_redirect_client(
  11446. const std::string &scheme, const std::string &host, int port, Request &req,
  11447. Response &res, const std::string &path, const std::string &location,
  11448. Error &error) {
  11449. // Determine if we need SSL
  11450. auto need_ssl = (scheme == "https");
  11451. // Clean up request headers that are host/client specific
  11452. // Remove headers that should not be carried over to new host
  11453. auto headers_to_remove = std::vector<std::string>{
  11454. "Host", "Proxy-Authorization", "Authorization", "Cookie", "Cookie2"};
  11455. for (const auto &header_name : headers_to_remove) {
  11456. auto it = req.headers.find(header_name);
  11457. while (it != req.headers.end()) {
  11458. it = req.headers.erase(it);
  11459. it = req.headers.find(header_name);
  11460. }
  11461. }
  11462. // Create appropriate client type and handle redirect
  11463. if (need_ssl) {
  11464. #ifdef CPPHTTPLIB_SSL_ENABLED
  11465. // Create SSL client for HTTPS redirect
  11466. SSLClient redirect_client(host, port);
  11467. // Setup basic client configuration first
  11468. setup_redirect_client(redirect_client);
  11469. redirect_client.enable_server_certificate_verification(
  11470. server_certificate_verification_);
  11471. redirect_client.enable_server_hostname_verification(
  11472. server_hostname_verification_);
  11473. redirect_client.system_ca_mode_ = system_ca_mode_;
  11474. // Transfer CA certificate to redirect client
  11475. if (!ca_cert_pem_.empty()) {
  11476. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11477. ca_cert_pem_.size());
  11478. }
  11479. if (!ca_cert_file_path_.empty()) {
  11480. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11481. }
  11482. // Client certificates are set through constructor for SSLClient
  11483. // NOTE: SSLClient constructor already takes client_cert_path and
  11484. // client_key_path so we need to create it properly if client certs are
  11485. // needed
  11486. // Execute the redirect
  11487. return detail::redirect(redirect_client, req, res, path, location, error);
  11488. #else
  11489. // SSL not supported - set appropriate error
  11490. error = Error::SSLConnection;
  11491. output_error_log(error, &req);
  11492. return false;
  11493. #endif
  11494. } else {
  11495. // HTTP redirect
  11496. ClientImpl redirect_client(host, port);
  11497. // Setup client with robust configuration
  11498. setup_redirect_client(redirect_client);
  11499. // Execute the redirect
  11500. return detail::redirect(redirect_client, req, res, path, location, error);
  11501. }
  11502. }
  11503. // New method for robust client setup (based on basic_manual_redirect.cpp
  11504. // logic)
  11505. template <typename ClientType>
  11506. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11507. // Copy basic settings first
  11508. client.set_connection_timeout(connection_timeout_sec_);
  11509. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11510. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11511. client.set_keep_alive(keep_alive_);
  11512. client.set_follow_location(
  11513. true); // Enable redirects to handle multi-step redirects
  11514. client.set_path_encode(path_encode_);
  11515. client.set_compress(compress_);
  11516. client.set_decompress(decompress_);
  11517. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11518. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11519. // 15.4, credentials must not be forwarded when redirecting to a different
  11520. // host. This function is only called for cross-host redirects; same-host
  11521. // redirects are handled directly in ClientImpl::redirect().
  11522. // Copy the proxy configuration unconditionally; the per-target bypass is
  11523. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11524. // still use the proxy.
  11525. client.no_proxy_entries_ = no_proxy_entries_;
  11526. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11527. client.set_proxy(proxy_host_, proxy_port_);
  11528. if (!proxy_basic_auth_username_.empty()) {
  11529. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11530. proxy_basic_auth_password_);
  11531. }
  11532. if (!proxy_bearer_token_auth_token_.empty()) {
  11533. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11534. }
  11535. #ifdef CPPHTTPLIB_SSL_ENABLED
  11536. if (!proxy_digest_auth_username_.empty()) {
  11537. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11538. proxy_digest_auth_password_);
  11539. }
  11540. #endif
  11541. }
  11542. // Copy network and socket settings
  11543. client.set_address_family(address_family_);
  11544. client.set_tcp_nodelay(tcp_nodelay_);
  11545. client.set_ipv6_v6only(ipv6_v6only_);
  11546. if (socket_options_) { client.set_socket_options(socket_options_); }
  11547. if (!interface_.empty()) { client.set_interface(interface_); }
  11548. // Copy logging and headers
  11549. if (logger_) { client.set_logger(logger_); }
  11550. if (error_logger_) { client.set_error_logger(error_logger_); }
  11551. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11552. // Each new client should generate its own headers based on its target host
  11553. }
  11554. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11555. const Request &req,
  11556. Error &error) const {
  11557. auto is_shutting_down = []() { return false; };
  11558. if (req.is_chunked_content_provider_) {
  11559. auto compressor = compress_ ? detail::create_compressor().first
  11560. : std::unique_ptr<detail::compressor>();
  11561. if (!compressor) {
  11562. compressor = detail::make_unique<detail::nocompressor>();
  11563. }
  11564. return detail::write_content_chunked(strm, req.content_provider_,
  11565. is_shutting_down, *compressor, error);
  11566. } else {
  11567. return detail::write_content_with_progress(
  11568. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11569. req.upload_progress, error);
  11570. }
  11571. }
  11572. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11573. bool close_connection, Error &error,
  11574. bool skip_body) {
  11575. // Prepare additional headers
  11576. if (close_connection) {
  11577. if (!req.has_header("Connection")) {
  11578. req.set_header("Connection", "close");
  11579. }
  11580. }
  11581. std::string ct_for_defaults;
  11582. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11583. ct_for_defaults = "text/plain";
  11584. }
  11585. prepare_default_headers(req, false, ct_for_defaults);
  11586. if (req.body.empty()) {
  11587. if (req.content_provider_) {
  11588. if (!req.is_chunked_content_provider_) {
  11589. if (!req.has_header("Content-Length")) {
  11590. auto length = std::to_string(req.content_length_);
  11591. req.set_header("Content-Length", length);
  11592. }
  11593. }
  11594. } else {
  11595. if (req.method == "POST" || req.method == "PUT" ||
  11596. req.method == "PATCH") {
  11597. req.set_header("Content-Length", "0");
  11598. }
  11599. }
  11600. }
  11601. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11602. if (!req.has_header("Authorization")) {
  11603. req.headers.insert(make_basic_authentication_header(
  11604. basic_auth_username_, basic_auth_password_, false));
  11605. }
  11606. }
  11607. if (!bearer_token_auth_token_.empty()) {
  11608. if (!req.has_header("Authorization")) {
  11609. req.headers.insert(make_bearer_token_authentication_header(
  11610. bearer_token_auth_token_, false));
  11611. }
  11612. }
  11613. // Proxy-Authorization is only sent when the proxy is actually used for
  11614. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11615. // credentials directly to the destination server.
  11616. if (is_proxy_enabled_for_host(host_)) {
  11617. if (!proxy_basic_auth_username_.empty() &&
  11618. !proxy_basic_auth_password_.empty() &&
  11619. !req.has_header("Proxy-Authorization")) {
  11620. req.headers.insert(make_basic_authentication_header(
  11621. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11622. }
  11623. if (!proxy_bearer_token_auth_token_.empty() &&
  11624. !req.has_header("Proxy-Authorization")) {
  11625. req.headers.insert(make_bearer_token_authentication_header(
  11626. proxy_bearer_token_auth_token_, true));
  11627. }
  11628. }
  11629. // Request line and headers
  11630. {
  11631. detail::BufferStream bstrm;
  11632. // Extract path and query from req.path
  11633. std::string path_part, query_part;
  11634. auto query_pos = req.path.find('?');
  11635. if (query_pos != std::string::npos) {
  11636. path_part = req.path.substr(0, query_pos);
  11637. query_part = req.path.substr(query_pos + 1);
  11638. } else {
  11639. path_part = req.path;
  11640. query_part = "";
  11641. }
  11642. // Encode path part. If the original `req.path` already contained a
  11643. // query component, preserve its raw query string (including parameter
  11644. // order) instead of reparsing and reassembling it which may reorder
  11645. // parameters due to container ordering (e.g. `Params` uses
  11646. // `std::multimap`). When there is no query in `req.path`, fall back to
  11647. // building a query from `req.params` so existing callers that pass
  11648. // `Params` continue to work.
  11649. auto path_with_query =
  11650. path_encode_ ? detail::encode_path(path_part) : path_part;
  11651. if (!query_part.empty()) {
  11652. // Normalize the query string (decode then re-encode) while preserving
  11653. // the original parameter order. When path encoding is disabled the
  11654. // caller has supplied an already-encoded target and expects the exact
  11655. // bytes to be sent on the wire, so skip normalization for the query
  11656. // too. Normalizing here would decode-then-re-encode the query and
  11657. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11658. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11659. if (path_encode_) {
  11660. auto normalized = detail::normalize_query_string(query_part);
  11661. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11662. } else {
  11663. path_with_query += '?' + query_part;
  11664. }
  11665. // Still populate req.params for handlers/users who read them.
  11666. detail::parse_query_text(query_part, req.params);
  11667. } else {
  11668. // No query in path; parse any query_part (empty) and append params
  11669. // from `req.params` when present (preserves prior behavior for
  11670. // callers who provide Params separately).
  11671. detail::parse_query_text(query_part, req.params);
  11672. if (!req.params.empty()) {
  11673. path_with_query = append_query_params(path_with_query, req.params);
  11674. }
  11675. }
  11676. // Write request line and headers
  11677. if (detail::write_request_line(bstrm, req.method, path_with_query) < 0) {
  11678. // A rejected target (e.g. CR/LF smuggled in via a decoded redirect
  11679. // Location under set_path_encode(false)) must fail the request cleanly
  11680. // instead of emitting a request-line-less, header-injecting request.
  11681. error = Error::Write;
  11682. output_error_log(error, &req);
  11683. return false;
  11684. }
  11685. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11686. error)) {
  11687. output_error_log(error, &req);
  11688. return false;
  11689. }
  11690. // Flush buffer
  11691. auto &data = bstrm.get_buffer();
  11692. if (!detail::write_data(strm, data.data(), data.size())) {
  11693. error = Error::Write;
  11694. output_error_log(error, &req);
  11695. return false;
  11696. }
  11697. }
  11698. // After sending request line and headers, wait briefly for an early server
  11699. // response (e.g. 4xx) and avoid sending a potentially large request body
  11700. // unnecessarily. This workaround is only enabled on Windows because Unix
  11701. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11702. // buffering can accept large writes even when the peer already responded.
  11703. // Check the stream first (which covers SSL via `is_readable()`), then
  11704. // fall back to select on the socket. Only perform the wait for very large
  11705. // request bodies to avoid interfering with normal small requests and
  11706. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11707. // response. Skip this check when using Expect: 100-continue, as the protocol
  11708. // handles early responses properly.
  11709. #if defined(_WIN32)
  11710. if (!skip_body &&
  11711. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11712. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11713. auto start = std::chrono::high_resolution_clock::now();
  11714. for (;;) {
  11715. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11716. // from SSL internals. If the underlying socket is readable, assume an
  11717. // early response may be present.
  11718. auto sock = strm.socket();
  11719. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11720. return false;
  11721. }
  11722. // Fallback to stream-level check for non-socket streams or when the
  11723. // socket isn't reporting readable. Avoid using `is_readable()` for
  11724. // SSL, since `SSL_pending()` may report buffered records that do not
  11725. // indicate a complete application-level response yet.
  11726. if (!is_ssl() && strm.is_readable()) { return false; }
  11727. auto now = std::chrono::high_resolution_clock::now();
  11728. auto elapsed =
  11729. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11730. .count();
  11731. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11732. break;
  11733. }
  11734. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11735. }
  11736. }
  11737. #endif
  11738. // Body
  11739. if (skip_body) { return true; }
  11740. return write_request_body(strm, req, error);
  11741. }
  11742. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11743. Error &error) {
  11744. if (req.body.empty()) {
  11745. return write_content_with_provider(strm, req, error);
  11746. }
  11747. if (req.upload_progress) {
  11748. auto body_size = req.body.size();
  11749. size_t written = 0;
  11750. auto data = req.body.data();
  11751. while (written < body_size) {
  11752. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11753. if (!detail::write_data(strm, data + written, to_write)) {
  11754. error = Error::Write;
  11755. output_error_log(error, &req);
  11756. return false;
  11757. }
  11758. written += to_write;
  11759. if (!req.upload_progress(written, body_size)) {
  11760. error = Error::Canceled;
  11761. output_error_log(error, &req);
  11762. return false;
  11763. }
  11764. }
  11765. } else {
  11766. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11767. error = Error::Write;
  11768. output_error_log(error, &req);
  11769. return false;
  11770. }
  11771. }
  11772. return true;
  11773. }
  11774. inline std::unique_ptr<Response>
  11775. ClientImpl::send_with_content_provider_and_receiver(
  11776. Request &req, const char *body, size_t content_length,
  11777. ContentProvider content_provider,
  11778. ContentProviderWithoutLength content_provider_without_length,
  11779. const std::string &content_type, ContentReceiver content_receiver,
  11780. Error &error) {
  11781. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11782. auto enc = compress_
  11783. ? detail::create_compressor()
  11784. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11785. nullptr, nullptr);
  11786. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11787. if (enc.first && !content_provider_without_length) {
  11788. auto &compressor = enc.first;
  11789. if (content_provider) {
  11790. auto ok = true;
  11791. size_t offset = 0;
  11792. DataSink data_sink;
  11793. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11794. if (ok) {
  11795. auto last = offset + data_len == content_length;
  11796. auto ret = compressor->compress(
  11797. data, data_len, last,
  11798. [&](const char *compressed_data, size_t compressed_data_len) {
  11799. req.body.append(compressed_data, compressed_data_len);
  11800. return true;
  11801. });
  11802. if (ret) {
  11803. offset += data_len;
  11804. } else {
  11805. ok = false;
  11806. }
  11807. }
  11808. return ok;
  11809. };
  11810. while (ok && offset < content_length) {
  11811. if (!content_provider(offset, content_length - offset, data_sink)) {
  11812. error = Error::Canceled;
  11813. output_error_log(error, &req);
  11814. return nullptr;
  11815. }
  11816. }
  11817. } else {
  11818. if (!compressor->compress(body, content_length, true,
  11819. [&](const char *data, size_t data_len) {
  11820. req.body.append(data, data_len);
  11821. return true;
  11822. })) {
  11823. error = Error::Compression;
  11824. output_error_log(error, &req);
  11825. return nullptr;
  11826. }
  11827. }
  11828. } else {
  11829. if (content_provider) {
  11830. req.content_length_ = content_length;
  11831. req.content_provider_ = std::move(content_provider);
  11832. req.is_chunked_content_provider_ = false;
  11833. } else if (content_provider_without_length) {
  11834. req.content_length_ = 0;
  11835. req.content_provider_ = detail::ContentProviderAdapter(
  11836. std::move(content_provider_without_length));
  11837. req.is_chunked_content_provider_ = true;
  11838. req.set_header("Transfer-Encoding", "chunked");
  11839. } else {
  11840. req.body.assign(body, content_length);
  11841. }
  11842. }
  11843. if (content_receiver) {
  11844. req.content_receiver =
  11845. [content_receiver](const char *data, size_t data_length,
  11846. size_t /*offset*/, size_t /*total_length*/) {
  11847. return content_receiver(data, data_length);
  11848. };
  11849. }
  11850. auto res = detail::make_unique<Response>();
  11851. return send(req, *res, error) ? std::move(res) : nullptr;
  11852. }
  11853. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11854. const std::string &method, const std::string &path, const Headers &headers,
  11855. const char *body, size_t content_length, ContentProvider content_provider,
  11856. ContentProviderWithoutLength content_provider_without_length,
  11857. const std::string &content_type, ContentReceiver content_receiver,
  11858. UploadProgress progress) {
  11859. Request req;
  11860. req.method = method;
  11861. req.headers = headers;
  11862. req.path = path;
  11863. req.upload_progress = std::move(progress);
  11864. if (max_timeout_msec_ > 0) {
  11865. req.start_time_ = std::chrono::steady_clock::now();
  11866. }
  11867. auto error = Error::Success;
  11868. auto res = send_with_content_provider_and_receiver(
  11869. req, body, content_length, std::move(content_provider),
  11870. std::move(content_provider_without_length), content_type,
  11871. std::move(content_receiver), error);
  11872. #ifdef CPPHTTPLIB_SSL_ENABLED
  11873. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11874. last_backend_error_};
  11875. #else
  11876. return Result{std::move(res), error, std::move(req.headers)};
  11877. #endif
  11878. }
  11879. inline void ClientImpl::output_log(const Request &req,
  11880. const Response &res) const {
  11881. if (logger_) {
  11882. std::lock_guard<std::mutex> guard(logger_mutex_);
  11883. logger_(req, res);
  11884. }
  11885. }
  11886. inline void ClientImpl::output_error_log(const Error &err,
  11887. const Request *req) const {
  11888. if (error_logger_) {
  11889. std::lock_guard<std::mutex> guard(logger_mutex_);
  11890. error_logger_(err, req);
  11891. }
  11892. }
  11893. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11894. Response &res, bool close_connection,
  11895. Error &error) {
  11896. // Auto-add Expect: 100-continue for large bodies
  11897. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11898. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11899. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11900. req.set_header("Expect", "100-continue");
  11901. }
  11902. }
  11903. // Check for Expect: 100-continue
  11904. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11905. // Send request (skip body if using Expect: 100-continue)
  11906. auto write_request_success =
  11907. write_request(strm, req, close_connection, error, expect_100_continue);
  11908. #ifdef CPPHTTPLIB_SSL_ENABLED
  11909. if (is_ssl() && !expect_100_continue) {
  11910. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11911. if (!is_proxy_enabled) {
  11912. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11913. error = Error::SSLPeerCouldBeClosed_;
  11914. output_error_log(error, &req);
  11915. return false;
  11916. }
  11917. }
  11918. }
  11919. #endif
  11920. // Handle Expect: 100-continue.
  11921. //
  11922. // Wait for an interim/early response by attempting to read the status line
  11923. // under a short timeout, instead of trusting raw socket readability. Over
  11924. // TLS, post-handshake records (e.g. session tickets) make the socket
  11925. // readable without any HTTP response being available; relying on
  11926. // `select_read` there caused the body to be withheld forever and the
  11927. // request to fail with `Read` (#2458). If no status line arrives within the
  11928. // timeout, send the body anyway (matching curl's behavior).
  11929. auto status_line_read = false;
  11930. if (expect_100_continue && write_request_success) {
  11931. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11932. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11933. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11934. strm.set_read_timeout(sec, usec);
  11935. status_line_read = read_response_line(strm, req, res, false);
  11936. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11937. }
  11938. if (!status_line_read) {
  11939. // No interim response within the timeout: send the body and handle the
  11940. // response as usual.
  11941. if (!write_request_body(strm, req, error)) { return false; }
  11942. expect_100_continue = false; // Switch to normal response handling
  11943. }
  11944. }
  11945. // Receive response and headers
  11946. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11947. if ((!status_line_read &&
  11948. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11949. !detail::read_headers(strm, res.headers)) {
  11950. if (write_request_success) { error = Error::Read; }
  11951. output_error_log(error, &req);
  11952. return false;
  11953. }
  11954. if (!write_request_success) { return false; }
  11955. // Handle Expect: 100-continue response
  11956. if (expect_100_continue) {
  11957. if (res.status == StatusCode::Continue_100) {
  11958. // Server accepted, send the body
  11959. if (!write_request_body(strm, req, error)) { return false; }
  11960. // Read the actual response
  11961. res.headers.clear();
  11962. res.body.clear();
  11963. if (!read_response_line(strm, req, res) ||
  11964. !detail::read_headers(strm, res.headers)) {
  11965. error = Error::Read;
  11966. output_error_log(error, &req);
  11967. return false;
  11968. }
  11969. }
  11970. // If not 100 Continue, server returned an error; proceed with that response
  11971. }
  11972. // Body
  11973. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11974. req.method != "CONNECT") {
  11975. auto redirect = 300 < res.status && res.status < 400 &&
  11976. res.status != StatusCode::NotModified_304 &&
  11977. follow_location_;
  11978. if (req.response_handler && !redirect) {
  11979. if (!req.response_handler(res)) {
  11980. error = Error::Canceled;
  11981. output_error_log(error, &req);
  11982. return false;
  11983. }
  11984. }
  11985. auto out =
  11986. req.content_receiver
  11987. ? static_cast<ContentReceiverWithProgress>(
  11988. [&](const char *buf, size_t n, size_t off, size_t len) {
  11989. if (redirect) { return true; }
  11990. auto ret = req.content_receiver(buf, n, off, len);
  11991. if (!ret) {
  11992. error = Error::Canceled;
  11993. output_error_log(error, &req);
  11994. }
  11995. return ret;
  11996. })
  11997. : static_cast<ContentReceiverWithProgress>(
  11998. [&](const char *buf, size_t n, size_t /*off*/,
  11999. size_t /*len*/) {
  12000. assert(res.body.size() + n <= res.body.max_size());
  12001. if (payload_max_length_ > 0 &&
  12002. (res.body.size() >= payload_max_length_ ||
  12003. n > payload_max_length_ - res.body.size())) {
  12004. return false;
  12005. }
  12006. res.body.append(buf, n);
  12007. return true;
  12008. });
  12009. auto progress = [&](size_t current, size_t total) {
  12010. if (!req.download_progress || redirect) { return true; }
  12011. auto ret = req.download_progress(current, total);
  12012. if (!ret) {
  12013. error = Error::Canceled;
  12014. output_error_log(error, &req);
  12015. }
  12016. return ret;
  12017. };
  12018. if (res.has_header("Content-Length")) {
  12019. if (!req.content_receiver) {
  12020. auto len = res.get_header_value_u64("Content-Length");
  12021. if (len > res.body.max_size()) {
  12022. error = Error::Read;
  12023. output_error_log(error, &req);
  12024. return false;
  12025. }
  12026. // Cap the reservation by payload_max_length_ to avoid OOM when a
  12027. // hostile or malformed server sends an enormous Content-Length.
  12028. // The actual body read below is bounded by payload_max_length_,
  12029. // so reserving more than that is never useful.
  12030. auto reserve_len = static_cast<size_t>(len);
  12031. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  12032. reserve_len = payload_max_length_;
  12033. }
  12034. res.body.reserve(reserve_len);
  12035. }
  12036. }
  12037. if (res.status != StatusCode::NotModified_304) {
  12038. int dummy_status;
  12039. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  12040. ? (std::numeric_limits<size_t>::max)()
  12041. : payload_max_length_;
  12042. if (!detail::read_content(strm, res, max_length, dummy_status,
  12043. std::move(progress), std::move(out),
  12044. decompress_)) {
  12045. if (error != Error::Canceled) { error = Error::Read; }
  12046. output_error_log(error, &req);
  12047. return false;
  12048. }
  12049. }
  12050. }
  12051. // Log
  12052. output_log(req, res);
  12053. return true;
  12054. }
  12055. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  12056. const std::string &boundary, const UploadFormDataItems &items,
  12057. const FormDataProviderItems &provider_items) const {
  12058. size_t cur_item = 0;
  12059. size_t cur_start = 0;
  12060. // cur_item and cur_start are copied to within the std::function and
  12061. // maintain state between successive calls
  12062. return [&, cur_item, cur_start](size_t offset,
  12063. DataSink &sink) mutable -> bool {
  12064. if (!offset && !items.empty()) {
  12065. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12066. return true;
  12067. } else if (cur_item < provider_items.size()) {
  12068. if (!cur_start) {
  12069. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12070. provider_items[cur_item], boundary);
  12071. offset += begin.size();
  12072. cur_start = offset;
  12073. sink.os << begin;
  12074. }
  12075. DataSink cur_sink;
  12076. auto has_data = true;
  12077. cur_sink.write = sink.write;
  12078. cur_sink.done = [&]() { has_data = false; };
  12079. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12080. return false;
  12081. }
  12082. if (!has_data) {
  12083. sink.os << detail::serialize_multipart_formdata_item_end();
  12084. cur_item++;
  12085. cur_start = 0;
  12086. }
  12087. return true;
  12088. } else {
  12089. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12090. sink.done();
  12091. return true;
  12092. }
  12093. };
  12094. }
  12095. inline bool ClientImpl::process_socket(
  12096. const Socket &socket,
  12097. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12098. std::function<bool(Stream &strm)> callback) {
  12099. return detail::process_client_socket(
  12100. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12101. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12102. }
  12103. inline bool ClientImpl::is_ssl() const { return false; }
  12104. inline Result ClientImpl::Get(const std::string &path,
  12105. DownloadProgress progress) {
  12106. return Get(path, Headers(), std::move(progress));
  12107. }
  12108. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12109. DownloadProgress progress) {
  12110. return Get(path, params, Headers(), std::move(progress));
  12111. }
  12112. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12113. const Headers &headers,
  12114. DownloadProgress progress) {
  12115. if (params.empty()) { return Get(path, headers); }
  12116. std::string path_with_query = append_query_params(path, params);
  12117. return Get(path_with_query, headers, std::move(progress));
  12118. }
  12119. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12120. DownloadProgress progress) {
  12121. Request req;
  12122. req.method = "GET";
  12123. req.path = path;
  12124. req.headers = headers;
  12125. req.download_progress = std::move(progress);
  12126. if (max_timeout_msec_ > 0) {
  12127. req.start_time_ = std::chrono::steady_clock::now();
  12128. }
  12129. return send_(std::move(req));
  12130. }
  12131. inline Result ClientImpl::Get(const std::string &path,
  12132. ContentReceiver content_receiver,
  12133. DownloadProgress progress) {
  12134. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12135. std::move(progress));
  12136. }
  12137. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12138. ContentReceiver content_receiver,
  12139. DownloadProgress progress) {
  12140. return Get(path, headers, nullptr, std::move(content_receiver),
  12141. std::move(progress));
  12142. }
  12143. inline Result ClientImpl::Get(const std::string &path,
  12144. ResponseHandler response_handler,
  12145. ContentReceiver content_receiver,
  12146. DownloadProgress progress) {
  12147. return Get(path, Headers(), std::move(response_handler),
  12148. std::move(content_receiver), std::move(progress));
  12149. }
  12150. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12151. ResponseHandler response_handler,
  12152. ContentReceiver content_receiver,
  12153. DownloadProgress progress) {
  12154. Request req;
  12155. req.method = "GET";
  12156. req.path = path;
  12157. req.headers = headers;
  12158. req.response_handler = std::move(response_handler);
  12159. req.content_receiver =
  12160. [content_receiver](const char *data, size_t data_length,
  12161. size_t /*offset*/, size_t /*total_length*/) {
  12162. return content_receiver(data, data_length);
  12163. };
  12164. req.download_progress = std::move(progress);
  12165. if (max_timeout_msec_ > 0) {
  12166. req.start_time_ = std::chrono::steady_clock::now();
  12167. }
  12168. return send_(std::move(req));
  12169. }
  12170. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12171. const Headers &headers,
  12172. ContentReceiver content_receiver,
  12173. DownloadProgress progress) {
  12174. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12175. std::move(progress));
  12176. }
  12177. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12178. const Headers &headers,
  12179. ResponseHandler response_handler,
  12180. ContentReceiver content_receiver,
  12181. DownloadProgress progress) {
  12182. if (params.empty()) {
  12183. return Get(path, headers, std::move(response_handler),
  12184. std::move(content_receiver), std::move(progress));
  12185. }
  12186. std::string path_with_query = append_query_params(path, params);
  12187. return Get(path_with_query, headers, std::move(response_handler),
  12188. std::move(content_receiver), std::move(progress));
  12189. }
  12190. inline Result ClientImpl::Head(const std::string &path) {
  12191. return Head(path, Headers());
  12192. }
  12193. inline Result ClientImpl::Head(const std::string &path,
  12194. const Headers &headers) {
  12195. Request req;
  12196. req.method = "HEAD";
  12197. req.headers = headers;
  12198. req.path = path;
  12199. if (max_timeout_msec_ > 0) {
  12200. req.start_time_ = std::chrono::steady_clock::now();
  12201. }
  12202. return send_(std::move(req));
  12203. }
  12204. inline Result ClientImpl::Post(const std::string &path) {
  12205. return Post(path, std::string(), std::string());
  12206. }
  12207. inline Result ClientImpl::Post(const std::string &path,
  12208. const Headers &headers) {
  12209. return Post(path, headers, nullptr, 0, std::string());
  12210. }
  12211. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12212. size_t content_length,
  12213. const std::string &content_type,
  12214. UploadProgress progress) {
  12215. return Post(path, Headers(), body, content_length, content_type, progress);
  12216. }
  12217. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12218. const std::string &content_type,
  12219. UploadProgress progress) {
  12220. return Post(path, Headers(), body, content_type, progress);
  12221. }
  12222. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12223. return Post(path, Headers(), params);
  12224. }
  12225. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12226. ContentProvider content_provider,
  12227. const std::string &content_type,
  12228. UploadProgress progress) {
  12229. return Post(path, Headers(), content_length, std::move(content_provider),
  12230. content_type, progress);
  12231. }
  12232. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12233. ContentProvider content_provider,
  12234. const std::string &content_type,
  12235. ContentReceiver content_receiver,
  12236. UploadProgress progress) {
  12237. return Post(path, Headers(), content_length, std::move(content_provider),
  12238. content_type, std::move(content_receiver), progress);
  12239. }
  12240. inline Result ClientImpl::Post(const std::string &path,
  12241. ContentProviderWithoutLength content_provider,
  12242. const std::string &content_type,
  12243. UploadProgress progress) {
  12244. return Post(path, Headers(), std::move(content_provider), content_type,
  12245. progress);
  12246. }
  12247. inline Result ClientImpl::Post(const std::string &path,
  12248. ContentProviderWithoutLength content_provider,
  12249. const std::string &content_type,
  12250. ContentReceiver content_receiver,
  12251. UploadProgress progress) {
  12252. return Post(path, Headers(), std::move(content_provider), content_type,
  12253. std::move(content_receiver), progress);
  12254. }
  12255. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12256. const Params &params) {
  12257. auto query = detail::params_to_query_str(params);
  12258. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12259. }
  12260. inline Result ClientImpl::Post(const std::string &path,
  12261. const UploadFormDataItems &items,
  12262. UploadProgress progress) {
  12263. return Post(path, Headers(), items, progress);
  12264. }
  12265. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12266. const UploadFormDataItems &items,
  12267. UploadProgress progress) {
  12268. const auto &boundary = detail::make_multipart_data_boundary();
  12269. const auto &content_type =
  12270. detail::serialize_multipart_formdata_get_content_type(boundary);
  12271. auto content_length = detail::get_multipart_content_length(items, boundary);
  12272. return Post(path, headers, content_length,
  12273. detail::make_multipart_content_provider(items, boundary),
  12274. content_type, progress);
  12275. }
  12276. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12277. const UploadFormDataItems &items,
  12278. const std::string &boundary,
  12279. UploadProgress progress) {
  12280. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12281. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12282. }
  12283. const auto &content_type =
  12284. detail::serialize_multipart_formdata_get_content_type(boundary);
  12285. auto content_length = detail::get_multipart_content_length(items, boundary);
  12286. return Post(path, headers, content_length,
  12287. detail::make_multipart_content_provider(items, boundary),
  12288. content_type, progress);
  12289. }
  12290. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12291. const char *body, size_t content_length,
  12292. const std::string &content_type,
  12293. UploadProgress progress) {
  12294. return send_with_content_provider_and_receiver(
  12295. "POST", path, headers, body, content_length, nullptr, nullptr,
  12296. content_type, nullptr, progress);
  12297. }
  12298. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12299. const std::string &body,
  12300. const std::string &content_type,
  12301. UploadProgress progress) {
  12302. return send_with_content_provider_and_receiver(
  12303. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12304. content_type, nullptr, progress);
  12305. }
  12306. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12307. size_t content_length,
  12308. ContentProvider content_provider,
  12309. const std::string &content_type,
  12310. UploadProgress progress) {
  12311. return send_with_content_provider_and_receiver(
  12312. "POST", path, headers, nullptr, content_length,
  12313. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12314. }
  12315. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12316. size_t content_length,
  12317. ContentProvider content_provider,
  12318. const std::string &content_type,
  12319. ContentReceiver content_receiver,
  12320. DownloadProgress progress) {
  12321. return send_with_content_provider_and_receiver(
  12322. "POST", path, headers, nullptr, content_length,
  12323. std::move(content_provider), nullptr, content_type,
  12324. std::move(content_receiver), std::move(progress));
  12325. }
  12326. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12327. ContentProviderWithoutLength content_provider,
  12328. const std::string &content_type,
  12329. UploadProgress progress) {
  12330. return send_with_content_provider_and_receiver(
  12331. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12332. content_type, nullptr, progress);
  12333. }
  12334. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12335. ContentProviderWithoutLength content_provider,
  12336. const std::string &content_type,
  12337. ContentReceiver content_receiver,
  12338. DownloadProgress progress) {
  12339. return send_with_content_provider_and_receiver(
  12340. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12341. content_type, std::move(content_receiver), std::move(progress));
  12342. }
  12343. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12344. const UploadFormDataItems &items,
  12345. const FormDataProviderItems &provider_items,
  12346. UploadProgress progress) {
  12347. const auto &boundary = detail::make_multipart_data_boundary();
  12348. const auto &content_type =
  12349. detail::serialize_multipart_formdata_get_content_type(boundary);
  12350. return send_with_content_provider_and_receiver(
  12351. "POST", path, headers, nullptr, 0, nullptr,
  12352. get_multipart_content_provider(boundary, items, provider_items),
  12353. content_type, nullptr, progress);
  12354. }
  12355. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12356. const std::string &body,
  12357. const std::string &content_type,
  12358. ContentReceiver content_receiver,
  12359. DownloadProgress progress) {
  12360. Request req;
  12361. req.method = "POST";
  12362. req.path = path;
  12363. req.headers = headers;
  12364. req.body = body;
  12365. req.content_receiver =
  12366. [content_receiver](const char *data, size_t data_length,
  12367. size_t /*offset*/, size_t /*total_length*/) {
  12368. return content_receiver(data, data_length);
  12369. };
  12370. req.download_progress = std::move(progress);
  12371. if (max_timeout_msec_ > 0) {
  12372. req.start_time_ = std::chrono::steady_clock::now();
  12373. }
  12374. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12375. return send_(std::move(req));
  12376. }
  12377. inline Result ClientImpl::Put(const std::string &path) {
  12378. return Put(path, std::string(), std::string());
  12379. }
  12380. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12381. return Put(path, headers, nullptr, 0, std::string());
  12382. }
  12383. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12384. size_t content_length,
  12385. const std::string &content_type,
  12386. UploadProgress progress) {
  12387. return Put(path, Headers(), body, content_length, content_type, progress);
  12388. }
  12389. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12390. const std::string &content_type,
  12391. UploadProgress progress) {
  12392. return Put(path, Headers(), body, content_type, progress);
  12393. }
  12394. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12395. return Put(path, Headers(), params);
  12396. }
  12397. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12398. ContentProvider content_provider,
  12399. const std::string &content_type,
  12400. UploadProgress progress) {
  12401. return Put(path, Headers(), content_length, std::move(content_provider),
  12402. content_type, progress);
  12403. }
  12404. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12405. ContentProvider content_provider,
  12406. const std::string &content_type,
  12407. ContentReceiver content_receiver,
  12408. UploadProgress progress) {
  12409. return Put(path, Headers(), content_length, std::move(content_provider),
  12410. content_type, std::move(content_receiver), progress);
  12411. }
  12412. inline Result ClientImpl::Put(const std::string &path,
  12413. ContentProviderWithoutLength content_provider,
  12414. const std::string &content_type,
  12415. UploadProgress progress) {
  12416. return Put(path, Headers(), std::move(content_provider), content_type,
  12417. progress);
  12418. }
  12419. inline Result ClientImpl::Put(const std::string &path,
  12420. ContentProviderWithoutLength content_provider,
  12421. const std::string &content_type,
  12422. ContentReceiver content_receiver,
  12423. UploadProgress progress) {
  12424. return Put(path, Headers(), std::move(content_provider), content_type,
  12425. std::move(content_receiver), progress);
  12426. }
  12427. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12428. const Params &params) {
  12429. auto query = detail::params_to_query_str(params);
  12430. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12431. }
  12432. inline Result ClientImpl::Put(const std::string &path,
  12433. const UploadFormDataItems &items,
  12434. UploadProgress progress) {
  12435. return Put(path, Headers(), items, progress);
  12436. }
  12437. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12438. const UploadFormDataItems &items,
  12439. UploadProgress progress) {
  12440. const auto &boundary = detail::make_multipart_data_boundary();
  12441. const auto &content_type =
  12442. detail::serialize_multipart_formdata_get_content_type(boundary);
  12443. auto content_length = detail::get_multipart_content_length(items, boundary);
  12444. return Put(path, headers, content_length,
  12445. detail::make_multipart_content_provider(items, boundary),
  12446. content_type, progress);
  12447. }
  12448. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12449. const UploadFormDataItems &items,
  12450. const std::string &boundary,
  12451. UploadProgress progress) {
  12452. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12453. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12454. }
  12455. const auto &content_type =
  12456. detail::serialize_multipart_formdata_get_content_type(boundary);
  12457. auto content_length = detail::get_multipart_content_length(items, boundary);
  12458. return Put(path, headers, content_length,
  12459. detail::make_multipart_content_provider(items, boundary),
  12460. content_type, progress);
  12461. }
  12462. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12463. const char *body, size_t content_length,
  12464. const std::string &content_type,
  12465. UploadProgress progress) {
  12466. return send_with_content_provider_and_receiver(
  12467. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12468. content_type, nullptr, progress);
  12469. }
  12470. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12471. const std::string &body,
  12472. const std::string &content_type,
  12473. UploadProgress progress) {
  12474. return send_with_content_provider_and_receiver(
  12475. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12476. content_type, nullptr, progress);
  12477. }
  12478. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12479. size_t content_length,
  12480. ContentProvider content_provider,
  12481. const std::string &content_type,
  12482. UploadProgress progress) {
  12483. return send_with_content_provider_and_receiver(
  12484. "PUT", path, headers, nullptr, content_length,
  12485. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12486. }
  12487. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12488. size_t content_length,
  12489. ContentProvider content_provider,
  12490. const std::string &content_type,
  12491. ContentReceiver content_receiver,
  12492. UploadProgress progress) {
  12493. return send_with_content_provider_and_receiver(
  12494. "PUT", path, headers, nullptr, content_length,
  12495. std::move(content_provider), nullptr, content_type,
  12496. std::move(content_receiver), progress);
  12497. }
  12498. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12499. ContentProviderWithoutLength content_provider,
  12500. const std::string &content_type,
  12501. UploadProgress progress) {
  12502. return send_with_content_provider_and_receiver(
  12503. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12504. content_type, nullptr, progress);
  12505. }
  12506. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12507. ContentProviderWithoutLength content_provider,
  12508. const std::string &content_type,
  12509. ContentReceiver content_receiver,
  12510. UploadProgress progress) {
  12511. return send_with_content_provider_and_receiver(
  12512. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12513. content_type, std::move(content_receiver), progress);
  12514. }
  12515. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12516. const UploadFormDataItems &items,
  12517. const FormDataProviderItems &provider_items,
  12518. UploadProgress progress) {
  12519. const auto &boundary = detail::make_multipart_data_boundary();
  12520. const auto &content_type =
  12521. detail::serialize_multipart_formdata_get_content_type(boundary);
  12522. return send_with_content_provider_and_receiver(
  12523. "PUT", path, headers, nullptr, 0, nullptr,
  12524. get_multipart_content_provider(boundary, items, provider_items),
  12525. content_type, nullptr, progress);
  12526. }
  12527. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12528. const std::string &body,
  12529. const std::string &content_type,
  12530. ContentReceiver content_receiver,
  12531. DownloadProgress progress) {
  12532. Request req;
  12533. req.method = "PUT";
  12534. req.path = path;
  12535. req.headers = headers;
  12536. req.body = body;
  12537. req.content_receiver =
  12538. [content_receiver](const char *data, size_t data_length,
  12539. size_t /*offset*/, size_t /*total_length*/) {
  12540. return content_receiver(data, data_length);
  12541. };
  12542. req.download_progress = std::move(progress);
  12543. if (max_timeout_msec_ > 0) {
  12544. req.start_time_ = std::chrono::steady_clock::now();
  12545. }
  12546. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12547. return send_(std::move(req));
  12548. }
  12549. inline Result ClientImpl::Patch(const std::string &path) {
  12550. return Patch(path, std::string(), std::string());
  12551. }
  12552. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12553. UploadProgress progress) {
  12554. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12555. }
  12556. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12557. size_t content_length,
  12558. const std::string &content_type,
  12559. UploadProgress progress) {
  12560. return Patch(path, Headers(), body, content_length, content_type, progress);
  12561. }
  12562. inline Result ClientImpl::Patch(const std::string &path,
  12563. const std::string &body,
  12564. const std::string &content_type,
  12565. UploadProgress progress) {
  12566. return Patch(path, Headers(), body, content_type, progress);
  12567. }
  12568. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12569. return Patch(path, Headers(), params);
  12570. }
  12571. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12572. ContentProvider content_provider,
  12573. const std::string &content_type,
  12574. UploadProgress progress) {
  12575. return Patch(path, Headers(), content_length, std::move(content_provider),
  12576. content_type, progress);
  12577. }
  12578. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12579. ContentProvider content_provider,
  12580. const std::string &content_type,
  12581. ContentReceiver content_receiver,
  12582. UploadProgress progress) {
  12583. return Patch(path, Headers(), content_length, std::move(content_provider),
  12584. content_type, std::move(content_receiver), progress);
  12585. }
  12586. inline Result ClientImpl::Patch(const std::string &path,
  12587. ContentProviderWithoutLength content_provider,
  12588. const std::string &content_type,
  12589. UploadProgress progress) {
  12590. return Patch(path, Headers(), std::move(content_provider), content_type,
  12591. progress);
  12592. }
  12593. inline Result ClientImpl::Patch(const std::string &path,
  12594. ContentProviderWithoutLength content_provider,
  12595. const std::string &content_type,
  12596. ContentReceiver content_receiver,
  12597. UploadProgress progress) {
  12598. return Patch(path, Headers(), std::move(content_provider), content_type,
  12599. std::move(content_receiver), progress);
  12600. }
  12601. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12602. const Params &params) {
  12603. auto query = detail::params_to_query_str(params);
  12604. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12605. }
  12606. inline Result ClientImpl::Patch(const std::string &path,
  12607. const UploadFormDataItems &items,
  12608. UploadProgress progress) {
  12609. return Patch(path, Headers(), items, progress);
  12610. }
  12611. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12612. const UploadFormDataItems &items,
  12613. UploadProgress progress) {
  12614. const auto &boundary = detail::make_multipart_data_boundary();
  12615. const auto &content_type =
  12616. detail::serialize_multipart_formdata_get_content_type(boundary);
  12617. auto content_length = detail::get_multipart_content_length(items, boundary);
  12618. return Patch(path, headers, content_length,
  12619. detail::make_multipart_content_provider(items, boundary),
  12620. content_type, progress);
  12621. }
  12622. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12623. const UploadFormDataItems &items,
  12624. const std::string &boundary,
  12625. UploadProgress progress) {
  12626. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12627. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12628. }
  12629. const auto &content_type =
  12630. detail::serialize_multipart_formdata_get_content_type(boundary);
  12631. auto content_length = detail::get_multipart_content_length(items, boundary);
  12632. return Patch(path, headers, content_length,
  12633. detail::make_multipart_content_provider(items, boundary),
  12634. content_type, progress);
  12635. }
  12636. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12637. const char *body, size_t content_length,
  12638. const std::string &content_type,
  12639. UploadProgress progress) {
  12640. return send_with_content_provider_and_receiver(
  12641. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12642. content_type, nullptr, progress);
  12643. }
  12644. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12645. const std::string &body,
  12646. const std::string &content_type,
  12647. UploadProgress progress) {
  12648. return send_with_content_provider_and_receiver(
  12649. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12650. content_type, nullptr, progress);
  12651. }
  12652. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12653. size_t content_length,
  12654. ContentProvider content_provider,
  12655. const std::string &content_type,
  12656. UploadProgress progress) {
  12657. return send_with_content_provider_and_receiver(
  12658. "PATCH", path, headers, nullptr, content_length,
  12659. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12660. }
  12661. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12662. size_t content_length,
  12663. ContentProvider content_provider,
  12664. const std::string &content_type,
  12665. ContentReceiver content_receiver,
  12666. UploadProgress progress) {
  12667. return send_with_content_provider_and_receiver(
  12668. "PATCH", path, headers, nullptr, content_length,
  12669. std::move(content_provider), nullptr, content_type,
  12670. std::move(content_receiver), progress);
  12671. }
  12672. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12673. ContentProviderWithoutLength content_provider,
  12674. const std::string &content_type,
  12675. UploadProgress progress) {
  12676. return send_with_content_provider_and_receiver(
  12677. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12678. content_type, nullptr, progress);
  12679. }
  12680. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12681. ContentProviderWithoutLength content_provider,
  12682. const std::string &content_type,
  12683. ContentReceiver content_receiver,
  12684. UploadProgress progress) {
  12685. return send_with_content_provider_and_receiver(
  12686. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12687. content_type, std::move(content_receiver), progress);
  12688. }
  12689. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12690. const UploadFormDataItems &items,
  12691. const FormDataProviderItems &provider_items,
  12692. UploadProgress progress) {
  12693. const auto &boundary = detail::make_multipart_data_boundary();
  12694. const auto &content_type =
  12695. detail::serialize_multipart_formdata_get_content_type(boundary);
  12696. return send_with_content_provider_and_receiver(
  12697. "PATCH", path, headers, nullptr, 0, nullptr,
  12698. get_multipart_content_provider(boundary, items, provider_items),
  12699. content_type, nullptr, progress);
  12700. }
  12701. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12702. const std::string &body,
  12703. const std::string &content_type,
  12704. ContentReceiver content_receiver,
  12705. DownloadProgress progress) {
  12706. Request req;
  12707. req.method = "PATCH";
  12708. req.path = path;
  12709. req.headers = headers;
  12710. req.body = body;
  12711. req.content_receiver =
  12712. [content_receiver](const char *data, size_t data_length,
  12713. size_t /*offset*/, size_t /*total_length*/) {
  12714. return content_receiver(data, data_length);
  12715. };
  12716. req.download_progress = std::move(progress);
  12717. if (max_timeout_msec_ > 0) {
  12718. req.start_time_ = std::chrono::steady_clock::now();
  12719. }
  12720. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12721. return send_(std::move(req));
  12722. }
  12723. inline Result ClientImpl::Delete(const std::string &path,
  12724. DownloadProgress progress) {
  12725. return Delete(path, Headers(), std::string(), std::string(), progress);
  12726. }
  12727. inline Result ClientImpl::Delete(const std::string &path,
  12728. const Headers &headers,
  12729. DownloadProgress progress) {
  12730. return Delete(path, headers, std::string(), std::string(), progress);
  12731. }
  12732. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12733. size_t content_length,
  12734. const std::string &content_type,
  12735. DownloadProgress progress) {
  12736. return Delete(path, Headers(), body, content_length, content_type, progress);
  12737. }
  12738. inline Result ClientImpl::Delete(const std::string &path,
  12739. const std::string &body,
  12740. const std::string &content_type,
  12741. DownloadProgress progress) {
  12742. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12743. progress);
  12744. }
  12745. inline Result ClientImpl::Delete(const std::string &path,
  12746. const Headers &headers,
  12747. const std::string &body,
  12748. const std::string &content_type,
  12749. DownloadProgress progress) {
  12750. return Delete(path, headers, body.data(), body.size(), content_type,
  12751. progress);
  12752. }
  12753. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12754. DownloadProgress progress) {
  12755. return Delete(path, Headers(), params, progress);
  12756. }
  12757. inline Result ClientImpl::Delete(const std::string &path,
  12758. const Headers &headers, const Params &params,
  12759. DownloadProgress progress) {
  12760. auto query = detail::params_to_query_str(params);
  12761. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12762. progress);
  12763. }
  12764. inline Result ClientImpl::Delete(const std::string &path,
  12765. const Headers &headers, const char *body,
  12766. size_t content_length,
  12767. const std::string &content_type,
  12768. DownloadProgress progress) {
  12769. Request req;
  12770. req.method = "DELETE";
  12771. req.headers = headers;
  12772. req.path = path;
  12773. req.download_progress = std::move(progress);
  12774. if (max_timeout_msec_ > 0) {
  12775. req.start_time_ = std::chrono::steady_clock::now();
  12776. }
  12777. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12778. req.body.assign(body, content_length);
  12779. return send_(std::move(req));
  12780. }
  12781. inline Result ClientImpl::Options(const std::string &path) {
  12782. return Options(path, Headers());
  12783. }
  12784. inline Result ClientImpl::Options(const std::string &path,
  12785. const Headers &headers) {
  12786. Request req;
  12787. req.method = "OPTIONS";
  12788. req.headers = headers;
  12789. req.path = path;
  12790. if (max_timeout_msec_ > 0) {
  12791. req.start_time_ = std::chrono::steady_clock::now();
  12792. }
  12793. return send_(std::move(req));
  12794. }
  12795. inline void ClientImpl::stop() {
  12796. std::lock_guard<std::mutex> guard(socket_mutex_);
  12797. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12798. // do is to shutdown_socket, so that threads using this socket suddenly
  12799. // discover they can't read/write any more and error out. Everything else
  12800. // (closing the socket, shutting ssl down) is unsafe because these actions
  12801. // are not thread-safe.
  12802. if (socket_requests_in_flight_ > 0) {
  12803. shutdown_socket(socket_);
  12804. // Aside from that, we set a flag for the socket to be closed when we're
  12805. // done.
  12806. socket_should_be_closed_when_request_is_done_ = true;
  12807. return;
  12808. }
  12809. disconnect(/*gracefully=*/true);
  12810. }
  12811. inline std::string ClientImpl::host() const { return host_; }
  12812. inline int ClientImpl::port() const { return port_; }
  12813. inline size_t ClientImpl::is_socket_open() const {
  12814. std::lock_guard<std::mutex> guard(socket_mutex_);
  12815. return socket_.is_open();
  12816. }
  12817. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12818. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12819. connection_timeout_sec_ = sec;
  12820. connection_timeout_usec_ = usec;
  12821. }
  12822. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12823. read_timeout_sec_ = sec;
  12824. read_timeout_usec_ = usec;
  12825. }
  12826. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12827. write_timeout_sec_ = sec;
  12828. write_timeout_usec_ = usec;
  12829. }
  12830. inline void ClientImpl::set_max_timeout(time_t msec) {
  12831. max_timeout_msec_ = msec;
  12832. }
  12833. inline void ClientImpl::set_basic_auth(const std::string &username,
  12834. const std::string &password) {
  12835. basic_auth_username_ = username;
  12836. basic_auth_password_ = password;
  12837. }
  12838. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12839. bearer_token_auth_token_ = token;
  12840. }
  12841. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12842. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12843. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12844. inline void
  12845. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12846. addr_map_ = std::move(addr_map);
  12847. }
  12848. inline void ClientImpl::set_default_headers(Headers headers) {
  12849. default_headers_ = std::move(headers);
  12850. }
  12851. inline void ClientImpl::set_header_writer(
  12852. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12853. header_writer_ = writer;
  12854. }
  12855. inline void ClientImpl::set_address_family(int family) {
  12856. address_family_ = family;
  12857. }
  12858. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12859. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12860. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12861. socket_options_ = std::move(socket_options);
  12862. }
  12863. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12864. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12865. inline void ClientImpl::set_payload_max_length(size_t length) {
  12866. payload_max_length_ = length;
  12867. has_payload_max_length_ = true;
  12868. }
  12869. inline void ClientImpl::set_interface(const std::string &intf) {
  12870. interface_ = intf;
  12871. }
  12872. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12873. proxy_host_ = host;
  12874. proxy_port_ = port;
  12875. std::lock_guard<std::mutex> guard(socket_mutex_);
  12876. disconnect(/*gracefully=*/true);
  12877. }
  12878. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12879. const std::string &password) {
  12880. proxy_basic_auth_username_ = username;
  12881. proxy_basic_auth_password_ = password;
  12882. }
  12883. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12884. proxy_bearer_token_auth_token_ = token;
  12885. }
  12886. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12887. std::vector<detail::NoProxyEntry> parsed;
  12888. parsed.reserve(patterns.size());
  12889. for (const auto &p : patterns) {
  12890. auto trimmed = detail::trim_copy(p);
  12891. if (trimmed.empty()) { continue; }
  12892. detail::NoProxyEntry entry;
  12893. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12894. parsed.push_back(std::move(entry));
  12895. }
  12896. }
  12897. no_proxy_entries_ = std::move(parsed);
  12898. std::lock_guard<std::mutex> guard(socket_mutex_);
  12899. disconnect(/*gracefully=*/true);
  12900. }
  12901. #ifdef CPPHTTPLIB_SSL_ENABLED
  12902. inline void ClientImpl::set_digest_auth(const std::string &username,
  12903. const std::string &password) {
  12904. digest_auth_username_ = username;
  12905. digest_auth_password_ = password;
  12906. }
  12907. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12908. const std::string &ca_cert_dir_path) {
  12909. ca_cert_file_path_ = ca_cert_file_path;
  12910. ca_cert_dir_path_ = ca_cert_dir_path;
  12911. }
  12912. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12913. const std::string &password) {
  12914. proxy_digest_auth_username_ = username;
  12915. proxy_digest_auth_password_ = password;
  12916. }
  12917. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12918. server_certificate_verification_ = enabled;
  12919. }
  12920. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12921. server_hostname_verification_ = enabled;
  12922. }
  12923. inline void ClientImpl::enable_system_ca(bool enabled) {
  12924. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12925. }
  12926. #endif
  12927. inline void ClientImpl::set_logger(Logger logger) {
  12928. logger_ = std::move(logger);
  12929. }
  12930. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12931. error_logger_ = std::move(error_logger);
  12932. }
  12933. /*
  12934. * SSL/TLS Common Implementation
  12935. */
  12936. inline ClientConnection::~ClientConnection() {
  12937. #ifdef CPPHTTPLIB_SSL_ENABLED
  12938. if (session) {
  12939. tls::shutdown(session, true);
  12940. tls::free_session(session);
  12941. session = nullptr;
  12942. }
  12943. #endif
  12944. if (sock != INVALID_SOCKET) {
  12945. detail::close_socket(sock);
  12946. sock = INVALID_SOCKET;
  12947. }
  12948. }
  12949. // Universal client implementation
  12950. inline Client::Client(const std::string &scheme_host_port)
  12951. : Client(scheme_host_port, std::string(), std::string()) {}
  12952. inline Client::Client(const std::string &scheme_host_port,
  12953. const std::string &client_cert_path,
  12954. const std::string &client_key_path) {
  12955. detail::UrlComponents uc;
  12956. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12957. auto &scheme = uc.scheme;
  12958. #ifdef CPPHTTPLIB_SSL_ENABLED
  12959. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12960. #else
  12961. if (!scheme.empty() && scheme != "http") {
  12962. #endif
  12963. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12964. std::string msg = "'" + scheme + "' scheme is not supported.";
  12965. throw std::invalid_argument(msg);
  12966. #endif
  12967. return;
  12968. }
  12969. auto is_ssl = scheme == "https";
  12970. auto host = std::move(uc.host);
  12971. auto port = is_ssl ? 443 : 80;
  12972. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12973. if (is_ssl) {
  12974. #ifdef CPPHTTPLIB_SSL_ENABLED
  12975. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12976. client_key_path);
  12977. is_ssl_ = is_ssl;
  12978. #endif
  12979. } else {
  12980. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12981. client_key_path);
  12982. }
  12983. } else {
  12984. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12985. // if port param below changes.
  12986. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12987. client_cert_path, client_key_path);
  12988. }
  12989. }
  12990. inline Client::Client(const std::string &host, int port)
  12991. : Client(host, port, std::string(), std::string()) {}
  12992. inline Client::Client(const std::string &host, int port,
  12993. const std::string &client_cert_path,
  12994. const std::string &client_key_path)
  12995. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12996. client_key_path)) {}
  12997. inline Client::~Client() = default;
  12998. inline bool Client::is_valid() const {
  12999. return cli_ != nullptr && cli_->is_valid();
  13000. }
  13001. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  13002. return cli_->Get(path, std::move(progress));
  13003. }
  13004. inline Result Client::Get(const std::string &path, const Headers &headers,
  13005. DownloadProgress progress) {
  13006. return cli_->Get(path, headers, std::move(progress));
  13007. }
  13008. inline Result Client::Get(const std::string &path,
  13009. ContentReceiver content_receiver,
  13010. DownloadProgress progress) {
  13011. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  13012. }
  13013. inline Result Client::Get(const std::string &path, const Headers &headers,
  13014. ContentReceiver content_receiver,
  13015. DownloadProgress progress) {
  13016. return cli_->Get(path, headers, std::move(content_receiver),
  13017. std::move(progress));
  13018. }
  13019. inline Result Client::Get(const std::string &path,
  13020. ResponseHandler response_handler,
  13021. ContentReceiver content_receiver,
  13022. DownloadProgress progress) {
  13023. return cli_->Get(path, std::move(response_handler),
  13024. std::move(content_receiver), std::move(progress));
  13025. }
  13026. inline Result Client::Get(const std::string &path, const Headers &headers,
  13027. ResponseHandler response_handler,
  13028. ContentReceiver content_receiver,
  13029. DownloadProgress progress) {
  13030. return cli_->Get(path, headers, std::move(response_handler),
  13031. std::move(content_receiver), std::move(progress));
  13032. }
  13033. inline Result Client::Get(const std::string &path, const Params &params,
  13034. DownloadProgress progress) {
  13035. return cli_->Get(path, params, std::move(progress));
  13036. }
  13037. inline Result Client::Get(const std::string &path, const Params &params,
  13038. const Headers &headers, DownloadProgress progress) {
  13039. return cli_->Get(path, params, headers, std::move(progress));
  13040. }
  13041. inline Result Client::Get(const std::string &path, const Params &params,
  13042. const Headers &headers,
  13043. ContentReceiver content_receiver,
  13044. DownloadProgress progress) {
  13045. return cli_->Get(path, params, headers, std::move(content_receiver),
  13046. std::move(progress));
  13047. }
  13048. inline Result Client::Get(const std::string &path, const Params &params,
  13049. const Headers &headers,
  13050. ResponseHandler response_handler,
  13051. ContentReceiver content_receiver,
  13052. DownloadProgress progress) {
  13053. return cli_->Get(path, params, headers, std::move(response_handler),
  13054. std::move(content_receiver), std::move(progress));
  13055. }
  13056. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  13057. inline Result Client::Head(const std::string &path, const Headers &headers) {
  13058. return cli_->Head(path, headers);
  13059. }
  13060. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  13061. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13062. return cli_->Post(path, headers);
  13063. }
  13064. inline Result Client::Post(const std::string &path, const char *body,
  13065. size_t content_length,
  13066. const std::string &content_type,
  13067. UploadProgress progress) {
  13068. return cli_->Post(path, body, content_length, content_type, progress);
  13069. }
  13070. inline Result Client::Post(const std::string &path, const Headers &headers,
  13071. const char *body, size_t content_length,
  13072. const std::string &content_type,
  13073. UploadProgress progress) {
  13074. return cli_->Post(path, headers, body, content_length, content_type,
  13075. progress);
  13076. }
  13077. inline Result Client::Post(const std::string &path, const std::string &body,
  13078. const std::string &content_type,
  13079. UploadProgress progress) {
  13080. return cli_->Post(path, body, content_type, progress);
  13081. }
  13082. inline Result Client::Post(const std::string &path, const Headers &headers,
  13083. const std::string &body,
  13084. const std::string &content_type,
  13085. UploadProgress progress) {
  13086. return cli_->Post(path, headers, body, content_type, progress);
  13087. }
  13088. inline Result Client::Post(const std::string &path, size_t content_length,
  13089. ContentProvider content_provider,
  13090. const std::string &content_type,
  13091. UploadProgress progress) {
  13092. return cli_->Post(path, content_length, std::move(content_provider),
  13093. content_type, progress);
  13094. }
  13095. inline Result Client::Post(const std::string &path, size_t content_length,
  13096. ContentProvider content_provider,
  13097. const std::string &content_type,
  13098. ContentReceiver content_receiver,
  13099. UploadProgress progress) {
  13100. return cli_->Post(path, content_length, std::move(content_provider),
  13101. content_type, std::move(content_receiver), progress);
  13102. }
  13103. inline Result Client::Post(const std::string &path,
  13104. ContentProviderWithoutLength content_provider,
  13105. const std::string &content_type,
  13106. UploadProgress progress) {
  13107. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13108. }
  13109. inline Result Client::Post(const std::string &path,
  13110. ContentProviderWithoutLength content_provider,
  13111. const std::string &content_type,
  13112. ContentReceiver content_receiver,
  13113. UploadProgress progress) {
  13114. return cli_->Post(path, std::move(content_provider), content_type,
  13115. std::move(content_receiver), progress);
  13116. }
  13117. inline Result Client::Post(const std::string &path, const Headers &headers,
  13118. size_t content_length,
  13119. ContentProvider content_provider,
  13120. const std::string &content_type,
  13121. UploadProgress progress) {
  13122. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13123. content_type, progress);
  13124. }
  13125. inline Result Client::Post(const std::string &path, const Headers &headers,
  13126. size_t content_length,
  13127. ContentProvider content_provider,
  13128. const std::string &content_type,
  13129. ContentReceiver content_receiver,
  13130. DownloadProgress progress) {
  13131. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13132. content_type, std::move(content_receiver), progress);
  13133. }
  13134. inline Result Client::Post(const std::string &path, const Headers &headers,
  13135. ContentProviderWithoutLength content_provider,
  13136. const std::string &content_type,
  13137. UploadProgress progress) {
  13138. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13139. progress);
  13140. }
  13141. inline Result Client::Post(const std::string &path, const Headers &headers,
  13142. ContentProviderWithoutLength content_provider,
  13143. const std::string &content_type,
  13144. ContentReceiver content_receiver,
  13145. DownloadProgress progress) {
  13146. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13147. std::move(content_receiver), progress);
  13148. }
  13149. inline Result Client::Post(const std::string &path, const Params &params) {
  13150. return cli_->Post(path, params);
  13151. }
  13152. inline Result Client::Post(const std::string &path, const Headers &headers,
  13153. const Params &params) {
  13154. return cli_->Post(path, headers, params);
  13155. }
  13156. inline Result Client::Post(const std::string &path,
  13157. const UploadFormDataItems &items,
  13158. UploadProgress progress) {
  13159. return cli_->Post(path, items, progress);
  13160. }
  13161. inline Result Client::Post(const std::string &path, const Headers &headers,
  13162. const UploadFormDataItems &items,
  13163. UploadProgress progress) {
  13164. return cli_->Post(path, headers, items, progress);
  13165. }
  13166. inline Result Client::Post(const std::string &path, const Headers &headers,
  13167. const UploadFormDataItems &items,
  13168. const std::string &boundary,
  13169. UploadProgress progress) {
  13170. return cli_->Post(path, headers, items, boundary, progress);
  13171. }
  13172. inline Result Client::Post(const std::string &path, const Headers &headers,
  13173. const UploadFormDataItems &items,
  13174. const FormDataProviderItems &provider_items,
  13175. UploadProgress progress) {
  13176. return cli_->Post(path, headers, items, provider_items, progress);
  13177. }
  13178. inline Result Client::Post(const std::string &path, const Headers &headers,
  13179. const std::string &body,
  13180. const std::string &content_type,
  13181. ContentReceiver content_receiver,
  13182. DownloadProgress progress) {
  13183. return cli_->Post(path, headers, body, content_type,
  13184. std::move(content_receiver), progress);
  13185. }
  13186. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13187. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13188. return cli_->Put(path, headers);
  13189. }
  13190. inline Result Client::Put(const std::string &path, const char *body,
  13191. size_t content_length,
  13192. const std::string &content_type,
  13193. UploadProgress progress) {
  13194. return cli_->Put(path, body, content_length, content_type, progress);
  13195. }
  13196. inline Result Client::Put(const std::string &path, const Headers &headers,
  13197. const char *body, size_t content_length,
  13198. const std::string &content_type,
  13199. UploadProgress progress) {
  13200. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13201. }
  13202. inline Result Client::Put(const std::string &path, const std::string &body,
  13203. const std::string &content_type,
  13204. UploadProgress progress) {
  13205. return cli_->Put(path, body, content_type, progress);
  13206. }
  13207. inline Result Client::Put(const std::string &path, const Headers &headers,
  13208. const std::string &body,
  13209. const std::string &content_type,
  13210. UploadProgress progress) {
  13211. return cli_->Put(path, headers, body, content_type, progress);
  13212. }
  13213. inline Result Client::Put(const std::string &path, size_t content_length,
  13214. ContentProvider content_provider,
  13215. const std::string &content_type,
  13216. UploadProgress progress) {
  13217. return cli_->Put(path, content_length, std::move(content_provider),
  13218. content_type, progress);
  13219. }
  13220. inline Result Client::Put(const std::string &path, size_t content_length,
  13221. ContentProvider content_provider,
  13222. const std::string &content_type,
  13223. ContentReceiver content_receiver,
  13224. UploadProgress progress) {
  13225. return cli_->Put(path, content_length, std::move(content_provider),
  13226. content_type, std::move(content_receiver), progress);
  13227. }
  13228. inline Result Client::Put(const std::string &path,
  13229. ContentProviderWithoutLength content_provider,
  13230. const std::string &content_type,
  13231. UploadProgress progress) {
  13232. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13233. }
  13234. inline Result Client::Put(const std::string &path,
  13235. ContentProviderWithoutLength content_provider,
  13236. const std::string &content_type,
  13237. ContentReceiver content_receiver,
  13238. UploadProgress progress) {
  13239. return cli_->Put(path, std::move(content_provider), content_type,
  13240. std::move(content_receiver), progress);
  13241. }
  13242. inline Result Client::Put(const std::string &path, const Headers &headers,
  13243. size_t content_length,
  13244. ContentProvider content_provider,
  13245. const std::string &content_type,
  13246. UploadProgress progress) {
  13247. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13248. content_type, progress);
  13249. }
  13250. inline Result Client::Put(const std::string &path, const Headers &headers,
  13251. size_t content_length,
  13252. ContentProvider content_provider,
  13253. const std::string &content_type,
  13254. ContentReceiver content_receiver,
  13255. UploadProgress progress) {
  13256. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13257. content_type, std::move(content_receiver), progress);
  13258. }
  13259. inline Result Client::Put(const std::string &path, const Headers &headers,
  13260. ContentProviderWithoutLength content_provider,
  13261. const std::string &content_type,
  13262. UploadProgress progress) {
  13263. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13264. progress);
  13265. }
  13266. inline Result Client::Put(const std::string &path, const Headers &headers,
  13267. ContentProviderWithoutLength content_provider,
  13268. const std::string &content_type,
  13269. ContentReceiver content_receiver,
  13270. UploadProgress progress) {
  13271. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13272. std::move(content_receiver), progress);
  13273. }
  13274. inline Result Client::Put(const std::string &path, const Params &params) {
  13275. return cli_->Put(path, params);
  13276. }
  13277. inline Result Client::Put(const std::string &path, const Headers &headers,
  13278. const Params &params) {
  13279. return cli_->Put(path, headers, params);
  13280. }
  13281. inline Result Client::Put(const std::string &path,
  13282. const UploadFormDataItems &items,
  13283. UploadProgress progress) {
  13284. return cli_->Put(path, items, progress);
  13285. }
  13286. inline Result Client::Put(const std::string &path, const Headers &headers,
  13287. const UploadFormDataItems &items,
  13288. UploadProgress progress) {
  13289. return cli_->Put(path, headers, items, progress);
  13290. }
  13291. inline Result Client::Put(const std::string &path, const Headers &headers,
  13292. const UploadFormDataItems &items,
  13293. const std::string &boundary,
  13294. UploadProgress progress) {
  13295. return cli_->Put(path, headers, items, boundary, progress);
  13296. }
  13297. inline Result Client::Put(const std::string &path, const Headers &headers,
  13298. const UploadFormDataItems &items,
  13299. const FormDataProviderItems &provider_items,
  13300. UploadProgress progress) {
  13301. return cli_->Put(path, headers, items, provider_items, progress);
  13302. }
  13303. inline Result Client::Put(const std::string &path, const Headers &headers,
  13304. const std::string &body,
  13305. const std::string &content_type,
  13306. ContentReceiver content_receiver,
  13307. DownloadProgress progress) {
  13308. return cli_->Put(path, headers, body, content_type, content_receiver,
  13309. progress);
  13310. }
  13311. inline Result Client::Patch(const std::string &path) {
  13312. return cli_->Patch(path);
  13313. }
  13314. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13315. return cli_->Patch(path, headers);
  13316. }
  13317. inline Result Client::Patch(const std::string &path, const char *body,
  13318. size_t content_length,
  13319. const std::string &content_type,
  13320. UploadProgress progress) {
  13321. return cli_->Patch(path, body, content_length, content_type, progress);
  13322. }
  13323. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13324. const char *body, size_t content_length,
  13325. const std::string &content_type,
  13326. UploadProgress progress) {
  13327. return cli_->Patch(path, headers, body, content_length, content_type,
  13328. progress);
  13329. }
  13330. inline Result Client::Patch(const std::string &path, const std::string &body,
  13331. const std::string &content_type,
  13332. UploadProgress progress) {
  13333. return cli_->Patch(path, body, content_type, progress);
  13334. }
  13335. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13336. const std::string &body,
  13337. const std::string &content_type,
  13338. UploadProgress progress) {
  13339. return cli_->Patch(path, headers, body, content_type, progress);
  13340. }
  13341. inline Result Client::Patch(const std::string &path, size_t content_length,
  13342. ContentProvider content_provider,
  13343. const std::string &content_type,
  13344. UploadProgress progress) {
  13345. return cli_->Patch(path, content_length, std::move(content_provider),
  13346. content_type, progress);
  13347. }
  13348. inline Result Client::Patch(const std::string &path, size_t content_length,
  13349. ContentProvider content_provider,
  13350. const std::string &content_type,
  13351. ContentReceiver content_receiver,
  13352. UploadProgress progress) {
  13353. return cli_->Patch(path, content_length, std::move(content_provider),
  13354. content_type, std::move(content_receiver), progress);
  13355. }
  13356. inline Result Client::Patch(const std::string &path,
  13357. ContentProviderWithoutLength content_provider,
  13358. const std::string &content_type,
  13359. UploadProgress progress) {
  13360. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13361. }
  13362. inline Result Client::Patch(const std::string &path,
  13363. ContentProviderWithoutLength content_provider,
  13364. const std::string &content_type,
  13365. ContentReceiver content_receiver,
  13366. UploadProgress progress) {
  13367. return cli_->Patch(path, std::move(content_provider), content_type,
  13368. std::move(content_receiver), progress);
  13369. }
  13370. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13371. size_t content_length,
  13372. ContentProvider content_provider,
  13373. const std::string &content_type,
  13374. UploadProgress progress) {
  13375. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13376. content_type, progress);
  13377. }
  13378. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13379. size_t content_length,
  13380. ContentProvider content_provider,
  13381. const std::string &content_type,
  13382. ContentReceiver content_receiver,
  13383. UploadProgress progress) {
  13384. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13385. content_type, std::move(content_receiver), progress);
  13386. }
  13387. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13388. ContentProviderWithoutLength content_provider,
  13389. const std::string &content_type,
  13390. UploadProgress progress) {
  13391. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13392. progress);
  13393. }
  13394. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13395. ContentProviderWithoutLength content_provider,
  13396. const std::string &content_type,
  13397. ContentReceiver content_receiver,
  13398. UploadProgress progress) {
  13399. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13400. std::move(content_receiver), progress);
  13401. }
  13402. inline Result Client::Patch(const std::string &path, const Params &params) {
  13403. return cli_->Patch(path, params);
  13404. }
  13405. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13406. const Params &params) {
  13407. return cli_->Patch(path, headers, params);
  13408. }
  13409. inline Result Client::Patch(const std::string &path,
  13410. const UploadFormDataItems &items,
  13411. UploadProgress progress) {
  13412. return cli_->Patch(path, items, progress);
  13413. }
  13414. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13415. const UploadFormDataItems &items,
  13416. UploadProgress progress) {
  13417. return cli_->Patch(path, headers, items, progress);
  13418. }
  13419. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13420. const UploadFormDataItems &items,
  13421. const std::string &boundary,
  13422. UploadProgress progress) {
  13423. return cli_->Patch(path, headers, items, boundary, progress);
  13424. }
  13425. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13426. const UploadFormDataItems &items,
  13427. const FormDataProviderItems &provider_items,
  13428. UploadProgress progress) {
  13429. return cli_->Patch(path, headers, items, provider_items, progress);
  13430. }
  13431. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13432. const std::string &body,
  13433. const std::string &content_type,
  13434. ContentReceiver content_receiver,
  13435. DownloadProgress progress) {
  13436. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13437. progress);
  13438. }
  13439. inline Result Client::Delete(const std::string &path,
  13440. DownloadProgress progress) {
  13441. return cli_->Delete(path, progress);
  13442. }
  13443. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13444. DownloadProgress progress) {
  13445. return cli_->Delete(path, headers, progress);
  13446. }
  13447. inline Result Client::Delete(const std::string &path, const char *body,
  13448. size_t content_length,
  13449. const std::string &content_type,
  13450. DownloadProgress progress) {
  13451. return cli_->Delete(path, body, content_length, content_type, progress);
  13452. }
  13453. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13454. const char *body, size_t content_length,
  13455. const std::string &content_type,
  13456. DownloadProgress progress) {
  13457. return cli_->Delete(path, headers, body, content_length, content_type,
  13458. progress);
  13459. }
  13460. inline Result Client::Delete(const std::string &path, const std::string &body,
  13461. const std::string &content_type,
  13462. DownloadProgress progress) {
  13463. return cli_->Delete(path, body, content_type, progress);
  13464. }
  13465. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13466. const std::string &body,
  13467. const std::string &content_type,
  13468. DownloadProgress progress) {
  13469. return cli_->Delete(path, headers, body, content_type, progress);
  13470. }
  13471. inline Result Client::Delete(const std::string &path, const Params &params,
  13472. DownloadProgress progress) {
  13473. return cli_->Delete(path, params, progress);
  13474. }
  13475. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13476. const Params &params, DownloadProgress progress) {
  13477. return cli_->Delete(path, headers, params, progress);
  13478. }
  13479. inline Result Client::Options(const std::string &path) {
  13480. return cli_->Options(path);
  13481. }
  13482. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13483. return cli_->Options(path, headers);
  13484. }
  13485. inline ClientImpl::StreamHandle
  13486. Client::open_stream(const std::string &method, const std::string &path,
  13487. const Params &params, const Headers &headers,
  13488. const std::string &body, const std::string &content_type) {
  13489. return cli_->open_stream(method, path, params, headers, body, content_type);
  13490. }
  13491. inline bool Client::send(Request &req, Response &res, Error &error) {
  13492. return cli_->send(req, res, error);
  13493. }
  13494. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13495. inline void Client::stop() { cli_->stop(); }
  13496. inline std::string Client::host() const { return cli_->host(); }
  13497. inline int Client::port() const { return cli_->port(); }
  13498. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13499. inline socket_t Client::socket() const { return cli_->socket(); }
  13500. inline void
  13501. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13502. cli_->set_hostname_addr_map(std::move(addr_map));
  13503. }
  13504. inline void Client::set_default_headers(Headers headers) {
  13505. cli_->set_default_headers(std::move(headers));
  13506. }
  13507. inline void Client::set_header_writer(
  13508. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13509. cli_->set_header_writer(writer);
  13510. }
  13511. inline void Client::set_address_family(int family) {
  13512. cli_->set_address_family(family);
  13513. }
  13514. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13515. inline void Client::set_socket_options(SocketOptions socket_options) {
  13516. cli_->set_socket_options(std::move(socket_options));
  13517. }
  13518. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13519. cli_->set_connection_timeout(sec, usec);
  13520. }
  13521. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13522. cli_->set_read_timeout(sec, usec);
  13523. }
  13524. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13525. cli_->set_write_timeout(sec, usec);
  13526. }
  13527. inline void Client::set_basic_auth(const std::string &username,
  13528. const std::string &password) {
  13529. cli_->set_basic_auth(username, password);
  13530. }
  13531. inline void Client::set_bearer_token_auth(const std::string &token) {
  13532. cli_->set_bearer_token_auth(token);
  13533. }
  13534. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13535. inline void Client::set_follow_location(bool on) {
  13536. cli_->set_follow_location(on);
  13537. }
  13538. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13539. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13540. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13541. inline void Client::set_payload_max_length(size_t length) {
  13542. cli_->set_payload_max_length(length);
  13543. }
  13544. inline void Client::set_interface(const std::string &intf) {
  13545. cli_->set_interface(intf);
  13546. }
  13547. inline void Client::set_proxy(const std::string &host, int port) {
  13548. cli_->set_proxy(host, port);
  13549. }
  13550. inline void Client::set_proxy_basic_auth(const std::string &username,
  13551. const std::string &password) {
  13552. cli_->set_proxy_basic_auth(username, password);
  13553. }
  13554. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13555. cli_->set_proxy_bearer_token_auth(token);
  13556. }
  13557. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13558. cli_->set_no_proxy(patterns);
  13559. }
  13560. inline void Client::set_logger(Logger logger) {
  13561. cli_->set_logger(std::move(logger));
  13562. }
  13563. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13564. cli_->set_error_logger(std::move(error_logger));
  13565. }
  13566. /*
  13567. * Group 6: SSL Server and Client implementation
  13568. */
  13569. #ifdef CPPHTTPLIB_SSL_ENABLED
  13570. // SSL HTTP server implementation
  13571. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13572. const char *client_ca_cert_file_path,
  13573. const char *client_ca_cert_dir_path,
  13574. const char *private_key_password) {
  13575. using namespace tls;
  13576. ctx_ = create_server_context();
  13577. if (!ctx_) { return; }
  13578. // Load server certificate and private key
  13579. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13580. private_key_password)) {
  13581. last_ssl_error_ = static_cast<int>(get_error());
  13582. free_context(ctx_);
  13583. ctx_ = nullptr;
  13584. return;
  13585. }
  13586. // Load client CA certificates for client authentication
  13587. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13588. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13589. client_ca_cert_dir_path)) {
  13590. last_ssl_error_ = static_cast<int>(get_error());
  13591. free_context(ctx_);
  13592. ctx_ = nullptr;
  13593. return;
  13594. }
  13595. // Enable client certificate verification
  13596. set_verify_client(ctx_, true);
  13597. }
  13598. }
  13599. inline SSLServer::SSLServer(const PemMemory &pem) {
  13600. using namespace tls;
  13601. ctx_ = create_server_context();
  13602. if (ctx_) {
  13603. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13604. pem.private_key_password)) {
  13605. last_ssl_error_ = static_cast<int>(get_error());
  13606. free_context(ctx_);
  13607. ctx_ = nullptr;
  13608. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13609. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13610. last_ssl_error_ = static_cast<int>(get_error());
  13611. free_context(ctx_);
  13612. ctx_ = nullptr;
  13613. } else {
  13614. set_verify_client(ctx_, true);
  13615. }
  13616. }
  13617. }
  13618. }
  13619. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13620. using namespace tls;
  13621. ctx_ = create_server_context();
  13622. if (ctx_) {
  13623. if (!setup_callback(ctx_)) {
  13624. free_context(ctx_);
  13625. ctx_ = nullptr;
  13626. }
  13627. }
  13628. }
  13629. inline SSLServer::~SSLServer() {
  13630. if (ctx_) { tls::free_context(ctx_); }
  13631. }
  13632. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13633. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13634. using namespace tls;
  13635. // Create TLS session with mutex protection
  13636. session_t session = nullptr;
  13637. {
  13638. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13639. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13640. }
  13641. if (!session) {
  13642. last_ssl_error_ = static_cast<int>(get_error());
  13643. detail::shutdown_socket(sock);
  13644. detail::close_socket(sock);
  13645. return false;
  13646. }
  13647. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13648. bool handshake_done = false;
  13649. bool ret = false;
  13650. bool websocket_upgraded = false;
  13651. auto cleanup = detail::scope_exit([&] {
  13652. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13653. free_session(session);
  13654. detail::shutdown_socket(sock);
  13655. detail::close_socket(sock);
  13656. });
  13657. // Perform TLS accept handshake with timeout
  13658. TlsError tls_err;
  13659. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13660. &tls_err)) {
  13661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13662. // Map TlsError to legacy ssl_error for backward compatibility
  13663. if (tls_err.code == ErrorCode::WantRead) {
  13664. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13665. } else if (tls_err.code == ErrorCode::WantWrite) {
  13666. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13667. } else {
  13668. last_ssl_error_ = SSL_ERROR_SSL;
  13669. }
  13670. #else
  13671. last_ssl_error_ = static_cast<int>(get_error());
  13672. #endif
  13673. return false;
  13674. }
  13675. handshake_done = true;
  13676. std::string remote_addr;
  13677. int remote_port = 0;
  13678. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13679. std::string local_addr;
  13680. int local_port = 0;
  13681. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13682. ret = detail::process_server_socket_ssl(
  13683. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13684. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13685. write_timeout_usec_,
  13686. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13687. return process_request(
  13688. strm, remote_addr, remote_port, local_addr, local_port,
  13689. close_connection, connection_closed,
  13690. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13691. });
  13692. return ret;
  13693. }
  13694. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13695. const char *key_pem,
  13696. const char *client_ca_pem,
  13697. const char *password) {
  13698. if (!ctx_) { return false; }
  13699. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13700. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13701. return false;
  13702. }
  13703. if (client_ca_pem) {
  13704. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13705. }
  13706. return true;
  13707. }
  13708. // SSL HTTP client implementation
  13709. inline SSLClient::~SSLClient() {
  13710. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13711. // base function rather than the derived function once we get to the
  13712. // base class destructor, and won't free the SSL (causing a leak).
  13713. // This must happen before the context is freed below: some backends
  13714. // (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
  13715. // context, so freeing the context first leaves close_notify reading
  13716. // freed memory.
  13717. shutdown_ssl_impl(socket_, true);
  13718. if (ctx_) {
  13719. tls::free_context(ctx_);
  13720. ctx_ = nullptr;
  13721. }
  13722. }
  13723. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13724. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13725. shutdown_ssl_impl(socket, shutdown_gracefully);
  13726. }
  13727. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13728. bool shutdown_gracefully) {
  13729. if (socket.sock == INVALID_SOCKET) {
  13730. assert(socket.ssl == nullptr);
  13731. return;
  13732. }
  13733. if (socket.ssl) {
  13734. tls::shutdown(socket.ssl, shutdown_gracefully);
  13735. {
  13736. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13737. tls::free_session(socket.ssl);
  13738. }
  13739. socket.ssl = nullptr;
  13740. }
  13741. assert(socket.ssl == nullptr);
  13742. }
  13743. inline bool SSLClient::process_socket(
  13744. const Socket &socket,
  13745. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13746. std::function<bool(Stream &strm)> callback) {
  13747. assert(socket.ssl);
  13748. return detail::process_client_socket_ssl(
  13749. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13750. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13751. std::move(callback));
  13752. }
  13753. inline bool SSLClient::is_ssl() const { return true; }
  13754. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13755. if (!is_valid()) {
  13756. error = Error::SSLConnection;
  13757. return false;
  13758. }
  13759. return ClientImpl::create_and_connect_socket(socket, error);
  13760. }
  13761. inline bool SSLClient::setup_proxy_connection(
  13762. Socket &socket,
  13763. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13764. Response &res, bool &success, Error &error) {
  13765. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13766. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13767. return false;
  13768. }
  13769. if (!initialize_ssl(socket, error)) {
  13770. success = false;
  13771. return false;
  13772. }
  13773. return true;
  13774. }
  13775. // Assumes that socket_mutex_ is locked and that there are no requests in
  13776. // flight
  13777. inline bool SSLClient::connect_with_proxy(
  13778. Socket &socket,
  13779. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13780. Response &res, bool &success, Error &error) {
  13781. success = true;
  13782. Response proxy_res;
  13783. if (!detail::process_client_socket(
  13784. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13785. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13786. start_time, [&](Stream &strm) {
  13787. Request req2;
  13788. req2.method = "CONNECT";
  13789. req2.path =
  13790. detail::make_host_and_port_string_always_port(host_, port_);
  13791. if (max_timeout_msec_ > 0) {
  13792. req2.start_time_ = std::chrono::steady_clock::now();
  13793. }
  13794. return process_request(strm, req2, proxy_res, false, error);
  13795. })) {
  13796. // Thread-safe to close everything because we are assuming there are no
  13797. // requests in flight
  13798. shutdown_ssl(socket, true);
  13799. shutdown_socket(socket);
  13800. close_socket(socket);
  13801. success = false;
  13802. return false;
  13803. }
  13804. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13805. if (!proxy_digest_auth_username_.empty() &&
  13806. !proxy_digest_auth_password_.empty()) {
  13807. std::map<std::string, std::string> auth;
  13808. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13809. // Close the current socket and create a new one for the authenticated
  13810. // request
  13811. shutdown_ssl(socket, true);
  13812. shutdown_socket(socket);
  13813. close_socket(socket);
  13814. // Create a new socket for the authenticated CONNECT request
  13815. if (!ensure_socket_connection(socket, error)) {
  13816. success = false;
  13817. output_error_log(error, nullptr);
  13818. return false;
  13819. }
  13820. proxy_res = Response();
  13821. if (!detail::process_client_socket(
  13822. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13823. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13824. start_time, [&](Stream &strm) {
  13825. Request req3;
  13826. req3.method = "CONNECT";
  13827. req3.path = detail::make_host_and_port_string_always_port(
  13828. host_, port_);
  13829. req3.headers.insert(detail::make_digest_authentication_header(
  13830. req3, auth, 1, detail::random_string(10),
  13831. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13832. true));
  13833. if (max_timeout_msec_ > 0) {
  13834. req3.start_time_ = std::chrono::steady_clock::now();
  13835. }
  13836. return process_request(strm, req3, proxy_res, false, error);
  13837. })) {
  13838. // Thread-safe to close everything because we are assuming there are
  13839. // no requests in flight
  13840. shutdown_ssl(socket, true);
  13841. shutdown_socket(socket);
  13842. close_socket(socket);
  13843. success = false;
  13844. return false;
  13845. }
  13846. }
  13847. }
  13848. }
  13849. // If status code is not 200, proxy request is failed.
  13850. // Set error to ProxyConnection and return proxy response
  13851. // as the response of the request
  13852. if (proxy_res.status != StatusCode::OK_200) {
  13853. error = Error::ProxyConnection;
  13854. output_error_log(error, nullptr);
  13855. res = std::move(proxy_res);
  13856. // Thread-safe to close everything because we are assuming there are
  13857. // no requests in flight
  13858. shutdown_ssl(socket, true);
  13859. shutdown_socket(socket);
  13860. close_socket(socket);
  13861. return false;
  13862. }
  13863. return true;
  13864. }
  13865. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13866. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13867. if (is_proxy_enabled_for_host(host_)) { return true; }
  13868. if (!initialize_ssl(socket, error)) {
  13869. shutdown_socket(socket);
  13870. close_socket(socket);
  13871. return false;
  13872. }
  13873. return true;
  13874. }
  13875. // SSL HTTP client implementation
  13876. inline SSLClient::SSLClient(const std::string &host)
  13877. : SSLClient(host, 443, std::string(), std::string()) {}
  13878. inline SSLClient::SSLClient(const std::string &host, int port)
  13879. : SSLClient(host, port, std::string(), std::string()) {}
  13880. inline void SSLClient::init_ctx() {
  13881. ctx_ = tls::create_client_context();
  13882. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13883. }
  13884. inline void SSLClient::reset_ctx_on_error() {
  13885. last_backend_error_ = tls::get_error();
  13886. tls::free_context(ctx_);
  13887. ctx_ = nullptr;
  13888. }
  13889. inline SSLClient::SSLClient(const std::string &host, int port,
  13890. const std::string &client_cert_path,
  13891. const std::string &client_key_path,
  13892. const std::string &private_key_password)
  13893. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13894. init_ctx();
  13895. if (!ctx_) { return; }
  13896. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13897. const char *password =
  13898. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13899. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13900. client_key_path.c_str(), password)) {
  13901. reset_ctx_on_error();
  13902. }
  13903. }
  13904. }
  13905. inline SSLClient::SSLClient(const std::string &host, int port,
  13906. const PemMemory &pem)
  13907. : ClientImpl(host, port) {
  13908. init_ctx();
  13909. if (!ctx_) { return; }
  13910. if (pem.cert_pem && pem.key_pem) {
  13911. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13912. pem.private_key_password)) {
  13913. reset_ctx_on_error();
  13914. }
  13915. }
  13916. }
  13917. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13918. if (ca_cert_store && ctx_) {
  13919. // set_ca_store takes ownership of ca_cert_store
  13920. tls::set_ca_store(ctx_, ca_cert_store);
  13921. ca_cert_store_set_ = true;
  13922. } else if (ca_cert_store) {
  13923. tls::free_ca_store(ca_cert_store);
  13924. }
  13925. }
  13926. inline void
  13927. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13928. if (!ctx_) { return; }
  13929. tls::set_verify_callback(ctx_, verifier);
  13930. }
  13931. inline void SSLClient::set_session_verifier(
  13932. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13933. session_verifier_ = std::move(verifier);
  13934. }
  13935. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13936. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13937. enable_windows_cert_verification_ = enabled;
  13938. }
  13939. #endif
  13940. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13941. std::size_t size) {
  13942. if (ctx_ && ca_cert && size > 0) {
  13943. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13944. tls::load_ca_pem(ctx_, ca_cert, size);
  13945. }
  13946. }
  13947. inline bool SSLClient::load_certs() {
  13948. auto ret = true;
  13949. std::call_once(initialize_cert_, [&]() {
  13950. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13951. ret = detail::load_client_ca_config(
  13952. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13953. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13954. last_backend_error_);
  13955. });
  13956. return ret;
  13957. }
  13958. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13959. using namespace tls;
  13960. // Load CA certificates if server verification is enabled
  13961. if (server_certificate_verification_) {
  13962. if (!load_certs()) {
  13963. error = Error::SSLLoadingCerts;
  13964. output_error_log(error, nullptr);
  13965. return false;
  13966. }
  13967. }
  13968. bool is_ip = detail::is_ip_address(host_);
  13969. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13970. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13971. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13972. // Chain verification happens during the handshake even for IP hosts; the
  13973. // certificate identity is verified post-handshake via verify_hostname().
  13974. set_verify_client(ctx_, server_certificate_verification_);
  13975. #endif
  13976. // Create TLS session
  13977. session_t session = nullptr;
  13978. {
  13979. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13980. session = create_session(ctx_, socket.sock);
  13981. }
  13982. if (!session) {
  13983. error = Error::SSLConnection;
  13984. last_backend_error_ = get_error();
  13985. return false;
  13986. }
  13987. // Use scope_exit to ensure session is freed on error paths
  13988. bool success = false;
  13989. auto session_guard = detail::scope_exit([&] {
  13990. if (!success) { free_session(session); }
  13991. });
  13992. // Set SNI extension (skip for IP addresses per RFC 6066).
  13993. // On MbedTLS, set_sni also enables hostname verification internally.
  13994. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13995. if (!is_ip) {
  13996. if (!set_sni(session, host_.c_str())) {
  13997. error = Error::SSLConnection;
  13998. last_backend_error_ = get_error();
  13999. return false;
  14000. }
  14001. }
  14002. // Perform non-blocking TLS handshake with timeout
  14003. TlsError tls_err;
  14004. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  14005. connection_timeout_usec_, &tls_err)) {
  14006. last_ssl_error_ = static_cast<int>(tls_err.code);
  14007. last_backend_error_ = tls_err.backend_code;
  14008. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  14009. error = Error::SSLServerVerification;
  14010. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  14011. error = Error::SSLServerHostnameVerification;
  14012. } else {
  14013. error = Error::SSLConnection;
  14014. }
  14015. output_error_log(error, nullptr);
  14016. return false;
  14017. }
  14018. // Post-handshake session verifier callback
  14019. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  14020. if (session_verifier_) { verification_status = session_verifier_(session); }
  14021. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  14022. last_backend_error_ = get_error();
  14023. error = Error::SSLServerVerification;
  14024. output_error_log(error, nullptr);
  14025. return false;
  14026. }
  14027. // Default server certificate verification
  14028. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  14029. server_certificate_verification_) {
  14030. verify_result_ = tls::get_verify_result(session);
  14031. if (verify_result_ != 0) {
  14032. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  14033. error = Error::SSLServerVerification;
  14034. output_error_log(error, nullptr);
  14035. return false;
  14036. }
  14037. auto server_cert = get_peer_cert(session);
  14038. if (!server_cert) {
  14039. last_backend_error_ = get_error();
  14040. error = Error::SSLServerVerification;
  14041. output_error_log(error, nullptr);
  14042. return false;
  14043. }
  14044. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  14045. // Hostname verification (post-handshake for all cases).
  14046. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  14047. // On MbedTLS, set_sni already enabled hostname verification during
  14048. // handshake for non-IP hosts, but this check is still needed for IP
  14049. // addresses where SNI is not set.
  14050. if (server_hostname_verification_) {
  14051. if (!verify_hostname(server_cert, host_.c_str())) {
  14052. last_backend_error_ = hostname_mismatch_code();
  14053. error = Error::SSLServerHostnameVerification;
  14054. output_error_log(error, nullptr);
  14055. return false;
  14056. }
  14057. }
  14058. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14059. // Additional Windows Schannel verification.
  14060. // This provides real-time certificate validation with Windows Update
  14061. // integration, working with both OpenSSL and MbedTLS backends.
  14062. // Skip when a custom CA cert is specified, as the Windows certificate
  14063. // store would not know about user-provided CA certificates. Also skip
  14064. // when system CA trust is explicitly disabled.
  14065. if (enable_windows_cert_verification_ &&
  14066. system_ca_mode_ != SystemCAMode::Disabled &&
  14067. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  14068. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  14069. std::vector<unsigned char> der;
  14070. if (get_cert_der(server_cert, der)) {
  14071. uint64_t wincrypt_error = 0;
  14072. if (!detail::verify_cert_with_windows_schannel(
  14073. der, host_, server_hostname_verification_, wincrypt_error)) {
  14074. last_backend_error_ = wincrypt_error;
  14075. error = Error::SSLServerVerification;
  14076. output_error_log(error, nullptr);
  14077. return false;
  14078. }
  14079. }
  14080. }
  14081. #endif
  14082. }
  14083. success = true;
  14084. socket.ssl = session;
  14085. return true;
  14086. }
  14087. inline void Client::set_digest_auth(const std::string &username,
  14088. const std::string &password) {
  14089. cli_->set_digest_auth(username, password);
  14090. }
  14091. inline void Client::set_proxy_digest_auth(const std::string &username,
  14092. const std::string &password) {
  14093. cli_->set_proxy_digest_auth(username, password);
  14094. }
  14095. inline void Client::enable_server_certificate_verification(bool enabled) {
  14096. cli_->enable_server_certificate_verification(enabled);
  14097. }
  14098. inline void Client::enable_server_hostname_verification(bool enabled) {
  14099. cli_->enable_server_hostname_verification(enabled);
  14100. }
  14101. inline void Client::enable_system_ca(bool enabled) {
  14102. cli_->enable_system_ca(enabled);
  14103. }
  14104. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14105. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14106. if (is_ssl_) {
  14107. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14108. enabled);
  14109. }
  14110. }
  14111. #endif
  14112. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14113. const std::string &ca_cert_dir_path) {
  14114. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14115. }
  14116. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14117. if (is_ssl_) {
  14118. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14119. } else if (ca_cert_store) {
  14120. tls::free_ca_store(ca_cert_store);
  14121. }
  14122. }
  14123. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14124. if (is_ssl_) {
  14125. // Use the PEM-based path so the CA data is retained for redirect transfer
  14126. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14127. }
  14128. }
  14129. inline void
  14130. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14131. if (is_ssl_) {
  14132. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14133. std::move(verifier));
  14134. }
  14135. }
  14136. inline void Client::set_session_verifier(
  14137. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14138. if (is_ssl_) {
  14139. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14140. }
  14141. }
  14142. inline tls::ctx_t Client::tls_context() const {
  14143. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14144. return nullptr;
  14145. }
  14146. #endif // CPPHTTPLIB_SSL_ENABLED
  14147. /*
  14148. * Group 7: TLS abstraction layer - Common API
  14149. */
  14150. #ifdef CPPHTTPLIB_SSL_ENABLED
  14151. namespace tls {
  14152. // Helper for PeerCert construction
  14153. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14154. return PeerCert(get_peer_cert(session));
  14155. }
  14156. namespace impl {
  14157. inline VerifyCallback &get_verify_callback() {
  14158. static thread_local VerifyCallback callback;
  14159. return callback;
  14160. }
  14161. inline VerifyCallback &get_mbedtls_verify_callback() {
  14162. static thread_local VerifyCallback callback;
  14163. return callback;
  14164. }
  14165. // Check if a string is an IPv4 address
  14166. inline bool is_ipv4_address(const std::string &str) {
  14167. int dots = 0;
  14168. for (char c : str) {
  14169. if (c == '.') {
  14170. dots++;
  14171. } else if (!detail::is_ascii_digit(c)) {
  14172. return false;
  14173. }
  14174. }
  14175. return dots == 3;
  14176. }
  14177. // Parse IPv4 address string to bytes
  14178. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14179. const char *p = str.c_str();
  14180. for (int i = 0; i < 4; i++) {
  14181. if (i > 0) {
  14182. if (*p != '.') { return false; }
  14183. p++;
  14184. }
  14185. int val = 0;
  14186. int digits = 0;
  14187. while (detail::is_ascii_digit(*p)) {
  14188. val = val * 10 + (*p - '0');
  14189. if (val > 255) { return false; }
  14190. p++;
  14191. digits++;
  14192. }
  14193. if (digits == 0) { return false; }
  14194. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14195. if (digits > 1 && *(p - digits) == '0') { return false; }
  14196. out[i] = static_cast<unsigned char>(val);
  14197. }
  14198. return *p == '\0';
  14199. }
  14200. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14201. // `out` must have room for at least 16 bytes. Returns the address length
  14202. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14203. // literal. Used to match a host against iPAddress SANs the same way the
  14204. // OpenSSL backend does via X509_check_ip.
  14205. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14206. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14207. struct in6_addr addr6 = {};
  14208. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14209. memcpy(out, &addr6, 16);
  14210. return 16;
  14211. }
  14212. return 0;
  14213. }
  14214. #ifdef _WIN32
  14215. // Enumerate Windows system certificates and call callback with DER data
  14216. template <typename Callback>
  14217. inline bool enumerate_windows_system_certs(Callback cb) {
  14218. bool loaded = false;
  14219. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14220. for (auto store_name : store_names) {
  14221. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14222. if (hStore) {
  14223. PCCERT_CONTEXT pContext = nullptr;
  14224. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14225. nullptr) {
  14226. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14227. loaded = true;
  14228. }
  14229. }
  14230. CertCloseStore(hStore, 0);
  14231. }
  14232. }
  14233. return loaded;
  14234. }
  14235. #endif
  14236. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14237. // Enumerate macOS Keychain certificates and call callback with DER data
  14238. template <typename Callback>
  14239. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14240. bool loaded = false;
  14241. const SecTrustSettingsDomain domains[] = {
  14242. kSecTrustSettingsDomainSystem,
  14243. kSecTrustSettingsDomainAdmin,
  14244. kSecTrustSettingsDomainUser,
  14245. };
  14246. for (auto domain : domains) {
  14247. CFArrayRef certs = nullptr;
  14248. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14249. if (status != errSecSuccess || !certs) {
  14250. if (certs) CFRelease(certs);
  14251. continue;
  14252. }
  14253. CFIndex count = CFArrayGetCount(certs);
  14254. for (CFIndex i = 0; i < count; i++) {
  14255. SecCertificateRef cert =
  14256. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14257. CFDataRef data = SecCertificateCopyData(cert);
  14258. if (data) {
  14259. if (cb(CFDataGetBytePtr(data),
  14260. static_cast<size_t>(CFDataGetLength(data)))) {
  14261. loaded = true;
  14262. }
  14263. CFRelease(data);
  14264. }
  14265. }
  14266. CFRelease(certs);
  14267. }
  14268. return loaded;
  14269. }
  14270. #endif
  14271. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14272. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14273. // Common CA certificate file paths on Linux/Unix
  14274. inline const char **system_ca_paths() {
  14275. static const char *paths[] = {
  14276. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14277. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14278. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14279. "/etc/pki/tls/cacert.pem", // OpenELEC
  14280. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14281. nullptr};
  14282. return paths;
  14283. }
  14284. // Common CA certificate directory paths on Linux/Unix
  14285. inline const char **system_ca_dirs() {
  14286. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14287. "/etc/pki/tls/certs", // RHEL/CentOS
  14288. "/usr/share/ca-certificates", // Other
  14289. nullptr};
  14290. return dirs;
  14291. }
  14292. #endif
  14293. } // namespace impl
  14294. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14295. const char *ca_dir) {
  14296. if (!ctx) { return false; }
  14297. bool success = true;
  14298. if (ca_file && *ca_file) {
  14299. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14300. }
  14301. if (ca_dir && *ca_dir) {
  14302. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14303. }
  14304. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14305. // Set CA list for client certificate request (CertificateRequest message)
  14306. if (ca_file && *ca_file) {
  14307. auto list = SSL_load_client_CA_file(ca_file);
  14308. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14309. }
  14310. #endif
  14311. return success;
  14312. }
  14313. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14314. const char *password) {
  14315. return set_client_cert_pem(ctx, cert, key, password);
  14316. }
  14317. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14318. const char *key_path, const char *password) {
  14319. return set_client_cert_file(ctx, cert_path, key_path, password);
  14320. }
  14321. // PeerCert implementation
  14322. inline PeerCert::PeerCert() = default;
  14323. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14324. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14325. other.cert_ = nullptr;
  14326. }
  14327. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14328. if (this != &other) {
  14329. if (cert_) { free_cert(cert_); }
  14330. cert_ = other.cert_;
  14331. other.cert_ = nullptr;
  14332. }
  14333. return *this;
  14334. }
  14335. inline PeerCert::~PeerCert() {
  14336. if (cert_) { free_cert(cert_); }
  14337. }
  14338. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14339. inline std::string PeerCert::subject_cn() const {
  14340. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14341. }
  14342. inline std::string PeerCert::issuer_name() const {
  14343. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14344. }
  14345. inline bool PeerCert::check_hostname(const char *hostname) const {
  14346. return cert_ ? verify_hostname(cert_, hostname) : false;
  14347. }
  14348. inline std::vector<SanEntry> PeerCert::sans() const {
  14349. std::vector<SanEntry> result;
  14350. if (cert_) { get_cert_sans(cert_, result); }
  14351. return result;
  14352. }
  14353. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14354. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14355. }
  14356. inline std::string PeerCert::serial() const {
  14357. return cert_ ? get_cert_serial(cert_) : std::string();
  14358. }
  14359. // VerifyContext method implementations
  14360. inline std::string VerifyContext::subject_cn() const {
  14361. return cert ? get_cert_subject_cn(cert) : std::string();
  14362. }
  14363. inline std::string VerifyContext::issuer_name() const {
  14364. return cert ? get_cert_issuer_name(cert) : std::string();
  14365. }
  14366. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14367. return cert ? verify_hostname(cert, hostname) : false;
  14368. }
  14369. inline std::vector<SanEntry> VerifyContext::sans() const {
  14370. std::vector<SanEntry> result;
  14371. if (cert) { get_cert_sans(cert, result); }
  14372. return result;
  14373. }
  14374. inline bool VerifyContext::validity(time_t &not_before,
  14375. time_t &not_after) const {
  14376. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14377. }
  14378. inline std::string VerifyContext::serial() const {
  14379. return cert ? get_cert_serial(cert) : std::string();
  14380. }
  14381. // TlsError static method implementation
  14382. inline std::string TlsError::verify_error_to_string(long error_code) {
  14383. return verify_error_string(error_code);
  14384. }
  14385. } // namespace tls
  14386. // Request::peer_cert() implementation
  14387. inline tls::PeerCert Request::peer_cert() const {
  14388. return tls::get_peer_cert_from_session(ssl);
  14389. }
  14390. // Request::sni() implementation
  14391. inline std::string Request::sni() const {
  14392. if (!ssl) { return std::string(); }
  14393. const char *s = tls::get_sni(ssl);
  14394. return s ? std::string(s) : std::string();
  14395. }
  14396. #endif // CPPHTTPLIB_SSL_ENABLED
  14397. /*
  14398. * Group 8: TLS abstraction layer - OpenSSL backend
  14399. */
  14400. /*
  14401. * OpenSSL Backend Implementation
  14402. */
  14403. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14404. namespace tls {
  14405. namespace impl {
  14406. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14407. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14408. switch (ssl_error) {
  14409. case SSL_ERROR_NONE: return ErrorCode::Success;
  14410. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14411. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14412. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14413. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14414. case SSL_ERROR_SSL:
  14415. default: return ErrorCode::Fatal;
  14416. }
  14417. }
  14418. // Helper: Create client CA list from PEM string
  14419. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14420. // Caller takes ownership of returned list
  14421. inline STACK_OF(X509_NAME) *
  14422. create_client_ca_list_from_pem(const char *ca_pem) {
  14423. if (!ca_pem) { return nullptr; }
  14424. auto ca_list = sk_X509_NAME_new_null();
  14425. if (!ca_list) { return nullptr; }
  14426. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14427. if (!bio) {
  14428. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14429. return nullptr;
  14430. }
  14431. X509 *cert = nullptr;
  14432. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14433. nullptr) {
  14434. const X509_NAME *name = X509_get_subject_name(cert);
  14435. if (name) {
  14436. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14437. }
  14438. X509_free(cert);
  14439. }
  14440. BIO_free(bio);
  14441. return ca_list;
  14442. }
  14443. // OpenSSL verify callback wrapper
  14444. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14445. auto &callback = get_verify_callback();
  14446. if (!callback) { return preverify_ok; }
  14447. // Get SSL object from X509_STORE_CTX
  14448. auto ssl = static_cast<SSL *>(
  14449. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14450. if (!ssl) { return preverify_ok; }
  14451. // Get current certificate and depth
  14452. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14453. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14454. int error = X509_STORE_CTX_get_error(ctx);
  14455. // Build context
  14456. VerifyContext verify_ctx;
  14457. verify_ctx.session = static_cast<session_t>(ssl);
  14458. verify_ctx.cert = static_cast<cert_t>(cert);
  14459. verify_ctx.depth = depth;
  14460. verify_ctx.preverify_ok = (preverify_ok != 0);
  14461. verify_ctx.error_code = error;
  14462. verify_ctx.error_string =
  14463. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14464. return callback(verify_ctx) ? 1 : 0;
  14465. }
  14466. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14467. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14468. // that must be released with release_store_objects
  14469. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14470. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14471. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14472. #endif
  14473. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14474. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14475. return X509_STORE_get1_objects(store);
  14476. #else
  14477. return X509_STORE_get0_objects(store);
  14478. #endif
  14479. }
  14480. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14481. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14482. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14483. #else
  14484. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14485. #endif
  14486. }
  14487. } // namespace impl
  14488. inline ctx_t create_client_context() {
  14489. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14490. if (ctx) {
  14491. // Disable auto-retry to properly handle non-blocking I/O
  14492. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14493. // Set minimum TLS version
  14494. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14495. }
  14496. return static_cast<ctx_t>(ctx);
  14497. }
  14498. inline void free_context(ctx_t ctx) {
  14499. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14500. }
  14501. inline bool set_min_version(ctx_t ctx, Version version) {
  14502. if (!ctx) return false;
  14503. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14504. static_cast<int>(version)) == 1;
  14505. }
  14506. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14507. if (!ctx || !pem || len == 0) return false;
  14508. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14509. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14510. if (!store) return false;
  14511. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14512. if (!bio) return false;
  14513. bool ok = true;
  14514. X509 *cert = nullptr;
  14515. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14516. nullptr) {
  14517. if (X509_STORE_add_cert(store, cert) != 1) {
  14518. // Ignore duplicate errors
  14519. auto err = ERR_peek_last_error();
  14520. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14521. ok = false;
  14522. }
  14523. }
  14524. X509_free(cert);
  14525. if (!ok) break;
  14526. }
  14527. BIO_free(bio);
  14528. // Clear any "no more certificates" errors
  14529. ERR_clear_error();
  14530. return ok;
  14531. }
  14532. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14533. if (!ctx || !file_path) return false;
  14534. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14535. nullptr) == 1;
  14536. }
  14537. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14538. if (!ctx || !dir_path) return false;
  14539. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14540. dir_path) == 1;
  14541. }
  14542. inline bool load_system_certs(ctx_t ctx) {
  14543. if (!ctx) return false;
  14544. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14545. #ifdef _WIN32
  14546. // Windows: Load from system certificate store (ROOT and CA)
  14547. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14548. if (!store) return false;
  14549. bool loaded_any = false;
  14550. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14551. for (auto store_name : store_names) {
  14552. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14553. if (!hStore) continue;
  14554. PCCERT_CONTEXT pContext = nullptr;
  14555. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14556. nullptr) {
  14557. const unsigned char *data = pContext->pbCertEncoded;
  14558. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14559. if (x509) {
  14560. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14561. X509_free(x509);
  14562. }
  14563. }
  14564. CertCloseStore(hStore, 0);
  14565. }
  14566. return loaded_any;
  14567. #elif defined(__APPLE__)
  14568. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14569. // macOS: Load from Keychain
  14570. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14571. if (!store) return false;
  14572. bool loaded_any = false;
  14573. const SecTrustSettingsDomain domains[] = {
  14574. kSecTrustSettingsDomainSystem,
  14575. kSecTrustSettingsDomainAdmin,
  14576. kSecTrustSettingsDomainUser,
  14577. };
  14578. for (auto domain : domains) {
  14579. CFArrayRef certs = nullptr;
  14580. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14581. !certs) {
  14582. if (certs) CFRelease(certs);
  14583. continue;
  14584. }
  14585. auto count = CFArrayGetCount(certs);
  14586. for (CFIndex i = 0; i < count; i++) {
  14587. auto cert = reinterpret_cast<SecCertificateRef>(
  14588. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14589. CFDataRef der = SecCertificateCopyData(cert);
  14590. if (der) {
  14591. const unsigned char *data = CFDataGetBytePtr(der);
  14592. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14593. if (x509) {
  14594. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14595. X509_free(x509);
  14596. }
  14597. CFRelease(der);
  14598. }
  14599. }
  14600. CFRelease(certs);
  14601. }
  14602. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14603. #else
  14604. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14605. #endif
  14606. #else
  14607. // Other Unix: use default verify paths
  14608. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14609. #endif
  14610. }
  14611. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14612. const char *password) {
  14613. if (!ctx || !cert || !key) return false;
  14614. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14615. // Load certificate
  14616. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14617. if (!cert_bio) return false;
  14618. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14619. BIO_free(cert_bio);
  14620. if (!x509) return false;
  14621. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14622. X509_free(x509);
  14623. if (!cert_ok) return false;
  14624. // Load private key
  14625. auto key_bio = BIO_new_mem_buf(key, -1);
  14626. if (!key_bio) return false;
  14627. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14628. password ? const_cast<char *>(password)
  14629. : nullptr);
  14630. BIO_free(key_bio);
  14631. if (!pkey) return false;
  14632. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14633. EVP_PKEY_free(pkey);
  14634. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14635. }
  14636. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14637. const char *key_path, const char *password) {
  14638. if (!ctx || !cert_path || !key_path) return false;
  14639. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14640. if (password && password[0] != '\0') {
  14641. SSL_CTX_set_default_passwd_cb_userdata(
  14642. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14643. }
  14644. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14645. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14646. }
  14647. inline ctx_t create_server_context() {
  14648. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14649. if (ctx) {
  14650. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14651. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14652. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14653. }
  14654. return static_cast<ctx_t>(ctx);
  14655. }
  14656. inline void set_verify_client(ctx_t ctx, bool require) {
  14657. if (!ctx) return;
  14658. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14659. require
  14660. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14661. : SSL_VERIFY_NONE,
  14662. nullptr);
  14663. }
  14664. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14665. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14666. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14667. SSL *ssl = SSL_new(ssl_ctx);
  14668. if (!ssl) return nullptr;
  14669. // Disable auto-retry for proper non-blocking I/O handling
  14670. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14671. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14672. if (!bio) {
  14673. SSL_free(ssl);
  14674. return nullptr;
  14675. }
  14676. SSL_set_bio(ssl, bio, bio);
  14677. return static_cast<session_t>(ssl);
  14678. }
  14679. inline void free_session(session_t session) {
  14680. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14681. }
  14682. inline bool set_sni(session_t session, const char *hostname) {
  14683. if (!session || !hostname) return false;
  14684. auto ssl = static_cast<SSL *>(session);
  14685. // Set SNI (Server Name Indication) only - does not enable verification
  14686. #if defined(OPENSSL_IS_BORINGSSL)
  14687. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14688. #else
  14689. // Direct call instead of macro to suppress -Wold-style-cast warning
  14690. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14691. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14692. #endif
  14693. }
  14694. inline bool set_hostname(session_t session, const char *hostname) {
  14695. if (!session || !hostname) return false;
  14696. auto ssl = static_cast<SSL *>(session);
  14697. // Enable hostname verification
  14698. auto param = SSL_get0_param(ssl);
  14699. if (!param) return false;
  14700. if (detail::is_ip_address(hostname)) {
  14701. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14702. // certificate's IP SANs instead of its DNS names
  14703. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14704. } else {
  14705. // Set SNI (Server Name Indication)
  14706. if (!set_sni(session, hostname)) { return false; }
  14707. X509_VERIFY_PARAM_set_hostflags(param,
  14708. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14709. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14710. }
  14711. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14712. return true;
  14713. }
  14714. inline TlsError connect(session_t session) {
  14715. if (!session) { return TlsError(); }
  14716. auto ssl = static_cast<SSL *>(session);
  14717. auto ret = SSL_connect(ssl);
  14718. TlsError err;
  14719. if (ret == 1) {
  14720. err.code = ErrorCode::Success;
  14721. } else {
  14722. auto ssl_err = SSL_get_error(ssl, ret);
  14723. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14724. err.backend_code = ERR_get_error();
  14725. }
  14726. return err;
  14727. }
  14728. inline TlsError accept(session_t session) {
  14729. if (!session) { return TlsError(); }
  14730. auto ssl = static_cast<SSL *>(session);
  14731. auto ret = SSL_accept(ssl);
  14732. TlsError err;
  14733. if (ret == 1) {
  14734. err.code = ErrorCode::Success;
  14735. } else {
  14736. auto ssl_err = SSL_get_error(ssl, ret);
  14737. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14738. err.backend_code = ERR_get_error();
  14739. }
  14740. return err;
  14741. }
  14742. inline bool connect_nonblocking(session_t session, socket_t sock,
  14743. time_t timeout_sec, time_t timeout_usec,
  14744. TlsError *err) {
  14745. if (!session) {
  14746. if (err) { err->code = ErrorCode::Fatal; }
  14747. return false;
  14748. }
  14749. auto ssl = static_cast<SSL *>(session);
  14750. auto bio = SSL_get_rbio(ssl);
  14751. // Set non-blocking mode for handshake
  14752. detail::set_nonblocking(sock, true);
  14753. if (bio) { BIO_set_nbio(bio, 1); }
  14754. auto cleanup = detail::scope_exit([&]() {
  14755. // Restore blocking mode after handshake
  14756. if (bio) { BIO_set_nbio(bio, 0); }
  14757. detail::set_nonblocking(sock, false);
  14758. });
  14759. auto res = 0;
  14760. while ((res = SSL_connect(ssl)) != 1) {
  14761. auto ssl_err = SSL_get_error(ssl, res);
  14762. switch (ssl_err) {
  14763. case SSL_ERROR_WANT_READ:
  14764. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14765. continue;
  14766. }
  14767. break;
  14768. case SSL_ERROR_WANT_WRITE:
  14769. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14770. continue;
  14771. }
  14772. break;
  14773. default: break;
  14774. }
  14775. if (err) {
  14776. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14777. err->backend_code = ERR_get_error();
  14778. }
  14779. return false;
  14780. }
  14781. if (err) { err->code = ErrorCode::Success; }
  14782. return true;
  14783. }
  14784. inline bool accept_nonblocking(session_t session, socket_t sock,
  14785. time_t timeout_sec, time_t timeout_usec,
  14786. TlsError *err) {
  14787. if (!session) {
  14788. if (err) { err->code = ErrorCode::Fatal; }
  14789. return false;
  14790. }
  14791. auto ssl = static_cast<SSL *>(session);
  14792. auto bio = SSL_get_rbio(ssl);
  14793. // Set non-blocking mode for handshake
  14794. detail::set_nonblocking(sock, true);
  14795. if (bio) { BIO_set_nbio(bio, 1); }
  14796. auto cleanup = detail::scope_exit([&]() {
  14797. // Restore blocking mode after handshake
  14798. if (bio) { BIO_set_nbio(bio, 0); }
  14799. detail::set_nonblocking(sock, false);
  14800. });
  14801. auto res = 0;
  14802. while ((res = SSL_accept(ssl)) != 1) {
  14803. auto ssl_err = SSL_get_error(ssl, res);
  14804. switch (ssl_err) {
  14805. case SSL_ERROR_WANT_READ:
  14806. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14807. continue;
  14808. }
  14809. break;
  14810. case SSL_ERROR_WANT_WRITE:
  14811. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14812. continue;
  14813. }
  14814. break;
  14815. default: break;
  14816. }
  14817. if (err) {
  14818. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14819. err->backend_code = ERR_get_error();
  14820. }
  14821. return false;
  14822. }
  14823. if (err) { err->code = ErrorCode::Success; }
  14824. return true;
  14825. }
  14826. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14827. if (!session || !buf) {
  14828. err.code = ErrorCode::Fatal;
  14829. return -1;
  14830. }
  14831. auto ssl = static_cast<SSL *>(session);
  14832. constexpr auto max_len =
  14833. static_cast<size_t>((std::numeric_limits<int>::max)());
  14834. if (len > max_len) { len = max_len; }
  14835. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14836. if (ret > 0) {
  14837. err.code = ErrorCode::Success;
  14838. return ret;
  14839. }
  14840. auto ssl_err = SSL_get_error(ssl, ret);
  14841. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14842. if (err.code == ErrorCode::PeerClosed) {
  14843. return 0;
  14844. } // Gracefully handle the peer closed state.
  14845. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14846. return -1;
  14847. }
  14848. inline ssize_t write(session_t session, const void *buf, size_t len,
  14849. TlsError &err) {
  14850. if (!session || !buf) {
  14851. err.code = ErrorCode::Fatal;
  14852. return -1;
  14853. }
  14854. auto ssl = static_cast<SSL *>(session);
  14855. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14856. if (ret > 0) {
  14857. err.code = ErrorCode::Success;
  14858. return ret;
  14859. }
  14860. auto ssl_err = SSL_get_error(ssl, ret);
  14861. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14862. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14863. return -1;
  14864. }
  14865. inline int pending(const_session_t session) {
  14866. if (!session) return 0;
  14867. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14868. }
  14869. inline void shutdown(session_t session, bool graceful) {
  14870. if (!session) return;
  14871. auto ssl = static_cast<SSL *>(session);
  14872. if (graceful) {
  14873. // First call sends close_notify
  14874. if (SSL_shutdown(ssl) == 0) {
  14875. // Second call waits for peer's close_notify
  14876. SSL_shutdown(ssl);
  14877. }
  14878. }
  14879. }
  14880. inline bool is_peer_closed(session_t session, socket_t sock) {
  14881. if (!session) return true;
  14882. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14883. detail::set_nonblocking(sock, true);
  14884. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14885. auto ssl = static_cast<SSL *>(session);
  14886. char buf;
  14887. auto ret = SSL_peek(ssl, &buf, 1);
  14888. if (ret > 0) return false;
  14889. auto err = SSL_get_error(ssl, ret);
  14890. return err == SSL_ERROR_ZERO_RETURN;
  14891. }
  14892. inline cert_t get_peer_cert(const_session_t session) {
  14893. if (!session) return nullptr;
  14894. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14895. static_cast<SSL *>(const_cast<void *>(session))));
  14896. }
  14897. inline void free_cert(cert_t cert) {
  14898. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14899. }
  14900. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14901. if (!cert || !hostname) return false;
  14902. auto x509 = static_cast<X509 *>(cert);
  14903. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14904. if (detail::is_ip_address(hostname)) {
  14905. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14906. }
  14907. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14908. }
  14909. inline uint64_t hostname_mismatch_code() {
  14910. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14911. }
  14912. inline long get_verify_result(const_session_t session) {
  14913. if (!session) return X509_V_ERR_UNSPECIFIED;
  14914. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14915. }
  14916. inline std::string get_cert_subject_cn(cert_t cert) {
  14917. if (!cert) return "";
  14918. auto x509 = static_cast<X509 *>(cert);
  14919. auto subject_name = X509_get_subject_name(x509);
  14920. if (!subject_name) return "";
  14921. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14922. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14923. if (idx < 0) return "";
  14924. auto entry = X509_NAME_get_entry(subject_name, idx);
  14925. if (!entry) return "";
  14926. auto data = X509_NAME_ENTRY_get_data(entry);
  14927. if (!data) return "";
  14928. return std::string(
  14929. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14930. static_cast<size_t>(ASN1_STRING_length(data)));
  14931. }
  14932. inline std::string get_cert_issuer_name(cert_t cert) {
  14933. if (!cert) return "";
  14934. auto x509 = static_cast<X509 *>(cert);
  14935. auto issuer_name = X509_get_issuer_name(x509);
  14936. if (!issuer_name) return "";
  14937. char buf[256];
  14938. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14939. return std::string(buf);
  14940. }
  14941. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14942. sans.clear();
  14943. if (!cert) return false;
  14944. auto x509 = static_cast<X509 *>(cert);
  14945. auto names = static_cast<GENERAL_NAMES *>(
  14946. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14947. if (!names) return true; // No SANs is valid
  14948. auto count = sk_GENERAL_NAME_num(names);
  14949. for (decltype(count) i = 0; i < count; i++) {
  14950. auto gen = sk_GENERAL_NAME_value(names, i);
  14951. if (!gen) continue;
  14952. SanEntry entry;
  14953. switch (gen->type) {
  14954. case GEN_DNS:
  14955. entry.type = SanType::DNS;
  14956. if (gen->d.dNSName) {
  14957. entry.value = std::string(
  14958. reinterpret_cast<const char *>(
  14959. ASN1_STRING_get0_data(gen->d.dNSName)),
  14960. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14961. }
  14962. break;
  14963. case GEN_IPADD:
  14964. entry.type = SanType::IP;
  14965. if (gen->d.iPAddress) {
  14966. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14967. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14968. if (len == 4) {
  14969. // IPv4
  14970. char buf[INET_ADDRSTRLEN];
  14971. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14972. entry.value = buf;
  14973. } else if (len == 16) {
  14974. // IPv6
  14975. char buf[INET6_ADDRSTRLEN];
  14976. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14977. entry.value = buf;
  14978. }
  14979. }
  14980. break;
  14981. case GEN_EMAIL:
  14982. entry.type = SanType::EMAIL;
  14983. if (gen->d.rfc822Name) {
  14984. entry.value = std::string(
  14985. reinterpret_cast<const char *>(
  14986. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14987. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14988. }
  14989. break;
  14990. case GEN_URI:
  14991. entry.type = SanType::URI;
  14992. if (gen->d.uniformResourceIdentifier) {
  14993. entry.value = std::string(
  14994. reinterpret_cast<const char *>(
  14995. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14996. static_cast<size_t>(
  14997. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14998. }
  14999. break;
  15000. default: entry.type = SanType::OTHER; break;
  15001. }
  15002. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15003. }
  15004. GENERAL_NAMES_free(names);
  15005. return true;
  15006. }
  15007. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15008. time_t &not_after) {
  15009. if (!cert) return false;
  15010. auto x509 = static_cast<X509 *>(cert);
  15011. auto nb = X509_get0_notBefore(x509);
  15012. auto na = X509_get0_notAfter(x509);
  15013. if (!nb || !na) return false;
  15014. ASN1_TIME *epoch = ASN1_TIME_new();
  15015. if (!epoch) return false;
  15016. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  15017. if (!ASN1_TIME_set(epoch, 0)) return false;
  15018. int pday, psec;
  15019. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  15020. not_before = 86400 * (time_t)pday + psec;
  15021. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  15022. not_after = 86400 * (time_t)pday + psec;
  15023. return true;
  15024. }
  15025. inline std::string get_cert_serial(cert_t cert) {
  15026. if (!cert) return "";
  15027. auto x509 = static_cast<X509 *>(cert);
  15028. auto serial = X509_get_serialNumber(x509);
  15029. if (!serial) return "";
  15030. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  15031. if (!bn) return "";
  15032. auto hex = BN_bn2hex(bn);
  15033. BN_free(bn);
  15034. if (!hex) return "";
  15035. std::string result(hex);
  15036. OPENSSL_free(hex);
  15037. return result;
  15038. }
  15039. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15040. if (!cert) return false;
  15041. auto x509 = static_cast<X509 *>(cert);
  15042. auto len = i2d_X509(x509, nullptr);
  15043. if (len < 0) return false;
  15044. der.resize(static_cast<size_t>(len));
  15045. auto p = der.data();
  15046. i2d_X509(x509, &p);
  15047. return true;
  15048. }
  15049. inline const char *get_sni(const_session_t session) {
  15050. if (!session) return nullptr;
  15051. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15052. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15053. }
  15054. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  15055. inline uint64_t get_error() { return ERR_get_error(); }
  15056. inline std::string error_string(uint64_t code) {
  15057. char buf[256];
  15058. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  15059. return std::string(buf);
  15060. }
  15061. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15062. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  15063. if (!mem) { return nullptr; }
  15064. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  15065. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  15066. if (!inf) { return nullptr; }
  15067. auto store = X509_STORE_new();
  15068. if (store) {
  15069. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  15070. auto itmp = sk_X509_INFO_value(inf, i);
  15071. if (!itmp) { continue; }
  15072. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  15073. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  15074. }
  15075. }
  15076. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  15077. return static_cast<ca_store_t>(store);
  15078. }
  15079. inline void free_ca_store(ca_store_t store) {
  15080. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15081. }
  15082. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15083. if (!ctx || !store) { return false; }
  15084. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15085. auto x509_store = static_cast<X509_STORE *>(store);
  15086. // Check if same store is already set
  15087. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15088. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15089. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15090. return true;
  15091. }
  15092. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15093. certs.clear();
  15094. if (!ctx) { return 0; }
  15095. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15096. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15097. if (!store) { return 0; }
  15098. auto objs = impl::get_store_objects(store);
  15099. if (!objs) { return 0; }
  15100. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15101. auto count = sk_X509_OBJECT_num(objs);
  15102. for (decltype(count) i = 0; i < count; i++) {
  15103. auto obj = sk_X509_OBJECT_value(objs, i);
  15104. if (!obj) { continue; }
  15105. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15106. auto x509 = X509_OBJECT_get0_X509(obj);
  15107. if (x509) {
  15108. // Increment reference count so caller can free it
  15109. X509_up_ref(x509);
  15110. certs.push_back(static_cast<cert_t>(x509));
  15111. }
  15112. }
  15113. }
  15114. return certs.size();
  15115. }
  15116. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15117. std::vector<std::string> names;
  15118. if (!ctx) { return names; }
  15119. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15120. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15121. if (!store) { return names; }
  15122. auto objs = impl::get_store_objects(store);
  15123. if (!objs) { return names; }
  15124. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15125. auto count = sk_X509_OBJECT_num(objs);
  15126. for (decltype(count) i = 0; i < count; i++) {
  15127. auto obj = sk_X509_OBJECT_value(objs, i);
  15128. if (!obj) { continue; }
  15129. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15130. auto x509 = X509_OBJECT_get0_X509(obj);
  15131. if (x509) {
  15132. auto subject = X509_get_subject_name(x509);
  15133. if (subject) {
  15134. char buf[512];
  15135. X509_NAME_oneline(subject, buf, sizeof(buf));
  15136. names.push_back(buf);
  15137. }
  15138. }
  15139. }
  15140. }
  15141. return names;
  15142. }
  15143. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15144. const char *key_pem, const char *password) {
  15145. if (!ctx || !cert_pem || !key_pem) { return false; }
  15146. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15147. // Load certificate from PEM
  15148. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15149. if (!cert_bio) { return false; }
  15150. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15151. BIO_free(cert_bio);
  15152. if (!cert) { return false; }
  15153. // Load private key from PEM
  15154. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15155. if (!key_bio) {
  15156. X509_free(cert);
  15157. return false;
  15158. }
  15159. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15160. password ? const_cast<char *>(password)
  15161. : nullptr);
  15162. BIO_free(key_bio);
  15163. if (!key) {
  15164. X509_free(cert);
  15165. return false;
  15166. }
  15167. // Update certificate and key
  15168. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15169. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15170. X509_free(cert);
  15171. EVP_PKEY_free(key);
  15172. return ret;
  15173. }
  15174. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15175. if (!ctx || !ca_pem) { return false; }
  15176. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15177. // Create new X509_STORE from PEM
  15178. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15179. if (!store) { return false; }
  15180. // SSL_CTX_set_cert_store takes ownership
  15181. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15182. // Set client CA list for client certificate request
  15183. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15184. if (ca_list) {
  15185. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15186. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15187. }
  15188. return true;
  15189. }
  15190. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15191. if (!ctx) { return false; }
  15192. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15193. impl::get_verify_callback() = std::move(callback);
  15194. if (impl::get_verify_callback()) {
  15195. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15196. } else {
  15197. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15198. }
  15199. return true;
  15200. }
  15201. inline long get_verify_error(const_session_t session) {
  15202. if (!session) { return -1; }
  15203. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15204. return SSL_get_verify_result(ssl);
  15205. }
  15206. inline std::string verify_error_string(long error_code) {
  15207. if (error_code == X509_V_OK) { return ""; }
  15208. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15209. return str ? str : "unknown error";
  15210. }
  15211. } // namespace tls
  15212. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15213. /*
  15214. * Group 9: TLS abstraction layer - Mbed TLS backend
  15215. */
  15216. /*
  15217. * Mbed TLS Backend Implementation
  15218. */
  15219. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15220. namespace tls {
  15221. namespace impl {
  15222. // Mbed TLS session wrapper
  15223. struct MbedTlsSession {
  15224. mbedtls_ssl_context ssl;
  15225. socket_t sock = INVALID_SOCKET;
  15226. std::string hostname; // For client: set via set_sni
  15227. std::string sni_hostname; // For server: received from client via SNI callback
  15228. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15229. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15230. MbedTlsSession(const MbedTlsSession &) = delete;
  15231. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15232. };
  15233. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15234. // queue)
  15235. inline int &mbedtls_last_error() {
  15236. static thread_local int err = 0;
  15237. return err;
  15238. }
  15239. // Helper to map Mbed TLS error to ErrorCode
  15240. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15241. if (ret == 0) { return ErrorCode::Success; }
  15242. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15243. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15244. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15245. return ErrorCode::PeerClosed;
  15246. }
  15247. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15248. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15249. out_errno = errno;
  15250. return ErrorCode::SyscallError;
  15251. }
  15252. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15253. return ErrorCode::CertVerifyFailed;
  15254. }
  15255. return ErrorCode::Fatal;
  15256. }
  15257. // BIO-like send callback for Mbed TLS
  15258. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15259. size_t len) {
  15260. auto sock = *static_cast<socket_t *>(ctx);
  15261. #ifdef _WIN32
  15262. auto ret =
  15263. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15264. if (ret == SOCKET_ERROR) {
  15265. int err = WSAGetLastError();
  15266. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15267. return MBEDTLS_ERR_NET_SEND_FAILED;
  15268. }
  15269. #else
  15270. auto ret = send(sock, buf, len, 0);
  15271. if (ret < 0) {
  15272. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15273. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15274. }
  15275. return MBEDTLS_ERR_NET_SEND_FAILED;
  15276. }
  15277. #endif
  15278. return static_cast<int>(ret);
  15279. }
  15280. // BIO-like recv callback for Mbed TLS
  15281. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15282. auto sock = *static_cast<socket_t *>(ctx);
  15283. #ifdef _WIN32
  15284. auto ret =
  15285. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15286. if (ret == SOCKET_ERROR) {
  15287. int err = WSAGetLastError();
  15288. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15289. return MBEDTLS_ERR_NET_RECV_FAILED;
  15290. }
  15291. #else
  15292. auto ret = recv(sock, buf, len, 0);
  15293. if (ret < 0) {
  15294. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15295. return MBEDTLS_ERR_SSL_WANT_READ;
  15296. }
  15297. return MBEDTLS_ERR_NET_RECV_FAILED;
  15298. }
  15299. #endif
  15300. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15301. return static_cast<int>(ret);
  15302. }
  15303. // MbedTlsContext constructor/destructor implementations
  15304. inline MbedTlsContext::MbedTlsContext() {
  15305. mbedtls_ssl_config_init(&conf);
  15306. mbedtls_entropy_init(&entropy);
  15307. mbedtls_ctr_drbg_init(&ctr_drbg);
  15308. mbedtls_x509_crt_init(&ca_chain);
  15309. mbedtls_x509_crt_init(&own_cert);
  15310. mbedtls_pk_init(&own_key);
  15311. }
  15312. inline MbedTlsContext::~MbedTlsContext() {
  15313. mbedtls_pk_free(&own_key);
  15314. mbedtls_x509_crt_free(&own_cert);
  15315. mbedtls_x509_crt_free(&ca_chain);
  15316. mbedtls_ctr_drbg_free(&ctr_drbg);
  15317. mbedtls_entropy_free(&entropy);
  15318. mbedtls_ssl_config_free(&conf);
  15319. }
  15320. // Thread-local storage for SNI captured during handshake
  15321. // This is needed because the SNI callback doesn't have a way to pass
  15322. // session-specific data before the session is fully set up
  15323. inline std::string &mbedpending_sni() {
  15324. static thread_local std::string sni;
  15325. return sni;
  15326. }
  15327. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15328. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15329. const unsigned char *name, size_t name_len) {
  15330. (void)p_ctx;
  15331. (void)ssl;
  15332. // Store SNI name in thread-local storage
  15333. // It will be retrieved and stored in the session after handshake
  15334. if (name && name_len > 0) {
  15335. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15336. } else {
  15337. mbedpending_sni().clear();
  15338. }
  15339. return 0; // Accept any SNI
  15340. }
  15341. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15342. int cert_depth, uint32_t *flags);
  15343. // MbedTLS verify callback wrapper
  15344. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15345. int cert_depth, uint32_t *flags) {
  15346. auto &callback = get_verify_callback();
  15347. if (!callback) { return 0; } // Continue with default verification
  15348. // data points to the MbedTlsSession
  15349. auto *session = static_cast<MbedTlsSession *>(data);
  15350. // Build context
  15351. VerifyContext verify_ctx;
  15352. verify_ctx.session = static_cast<session_t>(session);
  15353. verify_ctx.cert = static_cast<cert_t>(crt);
  15354. verify_ctx.depth = cert_depth;
  15355. verify_ctx.preverify_ok = (*flags == 0);
  15356. verify_ctx.error_code = static_cast<long>(*flags);
  15357. // Convert Mbed TLS flags to error string
  15358. static thread_local char error_buf[256];
  15359. if (*flags != 0) {
  15360. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15361. verify_ctx.error_string = error_buf;
  15362. } else {
  15363. verify_ctx.error_string = nullptr;
  15364. }
  15365. bool accepted = callback(verify_ctx);
  15366. if (accepted) {
  15367. *flags = 0; // Clear all error flags
  15368. return 0;
  15369. }
  15370. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15371. }
  15372. } // namespace impl
  15373. inline ctx_t create_client_context() {
  15374. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15375. if (!ctx) { return nullptr; }
  15376. ctx->is_server = false;
  15377. // Seed the random number generator
  15378. const char *pers = "httplib_client";
  15379. int ret = mbedtls_ctr_drbg_seed(
  15380. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15381. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15382. if (ret != 0) {
  15383. impl::mbedtls_last_error() = ret;
  15384. delete ctx;
  15385. return nullptr;
  15386. }
  15387. // Set up SSL config for client
  15388. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15389. MBEDTLS_SSL_TRANSPORT_STREAM,
  15390. MBEDTLS_SSL_PRESET_DEFAULT);
  15391. if (ret != 0) {
  15392. impl::mbedtls_last_error() = ret;
  15393. delete ctx;
  15394. return nullptr;
  15395. }
  15396. // Set random number generator
  15397. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15398. // Default: verify peer certificate
  15399. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15400. // Set minimum TLS version to 1.2
  15401. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15402. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15403. #else
  15404. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15405. MBEDTLS_SSL_MINOR_VERSION_3);
  15406. #endif
  15407. return static_cast<ctx_t>(ctx);
  15408. }
  15409. inline ctx_t create_server_context() {
  15410. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15411. if (!ctx) { return nullptr; }
  15412. ctx->is_server = true;
  15413. // Seed the random number generator
  15414. const char *pers = "httplib_server";
  15415. int ret = mbedtls_ctr_drbg_seed(
  15416. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15417. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15418. if (ret != 0) {
  15419. impl::mbedtls_last_error() = ret;
  15420. delete ctx;
  15421. return nullptr;
  15422. }
  15423. // Set up SSL config for server
  15424. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15425. MBEDTLS_SSL_TRANSPORT_STREAM,
  15426. MBEDTLS_SSL_PRESET_DEFAULT);
  15427. if (ret != 0) {
  15428. impl::mbedtls_last_error() = ret;
  15429. delete ctx;
  15430. return nullptr;
  15431. }
  15432. // Set random number generator
  15433. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15434. // Default: don't verify client
  15435. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15436. // Set minimum TLS version to 1.2
  15437. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15438. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15439. #else
  15440. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15441. MBEDTLS_SSL_MINOR_VERSION_3);
  15442. #endif
  15443. // Set SNI callback to capture client's SNI hostname
  15444. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15445. return static_cast<ctx_t>(ctx);
  15446. }
  15447. inline void free_context(ctx_t ctx) {
  15448. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15449. }
  15450. inline bool set_min_version(ctx_t ctx, Version version) {
  15451. if (!ctx) { return false; }
  15452. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15453. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15454. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15455. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15456. if (version >= Version::TLS1_3) {
  15457. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15458. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15459. #endif
  15460. }
  15461. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15462. #else
  15463. // Mbed TLS 2.x uses major/minor version numbers
  15464. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15465. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15466. if (version >= Version::TLS1_3) {
  15467. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15468. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15469. #else
  15470. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15471. #endif
  15472. }
  15473. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15474. #endif
  15475. return true;
  15476. }
  15477. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15478. if (!ctx || !pem) { return false; }
  15479. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15480. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15481. // Add null terminator if not present
  15482. std::string pem_str(pem, len);
  15483. int ret = mbedtls_x509_crt_parse(
  15484. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15485. pem_str.size() + 1);
  15486. if (ret != 0) {
  15487. impl::mbedtls_last_error() = ret;
  15488. return false;
  15489. }
  15490. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15491. return true;
  15492. }
  15493. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15494. if (!ctx || !file_path) { return false; }
  15495. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15496. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15497. if (ret != 0) {
  15498. impl::mbedtls_last_error() = ret;
  15499. return false;
  15500. }
  15501. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15502. return true;
  15503. }
  15504. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15505. if (!ctx || !dir_path) { return false; }
  15506. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15507. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15508. if (ret < 0) { // Returns number of certs on success, negative on error
  15509. impl::mbedtls_last_error() = ret;
  15510. return false;
  15511. }
  15512. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15513. return true;
  15514. }
  15515. inline bool load_system_certs(ctx_t ctx) {
  15516. if (!ctx) { return false; }
  15517. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15518. bool loaded = false;
  15519. #ifdef _WIN32
  15520. loaded = impl::enumerate_windows_system_certs(
  15521. [&](const unsigned char *data, size_t len) {
  15522. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15523. });
  15524. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15525. loaded = impl::enumerate_macos_keychain_certs(
  15526. [&](const unsigned char *data, size_t len) {
  15527. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15528. });
  15529. #else
  15530. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15531. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15532. loaded = true;
  15533. break;
  15534. }
  15535. }
  15536. if (!loaded) {
  15537. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15538. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15539. loaded = true;
  15540. break;
  15541. }
  15542. }
  15543. }
  15544. #endif
  15545. if (loaded) {
  15546. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15547. }
  15548. return loaded;
  15549. }
  15550. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15551. const char *password) {
  15552. if (!ctx || !cert || !key) { return false; }
  15553. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15554. // Parse certificate
  15555. std::string cert_str(cert);
  15556. int ret = mbedtls_x509_crt_parse(
  15557. &mctx->own_cert,
  15558. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15559. cert_str.size() + 1);
  15560. if (ret != 0) {
  15561. impl::mbedtls_last_error() = ret;
  15562. return false;
  15563. }
  15564. // Parse private key
  15565. std::string key_str(key);
  15566. const unsigned char *pwd =
  15567. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15568. size_t pwd_len = password ? strlen(password) : 0;
  15569. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15570. ret = mbedtls_pk_parse_key(
  15571. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15572. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15573. &mctx->ctr_drbg);
  15574. #else
  15575. ret = mbedtls_pk_parse_key(
  15576. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15577. key_str.size() + 1, pwd, pwd_len);
  15578. #endif
  15579. if (ret != 0) {
  15580. impl::mbedtls_last_error() = ret;
  15581. return false;
  15582. }
  15583. // Verify that the certificate and private key match
  15584. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15585. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15586. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15587. #else
  15588. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15589. #endif
  15590. if (ret != 0) {
  15591. impl::mbedtls_last_error() = ret;
  15592. return false;
  15593. }
  15594. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15595. if (ret != 0) {
  15596. impl::mbedtls_last_error() = ret;
  15597. return false;
  15598. }
  15599. return true;
  15600. }
  15601. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15602. const char *key_path, const char *password) {
  15603. if (!ctx || !cert_path || !key_path) { return false; }
  15604. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15605. // Parse certificate file
  15606. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15607. if (ret != 0) {
  15608. impl::mbedtls_last_error() = ret;
  15609. return false;
  15610. }
  15611. // Parse private key file
  15612. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15613. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15614. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15615. #else
  15616. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15617. #endif
  15618. if (ret != 0) {
  15619. impl::mbedtls_last_error() = ret;
  15620. return false;
  15621. }
  15622. // Verify that the certificate and private key match
  15623. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15624. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15625. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15626. #else
  15627. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15628. #endif
  15629. if (ret != 0) {
  15630. impl::mbedtls_last_error() = ret;
  15631. return false;
  15632. }
  15633. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15634. if (ret != 0) {
  15635. impl::mbedtls_last_error() = ret;
  15636. return false;
  15637. }
  15638. return true;
  15639. }
  15640. inline void set_verify_client(ctx_t ctx, bool require) {
  15641. if (!ctx) { return; }
  15642. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15643. mctx->verify_client = require;
  15644. if (require) {
  15645. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15646. } else {
  15647. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15648. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15649. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15650. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15651. : MBEDTLS_SSL_VERIFY_NONE);
  15652. }
  15653. }
  15654. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15655. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15656. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15657. auto session = new (std::nothrow) impl::MbedTlsSession();
  15658. if (!session) { return nullptr; }
  15659. session->sock = sock;
  15660. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15661. if (ret != 0) {
  15662. impl::mbedtls_last_error() = ret;
  15663. delete session;
  15664. return nullptr;
  15665. }
  15666. // Explicitly opt out of in-handshake hostname verification by default;
  15667. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15668. // fails outright when no hostname was set. set_sni() installs the real
  15669. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15670. // caller verifies the certificate identity post-handshake via
  15671. // verify_hostname().
  15672. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15673. // Set BIO callbacks
  15674. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15675. impl::mbedtls_net_recv_cb, nullptr);
  15676. // Set per-session verify callback with session pointer if callback is
  15677. // registered
  15678. if (mctx->has_verify_callback) {
  15679. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15680. session);
  15681. }
  15682. return static_cast<session_t>(session);
  15683. }
  15684. inline void free_session(session_t session) {
  15685. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15686. }
  15687. inline bool set_sni(session_t session, const char *hostname) {
  15688. if (!session || !hostname) { return false; }
  15689. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15690. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15691. if (ret != 0) {
  15692. impl::mbedtls_last_error() = ret;
  15693. return false;
  15694. }
  15695. msession->hostname = hostname;
  15696. return true;
  15697. }
  15698. inline bool set_hostname(session_t session, const char *hostname) {
  15699. // In Mbed TLS, set_hostname also sets up hostname verification
  15700. return set_sni(session, hostname);
  15701. }
  15702. inline TlsError connect(session_t session) {
  15703. TlsError err;
  15704. if (!session) {
  15705. err.code = ErrorCode::Fatal;
  15706. return err;
  15707. }
  15708. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15709. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15710. if (ret == 0) {
  15711. err.code = ErrorCode::Success;
  15712. } else {
  15713. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15714. err.backend_code = static_cast<uint64_t>(-ret);
  15715. impl::mbedtls_last_error() = ret;
  15716. }
  15717. return err;
  15718. }
  15719. inline TlsError accept(session_t session) {
  15720. // Same as connect for Mbed TLS - handshake works for both client and server
  15721. auto result = connect(session);
  15722. // After successful handshake, capture SNI from thread-local storage
  15723. if (result.code == ErrorCode::Success && session) {
  15724. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15725. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15726. impl::mbedpending_sni().clear();
  15727. }
  15728. return result;
  15729. }
  15730. inline bool connect_nonblocking(session_t session, socket_t sock,
  15731. time_t timeout_sec, time_t timeout_usec,
  15732. TlsError *err) {
  15733. if (!session) {
  15734. if (err) { err->code = ErrorCode::Fatal; }
  15735. return false;
  15736. }
  15737. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15738. // Set socket to non-blocking mode
  15739. detail::set_nonblocking(sock, true);
  15740. auto cleanup =
  15741. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15742. int ret;
  15743. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15744. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15745. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15746. continue;
  15747. }
  15748. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15749. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15750. continue;
  15751. }
  15752. }
  15753. // TlsError or timeout
  15754. if (err) {
  15755. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15756. err->backend_code = static_cast<uint64_t>(-ret);
  15757. }
  15758. impl::mbedtls_last_error() = ret;
  15759. return false;
  15760. }
  15761. if (err) { err->code = ErrorCode::Success; }
  15762. return true;
  15763. }
  15764. inline bool accept_nonblocking(session_t session, socket_t sock,
  15765. time_t timeout_sec, time_t timeout_usec,
  15766. TlsError *err) {
  15767. // Same implementation as connect for Mbed TLS
  15768. bool result =
  15769. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15770. // After successful handshake, capture SNI from thread-local storage
  15771. if (result && session) {
  15772. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15773. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15774. impl::mbedpending_sni().clear();
  15775. }
  15776. return result;
  15777. }
  15778. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15779. if (!session || !buf) {
  15780. err.code = ErrorCode::Fatal;
  15781. return -1;
  15782. }
  15783. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15784. int ret =
  15785. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15786. if (ret > 0) {
  15787. err.code = ErrorCode::Success;
  15788. return static_cast<ssize_t>(ret);
  15789. }
  15790. if (ret == 0) {
  15791. err.code = ErrorCode::PeerClosed;
  15792. return 0;
  15793. }
  15794. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15795. err.backend_code = static_cast<uint64_t>(-ret);
  15796. impl::mbedtls_last_error() = ret;
  15797. // mbedTLS signals a clean close_notify via a negative error code rather
  15798. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15799. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15800. return -1;
  15801. }
  15802. inline ssize_t write(session_t session, const void *buf, size_t len,
  15803. TlsError &err) {
  15804. if (!session || !buf) {
  15805. err.code = ErrorCode::Fatal;
  15806. return -1;
  15807. }
  15808. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15809. int ret = mbedtls_ssl_write(&msession->ssl,
  15810. static_cast<const unsigned char *>(buf), len);
  15811. if (ret > 0) {
  15812. err.code = ErrorCode::Success;
  15813. return static_cast<ssize_t>(ret);
  15814. }
  15815. if (ret == 0) {
  15816. err.code = ErrorCode::PeerClosed;
  15817. return 0;
  15818. }
  15819. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15820. err.backend_code = static_cast<uint64_t>(-ret);
  15821. impl::mbedtls_last_error() = ret;
  15822. return -1;
  15823. }
  15824. inline int pending(const_session_t session) {
  15825. if (!session) { return 0; }
  15826. auto msession =
  15827. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15828. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15829. }
  15830. inline void shutdown(session_t session, bool graceful) {
  15831. if (!session) { return; }
  15832. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15833. if (graceful) {
  15834. // Try to send close_notify, but don't block forever
  15835. int ret;
  15836. int attempts = 0;
  15837. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15838. attempts < 3) {
  15839. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15840. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15841. break;
  15842. }
  15843. attempts++;
  15844. }
  15845. }
  15846. }
  15847. inline bool is_peer_closed(session_t session, socket_t sock) {
  15848. if (!session || sock == INVALID_SOCKET) { return true; }
  15849. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15850. // Check if there's already decrypted data available in the TLS buffer
  15851. // If so, the connection is definitely alive
  15852. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15853. // Set socket to non-blocking to avoid blocking on read
  15854. detail::set_nonblocking(sock, true);
  15855. auto cleanup =
  15856. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15857. // Try a 1-byte read to check connection status
  15858. // Note: This will consume the byte if data is available, but for the
  15859. // purpose of checking if peer is closed, this should be acceptable
  15860. // since we're only called when we expect the connection might be closing
  15861. unsigned char buf;
  15862. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15863. // If we got data or WANT_READ (would block), connection is alive
  15864. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15865. // If we get a peer close notify or a connection reset, the peer is closed
  15866. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15867. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15868. }
  15869. inline cert_t get_peer_cert(const_session_t session) {
  15870. if (!session) { return nullptr; }
  15871. auto msession =
  15872. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15873. // Mbed TLS returns a pointer to the internal peer cert chain.
  15874. // WARNING: This pointer is only valid while the session is active.
  15875. // Do not use the certificate after calling free_session().
  15876. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15877. return const_cast<mbedtls_x509_crt *>(cert);
  15878. }
  15879. inline void free_cert(cert_t cert) {
  15880. // Mbed TLS: peer certificate is owned by the SSL context.
  15881. // No-op here, but callers should still call this for cross-backend
  15882. // portability.
  15883. (void)cert;
  15884. }
  15885. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15886. if (!cert || !hostname) { return false; }
  15887. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15888. std::string host_str(hostname);
  15889. // Check if hostname is an IP address (IPv4 or IPv6)
  15890. unsigned char ip_bytes[16];
  15891. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15892. auto is_ip = ip_len > 0;
  15893. // Check Subject Alternative Names (SAN)
  15894. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15895. // - DNS names: raw string bytes
  15896. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15897. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15898. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15899. const unsigned char *p = san->buf.p;
  15900. size_t len = san->buf.len;
  15901. if (is_ip) {
  15902. // For an IP host, only a matching iPAddress SAN of the same family
  15903. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15904. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15905. } else {
  15906. // Check if this SAN is a DNS name (printable ASCII string)
  15907. bool is_dns = len > 0;
  15908. for (size_t i = 0; i < len && is_dns; i++) {
  15909. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15910. }
  15911. if (is_dns) {
  15912. std::string san_name(reinterpret_cast<const char *>(p), len);
  15913. if (detail::match_hostname(san_name, host_str)) { return true; }
  15914. }
  15915. }
  15916. san = san->next;
  15917. }
  15918. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15919. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15920. // the OpenSSL backend's X509_check_ip behaves the same way).
  15921. if (!is_ip) {
  15922. char cn[256];
  15923. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15924. if (ret > 0) {
  15925. std::string cn_str(cn);
  15926. // Look for "CN=" in the DN string
  15927. size_t cn_pos = cn_str.find("CN=");
  15928. if (cn_pos != std::string::npos) {
  15929. size_t start = cn_pos + 3;
  15930. size_t end = cn_str.find(',', start);
  15931. std::string cn_value =
  15932. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15933. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15934. }
  15935. }
  15936. }
  15937. return false;
  15938. }
  15939. inline uint64_t hostname_mismatch_code() {
  15940. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15941. }
  15942. inline long get_verify_result(const_session_t session) {
  15943. if (!session) { return -1; }
  15944. auto msession =
  15945. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15946. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15947. // Return 0 (X509_V_OK equivalent) if verification passed
  15948. return flags == 0 ? 0 : static_cast<long>(flags);
  15949. }
  15950. inline std::string get_cert_subject_cn(cert_t cert) {
  15951. if (!cert) return "";
  15952. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15953. // Find the CN in the subject
  15954. const mbedtls_x509_name *name = &x509->subject;
  15955. while (name != nullptr) {
  15956. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15957. return std::string(reinterpret_cast<const char *>(name->val.p),
  15958. name->val.len);
  15959. }
  15960. name = name->next;
  15961. }
  15962. return "";
  15963. }
  15964. inline std::string get_cert_issuer_name(cert_t cert) {
  15965. if (!cert) return "";
  15966. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15967. // Build a human-readable issuer name string
  15968. char buf[512];
  15969. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15970. if (ret < 0) return "";
  15971. return std::string(buf);
  15972. }
  15973. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15974. sans.clear();
  15975. if (!cert) return false;
  15976. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15977. // Parse the Subject Alternative Name extension
  15978. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15979. while (cur != nullptr) {
  15980. if (cur->buf.len > 0) {
  15981. // Mbed TLS stores SAN as ASN.1 sequences
  15982. // The tag byte indicates the type
  15983. const unsigned char *p = cur->buf.p;
  15984. size_t len = cur->buf.len;
  15985. // First byte is the tag
  15986. unsigned char tag = *p;
  15987. p++;
  15988. len--;
  15989. // Parse length (simple single-byte length assumed)
  15990. if (len > 0 && *p < 0x80) {
  15991. size_t value_len = *p;
  15992. p++;
  15993. len--;
  15994. if (value_len <= len) {
  15995. SanEntry entry;
  15996. // ASN.1 context tags for GeneralName
  15997. switch (tag & 0x1F) {
  15998. case 2: // dNSName
  15999. entry.type = SanType::DNS;
  16000. entry.value =
  16001. std::string(reinterpret_cast<const char *>(p), value_len);
  16002. break;
  16003. case 7: // iPAddress
  16004. entry.type = SanType::IP;
  16005. if (value_len == 4) {
  16006. // IPv4
  16007. char buf[16];
  16008. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  16009. entry.value = buf;
  16010. } else if (value_len == 16) {
  16011. // IPv6
  16012. char buf[64];
  16013. snprintf(buf, sizeof(buf),
  16014. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16015. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16016. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  16017. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  16018. entry.value = buf;
  16019. }
  16020. break;
  16021. case 1: // rfc822Name (email)
  16022. entry.type = SanType::EMAIL;
  16023. entry.value =
  16024. std::string(reinterpret_cast<const char *>(p), value_len);
  16025. break;
  16026. case 6: // uniformResourceIdentifier
  16027. entry.type = SanType::URI;
  16028. entry.value =
  16029. std::string(reinterpret_cast<const char *>(p), value_len);
  16030. break;
  16031. default: entry.type = SanType::OTHER; break;
  16032. }
  16033. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16034. }
  16035. }
  16036. }
  16037. cur = cur->next;
  16038. }
  16039. return true;
  16040. }
  16041. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16042. time_t &not_after) {
  16043. if (!cert) return false;
  16044. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16045. // Convert mbedtls_x509_time to time_t
  16046. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  16047. struct tm tm_time = {};
  16048. tm_time.tm_year = t.year - 1900;
  16049. tm_time.tm_mon = t.mon - 1;
  16050. tm_time.tm_mday = t.day;
  16051. tm_time.tm_hour = t.hour;
  16052. tm_time.tm_min = t.min;
  16053. tm_time.tm_sec = t.sec;
  16054. #ifdef _WIN32
  16055. return _mkgmtime(&tm_time);
  16056. #else
  16057. return timegm(&tm_time);
  16058. #endif
  16059. };
  16060. not_before = to_time_t(x509->valid_from);
  16061. not_after = to_time_t(x509->valid_to);
  16062. return true;
  16063. }
  16064. inline std::string get_cert_serial(cert_t cert) {
  16065. if (!cert) return "";
  16066. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16067. // Convert serial number to hex string
  16068. std::string result;
  16069. result.reserve(x509->serial.len * 2);
  16070. for (size_t i = 0; i < x509->serial.len; i++) {
  16071. char hex[3];
  16072. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  16073. result += hex;
  16074. }
  16075. return result;
  16076. }
  16077. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16078. if (!cert) return false;
  16079. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16080. if (!crt->raw.p || crt->raw.len == 0) return false;
  16081. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16082. return true;
  16083. }
  16084. inline const char *get_sni(const_session_t session) {
  16085. if (!session) return nullptr;
  16086. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16087. // For server: return SNI received from client during handshake
  16088. if (!msession->sni_hostname.empty()) {
  16089. return msession->sni_hostname.c_str();
  16090. }
  16091. // For client: return the hostname set via set_sni
  16092. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16093. return nullptr;
  16094. }
  16095. inline uint64_t peek_error() {
  16096. // Mbed TLS doesn't have an error queue, return the last error
  16097. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16098. }
  16099. inline uint64_t get_error() {
  16100. // Mbed TLS doesn't have an error queue, return and clear the last error
  16101. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16102. impl::mbedtls_last_error() = 0;
  16103. return err;
  16104. }
  16105. inline std::string error_string(uint64_t code) {
  16106. char buf[256];
  16107. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16108. return std::string(buf);
  16109. }
  16110. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16111. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16112. if (!ca_chain) { return nullptr; }
  16113. mbedtls_x509_crt_init(ca_chain);
  16114. // mbedtls_x509_crt_parse expects null-terminated PEM
  16115. int ret = mbedtls_x509_crt_parse(ca_chain,
  16116. reinterpret_cast<const unsigned char *>(pem),
  16117. len + 1); // +1 for null terminator
  16118. if (ret != 0) {
  16119. // Try without +1 in case PEM is already null-terminated
  16120. ret = mbedtls_x509_crt_parse(
  16121. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16122. if (ret != 0) {
  16123. mbedtls_x509_crt_free(ca_chain);
  16124. delete ca_chain;
  16125. return nullptr;
  16126. }
  16127. }
  16128. return static_cast<ca_store_t>(ca_chain);
  16129. }
  16130. inline void free_ca_store(ca_store_t store) {
  16131. if (store) {
  16132. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16133. mbedtls_x509_crt_free(ca_chain);
  16134. delete ca_chain;
  16135. }
  16136. }
  16137. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16138. if (!ctx || !store) { return false; }
  16139. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16140. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16141. // Free existing CA chain
  16142. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16143. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16144. // Copy the CA chain (deep copy)
  16145. // Parse from the raw data of the source cert
  16146. mbedtls_x509_crt *src = ca_chain;
  16147. while (src != nullptr) {
  16148. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16149. src->raw.len);
  16150. if (ret != 0) {
  16151. free_ca_store(store);
  16152. return false;
  16153. }
  16154. src = src->next;
  16155. }
  16156. // This function takes ownership of the store; the chain was deep-copied
  16157. // above, so release the source
  16158. free_ca_store(store);
  16159. // Update the SSL config to use the new CA chain
  16160. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16161. return true;
  16162. }
  16163. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16164. certs.clear();
  16165. if (!ctx) { return 0; }
  16166. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16167. // Iterate through the CA chain
  16168. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16169. while (cert != nullptr && cert->raw.len > 0) {
  16170. // Create a copy of the certificate for the caller
  16171. auto *copy = new mbedtls_x509_crt;
  16172. mbedtls_x509_crt_init(copy);
  16173. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16174. if (ret == 0) {
  16175. certs.push_back(static_cast<cert_t>(copy));
  16176. } else {
  16177. mbedtls_x509_crt_free(copy);
  16178. delete copy;
  16179. }
  16180. cert = cert->next;
  16181. }
  16182. return certs.size();
  16183. }
  16184. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16185. std::vector<std::string> names;
  16186. if (!ctx) { return names; }
  16187. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16188. // Iterate through the CA chain
  16189. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16190. while (cert != nullptr && cert->raw.len > 0) {
  16191. char buf[512];
  16192. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16193. if (ret > 0) { names.push_back(buf); }
  16194. cert = cert->next;
  16195. }
  16196. return names;
  16197. }
  16198. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16199. const char *key_pem, const char *password) {
  16200. if (!ctx || !cert_pem || !key_pem) { return false; }
  16201. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16202. // Free existing certificate and key
  16203. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16204. mbedtls_pk_free(&mbed_ctx->own_key);
  16205. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16206. mbedtls_pk_init(&mbed_ctx->own_key);
  16207. // Parse certificate PEM
  16208. int ret = mbedtls_x509_crt_parse(
  16209. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16210. strlen(cert_pem) + 1);
  16211. if (ret != 0) {
  16212. impl::mbedtls_last_error() = ret;
  16213. return false;
  16214. }
  16215. // Parse private key PEM
  16216. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16217. ret = mbedtls_pk_parse_key(
  16218. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16219. strlen(key_pem) + 1,
  16220. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16221. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16222. &mbed_ctx->ctr_drbg);
  16223. #else
  16224. ret = mbedtls_pk_parse_key(
  16225. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16226. strlen(key_pem) + 1,
  16227. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16228. password ? strlen(password) : 0);
  16229. #endif
  16230. if (ret != 0) {
  16231. impl::mbedtls_last_error() = ret;
  16232. return false;
  16233. }
  16234. // Configure SSL to use the new certificate and key
  16235. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16236. &mbed_ctx->own_key);
  16237. if (ret != 0) {
  16238. impl::mbedtls_last_error() = ret;
  16239. return false;
  16240. }
  16241. return true;
  16242. }
  16243. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16244. if (!ctx || !ca_pem) { return false; }
  16245. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16246. // Free existing CA chain
  16247. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16248. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16249. // Parse CA PEM
  16250. int ret = mbedtls_x509_crt_parse(
  16251. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16252. strlen(ca_pem) + 1);
  16253. if (ret != 0) {
  16254. impl::mbedtls_last_error() = ret;
  16255. return false;
  16256. }
  16257. // Update SSL config to use new CA chain
  16258. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16259. return true;
  16260. }
  16261. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16262. if (!ctx) { return false; }
  16263. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16264. impl::get_verify_callback() = std::move(callback);
  16265. mbed_ctx->has_verify_callback =
  16266. static_cast<bool>(impl::get_verify_callback());
  16267. if (mbed_ctx->has_verify_callback) {
  16268. // Set OPTIONAL mode to ensure callback is called even when verification
  16269. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16270. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16271. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16272. nullptr);
  16273. } else {
  16274. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16275. }
  16276. return true;
  16277. }
  16278. inline long get_verify_error(const_session_t session) {
  16279. if (!session) { return -1; }
  16280. auto *msession =
  16281. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16282. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16283. }
  16284. inline std::string verify_error_string(long error_code) {
  16285. if (error_code == 0) { return ""; }
  16286. char buf[256];
  16287. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16288. static_cast<uint32_t>(error_code));
  16289. // Remove trailing newline if present
  16290. std::string result(buf);
  16291. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16292. result.pop_back();
  16293. }
  16294. return result;
  16295. }
  16296. } // namespace tls
  16297. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16298. /*
  16299. * Group 10: TLS abstraction layer - wolfSSL backend
  16300. */
  16301. /*
  16302. * wolfSSL Backend Implementation
  16303. */
  16304. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16305. namespace tls {
  16306. namespace impl {
  16307. // wolfSSL session wrapper
  16308. struct WolfSSLSession {
  16309. WOLFSSL *ssl = nullptr;
  16310. socket_t sock = INVALID_SOCKET;
  16311. std::string hostname; // For client: set via set_sni
  16312. std::string sni_hostname; // For server: received from client via SNI callback
  16313. WolfSSLSession() = default;
  16314. ~WolfSSLSession() {
  16315. if (ssl) { wolfSSL_free(ssl); }
  16316. }
  16317. WolfSSLSession(const WolfSSLSession &) = delete;
  16318. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16319. };
  16320. // Thread-local error code accessor for wolfSSL
  16321. inline uint64_t &wolfssl_last_error() {
  16322. static thread_local uint64_t err = 0;
  16323. return err;
  16324. }
  16325. // Helper to map wolfSSL error to ErrorCode.
  16326. // ssl_error is the value from wolfSSL_get_error().
  16327. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16328. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16329. int &out_errno) {
  16330. switch (ssl_error) {
  16331. case SSL_ERROR_NONE: return ErrorCode::Success;
  16332. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16333. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16334. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16335. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16336. default:
  16337. if (ssl) {
  16338. // wolfSSL stores the low-level error code as a negative value.
  16339. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16340. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16341. if (low_err == DOMAIN_NAME_MISMATCH) {
  16342. return ErrorCode::HostnameMismatch;
  16343. }
  16344. // Check verify result to distinguish cert verification from generic SSL
  16345. // errors.
  16346. long vr = wolfSSL_get_verify_result(ssl);
  16347. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16348. }
  16349. return ErrorCode::Fatal;
  16350. }
  16351. }
  16352. // WolfSSLContext constructor/destructor implementations
  16353. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16354. inline WolfSSLContext::~WolfSSLContext() {
  16355. if (ctx) { wolfSSL_CTX_free(ctx); }
  16356. }
  16357. // Thread-local storage for SNI captured during handshake
  16358. inline std::string &wolfssl_pending_sni() {
  16359. static thread_local std::string sni;
  16360. return sni;
  16361. }
  16362. // SNI callback for wolfSSL server to capture client's SNI hostname
  16363. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16364. (void)ret;
  16365. (void)exArg;
  16366. void *name_data = nullptr;
  16367. unsigned short name_len =
  16368. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16369. if (name_data && name_len > 0) {
  16370. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16371. name_len);
  16372. } else {
  16373. wolfssl_pending_sni().clear();
  16374. }
  16375. return 0; // Continue regardless
  16376. }
  16377. // wolfSSL verify callback wrapper
  16378. inline int wolfssl_verify_callback(int preverify_ok,
  16379. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16380. auto &callback = get_verify_callback();
  16381. if (!callback) { return preverify_ok; }
  16382. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16383. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16384. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16385. // Get the WOLFSSL object from the X509_STORE_CTX
  16386. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16387. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16388. VerifyContext verify_ctx;
  16389. verify_ctx.session = static_cast<session_t>(ssl);
  16390. verify_ctx.cert = static_cast<cert_t>(cert);
  16391. verify_ctx.depth = depth;
  16392. verify_ctx.preverify_ok = (preverify_ok != 0);
  16393. verify_ctx.error_code = static_cast<long>(err);
  16394. if (err != 0) {
  16395. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16396. } else {
  16397. verify_ctx.error_string = nullptr;
  16398. }
  16399. bool accepted = callback(verify_ctx);
  16400. return accepted ? 1 : 0;
  16401. }
  16402. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16403. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16404. wolfSSL_CTX_set_default_passwd_cb(
  16405. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16406. auto *pwd = static_cast<const char *>(userdata);
  16407. if (!pwd) return 0;
  16408. auto len = static_cast<int>(strlen(pwd));
  16409. if (len > size) len = size;
  16410. memcpy(buf, pwd, static_cast<size_t>(len));
  16411. return len;
  16412. });
  16413. }
  16414. } // namespace impl
  16415. inline ctx_t create_client_context() {
  16416. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16417. if (!ctx) { return nullptr; }
  16418. ctx->is_server = false;
  16419. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16420. if (!method) {
  16421. delete ctx;
  16422. return nullptr;
  16423. }
  16424. ctx->ctx = wolfSSL_CTX_new(method);
  16425. if (!ctx->ctx) {
  16426. delete ctx;
  16427. return nullptr;
  16428. }
  16429. // Default: verify peer certificate
  16430. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16431. return static_cast<ctx_t>(ctx);
  16432. }
  16433. inline ctx_t create_server_context() {
  16434. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16435. if (!ctx) { return nullptr; }
  16436. ctx->is_server = true;
  16437. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16438. if (!method) {
  16439. delete ctx;
  16440. return nullptr;
  16441. }
  16442. ctx->ctx = wolfSSL_CTX_new(method);
  16443. if (!ctx->ctx) {
  16444. delete ctx;
  16445. return nullptr;
  16446. }
  16447. // Default: don't verify client
  16448. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16449. // Enable SNI on server
  16450. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16451. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16452. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16453. return static_cast<ctx_t>(ctx);
  16454. }
  16455. inline void free_context(ctx_t ctx) {
  16456. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16457. }
  16458. inline bool set_min_version(ctx_t ctx, Version version) {
  16459. if (!ctx) { return false; }
  16460. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16461. int min_ver = WOLFSSL_TLSV1_2;
  16462. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16463. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16464. }
  16465. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16466. if (!ctx || !pem) { return false; }
  16467. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16468. int ret = wolfSSL_CTX_load_verify_buffer(
  16469. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16470. static_cast<long>(len), SSL_FILETYPE_PEM);
  16471. if (ret != SSL_SUCCESS) {
  16472. impl::wolfssl_last_error() =
  16473. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16474. return false;
  16475. }
  16476. wctx->ca_pem_data_.append(pem, len);
  16477. return true;
  16478. }
  16479. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16480. if (!ctx || !file_path) { return false; }
  16481. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16482. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16483. if (ret != SSL_SUCCESS) {
  16484. impl::wolfssl_last_error() =
  16485. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16486. return false;
  16487. }
  16488. return true;
  16489. }
  16490. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16491. if (!ctx || !dir_path) { return false; }
  16492. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16493. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16494. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16495. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16496. // immediately. Return true even on failure since the CA file may have
  16497. // already been loaded, matching OpenSSL's lenient behavior.
  16498. (void)ret;
  16499. return true;
  16500. }
  16501. inline bool load_system_certs(ctx_t ctx) {
  16502. if (!ctx) { return false; }
  16503. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16504. bool loaded = false;
  16505. #ifdef _WIN32
  16506. loaded = impl::enumerate_windows_system_certs(
  16507. [&](const unsigned char *data, size_t len) {
  16508. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16509. static_cast<long>(len),
  16510. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16511. });
  16512. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16513. loaded = impl::enumerate_macos_keychain_certs(
  16514. [&](const unsigned char *data, size_t len) {
  16515. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16516. static_cast<long>(len),
  16517. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16518. });
  16519. #else
  16520. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16521. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16522. SSL_SUCCESS) {
  16523. loaded = true;
  16524. break;
  16525. }
  16526. }
  16527. if (!loaded) {
  16528. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16529. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16530. SSL_SUCCESS) {
  16531. loaded = true;
  16532. break;
  16533. }
  16534. }
  16535. }
  16536. #endif
  16537. return loaded;
  16538. }
  16539. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16540. const char *password) {
  16541. if (!ctx || !cert || !key) { return false; }
  16542. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16543. // Load certificate
  16544. int ret = wolfSSL_CTX_use_certificate_buffer(
  16545. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16546. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16547. if (ret != SSL_SUCCESS) {
  16548. impl::wolfssl_last_error() =
  16549. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16550. return false;
  16551. }
  16552. // Set password callback if password is provided
  16553. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16554. // Load private key
  16555. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16556. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16557. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16558. if (ret != SSL_SUCCESS) {
  16559. impl::wolfssl_last_error() =
  16560. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16561. return false;
  16562. }
  16563. // Verify that the certificate and private key match
  16564. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16565. }
  16566. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16567. const char *key_path, const char *password) {
  16568. if (!ctx || !cert_path || !key_path) { return false; }
  16569. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16570. // Load certificate file
  16571. int ret =
  16572. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16573. if (ret != SSL_SUCCESS) {
  16574. impl::wolfssl_last_error() =
  16575. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16576. return false;
  16577. }
  16578. // Set password callback if password is provided
  16579. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16580. // Load private key file
  16581. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16582. if (ret != SSL_SUCCESS) {
  16583. impl::wolfssl_last_error() =
  16584. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16585. return false;
  16586. }
  16587. // Verify that the certificate and private key match
  16588. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16589. }
  16590. inline void set_verify_client(ctx_t ctx, bool require) {
  16591. if (!ctx) { return; }
  16592. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16593. wctx->verify_client = require;
  16594. if (require) {
  16595. wolfSSL_CTX_set_verify(
  16596. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16597. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16598. } else {
  16599. if (wctx->has_verify_callback) {
  16600. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16601. impl::wolfssl_verify_callback);
  16602. } else {
  16603. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16604. }
  16605. }
  16606. }
  16607. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16608. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16609. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16610. auto session = new (std::nothrow) impl::WolfSSLSession();
  16611. if (!session) { return nullptr; }
  16612. session->sock = sock;
  16613. session->ssl = wolfSSL_new(wctx->ctx);
  16614. if (!session->ssl) {
  16615. impl::wolfssl_last_error() =
  16616. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16617. delete session;
  16618. return nullptr;
  16619. }
  16620. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16621. return static_cast<session_t>(session);
  16622. }
  16623. inline void free_session(session_t session) {
  16624. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16625. }
  16626. inline bool set_sni(session_t session, const char *hostname) {
  16627. if (!session || !hostname) { return false; }
  16628. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16629. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16630. static_cast<word16>(strlen(hostname)));
  16631. if (ret != WOLFSSL_SUCCESS) {
  16632. impl::wolfssl_last_error() =
  16633. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16634. return false;
  16635. }
  16636. // Also set hostname for verification
  16637. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16638. wsession->hostname = hostname;
  16639. return true;
  16640. }
  16641. inline bool set_hostname(session_t session, const char *hostname) {
  16642. // In wolfSSL, set_hostname also sets up hostname verification
  16643. return set_sni(session, hostname);
  16644. }
  16645. inline TlsError connect(session_t session) {
  16646. TlsError err;
  16647. if (!session) {
  16648. err.code = ErrorCode::Fatal;
  16649. return err;
  16650. }
  16651. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16652. int ret = wolfSSL_connect(wsession->ssl);
  16653. if (ret == SSL_SUCCESS) {
  16654. err.code = ErrorCode::Success;
  16655. } else {
  16656. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16657. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16658. err.backend_code = static_cast<uint64_t>(ssl_error);
  16659. impl::wolfssl_last_error() = err.backend_code;
  16660. }
  16661. return err;
  16662. }
  16663. inline TlsError accept(session_t session) {
  16664. TlsError err;
  16665. if (!session) {
  16666. err.code = ErrorCode::Fatal;
  16667. return err;
  16668. }
  16669. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16670. int ret = wolfSSL_accept(wsession->ssl);
  16671. if (ret == SSL_SUCCESS) {
  16672. err.code = ErrorCode::Success;
  16673. // Capture SNI from thread-local storage after successful handshake
  16674. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16675. impl::wolfssl_pending_sni().clear();
  16676. } else {
  16677. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16678. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16679. err.backend_code = static_cast<uint64_t>(ssl_error);
  16680. impl::wolfssl_last_error() = err.backend_code;
  16681. }
  16682. return err;
  16683. }
  16684. inline bool connect_nonblocking(session_t session, socket_t sock,
  16685. time_t timeout_sec, time_t timeout_usec,
  16686. TlsError *err) {
  16687. if (!session) {
  16688. if (err) { err->code = ErrorCode::Fatal; }
  16689. return false;
  16690. }
  16691. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16692. // Set socket to non-blocking mode
  16693. detail::set_nonblocking(sock, true);
  16694. auto cleanup =
  16695. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16696. int ret;
  16697. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16698. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16699. if (ssl_error == SSL_ERROR_WANT_READ) {
  16700. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16701. continue;
  16702. }
  16703. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16704. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16705. continue;
  16706. }
  16707. }
  16708. // Error or timeout
  16709. if (err) {
  16710. err->code =
  16711. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16712. err->backend_code = static_cast<uint64_t>(ssl_error);
  16713. }
  16714. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16715. return false;
  16716. }
  16717. if (err) { err->code = ErrorCode::Success; }
  16718. return true;
  16719. }
  16720. inline bool accept_nonblocking(session_t session, socket_t sock,
  16721. time_t timeout_sec, time_t timeout_usec,
  16722. TlsError *err) {
  16723. if (!session) {
  16724. if (err) { err->code = ErrorCode::Fatal; }
  16725. return false;
  16726. }
  16727. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16728. // Set socket to non-blocking mode
  16729. detail::set_nonblocking(sock, true);
  16730. auto cleanup =
  16731. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16732. int ret;
  16733. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16734. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16735. if (ssl_error == SSL_ERROR_WANT_READ) {
  16736. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16737. continue;
  16738. }
  16739. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16740. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16741. continue;
  16742. }
  16743. }
  16744. // Error or timeout
  16745. if (err) {
  16746. err->code =
  16747. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16748. err->backend_code = static_cast<uint64_t>(ssl_error);
  16749. }
  16750. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16751. return false;
  16752. }
  16753. if (err) { err->code = ErrorCode::Success; }
  16754. // Capture SNI from thread-local storage after successful handshake
  16755. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16756. impl::wolfssl_pending_sni().clear();
  16757. return true;
  16758. }
  16759. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16760. if (!session || !buf) {
  16761. err.code = ErrorCode::Fatal;
  16762. return -1;
  16763. }
  16764. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16765. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16766. if (ret > 0) {
  16767. err.code = ErrorCode::Success;
  16768. return static_cast<ssize_t>(ret);
  16769. }
  16770. if (ret == 0) {
  16771. err.code = ErrorCode::PeerClosed;
  16772. return 0;
  16773. }
  16774. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16775. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16776. err.backend_code = static_cast<uint64_t>(ssl_error);
  16777. impl::wolfssl_last_error() = err.backend_code;
  16778. return -1;
  16779. }
  16780. inline ssize_t write(session_t session, const void *buf, size_t len,
  16781. TlsError &err) {
  16782. if (!session || !buf) {
  16783. err.code = ErrorCode::Fatal;
  16784. return -1;
  16785. }
  16786. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16787. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16788. if (ret > 0) {
  16789. err.code = ErrorCode::Success;
  16790. return static_cast<ssize_t>(ret);
  16791. }
  16792. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16793. // Treat this as an error (return -1) so callers don't spin in a
  16794. // write loop adding zero to the offset.
  16795. if (ret == 0) {
  16796. err.code = ErrorCode::PeerClosed;
  16797. return -1;
  16798. }
  16799. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16800. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16801. err.backend_code = static_cast<uint64_t>(ssl_error);
  16802. impl::wolfssl_last_error() = err.backend_code;
  16803. return -1;
  16804. }
  16805. inline int pending(const_session_t session) {
  16806. if (!session) { return 0; }
  16807. auto wsession =
  16808. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16809. return wolfSSL_pending(wsession->ssl);
  16810. }
  16811. inline void shutdown(session_t session, bool graceful) {
  16812. if (!session) { return; }
  16813. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16814. if (graceful) {
  16815. int ret;
  16816. int attempts = 0;
  16817. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16818. attempts < 3) {
  16819. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16820. if (ssl_error != SSL_ERROR_WANT_READ &&
  16821. ssl_error != SSL_ERROR_WANT_WRITE) {
  16822. break;
  16823. }
  16824. attempts++;
  16825. }
  16826. } else {
  16827. wolfSSL_shutdown(wsession->ssl);
  16828. }
  16829. }
  16830. inline bool is_peer_closed(session_t session, socket_t sock) {
  16831. if (!session || sock == INVALID_SOCKET) { return true; }
  16832. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16833. // Check if there's already decrypted data available
  16834. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16835. // Set socket to non-blocking to avoid blocking on read
  16836. detail::set_nonblocking(sock, true);
  16837. auto cleanup =
  16838. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16839. // Peek 1 byte to check connection status without consuming data
  16840. unsigned char buf;
  16841. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16842. // If we got data or WANT_READ (would block), connection is alive
  16843. if (ret > 0) { return false; }
  16844. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16845. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16846. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16847. ret == 0;
  16848. }
  16849. inline cert_t get_peer_cert(const_session_t session) {
  16850. if (!session) { return nullptr; }
  16851. auto wsession =
  16852. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16853. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16854. return static_cast<cert_t>(cert);
  16855. }
  16856. inline void free_cert(cert_t cert) {
  16857. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16858. }
  16859. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16860. if (!cert || !hostname) { return false; }
  16861. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16862. std::string host_str(hostname);
  16863. // Check if hostname is an IP address (IPv4 or IPv6)
  16864. unsigned char ip_bytes[16];
  16865. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16866. auto is_ip = ip_len > 0;
  16867. // Check Subject Alternative Names
  16868. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16869. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16870. if (san_names) {
  16871. int san_count = wolfSSL_sk_num(san_names);
  16872. for (int i = 0; i < san_count; i++) {
  16873. auto *names =
  16874. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16875. if (!names) continue;
  16876. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16877. // DNS name
  16878. unsigned char *dns_name = nullptr;
  16879. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16880. if (dns_name && dns_len > 0) {
  16881. std::string san_name(reinterpret_cast<char *>(dns_name),
  16882. static_cast<size_t>(dns_len));
  16883. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16884. if (detail::match_hostname(san_name, host_str)) {
  16885. wolfSSL_sk_free(san_names);
  16886. return true;
  16887. }
  16888. }
  16889. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16890. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16891. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16892. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16893. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16894. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16895. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16896. wolfSSL_sk_free(san_names);
  16897. return true;
  16898. }
  16899. }
  16900. }
  16901. wolfSSL_sk_free(san_names);
  16902. }
  16903. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16904. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16905. // the OpenSSL backend's X509_check_ip behaves the same way).
  16906. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16907. if (subject) {
  16908. char cn[256] = {};
  16909. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16910. sizeof(cn));
  16911. if (cn_len > 0) {
  16912. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16913. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16914. }
  16915. }
  16916. return false;
  16917. }
  16918. inline uint64_t hostname_mismatch_code() {
  16919. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16920. }
  16921. inline long get_verify_result(const_session_t session) {
  16922. if (!session) { return -1; }
  16923. auto wsession =
  16924. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16925. long result = wolfSSL_get_verify_result(wsession->ssl);
  16926. return result;
  16927. }
  16928. inline std::string get_cert_subject_cn(cert_t cert) {
  16929. if (!cert) return "";
  16930. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16931. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16932. if (!subject) return "";
  16933. char cn[256] = {};
  16934. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16935. sizeof(cn));
  16936. if (cn_len <= 0) return "";
  16937. return std::string(cn, static_cast<size_t>(cn_len));
  16938. }
  16939. inline std::string get_cert_issuer_name(cert_t cert) {
  16940. if (!cert) return "";
  16941. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16942. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16943. if (!issuer) return "";
  16944. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16945. if (!name_str) return "";
  16946. std::string result(name_str);
  16947. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16948. return result;
  16949. }
  16950. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16951. sans.clear();
  16952. if (!cert) return false;
  16953. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16954. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16955. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16956. if (!san_names) return true; // No SANs is not an error
  16957. int count = wolfSSL_sk_num(san_names);
  16958. for (int i = 0; i < count; i++) {
  16959. auto *name =
  16960. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16961. if (!name) continue;
  16962. SanEntry entry;
  16963. switch (name->type) {
  16964. case WOLFSSL_GEN_DNS: {
  16965. entry.type = SanType::DNS;
  16966. unsigned char *dns_name = nullptr;
  16967. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16968. if (dns_name && dns_len > 0) {
  16969. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16970. static_cast<size_t>(dns_len));
  16971. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16972. }
  16973. break;
  16974. }
  16975. case WOLFSSL_GEN_IPADD: {
  16976. entry.type = SanType::IP;
  16977. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16978. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16979. if (ip_data && ip_len == 4) {
  16980. char buf[16];
  16981. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16982. ip_data[2], ip_data[3]);
  16983. entry.value = buf;
  16984. } else if (ip_data && ip_len == 16) {
  16985. char buf[64];
  16986. snprintf(buf, sizeof(buf),
  16987. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16988. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16989. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16990. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16991. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16992. ip_data[14], ip_data[15]);
  16993. entry.value = buf;
  16994. }
  16995. break;
  16996. }
  16997. case WOLFSSL_GEN_EMAIL:
  16998. entry.type = SanType::EMAIL;
  16999. {
  17000. unsigned char *email = nullptr;
  17001. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  17002. if (email && email_len > 0) {
  17003. entry.value = std::string(reinterpret_cast<char *>(email),
  17004. static_cast<size_t>(email_len));
  17005. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  17006. }
  17007. }
  17008. break;
  17009. case WOLFSSL_GEN_URI:
  17010. entry.type = SanType::URI;
  17011. {
  17012. unsigned char *uri = nullptr;
  17013. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  17014. &uri, name->d.uniformResourceIdentifier);
  17015. if (uri && uri_len > 0) {
  17016. entry.value = std::string(reinterpret_cast<char *>(uri),
  17017. static_cast<size_t>(uri_len));
  17018. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  17019. }
  17020. }
  17021. break;
  17022. default: entry.type = SanType::OTHER; break;
  17023. }
  17024. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  17025. }
  17026. wolfSSL_sk_free(san_names);
  17027. return true;
  17028. }
  17029. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  17030. time_t &not_after) {
  17031. if (!cert) return false;
  17032. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17033. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  17034. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  17035. if (!nb || !na) return false;
  17036. // wolfSSL_ASN1_TIME_to_tm is available
  17037. struct tm tm_nb = {}, tm_na = {};
  17038. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  17039. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  17040. #ifdef _WIN32
  17041. not_before = _mkgmtime(&tm_nb);
  17042. not_after = _mkgmtime(&tm_na);
  17043. #else
  17044. not_before = timegm(&tm_nb);
  17045. not_after = timegm(&tm_na);
  17046. #endif
  17047. return true;
  17048. }
  17049. inline std::string get_cert_serial(cert_t cert) {
  17050. if (!cert) return "";
  17051. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17052. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  17053. if (!serial_asn1) return "";
  17054. // Get the serial number data
  17055. int len = serial_asn1->length;
  17056. unsigned char *data = serial_asn1->data;
  17057. if (!data || len <= 0) return "";
  17058. std::string result;
  17059. result.reserve(static_cast<size_t>(len) * 2);
  17060. for (int i = 0; i < len; i++) {
  17061. char hex[3];
  17062. snprintf(hex, sizeof(hex), "%02X", data[i]);
  17063. result += hex;
  17064. }
  17065. return result;
  17066. }
  17067. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17068. if (!cert) return false;
  17069. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17070. int der_len = 0;
  17071. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  17072. if (!der_data || der_len <= 0) return false;
  17073. der.assign(der_data, der_data + der_len);
  17074. return true;
  17075. }
  17076. inline const char *get_sni(const_session_t session) {
  17077. if (!session) return nullptr;
  17078. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17079. // For server: return SNI received from client during handshake
  17080. if (!wsession->sni_hostname.empty()) {
  17081. return wsession->sni_hostname.c_str();
  17082. }
  17083. // For client: return the hostname set via set_sni
  17084. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17085. return nullptr;
  17086. }
  17087. inline uint64_t peek_error() {
  17088. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17089. }
  17090. inline uint64_t get_error() {
  17091. uint64_t err = impl::wolfssl_last_error();
  17092. impl::wolfssl_last_error() = 0;
  17093. return err;
  17094. }
  17095. inline std::string error_string(uint64_t code) {
  17096. char buf[256];
  17097. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17098. return std::string(buf);
  17099. }
  17100. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17101. if (!pem || len == 0) { return nullptr; }
  17102. // Validate by attempting to load into a temporary ctx
  17103. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17104. if (!tmp_ctx) { return nullptr; }
  17105. int ret = wolfSSL_CTX_load_verify_buffer(
  17106. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17107. static_cast<long>(len), SSL_FILETYPE_PEM);
  17108. wolfSSL_CTX_free(tmp_ctx);
  17109. if (ret != SSL_SUCCESS) { return nullptr; }
  17110. return static_cast<ca_store_t>(
  17111. new impl::WolfSSLCAStore{std::string(pem, len)});
  17112. }
  17113. inline void free_ca_store(ca_store_t store) {
  17114. delete static_cast<impl::WolfSSLCAStore *>(store);
  17115. }
  17116. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17117. if (!ctx || !store) { return false; }
  17118. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17119. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17120. int ret = wolfSSL_CTX_load_verify_buffer(
  17121. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17122. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17123. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17124. // This function takes ownership of the store; the PEM data was copied into
  17125. // the context, so release the source
  17126. free_ca_store(store);
  17127. return ret == SSL_SUCCESS;
  17128. }
  17129. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17130. certs.clear();
  17131. if (!ctx) { return 0; }
  17132. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17133. if (wctx->ca_pem_data_.empty()) { return 0; }
  17134. const std::string &pem = wctx->ca_pem_data_;
  17135. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17136. const std::string end_marker = "-----END CERTIFICATE-----";
  17137. size_t pos = 0;
  17138. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17139. size_t end_pos = pem.find(end_marker, pos);
  17140. if (end_pos == std::string::npos) { break; }
  17141. end_pos += end_marker.size();
  17142. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17143. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17144. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17145. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17146. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17147. pos = end_pos;
  17148. }
  17149. return certs.size();
  17150. }
  17151. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17152. std::vector<std::string> names;
  17153. if (!ctx) { return names; }
  17154. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17155. if (wctx->ca_pem_data_.empty()) { return names; }
  17156. const std::string &pem = wctx->ca_pem_data_;
  17157. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17158. const std::string end_marker = "-----END CERTIFICATE-----";
  17159. size_t pos = 0;
  17160. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17161. size_t end_pos = pem.find(end_marker, pos);
  17162. if (end_pos == std::string::npos) { break; }
  17163. end_pos += end_marker.size();
  17164. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17165. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17166. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17167. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17168. if (x509) {
  17169. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17170. if (subject) {
  17171. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17172. if (name_str) {
  17173. names.push_back(name_str);
  17174. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17175. }
  17176. }
  17177. wolfSSL_X509_free(x509);
  17178. }
  17179. pos = end_pos;
  17180. }
  17181. return names;
  17182. }
  17183. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17184. const char *key_pem, const char *password) {
  17185. if (!ctx || !cert_pem || !key_pem) { return false; }
  17186. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17187. // Load new certificate
  17188. int ret = wolfSSL_CTX_use_certificate_buffer(
  17189. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17190. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17191. if (ret != SSL_SUCCESS) {
  17192. impl::wolfssl_last_error() =
  17193. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17194. return false;
  17195. }
  17196. // Set password if provided
  17197. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17198. // Load new private key
  17199. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17200. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17201. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17202. if (ret != SSL_SUCCESS) {
  17203. impl::wolfssl_last_error() =
  17204. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17205. return false;
  17206. }
  17207. return true;
  17208. }
  17209. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17210. if (!ctx || !ca_pem) { return false; }
  17211. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17212. int ret = wolfSSL_CTX_load_verify_buffer(
  17213. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17214. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17215. if (ret != SSL_SUCCESS) {
  17216. impl::wolfssl_last_error() =
  17217. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17218. return false;
  17219. }
  17220. return true;
  17221. }
  17222. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17223. if (!ctx) { return false; }
  17224. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17225. impl::get_verify_callback() = std::move(callback);
  17226. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17227. if (wctx->has_verify_callback) {
  17228. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17229. impl::wolfssl_verify_callback);
  17230. } else {
  17231. wolfSSL_CTX_set_verify(
  17232. wctx->ctx,
  17233. wctx->verify_client
  17234. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17235. : SSL_VERIFY_NONE,
  17236. nullptr);
  17237. }
  17238. return true;
  17239. }
  17240. inline long get_verify_error(const_session_t session) {
  17241. if (!session) { return -1; }
  17242. auto *wsession =
  17243. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17244. return wolfSSL_get_verify_result(wsession->ssl);
  17245. }
  17246. inline std::string verify_error_string(long error_code) {
  17247. if (error_code == 0) { return ""; }
  17248. const char *str =
  17249. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17250. return str ? std::string(str) : std::string();
  17251. }
  17252. } // namespace tls
  17253. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17254. // WebSocket implementation
  17255. namespace ws {
  17256. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17257. bool fin) {
  17258. std::lock_guard<std::mutex> lock(write_mutex_);
  17259. if (closed_) { return false; }
  17260. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17261. }
  17262. inline ReadResult WebSocket::read(std::string &msg) {
  17263. while (!closed_) {
  17264. Opcode opcode;
  17265. std::string payload;
  17266. bool fin;
  17267. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17268. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17269. closed_ = true;
  17270. return Fail;
  17271. }
  17272. switch (opcode) {
  17273. case Opcode::Ping: {
  17274. std::lock_guard<std::mutex> lock(write_mutex_);
  17275. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17276. payload.size(), true, !is_server_);
  17277. continue;
  17278. }
  17279. case Opcode::Pong: {
  17280. std::lock_guard<std::mutex> lock(ping_mutex_);
  17281. unacked_pings_ = 0;
  17282. continue;
  17283. }
  17284. case Opcode::Close: {
  17285. if (!closed_.exchange(true)) {
  17286. // Echo close frame back
  17287. std::lock_guard<std::mutex> lock(write_mutex_);
  17288. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17289. payload.size(), true, !is_server_);
  17290. }
  17291. return Fail;
  17292. }
  17293. case Opcode::Text:
  17294. case Opcode::Binary: {
  17295. auto result = opcode == Opcode::Text ? Text : Binary;
  17296. msg = std::move(payload);
  17297. // Handle fragmentation
  17298. if (!fin) {
  17299. while (true) {
  17300. Opcode cont_opcode;
  17301. std::string cont_payload;
  17302. bool cont_fin;
  17303. if (!impl::read_websocket_frame(
  17304. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17305. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17306. closed_ = true;
  17307. return Fail;
  17308. }
  17309. if (cont_opcode == Opcode::Ping) {
  17310. std::lock_guard<std::mutex> lock(write_mutex_);
  17311. detail::write_websocket_frame(
  17312. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17313. true, !is_server_);
  17314. continue;
  17315. }
  17316. if (cont_opcode == Opcode::Pong) {
  17317. std::lock_guard<std::mutex> lock(ping_mutex_);
  17318. unacked_pings_ = 0;
  17319. continue;
  17320. }
  17321. if (cont_opcode == Opcode::Close) {
  17322. if (!closed_.exchange(true)) {
  17323. std::lock_guard<std::mutex> lock(write_mutex_);
  17324. detail::write_websocket_frame(
  17325. strm_, Opcode::Close, cont_payload.data(),
  17326. cont_payload.size(), true, !is_server_);
  17327. }
  17328. return Fail;
  17329. }
  17330. // RFC 6455: continuation frames must use opcode 0x0
  17331. if (cont_opcode != Opcode::Continuation) {
  17332. closed_ = true;
  17333. return Fail;
  17334. }
  17335. msg += cont_payload;
  17336. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17337. closed_ = true;
  17338. return Fail;
  17339. }
  17340. if (cont_fin) { break; }
  17341. }
  17342. }
  17343. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17344. if (result == Text && !impl::is_valid_utf8(msg)) {
  17345. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17346. return Fail;
  17347. }
  17348. return result;
  17349. }
  17350. default: closed_ = true; return Fail;
  17351. }
  17352. }
  17353. return Fail;
  17354. }
  17355. inline bool WebSocket::send(const std::string &data) {
  17356. return send_frame(Opcode::Text, data.data(), data.size());
  17357. }
  17358. inline bool WebSocket::send(const char *data, size_t len) {
  17359. return send_frame(Opcode::Binary, data, len);
  17360. }
  17361. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17362. if (closed_.exchange(true)) { return; }
  17363. ping_cv_.notify_all();
  17364. std::string payload;
  17365. auto code = static_cast<uint16_t>(status);
  17366. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17367. payload.push_back(static_cast<char>(code & 0xFF));
  17368. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17369. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17370. payload += reason.substr(0, 123);
  17371. {
  17372. std::lock_guard<std::mutex> lock(write_mutex_);
  17373. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17374. payload.size(), true, !is_server_);
  17375. }
  17376. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17377. // Close response before closing the TCP connection. Use a short timeout to
  17378. // avoid hanging if the peer doesn't respond.
  17379. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17380. Opcode op;
  17381. std::string resp;
  17382. bool fin;
  17383. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17384. if (op == Opcode::Close) { break; }
  17385. }
  17386. }
  17387. inline WebSocket::~WebSocket() {
  17388. {
  17389. std::lock_guard<std::mutex> lock(ping_mutex_);
  17390. closed_ = true;
  17391. }
  17392. ping_cv_.notify_all();
  17393. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17394. }
  17395. inline void WebSocket::start_heartbeat() {
  17396. if (ping_interval_sec_ == 0) { return; }
  17397. ping_thread_ = std::thread([this]() {
  17398. std::unique_lock<std::mutex> lock(ping_mutex_);
  17399. while (!closed_) {
  17400. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17401. if (closed_) { break; }
  17402. // If the peer has failed to respond to the previous pings, give up.
  17403. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17404. // opt-in liveness check controlled by max_missed_pongs_.
  17405. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17406. lock.unlock();
  17407. close(CloseStatus::GoingAway, "pong timeout");
  17408. return;
  17409. }
  17410. lock.unlock();
  17411. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17412. lock.lock();
  17413. closed_ = true;
  17414. break;
  17415. }
  17416. lock.lock();
  17417. unacked_pings_++;
  17418. }
  17419. });
  17420. }
  17421. inline const Request &WebSocket::request() const { return req_; }
  17422. inline bool WebSocket::is_open() const { return !closed_; }
  17423. // WebSocketClient implementation
  17424. inline WebSocketClient::WebSocketClient(
  17425. const std::string &scheme_host_port_path, const Headers &headers)
  17426. : headers_(headers) {
  17427. detail::UrlComponents uc;
  17428. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17429. !uc.host.empty() && !uc.path.empty()) {
  17430. auto &scheme = uc.scheme;
  17431. #ifdef CPPHTTPLIB_SSL_ENABLED
  17432. if (scheme != "ws" && scheme != "wss") {
  17433. #else
  17434. if (scheme != "ws") {
  17435. #endif
  17436. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17437. std::string msg = "'" + scheme + "' scheme is not supported.";
  17438. throw std::invalid_argument(msg);
  17439. #endif
  17440. return;
  17441. }
  17442. auto is_ssl = scheme == "wss";
  17443. host_ = std::move(uc.host);
  17444. port_ = is_ssl ? 443 : 80;
  17445. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17446. path_ = std::move(uc.path);
  17447. if (!uc.query.empty()) { path_ += uc.query; }
  17448. #ifdef CPPHTTPLIB_SSL_ENABLED
  17449. is_ssl_ = is_ssl;
  17450. if (is_ssl_) {
  17451. // The context lives as long as the client so that CA configuration
  17452. // survives reconnects; sessions are created per connection.
  17453. tls_ctx_ = tls::create_client_context();
  17454. if (!tls_ctx_) { return; }
  17455. }
  17456. #else
  17457. if (is_ssl) { return; }
  17458. #endif
  17459. is_valid_ = true;
  17460. }
  17461. }
  17462. inline WebSocketClient::~WebSocketClient() {
  17463. shutdown_and_close();
  17464. #ifdef CPPHTTPLIB_SSL_ENABLED
  17465. if (tls_ctx_) {
  17466. tls::free_context(tls_ctx_);
  17467. tls_ctx_ = nullptr;
  17468. }
  17469. #endif
  17470. }
  17471. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17472. inline void WebSocketClient::shutdown_and_close() {
  17473. // Send the close frame while the TLS session is still alive: ws_ holds an
  17474. // SSLSocketStream that keeps a raw pointer to tls_session_, so the session
  17475. // must outlive ws_->close() and ws_.reset() to avoid a use-after-free.
  17476. if (ws_ && ws_->is_open()) { ws_->close(); }
  17477. ws_.reset();
  17478. #ifdef CPPHTTPLIB_SSL_ENABLED
  17479. if (is_ssl_) {
  17480. if (tls_session_) {
  17481. tls::shutdown(tls_session_, true);
  17482. tls::free_session(tls_session_);
  17483. tls_session_ = nullptr;
  17484. }
  17485. }
  17486. #endif
  17487. if (sock_ != INVALID_SOCKET) {
  17488. detail::shutdown_socket(sock_);
  17489. detail::close_socket(sock_);
  17490. sock_ = INVALID_SOCKET;
  17491. }
  17492. }
  17493. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17494. #ifdef CPPHTTPLIB_SSL_ENABLED
  17495. if (is_ssl_) {
  17496. if (server_certificate_verification_ && !certs_loaded_) {
  17497. uint64_t backend_error = 0;
  17498. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17499. custom_ca_loaded_, system_ca_mode_,
  17500. backend_error);
  17501. certs_loaded_ = true;
  17502. }
  17503. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17504. server_certificate_verification_,
  17505. read_timeout_sec_,
  17506. read_timeout_usec_)) {
  17507. return false;
  17508. }
  17509. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17510. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17511. write_timeout_sec_, write_timeout_usec_));
  17512. return true;
  17513. }
  17514. #endif
  17515. strm = std::unique_ptr<Stream>(
  17516. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17517. write_timeout_sec_, write_timeout_usec_));
  17518. return true;
  17519. }
  17520. inline bool WebSocketClient::connect() {
  17521. if (!is_valid_) { return false; }
  17522. shutdown_and_close();
  17523. // Check is custom IP specified for host_
  17524. std::string ip;
  17525. auto it = addr_map_.find(host_);
  17526. if (it != addr_map_.end()) { ip = it->second; }
  17527. Error error;
  17528. sock_ = detail::create_client_socket(
  17529. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17530. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17531. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17532. write_timeout_usec_, interface_, error);
  17533. if (sock_ == INVALID_SOCKET) { return false; }
  17534. std::unique_ptr<Stream> strm;
  17535. if (!create_stream(strm)) {
  17536. shutdown_and_close();
  17537. return false;
  17538. }
  17539. #ifdef CPPHTTPLIB_SSL_ENABLED
  17540. auto is_ssl = is_ssl_;
  17541. #else
  17542. auto is_ssl = false;
  17543. #endif
  17544. std::string selected_subprotocol;
  17545. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17546. headers_, selected_subprotocol)) {
  17547. shutdown_and_close();
  17548. return false;
  17549. }
  17550. subprotocol_ = std::move(selected_subprotocol);
  17551. Request req;
  17552. req.method = "GET";
  17553. req.path = path_;
  17554. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17555. websocket_ping_interval_sec_,
  17556. websocket_max_missed_pongs_));
  17557. return true;
  17558. }
  17559. inline ReadResult WebSocketClient::read(std::string &msg) {
  17560. if (!ws_) { return Fail; }
  17561. return ws_->read(msg);
  17562. }
  17563. inline bool WebSocketClient::send(const std::string &data) {
  17564. if (!ws_) { return false; }
  17565. return ws_->send(data);
  17566. }
  17567. inline bool WebSocketClient::send(const char *data, size_t len) {
  17568. if (!ws_) { return false; }
  17569. return ws_->send(data, len);
  17570. }
  17571. inline void WebSocketClient::close(CloseStatus status,
  17572. const std::string &reason) {
  17573. if (ws_) { ws_->close(status, reason); }
  17574. }
  17575. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17576. inline const std::string &WebSocketClient::subprotocol() const {
  17577. return subprotocol_;
  17578. }
  17579. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17580. read_timeout_sec_ = sec;
  17581. read_timeout_usec_ = usec;
  17582. }
  17583. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17584. write_timeout_sec_ = sec;
  17585. write_timeout_usec_ = usec;
  17586. }
  17587. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17588. websocket_ping_interval_sec_ = sec;
  17589. }
  17590. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17591. websocket_max_missed_pongs_ = count;
  17592. }
  17593. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17594. inline void WebSocketClient::set_address_family(int family) {
  17595. address_family_ = family;
  17596. }
  17597. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17598. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17599. socket_options_ = std::move(socket_options);
  17600. }
  17601. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17602. connection_timeout_sec_ = sec;
  17603. connection_timeout_usec_ = usec;
  17604. }
  17605. inline void WebSocketClient::set_interface(const std::string &intf) {
  17606. interface_ = intf;
  17607. }
  17608. inline void WebSocketClient::set_hostname_addr_map(
  17609. std::map<std::string, std::string> addr_map) {
  17610. addr_map_ = std::move(addr_map);
  17611. }
  17612. #ifdef CPPHTTPLIB_SSL_ENABLED
  17613. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17614. ca_cert_file_path_ = path;
  17615. }
  17616. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17617. if (store && tls_ctx_) {
  17618. // set_ca_store takes ownership of store
  17619. tls::set_ca_store(tls_ctx_, store);
  17620. custom_ca_loaded_ = true;
  17621. } else if (store) {
  17622. tls::free_ca_store(store);
  17623. }
  17624. }
  17625. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17626. std::size_t size) {
  17627. if (tls_ctx_ && ca_cert && size > 0) {
  17628. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17629. custom_ca_loaded_ = true;
  17630. }
  17631. }
  17632. inline void
  17633. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17634. server_certificate_verification_ = enabled;
  17635. }
  17636. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17637. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17638. }
  17639. #endif // CPPHTTPLIB_SSL_ENABLED
  17640. } // namespace ws
  17641. // ----------------------------------------------------------------------------
  17642. } // namespace httplib
  17643. #endif // CPPHTTPLIB_HTTPLIB_H