httplib.h 670 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385
  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.39.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x002700"
  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. /*
  160. * Headers
  161. */
  162. #ifdef _WIN32
  163. #ifndef _CRT_SECURE_NO_WARNINGS
  164. #define _CRT_SECURE_NO_WARNINGS
  165. #endif //_CRT_SECURE_NO_WARNINGS
  166. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  167. #define _CRT_NONSTDC_NO_DEPRECATE
  168. #endif //_CRT_NONSTDC_NO_DEPRECATE
  169. #if defined(_MSC_VER)
  170. #if _MSC_VER < 1900
  171. #error Sorry, Visual Studio versions prior to 2015 are not supported
  172. #endif
  173. #pragma comment(lib, "ws2_32.lib")
  174. #ifndef _SSIZE_T_DEFINED
  175. using ssize_t = __int64;
  176. #define _SSIZE_T_DEFINED
  177. #endif
  178. #endif // _MSC_VER
  179. #ifndef S_ISREG
  180. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  181. #endif // S_ISREG
  182. #ifndef S_ISDIR
  183. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  184. #endif // S_ISDIR
  185. #ifndef NOMINMAX
  186. #define NOMINMAX
  187. #endif // NOMINMAX
  188. #include <io.h>
  189. #include <winsock2.h>
  190. #include <ws2tcpip.h>
  191. #if defined(__has_include)
  192. #if __has_include(<afunix.h>)
  193. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  194. #include <afunix.h>
  195. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  196. #endif
  197. #endif
  198. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  199. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  200. #endif
  201. using nfds_t = unsigned long;
  202. using socket_t = SOCKET;
  203. using socklen_t = int;
  204. #else // not _WIN32
  205. #include <arpa/inet.h>
  206. #if !defined(_AIX) && !defined(__MVS__)
  207. #include <ifaddrs.h>
  208. #endif
  209. #ifdef __MVS__
  210. #include <strings.h>
  211. #ifndef NI_MAXHOST
  212. #define NI_MAXHOST 1025
  213. #endif
  214. #endif
  215. #include <net/if.h>
  216. #include <netdb.h>
  217. #include <netinet/in.h>
  218. #ifdef __linux__
  219. #include <resolv.h>
  220. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  221. #endif
  222. #include <csignal>
  223. #include <netinet/tcp.h>
  224. #include <poll.h>
  225. #include <pthread.h>
  226. #include <sys/mman.h>
  227. #include <sys/socket.h>
  228. #include <sys/un.h>
  229. #include <unistd.h>
  230. using socket_t = int;
  231. #ifndef INVALID_SOCKET
  232. #define INVALID_SOCKET (-1)
  233. #endif
  234. #endif //_WIN32
  235. #if defined(__APPLE__)
  236. #include <TargetConditionals.h>
  237. #endif
  238. #include <algorithm>
  239. #include <array>
  240. #include <atomic>
  241. #include <cassert>
  242. #include <cctype>
  243. #include <chrono>
  244. #include <climits>
  245. #include <condition_variable>
  246. #include <cstdlib>
  247. #include <cstring>
  248. #include <errno.h>
  249. #include <exception>
  250. #include <fcntl.h>
  251. #include <fstream>
  252. #include <functional>
  253. #include <iomanip>
  254. #include <iostream>
  255. #include <list>
  256. #include <map>
  257. #include <memory>
  258. #include <mutex>
  259. #include <random>
  260. #include <regex>
  261. #include <set>
  262. #include <sstream>
  263. #include <string>
  264. #include <sys/stat.h>
  265. #include <system_error>
  266. #include <thread>
  267. #include <unordered_map>
  268. #include <unordered_set>
  269. #include <utility>
  270. #if __cplusplus >= 201703L
  271. #include <any>
  272. #endif
  273. // On macOS with a TLS backend, enable Keychain root certificates by default
  274. // unless the user explicitly opts out.
  275. #if defined(__APPLE__) && \
  276. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  277. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  278. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  279. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  280. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  281. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  282. #endif
  283. #endif
  284. // On Windows, enable Schannel certificate verification by default
  285. // unless the user explicitly opts out.
  286. #if defined(_WIN32) && \
  287. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  288. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  289. #endif
  290. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  291. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  292. #if TARGET_OS_MAC
  293. #include <CFNetwork/CFHost.h>
  294. #include <CoreFoundation/CoreFoundation.h>
  295. #endif
  296. #endif
  297. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  298. #ifdef _WIN32
  299. #include <wincrypt.h>
  300. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  301. // used
  302. #undef X509_NAME
  303. #undef X509_CERT_PAIR
  304. #undef X509_EXTENSIONS
  305. #undef PKCS7_SIGNER_INFO
  306. #ifdef _MSC_VER
  307. #pragma comment(lib, "crypt32.lib")
  308. #endif
  309. #endif // _WIN32
  310. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  311. #if TARGET_OS_MAC
  312. #include <Security/Security.h>
  313. #endif
  314. #endif
  315. #include <openssl/err.h>
  316. #include <openssl/evp.h>
  317. #include <openssl/ssl.h>
  318. #include <openssl/x509v3.h>
  319. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  320. #include <openssl/applink.c>
  321. #endif
  322. #include <iostream>
  323. #include <sstream>
  324. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  325. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  326. #error Please use OpenSSL or a current version of BoringSSL
  327. #endif
  328. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  329. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  330. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  331. #endif
  332. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  333. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  334. #include <mbedtls/ctr_drbg.h>
  335. #include <mbedtls/entropy.h>
  336. #include <mbedtls/error.h>
  337. #include <mbedtls/md5.h>
  338. #include <mbedtls/net_sockets.h>
  339. #include <mbedtls/oid.h>
  340. #include <mbedtls/pk.h>
  341. #include <mbedtls/sha1.h>
  342. #include <mbedtls/sha256.h>
  343. #include <mbedtls/sha512.h>
  344. #include <mbedtls/ssl.h>
  345. #include <mbedtls/x509_crt.h>
  346. #ifdef _WIN32
  347. #include <wincrypt.h>
  348. #ifdef _MSC_VER
  349. #pragma comment(lib, "crypt32.lib")
  350. #endif
  351. #endif // _WIN32
  352. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  353. #if TARGET_OS_MAC
  354. #include <Security/Security.h>
  355. #endif
  356. #endif
  357. // Mbed TLS 3.x API compatibility
  358. #if MBEDTLS_VERSION_MAJOR >= 3
  359. #define CPPHTTPLIB_MBEDTLS_V3
  360. #endif
  361. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  362. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  363. #include <wolfssl/options.h>
  364. #include <wolfssl/openssl/x509v3.h>
  365. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  366. #ifndef WOLFSSL_GEN_EMAIL
  367. #define WOLFSSL_GEN_EMAIL 1
  368. #endif
  369. #ifndef WOLFSSL_GEN_DNS
  370. #define WOLFSSL_GEN_DNS 2
  371. #endif
  372. #ifndef WOLFSSL_GEN_URI
  373. #define WOLFSSL_GEN_URI 6
  374. #endif
  375. #ifndef WOLFSSL_GEN_IPADD
  376. #define WOLFSSL_GEN_IPADD 7
  377. #endif
  378. #include <wolfssl/ssl.h>
  379. #include <wolfssl/wolfcrypt/hash.h>
  380. #include <wolfssl/wolfcrypt/md5.h>
  381. #include <wolfssl/wolfcrypt/sha256.h>
  382. #include <wolfssl/wolfcrypt/sha512.h>
  383. #ifdef _WIN32
  384. #include <wincrypt.h>
  385. #ifdef _MSC_VER
  386. #pragma comment(lib, "crypt32.lib")
  387. #endif
  388. #endif // _WIN32
  389. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  390. #if TARGET_OS_MAC
  391. #include <Security/Security.h>
  392. #endif
  393. #endif
  394. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  395. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  396. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  397. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  398. #define CPPHTTPLIB_SSL_ENABLED
  399. #endif
  400. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  401. #include <zlib.h>
  402. #endif
  403. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  404. #include <brotli/decode.h>
  405. #include <brotli/encode.h>
  406. #endif
  407. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  408. #include <zstd.h>
  409. #endif
  410. /*
  411. * Declaration
  412. */
  413. namespace httplib {
  414. namespace ws {
  415. class WebSocket;
  416. } // namespace ws
  417. namespace detail {
  418. /*
  419. * Backport std::make_unique from C++14.
  420. *
  421. * NOTE: This code came up with the following stackoverflow post:
  422. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  423. *
  424. */
  425. template <class T, class... Args>
  426. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  427. make_unique(Args &&...args) {
  428. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  429. }
  430. template <class T>
  431. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  432. make_unique(std::size_t n) {
  433. typedef typename std::remove_extent<T>::type RT;
  434. return std::unique_ptr<T>(new RT[n]);
  435. }
  436. namespace case_ignore {
  437. inline unsigned char to_lower(int c) {
  438. const static unsigned char table[256] = {
  439. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  440. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  441. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  442. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  443. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  444. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  445. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  446. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  447. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  448. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  449. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  450. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  451. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  452. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  453. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  454. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  455. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  456. 255,
  457. };
  458. return table[(unsigned char)(char)c];
  459. }
  460. inline std::string to_lower(const std::string &s) {
  461. std::string result = s;
  462. std::transform(
  463. result.begin(), result.end(), result.begin(),
  464. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  465. return result;
  466. }
  467. inline bool equal(const std::string &a, const std::string &b) {
  468. return a.size() == b.size() &&
  469. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  470. return to_lower(ca) == to_lower(cb);
  471. });
  472. }
  473. struct equal_to {
  474. bool operator()(const std::string &a, const std::string &b) const {
  475. return equal(a, b);
  476. }
  477. };
  478. struct hash {
  479. size_t operator()(const std::string &key) const {
  480. return hash_core(key.data(), key.size(), 0);
  481. }
  482. size_t hash_core(const char *s, size_t l, size_t h) const {
  483. return (l == 0) ? h
  484. : hash_core(s + 1, l - 1,
  485. // Unsets the 6 high bits of h, therefore no
  486. // overflow happens
  487. (((std::numeric_limits<size_t>::max)() >> 6) &
  488. h * 33) ^
  489. static_cast<unsigned char>(to_lower(*s)));
  490. }
  491. };
  492. template <typename T>
  493. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  494. detail::case_ignore::equal_to>;
  495. } // namespace case_ignore
  496. // This is based on
  497. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  498. struct scope_exit {
  499. explicit scope_exit(std::function<void(void)> &&f)
  500. : exit_function(std::move(f)), execute_on_destruction{true} {}
  501. scope_exit(scope_exit &&rhs) noexcept
  502. : exit_function(std::move(rhs.exit_function)),
  503. execute_on_destruction{rhs.execute_on_destruction} {
  504. rhs.release();
  505. }
  506. ~scope_exit() {
  507. if (execute_on_destruction) { this->exit_function(); }
  508. }
  509. void release() { this->execute_on_destruction = false; }
  510. private:
  511. scope_exit(const scope_exit &) = delete;
  512. void operator=(const scope_exit &) = delete;
  513. scope_exit &operator=(scope_exit &&) = delete;
  514. std::function<void(void)> exit_function;
  515. bool execute_on_destruction;
  516. };
  517. // Simple from_chars implementation for integer and double types (C++17
  518. // substitute)
  519. template <typename T> struct from_chars_result {
  520. const char *ptr;
  521. std::errc ec;
  522. };
  523. template <typename T>
  524. inline from_chars_result<T> from_chars(const char *first, const char *last,
  525. T &value, int base = 10) {
  526. value = 0;
  527. const char *p = first;
  528. bool negative = false;
  529. if (p != last && *p == '-') {
  530. negative = true;
  531. ++p;
  532. }
  533. if (p == last) { return {first, std::errc::invalid_argument}; }
  534. T result = 0;
  535. for (; p != last; ++p) {
  536. char c = *p;
  537. int digit = -1;
  538. if ('0' <= c && c <= '9') {
  539. digit = c - '0';
  540. } else if ('a' <= c && c <= 'z') {
  541. digit = c - 'a' + 10;
  542. } else if ('A' <= c && c <= 'Z') {
  543. digit = c - 'A' + 10;
  544. } else {
  545. break;
  546. }
  547. if (digit < 0 || digit >= base) { break; }
  548. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  549. return {p, std::errc::result_out_of_range};
  550. }
  551. result = result * base + digit;
  552. }
  553. if (p == first || (negative && p == first + 1)) {
  554. return {first, std::errc::invalid_argument};
  555. }
  556. value = negative ? -result : result;
  557. return {p, std::errc{}};
  558. }
  559. // from_chars for double (simple wrapper for strtod)
  560. inline from_chars_result<double> from_chars(const char *first, const char *last,
  561. double &value) {
  562. std::string s(first, last);
  563. char *endptr = nullptr;
  564. errno = 0;
  565. value = std::strtod(s.c_str(), &endptr);
  566. if (endptr == s.c_str()) { return {first, std::errc::invalid_argument}; }
  567. if (errno == ERANGE) {
  568. return {first + (endptr - s.c_str()), std::errc::result_out_of_range};
  569. }
  570. return {first + (endptr - s.c_str()), std::errc{}};
  571. }
  572. inline bool parse_port(const char *s, size_t len, int &port) {
  573. int val = 0;
  574. auto r = from_chars(s, s + len, val);
  575. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  576. port = val;
  577. return true;
  578. }
  579. inline bool parse_port(const std::string &s, int &port) {
  580. return parse_port(s.data(), s.size(), port);
  581. }
  582. } // namespace detail
  583. enum SSLVerifierResponse {
  584. // no decision has been made, use the built-in certificate verifier
  585. NoDecisionMade,
  586. // connection certificate is verified and accepted
  587. CertificateAccepted,
  588. // connection certificate was processed but is rejected
  589. CertificateRejected
  590. };
  591. enum StatusCode {
  592. // Information responses
  593. Continue_100 = 100,
  594. SwitchingProtocol_101 = 101,
  595. Processing_102 = 102,
  596. EarlyHints_103 = 103,
  597. // Successful responses
  598. OK_200 = 200,
  599. Created_201 = 201,
  600. Accepted_202 = 202,
  601. NonAuthoritativeInformation_203 = 203,
  602. NoContent_204 = 204,
  603. ResetContent_205 = 205,
  604. PartialContent_206 = 206,
  605. MultiStatus_207 = 207,
  606. AlreadyReported_208 = 208,
  607. IMUsed_226 = 226,
  608. // Redirection messages
  609. MultipleChoices_300 = 300,
  610. MovedPermanently_301 = 301,
  611. Found_302 = 302,
  612. SeeOther_303 = 303,
  613. NotModified_304 = 304,
  614. UseProxy_305 = 305,
  615. unused_306 = 306,
  616. TemporaryRedirect_307 = 307,
  617. PermanentRedirect_308 = 308,
  618. // Client error responses
  619. BadRequest_400 = 400,
  620. Unauthorized_401 = 401,
  621. PaymentRequired_402 = 402,
  622. Forbidden_403 = 403,
  623. NotFound_404 = 404,
  624. MethodNotAllowed_405 = 405,
  625. NotAcceptable_406 = 406,
  626. ProxyAuthenticationRequired_407 = 407,
  627. RequestTimeout_408 = 408,
  628. Conflict_409 = 409,
  629. Gone_410 = 410,
  630. LengthRequired_411 = 411,
  631. PreconditionFailed_412 = 412,
  632. PayloadTooLarge_413 = 413,
  633. UriTooLong_414 = 414,
  634. UnsupportedMediaType_415 = 415,
  635. RangeNotSatisfiable_416 = 416,
  636. ExpectationFailed_417 = 417,
  637. ImATeapot_418 = 418,
  638. MisdirectedRequest_421 = 421,
  639. UnprocessableContent_422 = 422,
  640. Locked_423 = 423,
  641. FailedDependency_424 = 424,
  642. TooEarly_425 = 425,
  643. UpgradeRequired_426 = 426,
  644. PreconditionRequired_428 = 428,
  645. TooManyRequests_429 = 429,
  646. RequestHeaderFieldsTooLarge_431 = 431,
  647. UnavailableForLegalReasons_451 = 451,
  648. // Server error responses
  649. InternalServerError_500 = 500,
  650. NotImplemented_501 = 501,
  651. BadGateway_502 = 502,
  652. ServiceUnavailable_503 = 503,
  653. GatewayTimeout_504 = 504,
  654. HttpVersionNotSupported_505 = 505,
  655. VariantAlsoNegotiates_506 = 506,
  656. InsufficientStorage_507 = 507,
  657. LoopDetected_508 = 508,
  658. NotExtended_510 = 510,
  659. NetworkAuthenticationRequired_511 = 511,
  660. };
  661. using Headers =
  662. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  663. detail::case_ignore::equal_to>;
  664. using Params = std::multimap<std::string, std::string>;
  665. using Match = std::smatch;
  666. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  667. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  668. // ----------------------------------------------------------------------------
  669. // httplib::any — type-erased value container (C++11 compatible)
  670. // On C++17+ builds, thin wrappers around std::any are provided.
  671. // ----------------------------------------------------------------------------
  672. #if __cplusplus >= 201703L
  673. using any = std::any;
  674. using bad_any_cast = std::bad_any_cast;
  675. template <typename T> T any_cast(const any &a) { return std::any_cast<T>(a); }
  676. template <typename T> T any_cast(any &a) { return std::any_cast<T>(a); }
  677. template <typename T> T any_cast(any &&a) {
  678. return std::any_cast<T>(std::move(a));
  679. }
  680. template <typename T> const T *any_cast(const any *a) noexcept {
  681. return std::any_cast<T>(a);
  682. }
  683. template <typename T> T *any_cast(any *a) noexcept {
  684. return std::any_cast<T>(a);
  685. }
  686. #else // C++11/14 implementation
  687. class bad_any_cast : public std::bad_cast {
  688. public:
  689. const char *what() const noexcept override { return "bad any_cast"; }
  690. };
  691. namespace detail {
  692. using any_type_id = const void *;
  693. // Returns a unique per-type ID without RTTI.
  694. // The static address is stable across TUs because function templates are
  695. // implicitly inline and the ODR merges their statics into one.
  696. template <typename T> any_type_id any_typeid() noexcept {
  697. static const char id = 0;
  698. return &id;
  699. }
  700. struct any_storage {
  701. virtual ~any_storage() = default;
  702. virtual std::unique_ptr<any_storage> clone() const = 0;
  703. virtual any_type_id type_id() const noexcept = 0;
  704. };
  705. template <typename T> struct any_value final : any_storage {
  706. T value;
  707. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  708. std::unique_ptr<any_storage> clone() const override {
  709. return std::unique_ptr<any_storage>(new any_value<T>(value));
  710. }
  711. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  712. };
  713. } // namespace detail
  714. class any {
  715. std::unique_ptr<detail::any_storage> storage_;
  716. public:
  717. any() noexcept = default;
  718. any(const any &o) : storage_(o.storage_ ? o.storage_->clone() : nullptr) {}
  719. any(any &&) noexcept = default;
  720. any &operator=(const any &o) {
  721. storage_ = o.storage_ ? o.storage_->clone() : nullptr;
  722. return *this;
  723. }
  724. any &operator=(any &&) noexcept = default;
  725. template <
  726. typename T, typename D = typename std::decay<T>::type,
  727. typename std::enable_if<!std::is_same<D, any>::value, int>::type = 0>
  728. any(T &&v) : storage_(new detail::any_value<D>(std::forward<T>(v))) {}
  729. template <
  730. typename T, typename D = typename std::decay<T>::type,
  731. typename std::enable_if<!std::is_same<D, any>::value, int>::type = 0>
  732. any &operator=(T &&v) {
  733. storage_.reset(new detail::any_value<D>(std::forward<T>(v)));
  734. return *this;
  735. }
  736. bool has_value() const noexcept { return storage_ != nullptr; }
  737. void reset() noexcept { storage_.reset(); }
  738. template <typename T> friend T *any_cast(any *a) noexcept;
  739. template <typename T> friend const T *any_cast(const any *a) noexcept;
  740. };
  741. template <typename T> T *any_cast(any *a) noexcept {
  742. if (!a || !a->storage_) { return nullptr; }
  743. if (a->storage_->type_id() != detail::any_typeid<T>()) { return nullptr; }
  744. return &static_cast<detail::any_value<T> *>(a->storage_.get())->value;
  745. }
  746. template <typename T> const T *any_cast(const any *a) noexcept {
  747. if (!a || !a->storage_) { return nullptr; }
  748. if (a->storage_->type_id() != detail::any_typeid<T>()) { return nullptr; }
  749. return &static_cast<const detail::any_value<T> *>(a->storage_.get())->value;
  750. }
  751. template <typename T> T any_cast(const any &a) {
  752. using U =
  753. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  754. const U *p = any_cast<U>(&a);
  755. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  756. if (!p) { throw bad_any_cast{}; }
  757. #else
  758. if (!p) { std::abort(); }
  759. #endif
  760. return static_cast<T>(*p);
  761. }
  762. template <typename T> T any_cast(any &a) {
  763. using U =
  764. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  765. U *p = any_cast<U>(&a);
  766. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  767. if (!p) { throw bad_any_cast{}; }
  768. #else
  769. if (!p) { std::abort(); }
  770. #endif
  771. return static_cast<T>(*p);
  772. }
  773. template <typename T> T any_cast(any &&a) {
  774. using U =
  775. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  776. U *p = any_cast<U>(&a);
  777. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  778. if (!p) { throw bad_any_cast{}; }
  779. #else
  780. if (!p) { std::abort(); }
  781. #endif
  782. return static_cast<T>(std::move(*p));
  783. }
  784. #endif // __cplusplus >= 201703L
  785. struct Response;
  786. using ResponseHandler = std::function<bool(const Response &response)>;
  787. struct FormData {
  788. std::string name;
  789. std::string content;
  790. std::string filename;
  791. std::string content_type;
  792. Headers headers;
  793. };
  794. struct FormField {
  795. std::string name;
  796. std::string content;
  797. Headers headers;
  798. };
  799. using FormFields = std::multimap<std::string, FormField>;
  800. using FormFiles = std::multimap<std::string, FormData>;
  801. struct MultipartFormData {
  802. FormFields fields; // Text fields from multipart
  803. FormFiles files; // Files from multipart
  804. // Text field access
  805. std::string get_field(const std::string &key, size_t id = 0) const;
  806. std::vector<std::string> get_fields(const std::string &key) const;
  807. bool has_field(const std::string &key) const;
  808. size_t get_field_count(const std::string &key) const;
  809. // File access
  810. FormData get_file(const std::string &key, size_t id = 0) const;
  811. std::vector<FormData> get_files(const std::string &key) const;
  812. bool has_file(const std::string &key) const;
  813. size_t get_file_count(const std::string &key) const;
  814. };
  815. struct UploadFormData {
  816. std::string name;
  817. std::string content;
  818. std::string filename;
  819. std::string content_type;
  820. };
  821. using UploadFormDataItems = std::vector<UploadFormData>;
  822. class DataSink {
  823. public:
  824. DataSink() : os(&sb_), sb_(*this) {}
  825. DataSink(const DataSink &) = delete;
  826. DataSink &operator=(const DataSink &) = delete;
  827. DataSink(DataSink &&) = delete;
  828. DataSink &operator=(DataSink &&) = delete;
  829. std::function<bool(const char *data, size_t data_len)> write;
  830. std::function<bool()> is_writable;
  831. std::function<void()> done;
  832. std::function<void(const Headers &trailer)> done_with_trailer;
  833. std::ostream os;
  834. private:
  835. class data_sink_streambuf final : public std::streambuf {
  836. public:
  837. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  838. protected:
  839. std::streamsize xsputn(const char *s, std::streamsize n) override {
  840. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  841. return 0;
  842. }
  843. private:
  844. DataSink &sink_;
  845. };
  846. data_sink_streambuf sb_;
  847. };
  848. using ContentProvider =
  849. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  850. using ContentProviderWithoutLength =
  851. std::function<bool(size_t offset, DataSink &sink)>;
  852. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  853. struct FormDataProvider {
  854. std::string name;
  855. ContentProviderWithoutLength provider;
  856. std::string filename;
  857. std::string content_type;
  858. };
  859. using FormDataProviderItems = std::vector<FormDataProvider>;
  860. inline FormDataProvider
  861. make_file_provider(const std::string &name, const std::string &filepath,
  862. const std::string &filename = std::string(),
  863. const std::string &content_type = std::string()) {
  864. FormDataProvider fdp;
  865. fdp.name = name;
  866. fdp.filename = filename.empty() ? filepath : filename;
  867. fdp.content_type = content_type;
  868. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  869. std::ifstream f(filepath, std::ios::binary);
  870. if (!f) { return false; }
  871. if (offset > 0) {
  872. f.seekg(static_cast<std::streamoff>(offset));
  873. if (!f.good()) {
  874. sink.done();
  875. return true;
  876. }
  877. }
  878. char buf[8192];
  879. f.read(buf, sizeof(buf));
  880. auto n = static_cast<size_t>(f.gcount());
  881. if (n > 0) { return sink.write(buf, n); }
  882. sink.done(); // EOF
  883. return true;
  884. };
  885. return fdp;
  886. }
  887. inline std::pair<size_t, ContentProvider>
  888. make_file_body(const std::string &filepath) {
  889. size_t size = 0;
  890. {
  891. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  892. if (!f) { return {0, ContentProvider{}}; }
  893. size = static_cast<size_t>(f.tellg());
  894. }
  895. ContentProvider provider = [filepath](size_t offset, size_t length,
  896. DataSink &sink) -> bool {
  897. std::ifstream f(filepath, std::ios::binary);
  898. if (!f) { return false; }
  899. f.seekg(static_cast<std::streamoff>(offset));
  900. if (!f.good()) { return false; }
  901. char buf[8192];
  902. while (length > 0) {
  903. auto to_read = (std::min)(sizeof(buf), length);
  904. f.read(buf, static_cast<std::streamsize>(to_read));
  905. auto n = static_cast<size_t>(f.gcount());
  906. if (n == 0) { break; }
  907. if (!sink.write(buf, n)) { return false; }
  908. length -= n;
  909. }
  910. return true;
  911. };
  912. return {size, std::move(provider)};
  913. }
  914. using ContentReceiverWithProgress = std::function<bool(
  915. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  916. using ContentReceiver =
  917. std::function<bool(const char *data, size_t data_length)>;
  918. using FormDataHeader = std::function<bool(const FormData &file)>;
  919. class ContentReader {
  920. public:
  921. using Reader = std::function<bool(ContentReceiver receiver)>;
  922. using FormDataReader =
  923. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  924. ContentReader(Reader reader, FormDataReader multipart_reader)
  925. : reader_(std::move(reader)),
  926. formdata_reader_(std::move(multipart_reader)) {}
  927. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  928. return formdata_reader_(std::move(header), std::move(receiver));
  929. }
  930. bool operator()(ContentReceiver receiver) const {
  931. return reader_(std::move(receiver));
  932. }
  933. Reader reader_;
  934. FormDataReader formdata_reader_;
  935. };
  936. using Range = std::pair<ssize_t, ssize_t>;
  937. using Ranges = std::vector<Range>;
  938. #ifdef CPPHTTPLIB_SSL_ENABLED
  939. // TLS abstraction layer - public type definitions and API
  940. namespace tls {
  941. // Opaque handles (defined as void* for abstraction)
  942. using ctx_t = void *;
  943. using session_t = void *;
  944. using const_session_t = const void *; // For read-only session access
  945. using cert_t = void *;
  946. using ca_store_t = void *;
  947. // TLS versions
  948. enum class Version {
  949. TLS1_2 = 0x0303,
  950. TLS1_3 = 0x0304,
  951. };
  952. // Subject Alternative Names (SAN) entry types
  953. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  954. // SAN entry structure
  955. struct SanEntry {
  956. SanType type;
  957. std::string value;
  958. };
  959. // Verification context for certificate verification callback
  960. struct VerifyContext {
  961. session_t session; // TLS session handle
  962. cert_t cert; // Current certificate being verified
  963. int depth; // Certificate chain depth (0 = leaf)
  964. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  965. long error_code; // Backend-specific error code (0 = no error)
  966. const char *error_string; // Human-readable error description
  967. // Certificate introspection methods
  968. std::string subject_cn() const;
  969. std::string issuer_name() const;
  970. bool check_hostname(const char *hostname) const;
  971. std::vector<SanEntry> sans() const;
  972. bool validity(time_t &not_before, time_t &not_after) const;
  973. std::string serial() const;
  974. };
  975. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  976. // TlsError codes for TLS operations (backend-independent)
  977. enum class ErrorCode : int {
  978. Success = 0,
  979. WantRead, // Non-blocking: need to wait for read
  980. WantWrite, // Non-blocking: need to wait for write
  981. PeerClosed, // Peer closed the connection
  982. Fatal, // Unrecoverable error
  983. SyscallError, // System call error (check sys_errno)
  984. CertVerifyFailed, // Certificate verification failed
  985. HostnameMismatch, // Hostname verification failed
  986. };
  987. // TLS error information
  988. struct TlsError {
  989. ErrorCode code = ErrorCode::Fatal;
  990. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  991. int sys_errno = 0; // errno when SyscallError
  992. // Convert verification error code to human-readable string
  993. static std::string verify_error_to_string(long error_code);
  994. };
  995. // RAII wrapper for peer certificate
  996. class PeerCert {
  997. public:
  998. PeerCert();
  999. PeerCert(PeerCert &&other) noexcept;
  1000. PeerCert &operator=(PeerCert &&other) noexcept;
  1001. ~PeerCert();
  1002. PeerCert(const PeerCert &) = delete;
  1003. PeerCert &operator=(const PeerCert &) = delete;
  1004. explicit operator bool() const;
  1005. std::string subject_cn() const;
  1006. std::string issuer_name() const;
  1007. bool check_hostname(const char *hostname) const;
  1008. std::vector<SanEntry> sans() const;
  1009. bool validity(time_t &not_before, time_t &not_after) const;
  1010. std::string serial() const;
  1011. private:
  1012. explicit PeerCert(cert_t cert);
  1013. cert_t cert_ = nullptr;
  1014. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1015. };
  1016. // Callback for TLS context setup (used by SSLServer constructor)
  1017. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1018. } // namespace tls
  1019. #endif
  1020. struct Request {
  1021. std::string method;
  1022. std::string path;
  1023. std::string matched_route;
  1024. Params params;
  1025. Headers headers;
  1026. Headers trailers;
  1027. std::string body;
  1028. std::string remote_addr;
  1029. int remote_port = -1;
  1030. std::string local_addr;
  1031. int local_port = -1;
  1032. // for server
  1033. std::string version;
  1034. std::string target;
  1035. MultipartFormData form;
  1036. Ranges ranges;
  1037. Match matches;
  1038. std::unordered_map<std::string, std::string> path_params;
  1039. std::function<bool()> is_connection_closed = []() { return true; };
  1040. // for client
  1041. std::vector<std::string> accept_content_types;
  1042. ResponseHandler response_handler;
  1043. ContentReceiverWithProgress content_receiver;
  1044. DownloadProgress download_progress;
  1045. UploadProgress upload_progress;
  1046. bool has_header(const std::string &key) const;
  1047. std::string get_header_value(const std::string &key, const char *def = "",
  1048. size_t id = 0) const;
  1049. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1050. size_t id = 0) const;
  1051. size_t get_header_value_count(const std::string &key) const;
  1052. void set_header(const std::string &key, const std::string &val);
  1053. bool has_trailer(const std::string &key) const;
  1054. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1055. size_t get_trailer_value_count(const std::string &key) const;
  1056. bool has_param(const std::string &key) const;
  1057. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1058. size_t get_param_value_count(const std::string &key) const;
  1059. bool is_multipart_form_data() const;
  1060. // private members...
  1061. bool body_consumed_ = false;
  1062. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1063. size_t content_length_ = 0;
  1064. ContentProvider content_provider_;
  1065. bool is_chunked_content_provider_ = false;
  1066. size_t authorization_count_ = 0;
  1067. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1068. (std::chrono::steady_clock::time_point::min)();
  1069. #ifdef CPPHTTPLIB_SSL_ENABLED
  1070. tls::const_session_t ssl = nullptr;
  1071. tls::PeerCert peer_cert() const;
  1072. std::string sni() const;
  1073. #endif
  1074. };
  1075. struct Response {
  1076. std::string version;
  1077. int status = -1;
  1078. std::string reason;
  1079. Headers headers;
  1080. Headers trailers;
  1081. std::string body;
  1082. std::string location; // Redirect location
  1083. // User-defined context — set by pre-routing/pre-request handlers and read
  1084. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1085. std::map<std::string, any> user_data;
  1086. bool has_header(const std::string &key) const;
  1087. std::string get_header_value(const std::string &key, const char *def = "",
  1088. size_t id = 0) const;
  1089. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1090. size_t id = 0) const;
  1091. size_t get_header_value_count(const std::string &key) const;
  1092. void set_header(const std::string &key, const std::string &val);
  1093. bool has_trailer(const std::string &key) const;
  1094. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1095. size_t get_trailer_value_count(const std::string &key) const;
  1096. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1097. void set_content(const char *s, size_t n, const std::string &content_type);
  1098. void set_content(const std::string &s, const std::string &content_type);
  1099. void set_content(std::string &&s, const std::string &content_type);
  1100. void set_content_provider(
  1101. size_t length, const std::string &content_type, ContentProvider provider,
  1102. ContentProviderResourceReleaser resource_releaser = nullptr);
  1103. void set_content_provider(
  1104. const std::string &content_type, ContentProviderWithoutLength provider,
  1105. ContentProviderResourceReleaser resource_releaser = nullptr);
  1106. void set_chunked_content_provider(
  1107. const std::string &content_type, ContentProviderWithoutLength provider,
  1108. ContentProviderResourceReleaser resource_releaser = nullptr);
  1109. void set_file_content(const std::string &path,
  1110. const std::string &content_type);
  1111. void set_file_content(const std::string &path);
  1112. Response() = default;
  1113. Response(const Response &) = default;
  1114. Response &operator=(const Response &) = default;
  1115. Response(Response &&) = default;
  1116. Response &operator=(Response &&) = default;
  1117. ~Response() {
  1118. if (content_provider_resource_releaser_) {
  1119. content_provider_resource_releaser_(content_provider_success_);
  1120. }
  1121. }
  1122. // private members...
  1123. size_t content_length_ = 0;
  1124. ContentProvider content_provider_;
  1125. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1126. bool is_chunked_content_provider_ = false;
  1127. bool content_provider_success_ = false;
  1128. std::string file_content_path_;
  1129. std::string file_content_content_type_;
  1130. };
  1131. enum class Error {
  1132. Success = 0,
  1133. Unknown,
  1134. Connection,
  1135. BindIPAddress,
  1136. Read,
  1137. Write,
  1138. ExceedRedirectCount,
  1139. Canceled,
  1140. SSLConnection,
  1141. SSLLoadingCerts,
  1142. SSLServerVerification,
  1143. SSLServerHostnameVerification,
  1144. UnsupportedMultipartBoundaryChars,
  1145. Compression,
  1146. ConnectionTimeout,
  1147. ProxyConnection,
  1148. ConnectionClosed,
  1149. Timeout,
  1150. ResourceExhaustion,
  1151. TooManyFormDataFiles,
  1152. ExceedMaxPayloadSize,
  1153. ExceedUriMaxLength,
  1154. ExceedMaxSocketDescriptorCount,
  1155. InvalidRequestLine,
  1156. InvalidHTTPMethod,
  1157. InvalidHTTPVersion,
  1158. InvalidHeaders,
  1159. MultipartParsing,
  1160. OpenFile,
  1161. Listen,
  1162. GetSockName,
  1163. UnsupportedAddressFamily,
  1164. HTTPParsing,
  1165. InvalidRangeHeader,
  1166. // For internal use only
  1167. SSLPeerCouldBeClosed_,
  1168. };
  1169. std::string to_string(Error error);
  1170. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1171. class Stream {
  1172. public:
  1173. virtual ~Stream() = default;
  1174. virtual bool is_readable() const = 0;
  1175. virtual bool wait_readable() const = 0;
  1176. virtual bool wait_writable() const = 0;
  1177. virtual bool is_peer_alive() const { return wait_writable(); }
  1178. virtual ssize_t read(char *ptr, size_t size) = 0;
  1179. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1180. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1181. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1182. virtual socket_t socket() const = 0;
  1183. virtual time_t duration() const = 0;
  1184. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1185. (void)sec;
  1186. (void)usec;
  1187. }
  1188. ssize_t write(const char *ptr);
  1189. ssize_t write(const std::string &s);
  1190. Error get_error() const { return error_; }
  1191. protected:
  1192. Error error_ = Error::Success;
  1193. };
  1194. class TaskQueue {
  1195. public:
  1196. TaskQueue() = default;
  1197. virtual ~TaskQueue() = default;
  1198. virtual bool enqueue(std::function<void()> fn) = 0;
  1199. virtual void shutdown() = 0;
  1200. virtual void on_idle() {}
  1201. };
  1202. class ThreadPool final : public TaskQueue {
  1203. public:
  1204. explicit ThreadPool(size_t n, size_t max_n = 0, size_t mqr = 0);
  1205. ThreadPool(const ThreadPool &) = delete;
  1206. ~ThreadPool() override = default;
  1207. bool enqueue(std::function<void()> fn) override;
  1208. void shutdown() override;
  1209. private:
  1210. void worker(bool is_dynamic);
  1211. void move_to_finished(std::thread::id id);
  1212. void cleanup_finished_threads();
  1213. size_t base_thread_count_;
  1214. size_t max_thread_count_;
  1215. size_t max_queued_requests_;
  1216. size_t idle_thread_count_;
  1217. bool shutdown_;
  1218. std::list<std::function<void()>> jobs_;
  1219. std::vector<std::thread> threads_; // base threads
  1220. std::list<std::thread> dynamic_threads_; // dynamic threads
  1221. std::vector<std::thread>
  1222. finished_threads_; // exited dynamic threads awaiting join
  1223. std::condition_variable cond_;
  1224. std::mutex mutex_;
  1225. };
  1226. using Logger = std::function<void(const Request &, const Response &)>;
  1227. // Forward declaration for Error type
  1228. enum class Error;
  1229. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1230. using SocketOptions = std::function<void(socket_t sock)>;
  1231. void default_socket_options(socket_t sock);
  1232. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1233. const char *status_message(int status);
  1234. std::string to_string(Error error);
  1235. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1236. std::string get_bearer_token_auth(const Request &req);
  1237. namespace detail {
  1238. class MatcherBase {
  1239. public:
  1240. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1241. virtual ~MatcherBase() = default;
  1242. const std::string &pattern() const { return pattern_; }
  1243. // Match request path and populate its matches and
  1244. virtual bool match(Request &request) const = 0;
  1245. private:
  1246. std::string pattern_;
  1247. };
  1248. /**
  1249. * Captures parameters in request path and stores them in Request::path_params
  1250. *
  1251. * Capture name is a substring of a pattern from : to /.
  1252. * The rest of the pattern is matched against the request path directly
  1253. * Parameters are captured starting from the next character after
  1254. * the end of the last matched static pattern fragment until the next /.
  1255. *
  1256. * Example pattern:
  1257. * "/path/fragments/:capture/more/fragments/:second_capture"
  1258. * Static fragments:
  1259. * "/path/fragments/", "more/fragments/"
  1260. *
  1261. * Given the following request path:
  1262. * "/path/fragments/:1/more/fragments/:2"
  1263. * the resulting capture will be
  1264. * {{"capture", "1"}, {"second_capture", "2"}}
  1265. */
  1266. class PathParamsMatcher final : public MatcherBase {
  1267. public:
  1268. PathParamsMatcher(const std::string &pattern);
  1269. bool match(Request &request) const override;
  1270. private:
  1271. // Treat segment separators as the end of path parameter capture
  1272. // Does not need to handle query parameters as they are parsed before path
  1273. // matching
  1274. static constexpr char separator = '/';
  1275. // Contains static path fragments to match against, excluding the '/' after
  1276. // path params
  1277. // Fragments are separated by path params
  1278. std::vector<std::string> static_fragments_;
  1279. // Stores the names of the path parameters to be used as keys in the
  1280. // Request::path_params map
  1281. std::vector<std::string> param_names_;
  1282. };
  1283. /**
  1284. * Performs std::regex_match on request path
  1285. * and stores the result in Request::matches
  1286. *
  1287. * Note that regex match is performed directly on the whole request.
  1288. * This means that wildcard patterns may match multiple path segments with /:
  1289. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1290. */
  1291. class RegexMatcher final : public MatcherBase {
  1292. public:
  1293. RegexMatcher(const std::string &pattern)
  1294. : MatcherBase(pattern), regex_(pattern) {}
  1295. bool match(Request &request) const override;
  1296. private:
  1297. std::regex regex_;
  1298. };
  1299. int close_socket(socket_t sock);
  1300. ssize_t write_headers(Stream &strm, const Headers &headers);
  1301. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1302. time_t usec);
  1303. } // namespace detail
  1304. class Server {
  1305. public:
  1306. using Handler = std::function<void(const Request &, Response &)>;
  1307. using ExceptionHandler =
  1308. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1309. enum class HandlerResponse {
  1310. Handled,
  1311. Unhandled,
  1312. };
  1313. using HandlerWithResponse =
  1314. std::function<HandlerResponse(const Request &, Response &)>;
  1315. using HandlerWithContentReader = std::function<void(
  1316. const Request &, Response &, const ContentReader &content_reader)>;
  1317. using Expect100ContinueHandler =
  1318. std::function<int(const Request &, Response &)>;
  1319. using WebSocketHandler =
  1320. std::function<void(const Request &, ws::WebSocket &)>;
  1321. using SubProtocolSelector =
  1322. std::function<std::string(const std::vector<std::string> &protocols)>;
  1323. Server();
  1324. virtual ~Server();
  1325. virtual bool is_valid() const;
  1326. Server &Get(const std::string &pattern, Handler handler);
  1327. Server &Post(const std::string &pattern, Handler handler);
  1328. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1329. Server &Put(const std::string &pattern, Handler handler);
  1330. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1331. Server &Patch(const std::string &pattern, Handler handler);
  1332. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1333. Server &Delete(const std::string &pattern, Handler handler);
  1334. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1335. Server &Options(const std::string &pattern, Handler handler);
  1336. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1337. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1338. SubProtocolSelector sub_protocol_selector);
  1339. bool set_base_dir(const std::string &dir,
  1340. const std::string &mount_point = std::string());
  1341. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1342. Headers headers = Headers());
  1343. bool remove_mount_point(const std::string &mount_point);
  1344. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1345. const std::string &mime);
  1346. Server &set_default_file_mimetype(const std::string &mime);
  1347. Server &set_file_request_handler(Handler handler);
  1348. template <class ErrorHandlerFunc>
  1349. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1350. return set_error_handler_core(
  1351. std::forward<ErrorHandlerFunc>(handler),
  1352. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1353. }
  1354. Server &set_exception_handler(ExceptionHandler handler);
  1355. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1356. Server &set_post_routing_handler(Handler handler);
  1357. Server &set_pre_request_handler(HandlerWithResponse handler);
  1358. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1359. Server &set_logger(Logger logger);
  1360. Server &set_pre_compression_logger(Logger logger);
  1361. Server &set_error_logger(ErrorLogger error_logger);
  1362. Server &set_address_family(int family);
  1363. Server &set_tcp_nodelay(bool on);
  1364. Server &set_ipv6_v6only(bool on);
  1365. Server &set_socket_options(SocketOptions socket_options);
  1366. Server &set_default_headers(Headers headers);
  1367. Server &
  1368. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1369. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1370. Server &set_keep_alive_max_count(size_t count);
  1371. Server &set_keep_alive_timeout(time_t sec);
  1372. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1373. template <class Rep, class Period>
  1374. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1375. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1376. template <class Rep, class Period>
  1377. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1378. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1379. template <class Rep, class Period>
  1380. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1381. Server &set_payload_max_length(size_t length);
  1382. Server &set_websocket_ping_interval(time_t sec);
  1383. template <class Rep, class Period>
  1384. Server &set_websocket_ping_interval(
  1385. const std::chrono::duration<Rep, Period> &duration);
  1386. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1387. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1388. bool listen_after_bind();
  1389. bool listen(const std::string &host, int port, int socket_flags = 0);
  1390. bool is_running() const;
  1391. void wait_until_ready() const;
  1392. void stop();
  1393. void decommission();
  1394. std::function<TaskQueue *(void)> new_task_queue;
  1395. protected:
  1396. bool process_request(Stream &strm, const std::string &remote_addr,
  1397. int remote_port, const std::string &local_addr,
  1398. int local_port, bool close_connection,
  1399. bool &connection_closed,
  1400. const std::function<void(Request &)> &setup_request,
  1401. bool *websocket_upgraded = nullptr);
  1402. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1403. std::vector<std::string> trusted_proxies_;
  1404. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1405. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1406. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1407. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1408. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1409. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1410. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1411. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1412. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1413. time_t websocket_ping_interval_sec_ =
  1414. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1415. private:
  1416. using Handlers =
  1417. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1418. using HandlersForContentReader =
  1419. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1420. HandlerWithContentReader>>;
  1421. static std::unique_ptr<detail::MatcherBase>
  1422. make_matcher(const std::string &pattern);
  1423. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1424. Server &set_error_handler_core(Handler handler, std::false_type);
  1425. socket_t create_server_socket(const std::string &host, int port,
  1426. int socket_flags,
  1427. SocketOptions socket_options) const;
  1428. int bind_internal(const std::string &host, int port, int socket_flags);
  1429. bool listen_internal();
  1430. bool routing(Request &req, Response &res, Stream &strm);
  1431. bool handle_file_request(Request &req, Response &res);
  1432. bool check_if_not_modified(const Request &req, Response &res,
  1433. const std::string &etag, time_t mtime) const;
  1434. bool check_if_range(Request &req, const std::string &etag,
  1435. time_t mtime) const;
  1436. bool dispatch_request(Request &req, Response &res,
  1437. const Handlers &handlers) const;
  1438. bool dispatch_request_for_content_reader(
  1439. Request &req, Response &res, ContentReader content_reader,
  1440. const HandlersForContentReader &handlers) const;
  1441. bool parse_request_line(const char *s, Request &req) const;
  1442. void apply_ranges(const Request &req, Response &res,
  1443. std::string &content_type, std::string &boundary) const;
  1444. bool write_response(Stream &strm, bool close_connection, Request &req,
  1445. Response &res);
  1446. bool write_response_with_content(Stream &strm, bool close_connection,
  1447. const Request &req, Response &res);
  1448. bool write_response_core(Stream &strm, bool close_connection,
  1449. const Request &req, Response &res,
  1450. bool need_apply_ranges);
  1451. bool write_content_with_provider(Stream &strm, const Request &req,
  1452. Response &res, const std::string &boundary,
  1453. const std::string &content_type);
  1454. bool read_content(Stream &strm, Request &req, Response &res);
  1455. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1456. Response &res,
  1457. ContentReceiver receiver,
  1458. FormDataHeader multipart_header,
  1459. ContentReceiver multipart_receiver);
  1460. bool read_content_core(Stream &strm, Request &req, Response &res,
  1461. ContentReceiver receiver,
  1462. FormDataHeader multipart_header,
  1463. ContentReceiver multipart_receiver) const;
  1464. virtual bool process_and_close_socket(socket_t sock);
  1465. void output_log(const Request &req, const Response &res) const;
  1466. void output_pre_compression_log(const Request &req,
  1467. const Response &res) const;
  1468. void output_error_log(const Error &err, const Request *req) const;
  1469. std::atomic<bool> is_running_{false};
  1470. std::atomic<bool> is_decommissioned{false};
  1471. struct MountPointEntry {
  1472. std::string mount_point;
  1473. std::string base_dir;
  1474. std::string resolved_base_dir;
  1475. Headers headers;
  1476. };
  1477. std::vector<MountPointEntry> base_dirs_;
  1478. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1479. std::string default_file_mimetype_ = "application/octet-stream";
  1480. Handler file_request_handler_;
  1481. Handlers get_handlers_;
  1482. Handlers post_handlers_;
  1483. HandlersForContentReader post_handlers_for_content_reader_;
  1484. Handlers put_handlers_;
  1485. HandlersForContentReader put_handlers_for_content_reader_;
  1486. Handlers patch_handlers_;
  1487. HandlersForContentReader patch_handlers_for_content_reader_;
  1488. Handlers delete_handlers_;
  1489. HandlersForContentReader delete_handlers_for_content_reader_;
  1490. Handlers options_handlers_;
  1491. struct WebSocketHandlerEntry {
  1492. std::unique_ptr<detail::MatcherBase> matcher;
  1493. WebSocketHandler handler;
  1494. SubProtocolSelector sub_protocol_selector;
  1495. };
  1496. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1497. WebSocketHandlers websocket_handlers_;
  1498. HandlerWithResponse error_handler_;
  1499. ExceptionHandler exception_handler_;
  1500. HandlerWithResponse pre_routing_handler_;
  1501. Handler post_routing_handler_;
  1502. HandlerWithResponse pre_request_handler_;
  1503. Expect100ContinueHandler expect_100_continue_handler_;
  1504. mutable std::mutex logger_mutex_;
  1505. Logger logger_;
  1506. Logger pre_compression_logger_;
  1507. ErrorLogger error_logger_;
  1508. int address_family_ = AF_UNSPEC;
  1509. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1510. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1511. SocketOptions socket_options_ = default_socket_options;
  1512. Headers default_headers_;
  1513. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1514. detail::write_headers;
  1515. };
  1516. class Result {
  1517. public:
  1518. Result() = default;
  1519. Result(std::unique_ptr<Response> &&res, Error err,
  1520. Headers &&request_headers = Headers{})
  1521. : res_(std::move(res)), err_(err),
  1522. request_headers_(std::move(request_headers)) {}
  1523. // Response
  1524. operator bool() const { return res_ != nullptr; }
  1525. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1526. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1527. const Response &value() const { return *res_; }
  1528. Response &value() { return *res_; }
  1529. const Response &operator*() const { return *res_; }
  1530. Response &operator*() { return *res_; }
  1531. const Response *operator->() const { return res_.get(); }
  1532. Response *operator->() { return res_.get(); }
  1533. // Error
  1534. Error error() const { return err_; }
  1535. // Request Headers
  1536. bool has_request_header(const std::string &key) const;
  1537. std::string get_request_header_value(const std::string &key,
  1538. const char *def = "",
  1539. size_t id = 0) const;
  1540. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1541. size_t id = 0) const;
  1542. size_t get_request_header_value_count(const std::string &key) const;
  1543. private:
  1544. std::unique_ptr<Response> res_;
  1545. Error err_ = Error::Unknown;
  1546. Headers request_headers_;
  1547. #ifdef CPPHTTPLIB_SSL_ENABLED
  1548. public:
  1549. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1550. int ssl_error)
  1551. : res_(std::move(res)), err_(err),
  1552. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1553. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1554. int ssl_error, uint64_t ssl_backend_error)
  1555. : res_(std::move(res)), err_(err),
  1556. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1557. ssl_backend_error_(ssl_backend_error) {}
  1558. int ssl_error() const { return ssl_error_; }
  1559. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1560. private:
  1561. int ssl_error_ = 0;
  1562. uint64_t ssl_backend_error_ = 0;
  1563. #endif
  1564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1565. public:
  1566. [[deprecated("Use ssl_backend_error() instead. "
  1567. "This function will be removed by v1.0.0.")]]
  1568. uint64_t ssl_openssl_error() const {
  1569. return ssl_backend_error_;
  1570. }
  1571. #endif
  1572. };
  1573. struct ClientConnection {
  1574. socket_t sock = INVALID_SOCKET;
  1575. bool is_open() const { return sock != INVALID_SOCKET; }
  1576. ClientConnection() = default;
  1577. ~ClientConnection();
  1578. ClientConnection(const ClientConnection &) = delete;
  1579. ClientConnection &operator=(const ClientConnection &) = delete;
  1580. ClientConnection(ClientConnection &&other) noexcept
  1581. : sock(other.sock)
  1582. #ifdef CPPHTTPLIB_SSL_ENABLED
  1583. ,
  1584. session(other.session)
  1585. #endif
  1586. {
  1587. other.sock = INVALID_SOCKET;
  1588. #ifdef CPPHTTPLIB_SSL_ENABLED
  1589. other.session = nullptr;
  1590. #endif
  1591. }
  1592. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1593. if (this != &other) {
  1594. sock = other.sock;
  1595. other.sock = INVALID_SOCKET;
  1596. #ifdef CPPHTTPLIB_SSL_ENABLED
  1597. session = other.session;
  1598. other.session = nullptr;
  1599. #endif
  1600. }
  1601. return *this;
  1602. }
  1603. #ifdef CPPHTTPLIB_SSL_ENABLED
  1604. tls::session_t session = nullptr;
  1605. #endif
  1606. };
  1607. namespace detail {
  1608. struct ChunkedDecoder;
  1609. struct BodyReader {
  1610. Stream *stream = nullptr;
  1611. bool has_content_length = false;
  1612. size_t content_length = 0;
  1613. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1614. size_t bytes_read = 0;
  1615. bool chunked = false;
  1616. bool eof = false;
  1617. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1618. Error last_error = Error::Success;
  1619. ssize_t read(char *buf, size_t len);
  1620. bool has_error() const { return last_error != Error::Success; }
  1621. };
  1622. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1623. size_t len) {
  1624. (void)stream;
  1625. return br.read(buf, len);
  1626. }
  1627. class decompressor;
  1628. } // namespace detail
  1629. class ClientImpl {
  1630. public:
  1631. explicit ClientImpl(const std::string &host);
  1632. explicit ClientImpl(const std::string &host, int port);
  1633. explicit ClientImpl(const std::string &host, int port,
  1634. const std::string &client_cert_path,
  1635. const std::string &client_key_path);
  1636. virtual ~ClientImpl();
  1637. virtual bool is_valid() const;
  1638. struct StreamHandle {
  1639. std::unique_ptr<Response> response;
  1640. Error error = Error::Success;
  1641. StreamHandle() = default;
  1642. StreamHandle(const StreamHandle &) = delete;
  1643. StreamHandle &operator=(const StreamHandle &) = delete;
  1644. StreamHandle(StreamHandle &&) = default;
  1645. StreamHandle &operator=(StreamHandle &&) = default;
  1646. ~StreamHandle() = default;
  1647. bool is_valid() const {
  1648. return response != nullptr && error == Error::Success;
  1649. }
  1650. ssize_t read(char *buf, size_t len);
  1651. void parse_trailers_if_needed();
  1652. Error get_read_error() const { return body_reader_.last_error; }
  1653. bool has_read_error() const { return body_reader_.has_error(); }
  1654. bool trailers_parsed_ = false;
  1655. private:
  1656. friend class ClientImpl;
  1657. ssize_t read_with_decompression(char *buf, size_t len);
  1658. std::unique_ptr<ClientConnection> connection_;
  1659. std::unique_ptr<Stream> socket_stream_;
  1660. Stream *stream_ = nullptr;
  1661. detail::BodyReader body_reader_;
  1662. std::unique_ptr<detail::decompressor> decompressor_;
  1663. std::string decompress_buffer_;
  1664. size_t decompress_offset_ = 0;
  1665. size_t decompressed_bytes_read_ = 0;
  1666. };
  1667. // clang-format off
  1668. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1669. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1670. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1671. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1672. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1673. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1674. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1675. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1676. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1677. Result Head(const std::string &path);
  1678. Result Head(const std::string &path, const Headers &headers);
  1679. Result Post(const std::string &path);
  1680. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1681. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1682. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1683. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1684. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1685. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1686. Result Post(const std::string &path, const Params &params);
  1687. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1688. Result Post(const std::string &path, const Headers &headers);
  1689. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1690. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1691. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1692. 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);
  1693. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1694. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1695. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1696. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1697. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1698. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1699. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1700. Result Put(const std::string &path);
  1701. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1702. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1703. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1704. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1705. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1706. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1707. Result Put(const std::string &path, const Params &params);
  1708. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1709. Result Put(const std::string &path, const Headers &headers);
  1710. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1711. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1712. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1713. 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);
  1714. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1715. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1716. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1717. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1718. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1719. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1720. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1721. Result Patch(const std::string &path);
  1722. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1723. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1724. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1725. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1726. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1727. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1728. Result Patch(const std::string &path, const Params &params);
  1729. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1730. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1731. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1732. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1733. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1734. 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);
  1735. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1736. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1737. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1738. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1739. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1740. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1741. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1742. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1743. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1744. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1745. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1746. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1747. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1748. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1749. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1750. Result Options(const std::string &path);
  1751. Result Options(const std::string &path, const Headers &headers);
  1752. // clang-format on
  1753. // Streaming API: Open a stream for reading response body incrementally
  1754. // Socket ownership is transferred to StreamHandle for true streaming
  1755. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1756. StreamHandle open_stream(const std::string &method, const std::string &path,
  1757. const Params &params = {},
  1758. const Headers &headers = {},
  1759. const std::string &body = {},
  1760. const std::string &content_type = {});
  1761. bool send(Request &req, Response &res, Error &error);
  1762. Result send(const Request &req);
  1763. void stop();
  1764. std::string host() const;
  1765. int port() const;
  1766. size_t is_socket_open() const;
  1767. socket_t socket() const;
  1768. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1769. void set_default_headers(Headers headers);
  1770. void
  1771. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1772. void set_address_family(int family);
  1773. void set_tcp_nodelay(bool on);
  1774. void set_ipv6_v6only(bool on);
  1775. void set_socket_options(SocketOptions socket_options);
  1776. void set_connection_timeout(time_t sec, time_t usec = 0);
  1777. template <class Rep, class Period>
  1778. void
  1779. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1780. void set_read_timeout(time_t sec, time_t usec = 0);
  1781. template <class Rep, class Period>
  1782. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1783. void set_write_timeout(time_t sec, time_t usec = 0);
  1784. template <class Rep, class Period>
  1785. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1786. void set_max_timeout(time_t msec);
  1787. template <class Rep, class Period>
  1788. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1789. void set_basic_auth(const std::string &username, const std::string &password);
  1790. void set_bearer_token_auth(const std::string &token);
  1791. void set_keep_alive(bool on);
  1792. void set_follow_location(bool on);
  1793. void set_path_encode(bool on);
  1794. void set_compress(bool on);
  1795. void set_decompress(bool on);
  1796. void set_payload_max_length(size_t length);
  1797. void set_interface(const std::string &intf);
  1798. void set_proxy(const std::string &host, int port);
  1799. void set_proxy_basic_auth(const std::string &username,
  1800. const std::string &password);
  1801. void set_proxy_bearer_token_auth(const std::string &token);
  1802. void set_logger(Logger logger);
  1803. void set_error_logger(ErrorLogger error_logger);
  1804. protected:
  1805. struct Socket {
  1806. socket_t sock = INVALID_SOCKET;
  1807. // For Mbed TLS compatibility: start_time for request timeout tracking
  1808. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1809. bool is_open() const { return sock != INVALID_SOCKET; }
  1810. #ifdef CPPHTTPLIB_SSL_ENABLED
  1811. tls::session_t ssl = nullptr;
  1812. #endif
  1813. };
  1814. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1815. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1816. virtual bool setup_proxy_connection(
  1817. Socket &socket,
  1818. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1819. Response &res, bool &success, Error &error);
  1820. // All of:
  1821. // shutdown_ssl
  1822. // shutdown_socket
  1823. // close_socket
  1824. // should ONLY be called when socket_mutex_ is locked.
  1825. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1826. // with a DIFFERENT thread sending requests using that socket.
  1827. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1828. void shutdown_socket(Socket &socket) const;
  1829. void close_socket(Socket &socket);
  1830. bool process_request(Stream &strm, Request &req, Response &res,
  1831. bool close_connection, Error &error);
  1832. bool write_content_with_provider(Stream &strm, const Request &req,
  1833. Error &error) const;
  1834. void copy_settings(const ClientImpl &rhs);
  1835. void output_log(const Request &req, const Response &res) const;
  1836. void output_error_log(const Error &err, const Request *req) const;
  1837. // Socket endpoint information
  1838. const std::string host_;
  1839. const int port_;
  1840. // Current open socket
  1841. Socket socket_;
  1842. mutable std::mutex socket_mutex_;
  1843. std::recursive_mutex request_mutex_;
  1844. // These are all protected under socket_mutex
  1845. size_t socket_requests_in_flight_ = 0;
  1846. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1847. bool socket_should_be_closed_when_request_is_done_ = false;
  1848. // Hostname-IP map
  1849. std::map<std::string, std::string> addr_map_;
  1850. // Default headers
  1851. Headers default_headers_;
  1852. // Header writer
  1853. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1854. detail::write_headers;
  1855. // Settings
  1856. std::string client_cert_path_;
  1857. std::string client_key_path_;
  1858. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1859. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1860. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1861. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1862. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1863. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1864. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1865. std::string basic_auth_username_;
  1866. std::string basic_auth_password_;
  1867. std::string bearer_token_auth_token_;
  1868. bool keep_alive_ = false;
  1869. bool follow_location_ = false;
  1870. bool path_encode_ = true;
  1871. int address_family_ = AF_UNSPEC;
  1872. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1873. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1874. SocketOptions socket_options_ = nullptr;
  1875. bool compress_ = false;
  1876. bool decompress_ = true;
  1877. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1878. bool has_payload_max_length_ = false;
  1879. std::string interface_;
  1880. std::string proxy_host_;
  1881. int proxy_port_ = -1;
  1882. std::string proxy_basic_auth_username_;
  1883. std::string proxy_basic_auth_password_;
  1884. std::string proxy_bearer_token_auth_token_;
  1885. mutable std::mutex logger_mutex_;
  1886. Logger logger_;
  1887. ErrorLogger error_logger_;
  1888. private:
  1889. bool send_(Request &req, Response &res, Error &error);
  1890. Result send_(Request &&req);
  1891. socket_t create_client_socket(Error &error) const;
  1892. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1893. bool skip_100_continue = true) const;
  1894. bool write_request(Stream &strm, Request &req, bool close_connection,
  1895. Error &error, bool skip_body = false);
  1896. bool write_request_body(Stream &strm, Request &req, Error &error);
  1897. void prepare_default_headers(Request &r, bool for_stream,
  1898. const std::string &ct);
  1899. bool redirect(Request &req, Response &res, Error &error);
  1900. bool create_redirect_client(const std::string &scheme,
  1901. const std::string &host, int port, Request &req,
  1902. Response &res, const std::string &path,
  1903. const std::string &location, Error &error);
  1904. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1905. bool handle_request(Stream &strm, Request &req, Response &res,
  1906. bool close_connection, Error &error);
  1907. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1908. Request &req, const char *body, size_t content_length,
  1909. ContentProvider content_provider,
  1910. ContentProviderWithoutLength content_provider_without_length,
  1911. const std::string &content_type, ContentReceiver content_receiver,
  1912. Error &error);
  1913. Result send_with_content_provider_and_receiver(
  1914. const std::string &method, const std::string &path,
  1915. const Headers &headers, const char *body, size_t content_length,
  1916. ContentProvider content_provider,
  1917. ContentProviderWithoutLength content_provider_without_length,
  1918. const std::string &content_type, ContentReceiver content_receiver,
  1919. UploadProgress progress);
  1920. ContentProviderWithoutLength get_multipart_content_provider(
  1921. const std::string &boundary, const UploadFormDataItems &items,
  1922. const FormDataProviderItems &provider_items) const;
  1923. virtual bool
  1924. process_socket(const Socket &socket,
  1925. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1926. std::function<bool(Stream &strm)> callback);
  1927. virtual bool is_ssl() const;
  1928. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1929. #ifdef CPPHTTPLIB_SSL_ENABLED
  1930. public:
  1931. void set_digest_auth(const std::string &username,
  1932. const std::string &password);
  1933. void set_proxy_digest_auth(const std::string &username,
  1934. const std::string &password);
  1935. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1936. const std::string &ca_cert_dir_path = std::string());
  1937. void enable_server_certificate_verification(bool enabled);
  1938. void enable_server_hostname_verification(bool enabled);
  1939. protected:
  1940. std::string digest_auth_username_;
  1941. std::string digest_auth_password_;
  1942. std::string proxy_digest_auth_username_;
  1943. std::string proxy_digest_auth_password_;
  1944. std::string ca_cert_file_path_;
  1945. std::string ca_cert_dir_path_;
  1946. bool server_certificate_verification_ = true;
  1947. bool server_hostname_verification_ = true;
  1948. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1949. int last_ssl_error_ = 0;
  1950. uint64_t last_backend_error_ = 0;
  1951. #endif
  1952. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1953. public:
  1954. [[deprecated("Use load_ca_cert_store() instead. "
  1955. "This function will be removed by v1.0.0.")]]
  1956. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1957. [[deprecated("Use tls::create_ca_store() instead. "
  1958. "This function will be removed by v1.0.0.")]]
  1959. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1960. [[deprecated("Use set_server_certificate_verifier(VerifyCallback) instead. "
  1961. "This function will be removed by v1.0.0.")]]
  1962. virtual void set_server_certificate_verifier(
  1963. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1964. #endif
  1965. };
  1966. class Client {
  1967. public:
  1968. // Universal interface
  1969. explicit Client(const std::string &scheme_host_port);
  1970. explicit Client(const std::string &scheme_host_port,
  1971. const std::string &client_cert_path,
  1972. const std::string &client_key_path);
  1973. // HTTP only interface
  1974. explicit Client(const std::string &host, int port);
  1975. explicit Client(const std::string &host, int port,
  1976. const std::string &client_cert_path,
  1977. const std::string &client_key_path);
  1978. Client(Client &&) = default;
  1979. Client &operator=(Client &&) = default;
  1980. ~Client();
  1981. bool is_valid() const;
  1982. // clang-format off
  1983. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1984. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1985. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1986. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1987. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1988. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1989. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1990. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1991. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1992. Result Head(const std::string &path);
  1993. Result Head(const std::string &path, const Headers &headers);
  1994. Result Post(const std::string &path);
  1995. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1996. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1997. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1998. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1999. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2000. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2001. Result Post(const std::string &path, const Params &params);
  2002. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2003. Result Post(const std::string &path, const Headers &headers);
  2004. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2005. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2006. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2007. 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);
  2008. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2009. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2010. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2011. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2012. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2013. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2014. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2015. Result Put(const std::string &path);
  2016. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2017. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2018. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2019. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2020. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2021. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2022. Result Put(const std::string &path, const Params &params);
  2023. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2024. Result Put(const std::string &path, const Headers &headers);
  2025. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2026. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2027. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2028. 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);
  2029. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2030. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2031. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2032. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2033. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2034. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2035. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2036. Result Patch(const std::string &path);
  2037. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2038. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2039. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2040. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2041. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2042. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2043. Result Patch(const std::string &path, const Params &params);
  2044. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2045. Result Patch(const std::string &path, const Headers &headers);
  2046. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2047. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2048. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2049. 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);
  2050. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2051. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2052. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2053. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2054. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2055. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2056. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2057. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2058. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2059. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2060. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2061. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2062. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2063. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2064. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2065. Result Options(const std::string &path);
  2066. Result Options(const std::string &path, const Headers &headers);
  2067. // clang-format on
  2068. // Streaming API: Open a stream for reading response body incrementally
  2069. // Socket ownership is transferred to StreamHandle for true streaming
  2070. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2071. ClientImpl::StreamHandle open_stream(const std::string &method,
  2072. const std::string &path,
  2073. const Params &params = {},
  2074. const Headers &headers = {},
  2075. const std::string &body = {},
  2076. const std::string &content_type = {});
  2077. bool send(Request &req, Response &res, Error &error);
  2078. Result send(const Request &req);
  2079. void stop();
  2080. std::string host() const;
  2081. int port() const;
  2082. size_t is_socket_open() const;
  2083. socket_t socket() const;
  2084. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2085. void set_default_headers(Headers headers);
  2086. void
  2087. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2088. void set_address_family(int family);
  2089. void set_tcp_nodelay(bool on);
  2090. void set_socket_options(SocketOptions socket_options);
  2091. void set_connection_timeout(time_t sec, time_t usec = 0);
  2092. template <class Rep, class Period>
  2093. void
  2094. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2095. void set_read_timeout(time_t sec, time_t usec = 0);
  2096. template <class Rep, class Period>
  2097. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2098. void set_write_timeout(time_t sec, time_t usec = 0);
  2099. template <class Rep, class Period>
  2100. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2101. void set_max_timeout(time_t msec);
  2102. template <class Rep, class Period>
  2103. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2104. void set_basic_auth(const std::string &username, const std::string &password);
  2105. void set_bearer_token_auth(const std::string &token);
  2106. void set_keep_alive(bool on);
  2107. void set_follow_location(bool on);
  2108. void set_path_encode(bool on);
  2109. void set_url_encode(bool on);
  2110. void set_compress(bool on);
  2111. void set_decompress(bool on);
  2112. void set_payload_max_length(size_t length);
  2113. void set_interface(const std::string &intf);
  2114. void set_proxy(const std::string &host, int port);
  2115. void set_proxy_basic_auth(const std::string &username,
  2116. const std::string &password);
  2117. void set_proxy_bearer_token_auth(const std::string &token);
  2118. void set_logger(Logger logger);
  2119. void set_error_logger(ErrorLogger error_logger);
  2120. private:
  2121. std::unique_ptr<ClientImpl> cli_;
  2122. #ifdef CPPHTTPLIB_SSL_ENABLED
  2123. public:
  2124. void set_digest_auth(const std::string &username,
  2125. const std::string &password);
  2126. void set_proxy_digest_auth(const std::string &username,
  2127. const std::string &password);
  2128. void enable_server_certificate_verification(bool enabled);
  2129. void enable_server_hostname_verification(bool enabled);
  2130. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2131. const std::string &ca_cert_dir_path = std::string());
  2132. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2133. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2134. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2135. void set_session_verifier(
  2136. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2137. tls::ctx_t tls_context() const;
  2138. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2139. void enable_windows_certificate_verification(bool enabled);
  2140. #endif
  2141. private:
  2142. bool is_ssl_ = false;
  2143. #endif
  2144. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2145. public:
  2146. [[deprecated("Use tls_context() instead. "
  2147. "This function will be removed by v1.0.0.")]]
  2148. SSL_CTX *ssl_context() const;
  2149. [[deprecated("Use set_session_verifier(session_t) instead. "
  2150. "This function will be removed by v1.0.0.")]]
  2151. void set_server_certificate_verifier(
  2152. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  2153. [[deprecated("Use Result::ssl_backend_error() instead. "
  2154. "This function will be removed by v1.0.0.")]]
  2155. long get_verify_result() const;
  2156. #endif
  2157. };
  2158. #ifdef CPPHTTPLIB_SSL_ENABLED
  2159. class SSLServer : public Server {
  2160. public:
  2161. SSLServer(const char *cert_path, const char *private_key_path,
  2162. const char *client_ca_cert_file_path = nullptr,
  2163. const char *client_ca_cert_dir_path = nullptr,
  2164. const char *private_key_password = nullptr);
  2165. struct PemMemory {
  2166. const char *cert_pem;
  2167. size_t cert_pem_len;
  2168. const char *key_pem;
  2169. size_t key_pem_len;
  2170. const char *client_ca_pem;
  2171. size_t client_ca_pem_len;
  2172. const char *private_key_password;
  2173. };
  2174. explicit SSLServer(const PemMemory &pem);
  2175. // The callback receives the ctx_t handle which can be cast to the
  2176. // appropriate backend type (SSL_CTX* for OpenSSL,
  2177. // tls::impl::MbedTlsContext* for Mbed TLS)
  2178. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2179. ~SSLServer() override;
  2180. bool is_valid() const override;
  2181. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2182. const char *client_ca_pem = nullptr,
  2183. const char *password = nullptr);
  2184. tls::ctx_t tls_context() const { return ctx_; }
  2185. int ssl_last_error() const { return last_ssl_error_; }
  2186. private:
  2187. bool process_and_close_socket(socket_t sock) override;
  2188. tls::ctx_t ctx_ = nullptr;
  2189. std::mutex ctx_mutex_;
  2190. int last_ssl_error_ = 0;
  2191. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2192. public:
  2193. [[deprecated("Use SSLServer(PemMemory) or "
  2194. "SSLServer(ContextSetupCallback) instead. "
  2195. "This constructor will be removed by v1.0.0.")]]
  2196. SSLServer(X509 *cert, EVP_PKEY *private_key,
  2197. X509_STORE *client_ca_cert_store = nullptr);
  2198. [[deprecated("Use SSLServer(ContextSetupCallback) instead. "
  2199. "This constructor will be removed by v1.0.0.")]]
  2200. SSLServer(
  2201. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  2202. [[deprecated("Use tls_context() instead. "
  2203. "This function will be removed by v1.0.0.")]]
  2204. SSL_CTX *ssl_context() const;
  2205. [[deprecated("Use update_certs_pem() instead. "
  2206. "This function will be removed by v1.0.0.")]]
  2207. void update_certs(X509 *cert, EVP_PKEY *private_key,
  2208. X509_STORE *client_ca_cert_store = nullptr);
  2209. #endif
  2210. };
  2211. class SSLClient final : public ClientImpl {
  2212. public:
  2213. explicit SSLClient(const std::string &host);
  2214. explicit SSLClient(const std::string &host, int port);
  2215. explicit SSLClient(const std::string &host, int port,
  2216. const std::string &client_cert_path,
  2217. const std::string &client_key_path,
  2218. const std::string &private_key_password = std::string());
  2219. struct PemMemory {
  2220. const char *cert_pem;
  2221. size_t cert_pem_len;
  2222. const char *key_pem;
  2223. size_t key_pem_len;
  2224. const char *private_key_password;
  2225. };
  2226. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2227. ~SSLClient() override;
  2228. bool is_valid() const override;
  2229. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2230. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2231. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2232. // Post-handshake session verifier (backend-independent)
  2233. void set_session_verifier(
  2234. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2235. tls::ctx_t tls_context() const { return ctx_; }
  2236. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2237. void enable_windows_certificate_verification(bool enabled);
  2238. #endif
  2239. private:
  2240. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2241. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2242. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2243. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2244. bool
  2245. process_socket(const Socket &socket,
  2246. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2247. std::function<bool(Stream &strm)> callback) override;
  2248. bool is_ssl() const override;
  2249. bool setup_proxy_connection(
  2250. Socket &socket,
  2251. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2252. Response &res, bool &success, Error &error) override;
  2253. bool connect_with_proxy(
  2254. Socket &sock,
  2255. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2256. Response &res, bool &success, Error &error);
  2257. bool initialize_ssl(Socket &socket, Error &error);
  2258. bool load_certs();
  2259. tls::ctx_t ctx_ = nullptr;
  2260. std::mutex ctx_mutex_;
  2261. std::once_flag initialize_cert_;
  2262. long verify_result_ = 0;
  2263. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2264. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2265. bool enable_windows_cert_verification_ = true;
  2266. #endif
  2267. friend class ClientImpl;
  2268. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2269. public:
  2270. [[deprecated("Use SSLClient(host, port, PemMemory) instead. "
  2271. "This constructor will be removed by v1.0.0.")]]
  2272. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  2273. EVP_PKEY *client_key,
  2274. const std::string &private_key_password = std::string());
  2275. [[deprecated("Use Result::ssl_backend_error() instead. "
  2276. "This function will be removed by v1.0.0.")]]
  2277. long get_verify_result() const;
  2278. [[deprecated("Use tls_context() instead. "
  2279. "This function will be removed by v1.0.0.")]]
  2280. SSL_CTX *ssl_context() const;
  2281. [[deprecated("Use set_session_verifier(session_t) instead. "
  2282. "This function will be removed by v1.0.0.")]]
  2283. void set_server_certificate_verifier(
  2284. std::function<SSLVerifierResponse(SSL *ssl)> verifier) override;
  2285. private:
  2286. bool verify_host(X509 *server_cert) const;
  2287. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  2288. bool verify_host_with_common_name(X509 *server_cert) const;
  2289. #endif
  2290. };
  2291. #endif // CPPHTTPLIB_SSL_ENABLED
  2292. namespace detail {
  2293. template <typename T, typename U>
  2294. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2295. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2296. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2297. duration - std::chrono::seconds(sec))
  2298. .count();
  2299. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2300. }
  2301. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2302. return N - 1;
  2303. }
  2304. inline bool is_numeric(const std::string &str) {
  2305. return !str.empty() &&
  2306. std::all_of(str.cbegin(), str.cend(),
  2307. [](unsigned char c) { return std::isdigit(c); });
  2308. }
  2309. inline size_t get_header_value_u64(const Headers &headers,
  2310. const std::string &key, size_t def,
  2311. size_t id, bool &is_invalid_value) {
  2312. is_invalid_value = false;
  2313. auto rng = headers.equal_range(key);
  2314. auto it = rng.first;
  2315. std::advance(it, static_cast<ssize_t>(id));
  2316. if (it != rng.second) {
  2317. if (is_numeric(it->second)) {
  2318. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2319. } else {
  2320. is_invalid_value = true;
  2321. }
  2322. }
  2323. return def;
  2324. }
  2325. inline size_t get_header_value_u64(const Headers &headers,
  2326. const std::string &key, size_t def,
  2327. size_t id) {
  2328. auto dummy = false;
  2329. return get_header_value_u64(headers, key, def, id, dummy);
  2330. }
  2331. } // namespace detail
  2332. template <class Rep, class Period>
  2333. inline Server &
  2334. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2335. detail::duration_to_sec_and_usec(
  2336. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2337. return *this;
  2338. }
  2339. template <class Rep, class Period>
  2340. inline Server &
  2341. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2342. detail::duration_to_sec_and_usec(
  2343. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2344. return *this;
  2345. }
  2346. template <class Rep, class Period>
  2347. inline Server &
  2348. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2349. detail::duration_to_sec_and_usec(
  2350. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2351. return *this;
  2352. }
  2353. template <class Rep, class Period>
  2354. inline void ClientImpl::set_connection_timeout(
  2355. const std::chrono::duration<Rep, Period> &duration) {
  2356. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2357. set_connection_timeout(sec, usec);
  2358. });
  2359. }
  2360. template <class Rep, class Period>
  2361. inline void ClientImpl::set_read_timeout(
  2362. const std::chrono::duration<Rep, Period> &duration) {
  2363. detail::duration_to_sec_and_usec(
  2364. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2365. }
  2366. template <class Rep, class Period>
  2367. inline void ClientImpl::set_write_timeout(
  2368. const std::chrono::duration<Rep, Period> &duration) {
  2369. detail::duration_to_sec_and_usec(
  2370. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2371. }
  2372. template <class Rep, class Period>
  2373. inline void ClientImpl::set_max_timeout(
  2374. const std::chrono::duration<Rep, Period> &duration) {
  2375. auto msec =
  2376. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2377. set_max_timeout(msec);
  2378. }
  2379. template <class Rep, class Period>
  2380. inline void Client::set_connection_timeout(
  2381. const std::chrono::duration<Rep, Period> &duration) {
  2382. cli_->set_connection_timeout(duration);
  2383. }
  2384. template <class Rep, class Period>
  2385. inline void
  2386. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2387. cli_->set_read_timeout(duration);
  2388. }
  2389. template <class Rep, class Period>
  2390. inline void
  2391. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2392. cli_->set_write_timeout(duration);
  2393. }
  2394. inline void Client::set_max_timeout(time_t msec) {
  2395. cli_->set_max_timeout(msec);
  2396. }
  2397. template <class Rep, class Period>
  2398. inline void
  2399. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2400. cli_->set_max_timeout(duration);
  2401. }
  2402. /*
  2403. * Forward declarations and types that will be part of the .h file if split into
  2404. * .h + .cc.
  2405. */
  2406. std::string hosted_at(const std::string &hostname);
  2407. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2408. // JavaScript-style URL encoding/decoding functions
  2409. std::string encode_uri_component(const std::string &value);
  2410. std::string encode_uri(const std::string &value);
  2411. std::string decode_uri_component(const std::string &value);
  2412. std::string decode_uri(const std::string &value);
  2413. // RFC 3986 compliant URL component encoding/decoding functions
  2414. std::string encode_path_component(const std::string &component);
  2415. std::string decode_path_component(const std::string &component);
  2416. std::string encode_query_component(const std::string &component,
  2417. bool space_as_plus = true);
  2418. std::string decode_query_component(const std::string &component,
  2419. bool plus_as_space = true);
  2420. std::string sanitize_filename(const std::string &filename);
  2421. std::string append_query_params(const std::string &path, const Params &params);
  2422. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2423. std::pair<std::string, std::string>
  2424. make_basic_authentication_header(const std::string &username,
  2425. const std::string &password,
  2426. bool is_proxy = false);
  2427. namespace detail {
  2428. #if defined(_WIN32)
  2429. inline std::wstring u8string_to_wstring(const char *s) {
  2430. if (!s) { return std::wstring(); }
  2431. auto len = static_cast<int>(strlen(s));
  2432. if (!len) { return std::wstring(); }
  2433. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2434. if (!wlen) { return std::wstring(); }
  2435. std::wstring ws;
  2436. ws.resize(wlen);
  2437. wlen = ::MultiByteToWideChar(
  2438. CP_UTF8, 0, s, len,
  2439. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2440. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2441. return ws;
  2442. }
  2443. #endif
  2444. struct FileStat {
  2445. FileStat(const std::string &path);
  2446. bool is_file() const;
  2447. bool is_dir() const;
  2448. time_t mtime() const;
  2449. size_t size() const;
  2450. private:
  2451. #if defined(_WIN32)
  2452. struct _stat st_;
  2453. #else
  2454. struct stat st_;
  2455. #endif
  2456. int ret_ = -1;
  2457. };
  2458. std::string make_host_and_port_string(const std::string &host, int port,
  2459. bool is_ssl);
  2460. std::string trim_copy(const std::string &s);
  2461. void divide(
  2462. const char *data, std::size_t size, char d,
  2463. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2464. fn);
  2465. void divide(
  2466. const std::string &str, char d,
  2467. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2468. fn);
  2469. void split(const char *b, const char *e, char d,
  2470. std::function<void(const char *, const char *)> fn);
  2471. void split(const char *b, const char *e, char d, size_t m,
  2472. std::function<void(const char *, const char *)> fn);
  2473. bool process_client_socket(
  2474. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2475. time_t write_timeout_sec, time_t write_timeout_usec,
  2476. time_t max_timeout_msec,
  2477. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2478. std::function<bool(Stream &)> callback);
  2479. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2480. int port, int address_family, bool tcp_nodelay,
  2481. bool ipv6_v6only, SocketOptions socket_options,
  2482. time_t connection_timeout_sec,
  2483. time_t connection_timeout_usec,
  2484. time_t read_timeout_sec, time_t read_timeout_usec,
  2485. time_t write_timeout_sec,
  2486. time_t write_timeout_usec,
  2487. const std::string &intf, Error &error);
  2488. const char *get_header_value(const Headers &headers, const std::string &key,
  2489. const char *def, size_t id);
  2490. std::string params_to_query_str(const Params &params);
  2491. void parse_query_text(const char *data, std::size_t size, Params &params);
  2492. void parse_query_text(const std::string &s, Params &params);
  2493. bool parse_multipart_boundary(const std::string &content_type,
  2494. std::string &boundary);
  2495. bool parse_range_header(const std::string &s, Ranges &ranges);
  2496. bool parse_accept_header(const std::string &s,
  2497. std::vector<std::string> &content_types);
  2498. int close_socket(socket_t sock);
  2499. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2500. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2501. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2502. EncodingType encoding_type(const Request &req, const Response &res);
  2503. class BufferStream final : public Stream {
  2504. public:
  2505. BufferStream() = default;
  2506. ~BufferStream() override = default;
  2507. bool is_readable() const override;
  2508. bool wait_readable() const override;
  2509. bool wait_writable() const override;
  2510. ssize_t read(char *ptr, size_t size) override;
  2511. ssize_t write(const char *ptr, size_t size) override;
  2512. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2513. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2514. socket_t socket() const override;
  2515. time_t duration() const override;
  2516. const std::string &get_buffer() const;
  2517. private:
  2518. std::string buffer;
  2519. size_t position = 0;
  2520. };
  2521. class compressor {
  2522. public:
  2523. virtual ~compressor() = default;
  2524. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2525. virtual bool compress(const char *data, size_t data_length, bool last,
  2526. Callback callback) = 0;
  2527. };
  2528. class decompressor {
  2529. public:
  2530. virtual ~decompressor() = default;
  2531. virtual bool is_valid() const = 0;
  2532. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2533. virtual bool decompress(const char *data, size_t data_length,
  2534. Callback callback) = 0;
  2535. };
  2536. class nocompressor final : public compressor {
  2537. public:
  2538. ~nocompressor() override = default;
  2539. bool compress(const char *data, size_t data_length, bool /*last*/,
  2540. Callback callback) override;
  2541. };
  2542. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2543. class gzip_compressor final : public compressor {
  2544. public:
  2545. gzip_compressor();
  2546. ~gzip_compressor() override;
  2547. bool compress(const char *data, size_t data_length, bool last,
  2548. Callback callback) override;
  2549. private:
  2550. bool is_valid_ = false;
  2551. z_stream strm_;
  2552. };
  2553. class gzip_decompressor final : public decompressor {
  2554. public:
  2555. gzip_decompressor();
  2556. ~gzip_decompressor() override;
  2557. bool is_valid() const override;
  2558. bool decompress(const char *data, size_t data_length,
  2559. Callback callback) override;
  2560. private:
  2561. bool is_valid_ = false;
  2562. z_stream strm_;
  2563. };
  2564. #endif
  2565. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2566. class brotli_compressor final : public compressor {
  2567. public:
  2568. brotli_compressor();
  2569. ~brotli_compressor();
  2570. bool compress(const char *data, size_t data_length, bool last,
  2571. Callback callback) override;
  2572. private:
  2573. BrotliEncoderState *state_ = nullptr;
  2574. };
  2575. class brotli_decompressor final : public decompressor {
  2576. public:
  2577. brotli_decompressor();
  2578. ~brotli_decompressor();
  2579. bool is_valid() const override;
  2580. bool decompress(const char *data, size_t data_length,
  2581. Callback callback) override;
  2582. private:
  2583. BrotliDecoderResult decoder_r;
  2584. BrotliDecoderState *decoder_s = nullptr;
  2585. };
  2586. #endif
  2587. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2588. class zstd_compressor : public compressor {
  2589. public:
  2590. zstd_compressor();
  2591. ~zstd_compressor();
  2592. bool compress(const char *data, size_t data_length, bool last,
  2593. Callback callback) override;
  2594. private:
  2595. ZSTD_CCtx *ctx_ = nullptr;
  2596. };
  2597. class zstd_decompressor : public decompressor {
  2598. public:
  2599. zstd_decompressor();
  2600. ~zstd_decompressor();
  2601. bool is_valid() const override;
  2602. bool decompress(const char *data, size_t data_length,
  2603. Callback callback) override;
  2604. private:
  2605. ZSTD_DCtx *ctx_ = nullptr;
  2606. };
  2607. #endif
  2608. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2609. // to store data. The call can set memory on stack for performance.
  2610. class stream_line_reader {
  2611. public:
  2612. stream_line_reader(Stream &strm, char *fixed_buffer,
  2613. size_t fixed_buffer_size);
  2614. const char *ptr() const;
  2615. size_t size() const;
  2616. bool end_with_crlf() const;
  2617. bool getline();
  2618. private:
  2619. void append(char c);
  2620. Stream &strm_;
  2621. char *fixed_buffer_;
  2622. const size_t fixed_buffer_size_;
  2623. size_t fixed_buffer_used_size_ = 0;
  2624. std::string growable_buffer_;
  2625. };
  2626. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2627. const Headers &src_headers);
  2628. struct ChunkedDecoder {
  2629. Stream &strm;
  2630. size_t chunk_remaining = 0;
  2631. bool finished = false;
  2632. char line_buf[64];
  2633. size_t last_chunk_total = 0;
  2634. size_t last_chunk_offset = 0;
  2635. explicit ChunkedDecoder(Stream &s);
  2636. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2637. size_t &out_chunk_total);
  2638. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2639. };
  2640. class mmap {
  2641. public:
  2642. mmap(const char *path);
  2643. ~mmap();
  2644. bool open(const char *path);
  2645. void close();
  2646. bool is_open() const;
  2647. size_t size() const;
  2648. const char *data() const;
  2649. private:
  2650. #if defined(_WIN32)
  2651. HANDLE hFile_ = NULL;
  2652. HANDLE hMapping_ = NULL;
  2653. #else
  2654. int fd_ = -1;
  2655. #endif
  2656. size_t size_ = 0;
  2657. void *addr_ = nullptr;
  2658. bool is_open_empty_file = false;
  2659. };
  2660. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2661. namespace fields {
  2662. bool is_token_char(char c);
  2663. bool is_token(const std::string &s);
  2664. bool is_field_name(const std::string &s);
  2665. bool is_vchar(char c);
  2666. bool is_obs_text(char c);
  2667. bool is_field_vchar(char c);
  2668. bool is_field_content(const std::string &s);
  2669. bool is_field_value(const std::string &s);
  2670. } // namespace fields
  2671. } // namespace detail
  2672. /*
  2673. * TLS Abstraction Layer Declarations
  2674. */
  2675. #ifdef CPPHTTPLIB_SSL_ENABLED
  2676. // TLS abstraction layer - backend-specific type declarations
  2677. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2678. namespace tls {
  2679. namespace impl {
  2680. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2681. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2682. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2683. struct MbedTlsContext {
  2684. mbedtls_ssl_config conf;
  2685. mbedtls_entropy_context entropy;
  2686. mbedtls_ctr_drbg_context ctr_drbg;
  2687. mbedtls_x509_crt ca_chain;
  2688. mbedtls_x509_crt own_cert;
  2689. mbedtls_pk_context own_key;
  2690. bool is_server = false;
  2691. bool verify_client = false;
  2692. bool has_verify_callback = false;
  2693. MbedTlsContext();
  2694. ~MbedTlsContext();
  2695. MbedTlsContext(const MbedTlsContext &) = delete;
  2696. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2697. };
  2698. } // namespace impl
  2699. } // namespace tls
  2700. #endif
  2701. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2702. namespace tls {
  2703. namespace impl {
  2704. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2705. // This struct is accessible via tls::impl for use in SSL context
  2706. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2707. struct WolfSSLContext {
  2708. WOLFSSL_CTX *ctx = nullptr;
  2709. bool is_server = false;
  2710. bool verify_client = false;
  2711. bool has_verify_callback = false;
  2712. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2713. WolfSSLContext();
  2714. ~WolfSSLContext();
  2715. WolfSSLContext(const WolfSSLContext &) = delete;
  2716. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2717. };
  2718. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2719. struct WolfSSLCAStore {
  2720. std::string pem_data;
  2721. };
  2722. } // namespace impl
  2723. } // namespace tls
  2724. #endif
  2725. #endif // CPPHTTPLIB_SSL_ENABLED
  2726. namespace stream {
  2727. class Result {
  2728. public:
  2729. Result();
  2730. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2731. Result(Result &&other) noexcept;
  2732. Result &operator=(Result &&other) noexcept;
  2733. Result(const Result &) = delete;
  2734. Result &operator=(const Result &) = delete;
  2735. // Response info
  2736. bool is_valid() const;
  2737. explicit operator bool() const;
  2738. int status() const;
  2739. const Headers &headers() const;
  2740. std::string get_header_value(const std::string &key,
  2741. const char *def = "") const;
  2742. bool has_header(const std::string &key) const;
  2743. Error error() const;
  2744. Error read_error() const;
  2745. bool has_read_error() const;
  2746. // Stream reading
  2747. bool next();
  2748. const char *data() const;
  2749. size_t size() const;
  2750. std::string read_all();
  2751. private:
  2752. ClientImpl::StreamHandle handle_;
  2753. std::string buffer_;
  2754. size_t current_size_ = 0;
  2755. size_t chunk_size_;
  2756. bool finished_ = false;
  2757. };
  2758. // GET
  2759. template <typename ClientType>
  2760. inline Result Get(ClientType &cli, const std::string &path,
  2761. size_t chunk_size = 8192) {
  2762. return Result{cli.open_stream("GET", path), chunk_size};
  2763. }
  2764. template <typename ClientType>
  2765. inline Result Get(ClientType &cli, const std::string &path,
  2766. const Headers &headers, size_t chunk_size = 8192) {
  2767. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2768. }
  2769. template <typename ClientType>
  2770. inline Result Get(ClientType &cli, const std::string &path,
  2771. const Params &params, size_t chunk_size = 8192) {
  2772. return Result{cli.open_stream("GET", path, params), chunk_size};
  2773. }
  2774. template <typename ClientType>
  2775. inline Result Get(ClientType &cli, const std::string &path,
  2776. const Params &params, const Headers &headers,
  2777. size_t chunk_size = 8192) {
  2778. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2779. }
  2780. // POST
  2781. template <typename ClientType>
  2782. inline Result Post(ClientType &cli, const std::string &path,
  2783. const std::string &body, const std::string &content_type,
  2784. size_t chunk_size = 8192) {
  2785. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2786. chunk_size};
  2787. }
  2788. template <typename ClientType>
  2789. inline Result Post(ClientType &cli, const std::string &path,
  2790. const Headers &headers, const std::string &body,
  2791. const std::string &content_type, size_t chunk_size = 8192) {
  2792. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2793. chunk_size};
  2794. }
  2795. template <typename ClientType>
  2796. inline Result Post(ClientType &cli, const std::string &path,
  2797. const Params &params, const std::string &body,
  2798. const std::string &content_type, size_t chunk_size = 8192) {
  2799. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2800. chunk_size};
  2801. }
  2802. template <typename ClientType>
  2803. inline Result Post(ClientType &cli, const std::string &path,
  2804. const Params &params, const Headers &headers,
  2805. const std::string &body, const std::string &content_type,
  2806. size_t chunk_size = 8192) {
  2807. return Result{
  2808. cli.open_stream("POST", path, params, headers, body, content_type),
  2809. chunk_size};
  2810. }
  2811. // PUT
  2812. template <typename ClientType>
  2813. inline Result Put(ClientType &cli, const std::string &path,
  2814. const std::string &body, const std::string &content_type,
  2815. size_t chunk_size = 8192) {
  2816. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2817. chunk_size};
  2818. }
  2819. template <typename ClientType>
  2820. inline Result Put(ClientType &cli, const std::string &path,
  2821. const Headers &headers, const std::string &body,
  2822. const std::string &content_type, size_t chunk_size = 8192) {
  2823. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2824. chunk_size};
  2825. }
  2826. template <typename ClientType>
  2827. inline Result Put(ClientType &cli, const std::string &path,
  2828. const Params &params, const std::string &body,
  2829. const std::string &content_type, size_t chunk_size = 8192) {
  2830. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2831. chunk_size};
  2832. }
  2833. template <typename ClientType>
  2834. inline Result Put(ClientType &cli, const std::string &path,
  2835. const Params &params, const Headers &headers,
  2836. const std::string &body, const std::string &content_type,
  2837. size_t chunk_size = 8192) {
  2838. return Result{
  2839. cli.open_stream("PUT", path, params, headers, body, content_type),
  2840. chunk_size};
  2841. }
  2842. // PATCH
  2843. template <typename ClientType>
  2844. inline Result Patch(ClientType &cli, const std::string &path,
  2845. const std::string &body, const std::string &content_type,
  2846. size_t chunk_size = 8192) {
  2847. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2848. chunk_size};
  2849. }
  2850. template <typename ClientType>
  2851. inline Result Patch(ClientType &cli, const std::string &path,
  2852. const Headers &headers, const std::string &body,
  2853. const std::string &content_type, size_t chunk_size = 8192) {
  2854. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2855. chunk_size};
  2856. }
  2857. template <typename ClientType>
  2858. inline Result Patch(ClientType &cli, const std::string &path,
  2859. const Params &params, const std::string &body,
  2860. const std::string &content_type, size_t chunk_size = 8192) {
  2861. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2862. chunk_size};
  2863. }
  2864. template <typename ClientType>
  2865. inline Result Patch(ClientType &cli, const std::string &path,
  2866. const Params &params, const Headers &headers,
  2867. const std::string &body, const std::string &content_type,
  2868. size_t chunk_size = 8192) {
  2869. return Result{
  2870. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2871. chunk_size};
  2872. }
  2873. // DELETE
  2874. template <typename ClientType>
  2875. inline Result Delete(ClientType &cli, const std::string &path,
  2876. size_t chunk_size = 8192) {
  2877. return Result{cli.open_stream("DELETE", path), chunk_size};
  2878. }
  2879. template <typename ClientType>
  2880. inline Result Delete(ClientType &cli, const std::string &path,
  2881. const Headers &headers, size_t chunk_size = 8192) {
  2882. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2883. }
  2884. template <typename ClientType>
  2885. inline Result Delete(ClientType &cli, const std::string &path,
  2886. const std::string &body, const std::string &content_type,
  2887. size_t chunk_size = 8192) {
  2888. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2889. chunk_size};
  2890. }
  2891. template <typename ClientType>
  2892. inline Result Delete(ClientType &cli, const std::string &path,
  2893. const Headers &headers, const std::string &body,
  2894. const std::string &content_type,
  2895. size_t chunk_size = 8192) {
  2896. return Result{
  2897. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2898. chunk_size};
  2899. }
  2900. template <typename ClientType>
  2901. inline Result Delete(ClientType &cli, const std::string &path,
  2902. const Params &params, size_t chunk_size = 8192) {
  2903. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2904. }
  2905. template <typename ClientType>
  2906. inline Result Delete(ClientType &cli, const std::string &path,
  2907. const Params &params, const Headers &headers,
  2908. size_t chunk_size = 8192) {
  2909. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2910. }
  2911. template <typename ClientType>
  2912. inline Result Delete(ClientType &cli, const std::string &path,
  2913. const Params &params, const std::string &body,
  2914. const std::string &content_type,
  2915. size_t chunk_size = 8192) {
  2916. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2917. chunk_size};
  2918. }
  2919. template <typename ClientType>
  2920. inline Result Delete(ClientType &cli, const std::string &path,
  2921. const Params &params, const Headers &headers,
  2922. const std::string &body, const std::string &content_type,
  2923. size_t chunk_size = 8192) {
  2924. return Result{
  2925. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2926. chunk_size};
  2927. }
  2928. // HEAD
  2929. template <typename ClientType>
  2930. inline Result Head(ClientType &cli, const std::string &path,
  2931. size_t chunk_size = 8192) {
  2932. return Result{cli.open_stream("HEAD", path), chunk_size};
  2933. }
  2934. template <typename ClientType>
  2935. inline Result Head(ClientType &cli, const std::string &path,
  2936. const Headers &headers, size_t chunk_size = 8192) {
  2937. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2938. }
  2939. template <typename ClientType>
  2940. inline Result Head(ClientType &cli, const std::string &path,
  2941. const Params &params, size_t chunk_size = 8192) {
  2942. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2943. }
  2944. template <typename ClientType>
  2945. inline Result Head(ClientType &cli, const std::string &path,
  2946. const Params &params, const Headers &headers,
  2947. size_t chunk_size = 8192) {
  2948. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2949. }
  2950. // OPTIONS
  2951. template <typename ClientType>
  2952. inline Result Options(ClientType &cli, const std::string &path,
  2953. size_t chunk_size = 8192) {
  2954. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2955. }
  2956. template <typename ClientType>
  2957. inline Result Options(ClientType &cli, const std::string &path,
  2958. const Headers &headers, size_t chunk_size = 8192) {
  2959. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2960. }
  2961. template <typename ClientType>
  2962. inline Result Options(ClientType &cli, const std::string &path,
  2963. const Params &params, size_t chunk_size = 8192) {
  2964. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2965. }
  2966. template <typename ClientType>
  2967. inline Result Options(ClientType &cli, const std::string &path,
  2968. const Params &params, const Headers &headers,
  2969. size_t chunk_size = 8192) {
  2970. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2971. }
  2972. } // namespace stream
  2973. namespace sse {
  2974. struct SSEMessage {
  2975. std::string event; // Event type (default: "message")
  2976. std::string data; // Event payload
  2977. std::string id; // Event ID for Last-Event-ID header
  2978. SSEMessage();
  2979. void clear();
  2980. };
  2981. class SSEClient {
  2982. public:
  2983. using MessageHandler = std::function<void(const SSEMessage &)>;
  2984. using ErrorHandler = std::function<void(Error)>;
  2985. using OpenHandler = std::function<void()>;
  2986. SSEClient(Client &client, const std::string &path);
  2987. SSEClient(Client &client, const std::string &path, const Headers &headers);
  2988. ~SSEClient();
  2989. SSEClient(const SSEClient &) = delete;
  2990. SSEClient &operator=(const SSEClient &) = delete;
  2991. // Event handlers
  2992. SSEClient &on_message(MessageHandler handler);
  2993. SSEClient &on_event(const std::string &type, MessageHandler handler);
  2994. SSEClient &on_open(OpenHandler handler);
  2995. SSEClient &on_error(ErrorHandler handler);
  2996. SSEClient &set_reconnect_interval(int ms);
  2997. SSEClient &set_max_reconnect_attempts(int n);
  2998. // Update headers (thread-safe)
  2999. SSEClient &set_headers(const Headers &headers);
  3000. // State accessors
  3001. bool is_connected() const;
  3002. const std::string &last_event_id() const;
  3003. // Blocking start - runs event loop with auto-reconnect
  3004. void start();
  3005. // Non-blocking start - runs in background thread
  3006. void start_async();
  3007. // Stop the client (thread-safe)
  3008. void stop();
  3009. private:
  3010. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3011. void run_event_loop();
  3012. void dispatch_event(const SSEMessage &msg);
  3013. bool should_reconnect(int count) const;
  3014. void wait_for_reconnect();
  3015. // Client and path
  3016. Client &client_;
  3017. std::string path_;
  3018. Headers headers_;
  3019. mutable std::mutex headers_mutex_;
  3020. // Callbacks
  3021. MessageHandler on_message_;
  3022. std::map<std::string, MessageHandler> event_handlers_;
  3023. OpenHandler on_open_;
  3024. ErrorHandler on_error_;
  3025. // Configuration
  3026. int reconnect_interval_ms_ = 3000;
  3027. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3028. // State
  3029. std::atomic<bool> running_{false};
  3030. std::atomic<bool> connected_{false};
  3031. std::string last_event_id_;
  3032. // Async support
  3033. std::thread async_thread_;
  3034. };
  3035. } // namespace sse
  3036. namespace ws {
  3037. enum class Opcode : uint8_t {
  3038. Continuation = 0x0,
  3039. Text = 0x1,
  3040. Binary = 0x2,
  3041. Close = 0x8,
  3042. Ping = 0x9,
  3043. Pong = 0xA,
  3044. };
  3045. enum class CloseStatus : uint16_t {
  3046. Normal = 1000,
  3047. GoingAway = 1001,
  3048. ProtocolError = 1002,
  3049. UnsupportedData = 1003,
  3050. NoStatus = 1005,
  3051. Abnormal = 1006,
  3052. InvalidPayload = 1007,
  3053. PolicyViolation = 1008,
  3054. MessageTooBig = 1009,
  3055. MandatoryExtension = 1010,
  3056. InternalError = 1011,
  3057. };
  3058. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3059. class WebSocket {
  3060. public:
  3061. WebSocket(const WebSocket &) = delete;
  3062. WebSocket &operator=(const WebSocket &) = delete;
  3063. ~WebSocket();
  3064. ReadResult read(std::string &msg);
  3065. bool send(const std::string &data);
  3066. bool send(const char *data, size_t len);
  3067. void close(CloseStatus status = CloseStatus::Normal,
  3068. const std::string &reason = "");
  3069. const Request &request() const;
  3070. bool is_open() const;
  3071. private:
  3072. friend class httplib::Server;
  3073. friend class WebSocketClient;
  3074. WebSocket(
  3075. Stream &strm, const Request &req, bool is_server,
  3076. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND)
  3077. : strm_(strm), req_(req), is_server_(is_server),
  3078. ping_interval_sec_(ping_interval_sec) {
  3079. start_heartbeat();
  3080. }
  3081. WebSocket(
  3082. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3083. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND)
  3084. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3085. is_server_(is_server), ping_interval_sec_(ping_interval_sec) {
  3086. start_heartbeat();
  3087. }
  3088. void start_heartbeat();
  3089. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3090. Stream &strm_;
  3091. std::unique_ptr<Stream> owned_strm_;
  3092. Request req_;
  3093. bool is_server_;
  3094. time_t ping_interval_sec_;
  3095. std::atomic<bool> closed_{false};
  3096. std::mutex write_mutex_;
  3097. std::thread ping_thread_;
  3098. std::mutex ping_mutex_;
  3099. std::condition_variable ping_cv_;
  3100. };
  3101. class WebSocketClient {
  3102. public:
  3103. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3104. const Headers &headers = {});
  3105. ~WebSocketClient();
  3106. WebSocketClient(const WebSocketClient &) = delete;
  3107. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3108. bool is_valid() const;
  3109. bool connect();
  3110. ReadResult read(std::string &msg);
  3111. bool send(const std::string &data);
  3112. bool send(const char *data, size_t len);
  3113. void close(CloseStatus status = CloseStatus::Normal,
  3114. const std::string &reason = "");
  3115. bool is_open() const;
  3116. const std::string &subprotocol() const;
  3117. void set_read_timeout(time_t sec, time_t usec = 0);
  3118. void set_write_timeout(time_t sec, time_t usec = 0);
  3119. void set_websocket_ping_interval(time_t sec);
  3120. void set_tcp_nodelay(bool on);
  3121. void set_address_family(int family);
  3122. void set_ipv6_v6only(bool on);
  3123. void set_socket_options(SocketOptions socket_options);
  3124. void set_connection_timeout(time_t sec, time_t usec = 0);
  3125. void set_interface(const std::string &intf);
  3126. #ifdef CPPHTTPLIB_SSL_ENABLED
  3127. void set_ca_cert_path(const std::string &path);
  3128. void set_ca_cert_store(tls::ca_store_t store);
  3129. void enable_server_certificate_verification(bool enabled);
  3130. #endif
  3131. private:
  3132. void shutdown_and_close();
  3133. bool create_stream(std::unique_ptr<Stream> &strm);
  3134. std::string host_;
  3135. int port_;
  3136. std::string path_;
  3137. Headers headers_;
  3138. std::string subprotocol_;
  3139. bool is_valid_ = false;
  3140. socket_t sock_ = INVALID_SOCKET;
  3141. std::unique_ptr<WebSocket> ws_;
  3142. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3143. time_t read_timeout_usec_ = 0;
  3144. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3145. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3146. time_t websocket_ping_interval_sec_ =
  3147. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3148. int address_family_ = AF_UNSPEC;
  3149. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3150. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3151. SocketOptions socket_options_ = nullptr;
  3152. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3153. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3154. std::string interface_;
  3155. #ifdef CPPHTTPLIB_SSL_ENABLED
  3156. bool is_ssl_ = false;
  3157. tls::ctx_t tls_ctx_ = nullptr;
  3158. tls::session_t tls_session_ = nullptr;
  3159. std::string ca_cert_file_path_;
  3160. tls::ca_store_t ca_cert_store_ = nullptr;
  3161. bool server_certificate_verification_ = true;
  3162. #endif
  3163. };
  3164. namespace impl {
  3165. bool is_valid_utf8(const std::string &s);
  3166. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3167. bool &fin, bool expect_masked, size_t max_len);
  3168. } // namespace impl
  3169. } // namespace ws
  3170. // ----------------------------------------------------------------------------
  3171. /*
  3172. * Implementation that will be part of the .cc file if split into .h + .cc.
  3173. */
  3174. namespace stream {
  3175. // stream::Result implementations
  3176. inline Result::Result() : chunk_size_(8192) {}
  3177. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3178. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3179. inline Result::Result(Result &&other) noexcept
  3180. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3181. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3182. finished_(other.finished_) {
  3183. other.current_size_ = 0;
  3184. other.finished_ = true;
  3185. }
  3186. inline Result &Result::operator=(Result &&other) noexcept {
  3187. if (this != &other) {
  3188. handle_ = std::move(other.handle_);
  3189. buffer_ = std::move(other.buffer_);
  3190. current_size_ = other.current_size_;
  3191. chunk_size_ = other.chunk_size_;
  3192. finished_ = other.finished_;
  3193. other.current_size_ = 0;
  3194. other.finished_ = true;
  3195. }
  3196. return *this;
  3197. }
  3198. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3199. inline Result::operator bool() const { return is_valid(); }
  3200. inline int Result::status() const {
  3201. return handle_.response ? handle_.response->status : -1;
  3202. }
  3203. inline const Headers &Result::headers() const {
  3204. static const Headers empty_headers;
  3205. return handle_.response ? handle_.response->headers : empty_headers;
  3206. }
  3207. inline std::string Result::get_header_value(const std::string &key,
  3208. const char *def) const {
  3209. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3210. }
  3211. inline bool Result::has_header(const std::string &key) const {
  3212. return handle_.response ? handle_.response->has_header(key) : false;
  3213. }
  3214. inline Error Result::error() const { return handle_.error; }
  3215. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3216. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3217. inline bool Result::next() {
  3218. if (!handle_.is_valid() || finished_) { return false; }
  3219. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3220. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3221. if (n > 0) {
  3222. current_size_ = static_cast<size_t>(n);
  3223. return true;
  3224. }
  3225. current_size_ = 0;
  3226. finished_ = true;
  3227. return false;
  3228. }
  3229. inline const char *Result::data() const { return buffer_.data(); }
  3230. inline size_t Result::size() const { return current_size_; }
  3231. inline std::string Result::read_all() {
  3232. std::string result;
  3233. while (next()) {
  3234. result.append(data(), size());
  3235. }
  3236. return result;
  3237. }
  3238. } // namespace stream
  3239. namespace sse {
  3240. // SSEMessage implementations
  3241. inline SSEMessage::SSEMessage() : event("message") {}
  3242. inline void SSEMessage::clear() {
  3243. event = "message";
  3244. data.clear();
  3245. id.clear();
  3246. }
  3247. // SSEClient implementations
  3248. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3249. : client_(client), path_(path) {}
  3250. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3251. const Headers &headers)
  3252. : client_(client), path_(path), headers_(headers) {}
  3253. inline SSEClient::~SSEClient() { stop(); }
  3254. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3255. on_message_ = std::move(handler);
  3256. return *this;
  3257. }
  3258. inline SSEClient &SSEClient::on_event(const std::string &type,
  3259. MessageHandler handler) {
  3260. event_handlers_[type] = std::move(handler);
  3261. return *this;
  3262. }
  3263. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3264. on_open_ = std::move(handler);
  3265. return *this;
  3266. }
  3267. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3268. on_error_ = std::move(handler);
  3269. return *this;
  3270. }
  3271. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3272. reconnect_interval_ms_ = ms;
  3273. return *this;
  3274. }
  3275. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3276. max_reconnect_attempts_ = n;
  3277. return *this;
  3278. }
  3279. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3280. std::lock_guard<std::mutex> lock(headers_mutex_);
  3281. headers_ = headers;
  3282. return *this;
  3283. }
  3284. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3285. inline const std::string &SSEClient::last_event_id() const {
  3286. return last_event_id_;
  3287. }
  3288. inline void SSEClient::start() {
  3289. running_.store(true);
  3290. run_event_loop();
  3291. }
  3292. inline void SSEClient::start_async() {
  3293. running_.store(true);
  3294. async_thread_ = std::thread([this]() { run_event_loop(); });
  3295. }
  3296. inline void SSEClient::stop() {
  3297. running_.store(false);
  3298. client_.stop(); // Cancel any pending operations
  3299. if (async_thread_.joinable()) { async_thread_.join(); }
  3300. }
  3301. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3302. int &retry_ms) {
  3303. // Blank line signals end of event
  3304. if (line.empty() || line == "\r") { return true; }
  3305. // Lines starting with ':' are comments (ignored)
  3306. if (!line.empty() && line[0] == ':') { return false; }
  3307. // Find the colon separator
  3308. auto colon_pos = line.find(':');
  3309. if (colon_pos == std::string::npos) {
  3310. // Line with no colon is treated as field name with empty value
  3311. return false;
  3312. }
  3313. auto field = line.substr(0, colon_pos);
  3314. std::string value;
  3315. // Value starts after colon, skip optional single space
  3316. if (colon_pos + 1 < line.size()) {
  3317. auto value_start = colon_pos + 1;
  3318. if (line[value_start] == ' ') { value_start++; }
  3319. value = line.substr(value_start);
  3320. // Remove trailing \r if present
  3321. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3322. }
  3323. // Handle known fields
  3324. if (field == "event") {
  3325. msg.event = value;
  3326. } else if (field == "data") {
  3327. // Multiple data lines are concatenated with newlines
  3328. if (!msg.data.empty()) { msg.data += "\n"; }
  3329. msg.data += value;
  3330. } else if (field == "id") {
  3331. // Empty id is valid (clears the last event ID)
  3332. msg.id = value;
  3333. } else if (field == "retry") {
  3334. // Parse retry interval in milliseconds
  3335. {
  3336. int v = 0;
  3337. auto res =
  3338. detail::from_chars(value.data(), value.data() + value.size(), v);
  3339. if (res.ec == std::errc{}) { retry_ms = v; }
  3340. }
  3341. }
  3342. // Unknown fields are ignored per SSE spec
  3343. return false;
  3344. }
  3345. inline void SSEClient::run_event_loop() {
  3346. auto reconnect_count = 0;
  3347. while (running_.load()) {
  3348. // Build headers, including Last-Event-ID if we have one
  3349. Headers request_headers;
  3350. {
  3351. std::lock_guard<std::mutex> lock(headers_mutex_);
  3352. request_headers = headers_;
  3353. }
  3354. if (!last_event_id_.empty()) {
  3355. request_headers.emplace("Last-Event-ID", last_event_id_);
  3356. }
  3357. // Open streaming connection
  3358. auto result = stream::Get(client_, path_, request_headers);
  3359. // Connection error handling
  3360. if (!result) {
  3361. connected_.store(false);
  3362. if (on_error_) { on_error_(result.error()); }
  3363. if (!should_reconnect(reconnect_count)) { break; }
  3364. wait_for_reconnect();
  3365. reconnect_count++;
  3366. continue;
  3367. }
  3368. if (result.status() != StatusCode::OK_200) {
  3369. connected_.store(false);
  3370. if (on_error_) { on_error_(Error::Connection); }
  3371. // For certain errors, don't reconnect.
  3372. // Note: 401 is intentionally absent so that handlers can refresh
  3373. // credentials via set_headers() and let the client reconnect.
  3374. if (result.status() == StatusCode::NoContent_204 ||
  3375. result.status() == StatusCode::NotFound_404 ||
  3376. result.status() == StatusCode::Forbidden_403) {
  3377. break;
  3378. }
  3379. if (!should_reconnect(reconnect_count)) { break; }
  3380. wait_for_reconnect();
  3381. reconnect_count++;
  3382. continue;
  3383. }
  3384. // Connection successful
  3385. connected_.store(true);
  3386. reconnect_count = 0;
  3387. if (on_open_) { on_open_(); }
  3388. // Event receiving loop
  3389. std::string buffer;
  3390. SSEMessage current_msg;
  3391. while (running_.load() && result.next()) {
  3392. buffer.append(result.data(), result.size());
  3393. // Process complete lines in the buffer
  3394. size_t line_start = 0;
  3395. size_t newline_pos;
  3396. while ((newline_pos = buffer.find('\n', line_start)) !=
  3397. std::string::npos) {
  3398. auto line = buffer.substr(line_start, newline_pos - line_start);
  3399. line_start = newline_pos + 1;
  3400. // Parse the line and check if event is complete
  3401. auto event_complete =
  3402. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3403. if (event_complete && !current_msg.data.empty()) {
  3404. // Update last_event_id for reconnection
  3405. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3406. // Dispatch event to appropriate handler
  3407. dispatch_event(current_msg);
  3408. current_msg.clear();
  3409. }
  3410. }
  3411. // Keep unprocessed data in buffer
  3412. buffer.erase(0, line_start);
  3413. }
  3414. // Connection ended
  3415. connected_.store(false);
  3416. if (!running_.load()) { break; }
  3417. // Check for read errors
  3418. if (result.has_read_error()) {
  3419. if (on_error_) { on_error_(result.read_error()); }
  3420. }
  3421. if (!should_reconnect(reconnect_count)) { break; }
  3422. wait_for_reconnect();
  3423. reconnect_count++;
  3424. }
  3425. connected_.store(false);
  3426. }
  3427. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3428. // Check for specific event type handler first
  3429. auto it = event_handlers_.find(msg.event);
  3430. if (it != event_handlers_.end()) {
  3431. it->second(msg);
  3432. return;
  3433. }
  3434. // Fall back to generic message handler
  3435. if (on_message_) { on_message_(msg); }
  3436. }
  3437. inline bool SSEClient::should_reconnect(int count) const {
  3438. if (!running_.load()) { return false; }
  3439. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3440. return count < max_reconnect_attempts_;
  3441. }
  3442. inline void SSEClient::wait_for_reconnect() {
  3443. // Use small increments to check running_ flag frequently
  3444. auto waited = 0;
  3445. while (running_.load() && waited < reconnect_interval_ms_) {
  3446. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3447. waited += 100;
  3448. }
  3449. }
  3450. } // namespace sse
  3451. #ifdef CPPHTTPLIB_SSL_ENABLED
  3452. /*
  3453. * TLS abstraction layer - internal function declarations
  3454. * These are implementation details and not part of the public API.
  3455. */
  3456. namespace tls {
  3457. // Client context
  3458. ctx_t create_client_context();
  3459. void free_context(ctx_t ctx);
  3460. bool set_min_version(ctx_t ctx, Version version);
  3461. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3462. bool load_ca_file(ctx_t ctx, const char *file_path);
  3463. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3464. bool load_system_certs(ctx_t ctx);
  3465. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3466. const char *password);
  3467. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3468. const char *key_path, const char *password);
  3469. // Server context
  3470. ctx_t create_server_context();
  3471. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3472. const char *password);
  3473. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3474. const char *key_path, const char *password);
  3475. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3476. void set_verify_client(ctx_t ctx, bool require);
  3477. // Session management
  3478. session_t create_session(ctx_t ctx, socket_t sock);
  3479. void free_session(session_t session);
  3480. bool set_sni(session_t session, const char *hostname);
  3481. bool set_hostname(session_t session, const char *hostname);
  3482. // Handshake (non-blocking capable)
  3483. TlsError connect(session_t session);
  3484. TlsError accept(session_t session);
  3485. // Handshake with timeout (blocking until timeout)
  3486. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3487. time_t timeout_usec, TlsError *err);
  3488. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3489. time_t timeout_usec, TlsError *err);
  3490. // I/O (non-blocking capable)
  3491. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3492. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3493. int pending(const_session_t session);
  3494. void shutdown(session_t session, bool graceful);
  3495. // Connection state
  3496. bool is_peer_closed(session_t session, socket_t sock);
  3497. // Certificate verification
  3498. cert_t get_peer_cert(const_session_t session);
  3499. void free_cert(cert_t cert);
  3500. bool verify_hostname(cert_t cert, const char *hostname);
  3501. uint64_t hostname_mismatch_code();
  3502. long get_verify_result(const_session_t session);
  3503. // Certificate introspection
  3504. std::string get_cert_subject_cn(cert_t cert);
  3505. std::string get_cert_issuer_name(cert_t cert);
  3506. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3507. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3508. std::string get_cert_serial(cert_t cert);
  3509. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3510. const char *get_sni(const_session_t session);
  3511. // CA store management
  3512. ca_store_t create_ca_store(const char *pem, size_t len);
  3513. void free_ca_store(ca_store_t store);
  3514. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3515. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3516. std::vector<std::string> get_ca_names(ctx_t ctx);
  3517. // Dynamic certificate update (for servers)
  3518. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3519. const char *password);
  3520. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3521. // Certificate verification callback
  3522. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3523. long get_verify_error(const_session_t session);
  3524. std::string verify_error_string(long error_code);
  3525. // TlsError information
  3526. uint64_t peek_error();
  3527. uint64_t get_error();
  3528. std::string error_string(uint64_t code);
  3529. } // namespace tls
  3530. #endif // CPPHTTPLIB_SSL_ENABLED
  3531. /*
  3532. * Group 1: detail namespace - Non-SSL utilities
  3533. */
  3534. namespace detail {
  3535. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3536. const void *optval, socklen_t optlen) {
  3537. return setsockopt(sock, level, optname,
  3538. #ifdef _WIN32
  3539. reinterpret_cast<const char *>(optval),
  3540. #else
  3541. optval,
  3542. #endif
  3543. optlen) == 0;
  3544. }
  3545. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3546. time_t sec, time_t usec) {
  3547. #ifdef _WIN32
  3548. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3549. #else
  3550. timeval timeout;
  3551. timeout.tv_sec = static_cast<long>(sec);
  3552. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3553. #endif
  3554. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3555. }
  3556. inline bool is_hex(char c, int &v) {
  3557. if (isdigit(c)) {
  3558. v = c - '0';
  3559. return true;
  3560. } else if ('A' <= c && c <= 'F') {
  3561. v = c - 'A' + 10;
  3562. return true;
  3563. } else if ('a' <= c && c <= 'f') {
  3564. v = c - 'a' + 10;
  3565. return true;
  3566. }
  3567. return false;
  3568. }
  3569. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3570. int &val) {
  3571. if (i >= s.size()) { return false; }
  3572. val = 0;
  3573. for (; cnt; i++, cnt--) {
  3574. if (!s[i]) { return false; }
  3575. auto v = 0;
  3576. if (is_hex(s[i], v)) {
  3577. val = val * 16 + v;
  3578. } else {
  3579. return false;
  3580. }
  3581. }
  3582. return true;
  3583. }
  3584. inline std::string from_i_to_hex(size_t n) {
  3585. static const auto charset = "0123456789abcdef";
  3586. std::string ret;
  3587. do {
  3588. ret = charset[n & 15] + ret;
  3589. n >>= 4;
  3590. } while (n > 0);
  3591. return ret;
  3592. }
  3593. inline std::string compute_etag(const FileStat &fs) {
  3594. if (!fs.is_file()) { return std::string(); }
  3595. // If mtime cannot be determined (negative value indicates an error
  3596. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3597. // value like 0 could collide with a real file that legitimately has
  3598. // mtime == 0 (epoch) and lead to misleading validators.
  3599. auto mtime_raw = fs.mtime();
  3600. if (mtime_raw < 0) { return std::string(); }
  3601. auto mtime = static_cast<size_t>(mtime_raw);
  3602. auto size = fs.size();
  3603. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3604. from_i_to_hex(size) + "\"";
  3605. }
  3606. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3607. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3608. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3609. inline std::string file_mtime_to_http_date(time_t mtime) {
  3610. if (mtime < 0) { return std::string(); }
  3611. struct tm tm_buf;
  3612. #ifdef _WIN32
  3613. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3614. #else
  3615. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3616. #endif
  3617. char buf[64];
  3618. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3619. return std::string();
  3620. }
  3621. return std::string(buf);
  3622. }
  3623. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3624. inline time_t parse_http_date(const std::string &date_str) {
  3625. struct tm tm_buf;
  3626. // Create a classic locale object once for all parsing attempts
  3627. const std::locale classic_locale = std::locale::classic();
  3628. // Try to parse using std::get_time (C++11, cross-platform)
  3629. auto try_parse = [&](const char *fmt) -> bool {
  3630. std::istringstream ss(date_str);
  3631. ss.imbue(classic_locale);
  3632. memset(&tm_buf, 0, sizeof(tm_buf));
  3633. ss >> std::get_time(&tm_buf, fmt);
  3634. return !ss.fail();
  3635. };
  3636. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3637. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3638. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3639. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3640. // asctime format: "Sun Nov 6 08:49:37 1994"
  3641. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3642. return static_cast<time_t>(-1);
  3643. }
  3644. }
  3645. }
  3646. #ifdef _WIN32
  3647. return _mkgmtime(&tm_buf);
  3648. #elif defined _AIX
  3649. return mktime(&tm_buf);
  3650. #else
  3651. return timegm(&tm_buf);
  3652. #endif
  3653. }
  3654. inline bool is_weak_etag(const std::string &s) {
  3655. // Check if the string is a weak ETag (starts with 'W/"')
  3656. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3657. }
  3658. inline bool is_strong_etag(const std::string &s) {
  3659. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3660. // chars)
  3661. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3662. }
  3663. inline size_t to_utf8(int code, char *buff) {
  3664. if (code < 0x0080) {
  3665. buff[0] = static_cast<char>(code & 0x7F);
  3666. return 1;
  3667. } else if (code < 0x0800) {
  3668. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3669. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3670. return 2;
  3671. } else if (code < 0xD800) {
  3672. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3673. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3674. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3675. return 3;
  3676. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3677. return 0;
  3678. } else if (code < 0x10000) {
  3679. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3680. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3681. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3682. return 3;
  3683. } else if (code < 0x110000) {
  3684. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3685. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3686. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3687. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3688. return 4;
  3689. }
  3690. // NOTREACHED
  3691. return 0;
  3692. }
  3693. } // namespace detail
  3694. namespace ws {
  3695. namespace impl {
  3696. inline bool is_valid_utf8(const std::string &s) {
  3697. size_t i = 0;
  3698. auto n = s.size();
  3699. while (i < n) {
  3700. auto c = static_cast<unsigned char>(s[i]);
  3701. size_t len;
  3702. uint32_t cp;
  3703. if (c < 0x80) {
  3704. i++;
  3705. continue;
  3706. } else if ((c & 0xE0) == 0xC0) {
  3707. len = 2;
  3708. cp = c & 0x1F;
  3709. } else if ((c & 0xF0) == 0xE0) {
  3710. len = 3;
  3711. cp = c & 0x0F;
  3712. } else if ((c & 0xF8) == 0xF0) {
  3713. len = 4;
  3714. cp = c & 0x07;
  3715. } else {
  3716. return false;
  3717. }
  3718. if (i + len > n) { return false; }
  3719. for (size_t j = 1; j < len; j++) {
  3720. auto b = static_cast<unsigned char>(s[i + j]);
  3721. if ((b & 0xC0) != 0x80) { return false; }
  3722. cp = (cp << 6) | (b & 0x3F);
  3723. }
  3724. // Overlong encoding check
  3725. if (len == 2 && cp < 0x80) { return false; }
  3726. if (len == 3 && cp < 0x800) { return false; }
  3727. if (len == 4 && cp < 0x10000) { return false; }
  3728. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3729. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3730. if (cp > 0x10FFFF) { return false; }
  3731. i += len;
  3732. }
  3733. return true;
  3734. }
  3735. } // namespace impl
  3736. } // namespace ws
  3737. namespace detail {
  3738. // NOTE: This code came up with the following stackoverflow post:
  3739. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3740. inline std::string base64_encode(const std::string &in) {
  3741. static const auto lookup =
  3742. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3743. std::string out;
  3744. out.reserve(in.size());
  3745. auto val = 0;
  3746. auto valb = -6;
  3747. for (auto c : in) {
  3748. val = (val << 8) + static_cast<uint8_t>(c);
  3749. valb += 8;
  3750. while (valb >= 0) {
  3751. out.push_back(lookup[(val >> valb) & 0x3F]);
  3752. valb -= 6;
  3753. }
  3754. }
  3755. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3756. while (out.size() % 4) {
  3757. out.push_back('=');
  3758. }
  3759. return out;
  3760. }
  3761. inline std::string sha1(const std::string &input) {
  3762. // RFC 3174 SHA-1 implementation
  3763. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3764. return (x << n) | (x >> (32 - n));
  3765. };
  3766. uint32_t h0 = 0x67452301;
  3767. uint32_t h1 = 0xEFCDAB89;
  3768. uint32_t h2 = 0x98BADCFE;
  3769. uint32_t h3 = 0x10325476;
  3770. uint32_t h4 = 0xC3D2E1F0;
  3771. // Pre-processing: adding padding bits
  3772. std::string msg = input;
  3773. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3774. msg.push_back(static_cast<char>(0x80));
  3775. while (msg.size() % 64 != 56) {
  3776. msg.push_back(0);
  3777. }
  3778. // Append original length in bits as 64-bit big-endian
  3779. for (int i = 56; i >= 0; i -= 8) {
  3780. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3781. }
  3782. // Process each 512-bit chunk
  3783. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3784. uint32_t w[80];
  3785. for (size_t i = 0; i < 16; i++) {
  3786. w[i] =
  3787. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3788. << 24) |
  3789. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3790. << 16) |
  3791. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3792. << 8) |
  3793. (static_cast<uint32_t>(
  3794. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3795. }
  3796. for (int i = 16; i < 80; i++) {
  3797. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3798. }
  3799. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3800. for (int i = 0; i < 80; i++) {
  3801. uint32_t f, k;
  3802. if (i < 20) {
  3803. f = (b & c) | ((~b) & d);
  3804. k = 0x5A827999;
  3805. } else if (i < 40) {
  3806. f = b ^ c ^ d;
  3807. k = 0x6ED9EBA1;
  3808. } else if (i < 60) {
  3809. f = (b & c) | (b & d) | (c & d);
  3810. k = 0x8F1BBCDC;
  3811. } else {
  3812. f = b ^ c ^ d;
  3813. k = 0xCA62C1D6;
  3814. }
  3815. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3816. e = d;
  3817. d = c;
  3818. c = left_rotate(b, 30);
  3819. b = a;
  3820. a = temp;
  3821. }
  3822. h0 += a;
  3823. h1 += b;
  3824. h2 += c;
  3825. h3 += d;
  3826. h4 += e;
  3827. }
  3828. // Produce the final hash as a 20-byte binary string
  3829. std::string hash(20, '\0');
  3830. for (size_t i = 0; i < 4; i++) {
  3831. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3832. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3833. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3834. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3835. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3836. }
  3837. return hash;
  3838. }
  3839. inline std::string websocket_accept_key(const std::string &client_key) {
  3840. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3841. return base64_encode(sha1(client_key + magic));
  3842. }
  3843. inline bool is_websocket_upgrade(const Request &req) {
  3844. if (req.method != "GET") { return false; }
  3845. // Check Upgrade: websocket (case-insensitive)
  3846. auto upgrade_it = req.headers.find("Upgrade");
  3847. if (upgrade_it == req.headers.end()) { return false; }
  3848. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3849. if (upgrade_val != "websocket") { return false; }
  3850. // Check Connection header contains "Upgrade"
  3851. auto connection_it = req.headers.find("Connection");
  3852. if (connection_it == req.headers.end()) { return false; }
  3853. auto connection_val = case_ignore::to_lower(connection_it->second);
  3854. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3855. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3856. // RFC 6455 Section 4.2.1
  3857. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3858. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3859. return false;
  3860. }
  3861. static const std::string b64chars =
  3862. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3863. for (size_t i = 0; i < 22; i++) {
  3864. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3865. }
  3866. // Check Sec-WebSocket-Version: 13
  3867. auto version = req.get_header_value("Sec-WebSocket-Version");
  3868. if (version != "13") { return false; }
  3869. return true;
  3870. }
  3871. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3872. const char *data, size_t len, bool fin,
  3873. bool mask) {
  3874. // First byte: FIN + opcode
  3875. uint8_t header[2];
  3876. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3877. (static_cast<uint8_t>(opcode) & 0x0F));
  3878. // Second byte: MASK + payload length
  3879. if (len < 126) {
  3880. header[1] = static_cast<uint8_t>(len);
  3881. if (mask) { header[1] |= 0x80; }
  3882. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3883. } else if (len <= 0xFFFF) {
  3884. header[1] = 126;
  3885. if (mask) { header[1] |= 0x80; }
  3886. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3887. uint8_t ext[2];
  3888. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  3889. ext[1] = static_cast<uint8_t>(len & 0xFF);
  3890. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  3891. } else {
  3892. header[1] = 127;
  3893. if (mask) { header[1] |= 0x80; }
  3894. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3895. uint8_t ext[8];
  3896. for (int i = 7; i >= 0; i--) {
  3897. ext[7 - i] = static_cast<uint8_t>((len >> (i * 8)) & 0xFF);
  3898. }
  3899. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  3900. }
  3901. if (mask) {
  3902. // Generate random mask key
  3903. thread_local std::mt19937 rng(std::random_device{}());
  3904. uint8_t mask_key[4];
  3905. auto r = rng();
  3906. std::memcpy(mask_key, &r, 4);
  3907. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  3908. // Write masked payload in chunks
  3909. const size_t chunk_size = 4096;
  3910. std::vector<char> buf((std::min)(len, chunk_size));
  3911. for (size_t offset = 0; offset < len; offset += chunk_size) {
  3912. size_t n = (std::min)(chunk_size, len - offset);
  3913. for (size_t i = 0; i < n; i++) {
  3914. buf[i] =
  3915. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  3916. }
  3917. if (strm.write(buf.data(), n) < 0) { return false; }
  3918. }
  3919. } else {
  3920. if (len > 0) {
  3921. if (strm.write(data, len) < 0) { return false; }
  3922. }
  3923. }
  3924. return true;
  3925. }
  3926. } // namespace detail
  3927. namespace ws {
  3928. namespace impl {
  3929. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  3930. std::string &payload, bool &fin,
  3931. bool expect_masked, size_t max_len) {
  3932. // Read first 2 bytes
  3933. uint8_t header[2];
  3934. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  3935. fin = (header[0] & 0x80) != 0;
  3936. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  3937. if (header[0] & 0x70) { return false; }
  3938. opcode = static_cast<Opcode>(header[0] & 0x0F);
  3939. bool masked = (header[1] & 0x80) != 0;
  3940. uint64_t payload_len = header[1] & 0x7F;
  3941. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  3942. // MUST have a payload length of 125 bytes or less
  3943. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  3944. if (is_control) {
  3945. if (!fin) { return false; }
  3946. if (payload_len > 125) { return false; }
  3947. }
  3948. if (masked != expect_masked) { return false; }
  3949. // Extended payload length
  3950. if (payload_len == 126) {
  3951. uint8_t ext[2];
  3952. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  3953. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  3954. } else if (payload_len == 127) {
  3955. uint8_t ext[8];
  3956. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  3957. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  3958. if (ext[0] & 0x80) { return false; }
  3959. payload_len = 0;
  3960. for (int i = 0; i < 8; i++) {
  3961. payload_len = (payload_len << 8) | ext[i];
  3962. }
  3963. }
  3964. if (payload_len > max_len) { return false; }
  3965. // Read mask key if present
  3966. uint8_t mask_key[4] = {0};
  3967. if (masked) {
  3968. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  3969. }
  3970. // Read payload
  3971. payload.resize(static_cast<size_t>(payload_len));
  3972. if (payload_len > 0) {
  3973. size_t total_read = 0;
  3974. while (total_read < payload_len) {
  3975. auto n = strm.read(&payload[total_read],
  3976. static_cast<size_t>(payload_len - total_read));
  3977. if (n <= 0) { return false; }
  3978. total_read += static_cast<size_t>(n);
  3979. }
  3980. }
  3981. // Unmask if needed
  3982. if (masked) {
  3983. for (size_t i = 0; i < payload.size(); i++) {
  3984. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  3985. }
  3986. }
  3987. return true;
  3988. }
  3989. } // namespace impl
  3990. } // namespace ws
  3991. namespace detail {
  3992. inline bool is_valid_path(const std::string &path) {
  3993. size_t level = 0;
  3994. size_t i = 0;
  3995. // Skip slash
  3996. while (i < path.size() && path[i] == '/') {
  3997. i++;
  3998. }
  3999. while (i < path.size()) {
  4000. // Read component
  4001. auto beg = i;
  4002. while (i < path.size() && path[i] != '/') {
  4003. if (path[i] == '\0') {
  4004. return false;
  4005. } else if (path[i] == '\\') {
  4006. return false;
  4007. }
  4008. i++;
  4009. }
  4010. auto len = i - beg;
  4011. assert(len > 0);
  4012. if (!path.compare(beg, len, ".")) {
  4013. ;
  4014. } else if (!path.compare(beg, len, "..")) {
  4015. if (level == 0) { return false; }
  4016. level--;
  4017. } else {
  4018. level++;
  4019. }
  4020. // Skip slash
  4021. while (i < path.size() && path[i] == '/') {
  4022. i++;
  4023. }
  4024. }
  4025. return true;
  4026. }
  4027. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4028. #if defined(_WIN32)
  4029. char buf[_MAX_PATH];
  4030. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4031. resolved = buf;
  4032. #else
  4033. char buf[PATH_MAX];
  4034. if (realpath(path, buf) == nullptr) { return false; }
  4035. resolved = buf;
  4036. #endif
  4037. return true;
  4038. }
  4039. inline bool is_path_within_base(const std::string &resolved_path,
  4040. const std::string &resolved_base) {
  4041. #if defined(_WIN32)
  4042. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4043. resolved_base.size()) == 0;
  4044. #else
  4045. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4046. resolved_base.size()) == 0;
  4047. #endif
  4048. }
  4049. inline FileStat::FileStat(const std::string &path) {
  4050. #if defined(_WIN32)
  4051. auto wpath = u8string_to_wstring(path.c_str());
  4052. ret_ = _wstat(wpath.c_str(), &st_);
  4053. #else
  4054. ret_ = stat(path.c_str(), &st_);
  4055. #endif
  4056. }
  4057. inline bool FileStat::is_file() const {
  4058. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4059. }
  4060. inline bool FileStat::is_dir() const {
  4061. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4062. }
  4063. inline time_t FileStat::mtime() const {
  4064. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4065. : static_cast<time_t>(-1);
  4066. }
  4067. inline size_t FileStat::size() const {
  4068. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4069. }
  4070. inline std::string encode_path(const std::string &s) {
  4071. std::string result;
  4072. result.reserve(s.size());
  4073. for (size_t i = 0; s[i]; i++) {
  4074. switch (s[i]) {
  4075. case ' ': result += "%20"; break;
  4076. case '+': result += "%2B"; break;
  4077. case '\r': result += "%0D"; break;
  4078. case '\n': result += "%0A"; break;
  4079. case '\'': result += "%27"; break;
  4080. case ',': result += "%2C"; break;
  4081. // case ':': result += "%3A"; break; // ok? probably...
  4082. case ';': result += "%3B"; break;
  4083. default:
  4084. auto c = static_cast<uint8_t>(s[i]);
  4085. if (c >= 0x80) {
  4086. result += '%';
  4087. char hex[4];
  4088. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4089. assert(len == 2);
  4090. result.append(hex, static_cast<size_t>(len));
  4091. } else {
  4092. result += s[i];
  4093. }
  4094. break;
  4095. }
  4096. }
  4097. return result;
  4098. }
  4099. inline std::string file_extension(const std::string &path) {
  4100. std::smatch m;
  4101. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4102. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4103. return std::string();
  4104. }
  4105. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4106. template <typename T>
  4107. inline bool parse_header(const char *beg, const char *end, T fn);
  4108. template <typename T>
  4109. inline bool parse_header(const char *beg, const char *end, T fn) {
  4110. // Skip trailing spaces and tabs.
  4111. while (beg < end && is_space_or_tab(end[-1])) {
  4112. end--;
  4113. }
  4114. auto p = beg;
  4115. while (p < end && *p != ':') {
  4116. p++;
  4117. }
  4118. auto name = std::string(beg, p);
  4119. if (!detail::fields::is_field_name(name)) { return false; }
  4120. if (p == end) { return false; }
  4121. auto key_end = p;
  4122. if (*p++ != ':') { return false; }
  4123. while (p < end && is_space_or_tab(*p)) {
  4124. p++;
  4125. }
  4126. if (p <= end) {
  4127. auto key_len = key_end - beg;
  4128. if (!key_len) { return false; }
  4129. auto key = std::string(beg, key_end);
  4130. auto val = std::string(p, end);
  4131. if (!detail::fields::is_field_value(val)) { return false; }
  4132. if (case_ignore::equal(key, "Location") ||
  4133. case_ignore::equal(key, "Referer")) {
  4134. fn(key, val);
  4135. } else {
  4136. fn(key, decode_path_component(val));
  4137. }
  4138. return true;
  4139. }
  4140. return false;
  4141. }
  4142. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4143. const Headers &src_headers) {
  4144. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4145. // transfer coding is complete when a chunk with a chunk-size of zero is
  4146. // received, possibly followed by a trailer section, and finally terminated by
  4147. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4148. //
  4149. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4150. // doesn't care for the existence of the final CRLF. In other words, it seems
  4151. // to be ok whether the final CRLF exists or not in the chunked data.
  4152. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4153. //
  4154. // According to the reference code in RFC 9112, cpp-httplib now allows
  4155. // chunked transfer coding data without the final CRLF.
  4156. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4157. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4158. "transfer-encoding",
  4159. "content-length",
  4160. "host",
  4161. "authorization",
  4162. "www-authenticate",
  4163. "proxy-authenticate",
  4164. "proxy-authorization",
  4165. "cookie",
  4166. "set-cookie",
  4167. "cache-control",
  4168. "expect",
  4169. "max-forwards",
  4170. "pragma",
  4171. "range",
  4172. "te",
  4173. "age",
  4174. "expires",
  4175. "date",
  4176. "location",
  4177. "retry-after",
  4178. "vary",
  4179. "warning",
  4180. "content-encoding",
  4181. "content-type",
  4182. "content-range",
  4183. "trailer"};
  4184. case_ignore::unordered_set<std::string> declared_trailers;
  4185. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4186. if (trailer_header && std::strlen(trailer_header)) {
  4187. auto len = std::strlen(trailer_header);
  4188. split(trailer_header, trailer_header + len, ',',
  4189. [&](const char *b, const char *e) {
  4190. const char *kbeg = b;
  4191. const char *kend = e;
  4192. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4193. ++kbeg;
  4194. }
  4195. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4196. --kend;
  4197. }
  4198. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4199. if (!key.empty() &&
  4200. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4201. declared_trailers.insert(key);
  4202. }
  4203. });
  4204. }
  4205. size_t trailer_header_count = 0;
  4206. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4207. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4208. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4209. constexpr auto line_terminator_len = 2;
  4210. auto line_beg = line_reader.ptr();
  4211. auto line_end =
  4212. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4213. if (!parse_header(line_beg, line_end,
  4214. [&](const std::string &key, const std::string &val) {
  4215. if (declared_trailers.find(key) !=
  4216. declared_trailers.end()) {
  4217. dest.emplace(key, val);
  4218. trailer_header_count++;
  4219. }
  4220. })) {
  4221. return false;
  4222. }
  4223. if (!line_reader.getline()) { return false; }
  4224. }
  4225. return true;
  4226. }
  4227. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4228. size_t right) {
  4229. while (b + left < e && is_space_or_tab(b[left])) {
  4230. left++;
  4231. }
  4232. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4233. right--;
  4234. }
  4235. return std::make_pair(left, right);
  4236. }
  4237. inline std::string trim_copy(const std::string &s) {
  4238. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4239. return s.substr(r.first, r.second - r.first);
  4240. }
  4241. inline std::string trim_double_quotes_copy(const std::string &s) {
  4242. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4243. return s.substr(1, s.size() - 2);
  4244. }
  4245. return s;
  4246. }
  4247. inline void
  4248. divide(const char *data, std::size_t size, char d,
  4249. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4250. fn) {
  4251. const auto it = std::find(data, data + size, d);
  4252. const auto found = static_cast<std::size_t>(it != data + size);
  4253. const auto lhs_data = data;
  4254. const auto lhs_size = static_cast<std::size_t>(it - data);
  4255. const auto rhs_data = it + found;
  4256. const auto rhs_size = size - lhs_size - found;
  4257. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4258. }
  4259. inline void
  4260. divide(const std::string &str, char d,
  4261. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4262. fn) {
  4263. divide(str.data(), str.size(), d, std::move(fn));
  4264. }
  4265. inline void split(const char *b, const char *e, char d,
  4266. std::function<void(const char *, const char *)> fn) {
  4267. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4268. }
  4269. inline void split(const char *b, const char *e, char d, size_t m,
  4270. std::function<void(const char *, const char *)> fn) {
  4271. size_t i = 0;
  4272. size_t beg = 0;
  4273. size_t count = 1;
  4274. while (e ? (b + i < e) : (b[i] != '\0')) {
  4275. if (b[i] == d && count < m) {
  4276. auto r = trim(b, e, beg, i);
  4277. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4278. beg = i + 1;
  4279. count++;
  4280. }
  4281. i++;
  4282. }
  4283. if (i) {
  4284. auto r = trim(b, e, beg, i);
  4285. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4286. }
  4287. }
  4288. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4289. std::function<bool(const char *, const char *)> fn) {
  4290. size_t i = 0;
  4291. size_t beg = 0;
  4292. size_t count = 1;
  4293. while (e ? (b + i < e) : (b[i] != '\0')) {
  4294. if (b[i] == d && count < m) {
  4295. auto r = trim(b, e, beg, i);
  4296. if (r.first < r.second) {
  4297. auto found = fn(&b[r.first], &b[r.second]);
  4298. if (found) { return true; }
  4299. }
  4300. beg = i + 1;
  4301. count++;
  4302. }
  4303. i++;
  4304. }
  4305. if (i) {
  4306. auto r = trim(b, e, beg, i);
  4307. if (r.first < r.second) {
  4308. auto found = fn(&b[r.first], &b[r.second]);
  4309. if (found) { return true; }
  4310. }
  4311. }
  4312. return false;
  4313. }
  4314. inline bool split_find(const char *b, const char *e, char d,
  4315. std::function<bool(const char *, const char *)> fn) {
  4316. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4317. std::move(fn));
  4318. }
  4319. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4320. size_t fixed_buffer_size)
  4321. : strm_(strm), fixed_buffer_(fixed_buffer),
  4322. fixed_buffer_size_(fixed_buffer_size) {}
  4323. inline const char *stream_line_reader::ptr() const {
  4324. if (growable_buffer_.empty()) {
  4325. return fixed_buffer_;
  4326. } else {
  4327. return growable_buffer_.data();
  4328. }
  4329. }
  4330. inline size_t stream_line_reader::size() const {
  4331. if (growable_buffer_.empty()) {
  4332. return fixed_buffer_used_size_;
  4333. } else {
  4334. return growable_buffer_.size();
  4335. }
  4336. }
  4337. inline bool stream_line_reader::end_with_crlf() const {
  4338. auto end = ptr() + size();
  4339. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4340. }
  4341. inline bool stream_line_reader::getline() {
  4342. fixed_buffer_used_size_ = 0;
  4343. growable_buffer_.clear();
  4344. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4345. char prev_byte = 0;
  4346. #endif
  4347. for (size_t i = 0;; i++) {
  4348. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4349. // Treat exceptionally long lines as an error to
  4350. // prevent infinite loops/memory exhaustion
  4351. return false;
  4352. }
  4353. char byte;
  4354. auto n = strm_.read(&byte, 1);
  4355. if (n < 0) {
  4356. return false;
  4357. } else if (n == 0) {
  4358. if (i == 0) {
  4359. return false;
  4360. } else {
  4361. break;
  4362. }
  4363. }
  4364. append(byte);
  4365. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4366. if (byte == '\n') { break; }
  4367. #else
  4368. if (prev_byte == '\r' && byte == '\n') { break; }
  4369. prev_byte = byte;
  4370. #endif
  4371. }
  4372. return true;
  4373. }
  4374. inline void stream_line_reader::append(char c) {
  4375. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4376. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4377. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4378. } else {
  4379. if (growable_buffer_.empty()) {
  4380. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4381. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4382. }
  4383. growable_buffer_ += c;
  4384. }
  4385. }
  4386. inline mmap::mmap(const char *path) { open(path); }
  4387. inline mmap::~mmap() { close(); }
  4388. inline bool mmap::open(const char *path) {
  4389. close();
  4390. #if defined(_WIN32)
  4391. auto wpath = u8string_to_wstring(path);
  4392. if (wpath.empty()) { return false; }
  4393. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  4394. OPEN_EXISTING, NULL);
  4395. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4396. LARGE_INTEGER size{};
  4397. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4398. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4399. // See:
  4400. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4401. if (static_cast<ULONGLONG>(size.QuadPart) >
  4402. (std::numeric_limits<decltype(size_)>::max)()) {
  4403. // `size_t` might be 32-bits, on 32-bits Windows.
  4404. return false;
  4405. }
  4406. size_ = static_cast<size_t>(size.QuadPart);
  4407. hMapping_ =
  4408. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4409. // Special treatment for an empty file...
  4410. if (hMapping_ == NULL && size_ == 0) {
  4411. close();
  4412. is_open_empty_file = true;
  4413. return true;
  4414. }
  4415. if (hMapping_ == NULL) {
  4416. close();
  4417. return false;
  4418. }
  4419. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4420. if (addr_ == nullptr) {
  4421. close();
  4422. return false;
  4423. }
  4424. #else
  4425. fd_ = ::open(path, O_RDONLY);
  4426. if (fd_ == -1) { return false; }
  4427. struct stat sb;
  4428. if (fstat(fd_, &sb) == -1) {
  4429. close();
  4430. return false;
  4431. }
  4432. size_ = static_cast<size_t>(sb.st_size);
  4433. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4434. // Special treatment for an empty file...
  4435. if (addr_ == MAP_FAILED && size_ == 0) {
  4436. close();
  4437. is_open_empty_file = true;
  4438. return false;
  4439. }
  4440. #endif
  4441. return true;
  4442. }
  4443. inline bool mmap::is_open() const {
  4444. return is_open_empty_file ? true : addr_ != nullptr;
  4445. }
  4446. inline size_t mmap::size() const { return size_; }
  4447. inline const char *mmap::data() const {
  4448. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4449. }
  4450. inline void mmap::close() {
  4451. #if defined(_WIN32)
  4452. if (addr_) {
  4453. ::UnmapViewOfFile(addr_);
  4454. addr_ = nullptr;
  4455. }
  4456. if (hMapping_) {
  4457. ::CloseHandle(hMapping_);
  4458. hMapping_ = NULL;
  4459. }
  4460. if (hFile_ != INVALID_HANDLE_VALUE) {
  4461. ::CloseHandle(hFile_);
  4462. hFile_ = INVALID_HANDLE_VALUE;
  4463. }
  4464. is_open_empty_file = false;
  4465. #else
  4466. if (addr_ != nullptr) {
  4467. munmap(addr_, size_);
  4468. addr_ = nullptr;
  4469. }
  4470. if (fd_ != -1) {
  4471. ::close(fd_);
  4472. fd_ = -1;
  4473. }
  4474. #endif
  4475. size_ = 0;
  4476. }
  4477. inline int close_socket(socket_t sock) {
  4478. #ifdef _WIN32
  4479. return closesocket(sock);
  4480. #else
  4481. return close(sock);
  4482. #endif
  4483. }
  4484. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4485. ssize_t res = 0;
  4486. while (true) {
  4487. res = fn();
  4488. if (res < 0 && errno == EINTR) {
  4489. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4490. continue;
  4491. }
  4492. break;
  4493. }
  4494. return res;
  4495. }
  4496. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4497. return handle_EINTR([&]() {
  4498. return recv(sock,
  4499. #ifdef _WIN32
  4500. static_cast<char *>(ptr), static_cast<int>(size),
  4501. #else
  4502. ptr, size,
  4503. #endif
  4504. flags);
  4505. });
  4506. }
  4507. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4508. int flags) {
  4509. return handle_EINTR([&]() {
  4510. return send(sock,
  4511. #ifdef _WIN32
  4512. static_cast<const char *>(ptr), static_cast<int>(size),
  4513. #else
  4514. ptr, size,
  4515. #endif
  4516. flags);
  4517. });
  4518. }
  4519. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4520. #ifdef _WIN32
  4521. return ::WSAPoll(fds, nfds, timeout);
  4522. #else
  4523. return ::poll(fds, nfds, timeout);
  4524. #endif
  4525. }
  4526. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4527. time_t usec) {
  4528. struct pollfd pfd;
  4529. pfd.fd = sock;
  4530. pfd.events = events;
  4531. pfd.revents = 0;
  4532. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4533. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4534. }
  4535. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4536. return select_impl(sock, POLLIN, sec, usec);
  4537. }
  4538. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4539. return select_impl(sock, POLLOUT, sec, usec);
  4540. }
  4541. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4542. time_t usec) {
  4543. struct pollfd pfd_read;
  4544. pfd_read.fd = sock;
  4545. pfd_read.events = POLLIN | POLLOUT;
  4546. pfd_read.revents = 0;
  4547. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4548. auto poll_res =
  4549. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4550. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4551. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4552. auto error = 0;
  4553. socklen_t len = sizeof(error);
  4554. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4555. reinterpret_cast<char *>(&error), &len);
  4556. auto successful = res >= 0 && !error;
  4557. return successful ? Error::Success : Error::Connection;
  4558. }
  4559. return Error::Connection;
  4560. }
  4561. inline bool is_socket_alive(socket_t sock) {
  4562. const auto val = detail::select_read(sock, 0, 0);
  4563. if (val == 0) {
  4564. return true;
  4565. } else if (val < 0 && errno == EBADF) {
  4566. return false;
  4567. }
  4568. char buf[1];
  4569. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4570. }
  4571. class SocketStream final : public Stream {
  4572. public:
  4573. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4574. time_t write_timeout_sec, time_t write_timeout_usec,
  4575. time_t max_timeout_msec = 0,
  4576. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4577. (std::chrono::steady_clock::time_point::min)());
  4578. ~SocketStream() override;
  4579. bool is_readable() const override;
  4580. bool wait_readable() const override;
  4581. bool wait_writable() const override;
  4582. bool is_peer_alive() const override;
  4583. ssize_t read(char *ptr, size_t size) override;
  4584. ssize_t write(const char *ptr, size_t size) override;
  4585. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4586. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4587. socket_t socket() const override;
  4588. time_t duration() const override;
  4589. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4590. private:
  4591. socket_t sock_;
  4592. time_t read_timeout_sec_;
  4593. time_t read_timeout_usec_;
  4594. time_t write_timeout_sec_;
  4595. time_t write_timeout_usec_;
  4596. time_t max_timeout_msec_;
  4597. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4598. std::vector<char> read_buff_;
  4599. size_t read_buff_off_ = 0;
  4600. size_t read_buff_content_size_ = 0;
  4601. static const size_t read_buff_size_ = 1024l * 4;
  4602. };
  4603. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4604. time_t keep_alive_timeout_sec) {
  4605. using namespace std::chrono;
  4606. const auto interval_usec =
  4607. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4608. // Avoid expensive `steady_clock::now()` call for the first time
  4609. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4610. const auto start = steady_clock::now() - microseconds{interval_usec};
  4611. const auto timeout = seconds{keep_alive_timeout_sec};
  4612. while (true) {
  4613. if (svr_sock == INVALID_SOCKET) {
  4614. break; // Server socket is closed
  4615. }
  4616. auto val = select_read(sock, 0, interval_usec);
  4617. if (val < 0) {
  4618. break; // Ssocket error
  4619. } else if (val == 0) {
  4620. if (steady_clock::now() - start > timeout) {
  4621. break; // Timeout
  4622. }
  4623. } else {
  4624. return true; // Ready for read
  4625. }
  4626. }
  4627. return false;
  4628. }
  4629. template <typename T>
  4630. inline bool
  4631. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4632. size_t keep_alive_max_count,
  4633. time_t keep_alive_timeout_sec, T callback) {
  4634. assert(keep_alive_max_count > 0);
  4635. auto ret = false;
  4636. auto count = keep_alive_max_count;
  4637. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4638. auto close_connection = count == 1;
  4639. auto connection_closed = false;
  4640. ret = callback(close_connection, connection_closed);
  4641. if (!ret || connection_closed) { break; }
  4642. count--;
  4643. }
  4644. return ret;
  4645. }
  4646. template <typename T>
  4647. inline bool
  4648. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4649. size_t keep_alive_max_count,
  4650. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4651. time_t read_timeout_usec, time_t write_timeout_sec,
  4652. time_t write_timeout_usec, T callback) {
  4653. return process_server_socket_core(
  4654. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4655. [&](bool close_connection, bool &connection_closed) {
  4656. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4657. write_timeout_sec, write_timeout_usec);
  4658. return callback(strm, close_connection, connection_closed);
  4659. });
  4660. }
  4661. inline bool process_client_socket(
  4662. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4663. time_t write_timeout_sec, time_t write_timeout_usec,
  4664. time_t max_timeout_msec,
  4665. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4666. std::function<bool(Stream &)> callback) {
  4667. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4668. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4669. start_time);
  4670. return callback(strm);
  4671. }
  4672. inline int shutdown_socket(socket_t sock) {
  4673. #ifdef _WIN32
  4674. return shutdown(sock, SD_BOTH);
  4675. #else
  4676. return shutdown(sock, SHUT_RDWR);
  4677. #endif
  4678. }
  4679. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4680. if (s.size() > 1 && s[0] == '\0') {
  4681. auto ret = s;
  4682. ret[0] = '@';
  4683. return ret;
  4684. }
  4685. return s;
  4686. }
  4687. inline std::string
  4688. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4689. if (s.size() > 1 && s[0] == '@') {
  4690. auto ret = s;
  4691. ret[0] = '\0';
  4692. return ret;
  4693. }
  4694. return s;
  4695. }
  4696. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4697. const struct addrinfo *hints,
  4698. struct addrinfo **res, time_t timeout_sec) {
  4699. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4700. if (timeout_sec <= 0) {
  4701. // No timeout specified, use standard getaddrinfo
  4702. return getaddrinfo(node, service, hints, res);
  4703. }
  4704. #ifdef _WIN32
  4705. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4706. OVERLAPPED overlapped = {0};
  4707. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4708. if (!event) { return EAI_FAIL; }
  4709. overlapped.hEvent = event;
  4710. PADDRINFOEXW result_addrinfo = nullptr;
  4711. HANDLE cancel_handle = nullptr;
  4712. ADDRINFOEXW hints_ex = {0};
  4713. if (hints) {
  4714. hints_ex.ai_flags = hints->ai_flags;
  4715. hints_ex.ai_family = hints->ai_family;
  4716. hints_ex.ai_socktype = hints->ai_socktype;
  4717. hints_ex.ai_protocol = hints->ai_protocol;
  4718. }
  4719. auto wnode = u8string_to_wstring(node);
  4720. auto wservice = u8string_to_wstring(service);
  4721. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4722. hints ? &hints_ex : nullptr, &result_addrinfo,
  4723. nullptr, &overlapped, nullptr, &cancel_handle);
  4724. if (ret == WSA_IO_PENDING) {
  4725. auto wait_result =
  4726. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4727. if (wait_result == WAIT_TIMEOUT) {
  4728. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4729. ::CloseHandle(event);
  4730. return EAI_AGAIN;
  4731. }
  4732. DWORD bytes_returned;
  4733. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4734. &bytes_returned, FALSE)) {
  4735. ::CloseHandle(event);
  4736. return ::WSAGetLastError();
  4737. }
  4738. }
  4739. ::CloseHandle(event);
  4740. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4741. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4742. return 0;
  4743. }
  4744. return ret;
  4745. #elif TARGET_OS_MAC
  4746. if (!node) { return EAI_NONAME; }
  4747. // macOS implementation using CFHost API for asynchronous DNS resolution
  4748. CFStringRef hostname_ref = CFStringCreateWithCString(
  4749. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4750. if (!hostname_ref) { return EAI_MEMORY; }
  4751. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4752. CFRelease(hostname_ref);
  4753. if (!host_ref) { return EAI_MEMORY; }
  4754. // Set up context for callback
  4755. struct CFHostContext {
  4756. bool completed = false;
  4757. bool success = false;
  4758. CFArrayRef addresses = nullptr;
  4759. std::mutex mutex;
  4760. std::condition_variable cv;
  4761. } context;
  4762. CFHostClientContext client_context;
  4763. memset(&client_context, 0, sizeof(client_context));
  4764. client_context.info = &context;
  4765. // Set callback
  4766. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4767. const CFStreamError *error, void *info) {
  4768. auto ctx = static_cast<CFHostContext *>(info);
  4769. std::lock_guard<std::mutex> lock(ctx->mutex);
  4770. if (error && error->error != 0) {
  4771. ctx->success = false;
  4772. } else {
  4773. Boolean hasBeenResolved;
  4774. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4775. if (ctx->addresses && hasBeenResolved) {
  4776. CFRetain(ctx->addresses);
  4777. ctx->success = true;
  4778. } else {
  4779. ctx->success = false;
  4780. }
  4781. }
  4782. ctx->completed = true;
  4783. ctx->cv.notify_one();
  4784. };
  4785. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4786. CFRelease(host_ref);
  4787. return EAI_SYSTEM;
  4788. }
  4789. // Schedule on run loop
  4790. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4791. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4792. // Start resolution
  4793. CFStreamError stream_error;
  4794. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4795. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4796. CFRelease(host_ref);
  4797. return EAI_FAIL;
  4798. }
  4799. // Wait for completion with timeout
  4800. auto timeout_time =
  4801. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4802. bool timed_out = false;
  4803. {
  4804. std::unique_lock<std::mutex> lock(context.mutex);
  4805. while (!context.completed) {
  4806. auto now = std::chrono::steady_clock::now();
  4807. if (now >= timeout_time) {
  4808. timed_out = true;
  4809. break;
  4810. }
  4811. // Run the runloop for a short time
  4812. lock.unlock();
  4813. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4814. lock.lock();
  4815. }
  4816. }
  4817. // Clean up
  4818. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4819. CFHostSetClient(host_ref, nullptr, nullptr);
  4820. if (timed_out || !context.completed) {
  4821. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4822. CFRelease(host_ref);
  4823. return EAI_AGAIN;
  4824. }
  4825. if (!context.success || !context.addresses) {
  4826. CFRelease(host_ref);
  4827. return EAI_NODATA;
  4828. }
  4829. // Convert CFArray to addrinfo
  4830. CFIndex count = CFArrayGetCount(context.addresses);
  4831. if (count == 0) {
  4832. CFRelease(context.addresses);
  4833. CFRelease(host_ref);
  4834. return EAI_NODATA;
  4835. }
  4836. struct addrinfo *result_addrinfo = nullptr;
  4837. struct addrinfo **current = &result_addrinfo;
  4838. for (CFIndex i = 0; i < count; i++) {
  4839. CFDataRef addr_data =
  4840. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4841. if (!addr_data) continue;
  4842. const struct sockaddr *sockaddr_ptr =
  4843. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4844. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4845. // Allocate addrinfo structure
  4846. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4847. if (!*current) {
  4848. freeaddrinfo(result_addrinfo);
  4849. CFRelease(context.addresses);
  4850. CFRelease(host_ref);
  4851. return EAI_MEMORY;
  4852. }
  4853. memset(*current, 0, sizeof(struct addrinfo));
  4854. // Set up addrinfo fields
  4855. (*current)->ai_family = sockaddr_ptr->sa_family;
  4856. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4857. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4858. (*current)->ai_addrlen = sockaddr_len;
  4859. // Copy sockaddr
  4860. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4861. if (!(*current)->ai_addr) {
  4862. freeaddrinfo(result_addrinfo);
  4863. CFRelease(context.addresses);
  4864. CFRelease(host_ref);
  4865. return EAI_MEMORY;
  4866. }
  4867. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4868. // Set port if service is specified
  4869. if (service && *service) {
  4870. int port = 0;
  4871. if (parse_port(service, strlen(service), port)) {
  4872. if (sockaddr_ptr->sa_family == AF_INET) {
  4873. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4874. ->sin_port = htons(static_cast<uint16_t>(port));
  4875. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4876. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4877. ->sin6_port = htons(static_cast<uint16_t>(port));
  4878. }
  4879. }
  4880. }
  4881. current = &((*current)->ai_next);
  4882. }
  4883. CFRelease(context.addresses);
  4884. CFRelease(host_ref);
  4885. *res = result_addrinfo;
  4886. return 0;
  4887. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4888. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4889. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4890. struct gaicb request;
  4891. struct gaicb *requests[1] = {&request};
  4892. struct sigevent sevp;
  4893. struct timespec timeout;
  4894. // Initialize the request structure
  4895. memset(&request, 0, sizeof(request));
  4896. request.ar_name = node;
  4897. request.ar_service = service;
  4898. request.ar_request = hints;
  4899. // Set up timeout
  4900. timeout.tv_sec = timeout_sec;
  4901. timeout.tv_nsec = 0;
  4902. // Initialize sigevent structure (not used, but required)
  4903. memset(&sevp, 0, sizeof(sevp));
  4904. sevp.sigev_notify = SIGEV_NONE;
  4905. // Start asynchronous resolution
  4906. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4907. if (start_result != 0) { return start_result; }
  4908. // Wait for completion with timeout
  4909. int wait_result =
  4910. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4911. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4912. // Completed successfully, get the result
  4913. int gai_result = gai_error(&request);
  4914. if (gai_result == 0) {
  4915. *res = request.ar_result;
  4916. return 0;
  4917. } else {
  4918. // Clean up on error
  4919. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4920. return gai_result;
  4921. }
  4922. } else if (wait_result == EAI_AGAIN) {
  4923. // Timeout occurred, cancel the request
  4924. gai_cancel(&request);
  4925. return EAI_AGAIN;
  4926. } else {
  4927. // Other error occurred
  4928. gai_cancel(&request);
  4929. return wait_result;
  4930. }
  4931. #else
  4932. // Fallback implementation using thread-based timeout for other Unix systems
  4933. struct GetAddrInfoState {
  4934. ~GetAddrInfoState() {
  4935. if (info) { freeaddrinfo(info); }
  4936. }
  4937. std::mutex mutex;
  4938. std::condition_variable result_cv;
  4939. bool completed = false;
  4940. int result = EAI_SYSTEM;
  4941. std::string node;
  4942. std::string service;
  4943. struct addrinfo hints;
  4944. struct addrinfo *info = nullptr;
  4945. };
  4946. // Allocate on the heap, so the resolver thread can keep using the data.
  4947. auto state = std::make_shared<GetAddrInfoState>();
  4948. if (node) { state->node = node; }
  4949. state->service = service;
  4950. state->hints = *hints;
  4951. std::thread resolve_thread([state]() {
  4952. auto thread_result =
  4953. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4954. &state->info);
  4955. std::lock_guard<std::mutex> lock(state->mutex);
  4956. state->result = thread_result;
  4957. state->completed = true;
  4958. state->result_cv.notify_one();
  4959. });
  4960. // Wait for completion or timeout
  4961. std::unique_lock<std::mutex> lock(state->mutex);
  4962. auto finished =
  4963. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4964. [&] { return state->completed; });
  4965. if (finished) {
  4966. // Operation completed within timeout
  4967. resolve_thread.join();
  4968. *res = state->info;
  4969. state->info = nullptr; // Pass ownership to caller
  4970. return state->result;
  4971. } else {
  4972. // Timeout occurred
  4973. resolve_thread.detach(); // Let the thread finish in background
  4974. return EAI_AGAIN; // Return timeout error
  4975. }
  4976. #endif
  4977. #else
  4978. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4979. return getaddrinfo(node, service, hints, res);
  4980. #endif
  4981. }
  4982. template <typename BindOrConnect>
  4983. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4984. int address_family, int socket_flags, bool tcp_nodelay,
  4985. bool ipv6_v6only, SocketOptions socket_options,
  4986. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4987. // Get address info
  4988. const char *node = nullptr;
  4989. struct addrinfo hints;
  4990. struct addrinfo *result;
  4991. memset(&hints, 0, sizeof(struct addrinfo));
  4992. hints.ai_socktype = SOCK_STREAM;
  4993. hints.ai_protocol = IPPROTO_IP;
  4994. if (!ip.empty()) {
  4995. node = ip.c_str();
  4996. // Ask getaddrinfo to convert IP in c-string to address
  4997. hints.ai_family = AF_UNSPEC;
  4998. hints.ai_flags = AI_NUMERICHOST;
  4999. } else {
  5000. if (!host.empty()) { node = host.c_str(); }
  5001. hints.ai_family = address_family;
  5002. hints.ai_flags = socket_flags;
  5003. }
  5004. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5005. if (hints.ai_family == AF_UNIX) {
  5006. const auto addrlen = host.length();
  5007. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5008. #ifdef SOCK_CLOEXEC
  5009. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5010. hints.ai_protocol);
  5011. #else
  5012. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5013. #endif
  5014. if (sock != INVALID_SOCKET) {
  5015. sockaddr_un addr{};
  5016. addr.sun_family = AF_UNIX;
  5017. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5018. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5019. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5020. hints.ai_addrlen = static_cast<socklen_t>(
  5021. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5022. #ifndef SOCK_CLOEXEC
  5023. #ifndef _WIN32
  5024. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5025. #endif
  5026. #endif
  5027. if (socket_options) { socket_options(sock); }
  5028. #ifdef _WIN32
  5029. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5030. // remove the option.
  5031. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5032. #endif
  5033. bool dummy;
  5034. if (!bind_or_connect(sock, hints, dummy)) {
  5035. close_socket(sock);
  5036. sock = INVALID_SOCKET;
  5037. }
  5038. }
  5039. return sock;
  5040. }
  5041. #endif
  5042. auto service = std::to_string(port);
  5043. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5044. timeout_sec)) {
  5045. #if defined __linux__ && !defined __ANDROID__
  5046. res_init();
  5047. #endif
  5048. return INVALID_SOCKET;
  5049. }
  5050. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5051. for (auto rp = result; rp; rp = rp->ai_next) {
  5052. // Create a socket
  5053. #ifdef _WIN32
  5054. auto sock =
  5055. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5056. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5057. /**
  5058. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5059. * and above the socket creation fails on older Windows Systems.
  5060. *
  5061. * Let's try to create a socket the old way in this case.
  5062. *
  5063. * Reference:
  5064. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5065. *
  5066. * WSA_FLAG_NO_HANDLE_INHERIT:
  5067. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5068. * SP1, and later
  5069. *
  5070. */
  5071. if (sock == INVALID_SOCKET) {
  5072. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5073. }
  5074. #else
  5075. #ifdef SOCK_CLOEXEC
  5076. auto sock =
  5077. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5078. #else
  5079. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5080. #endif
  5081. #endif
  5082. if (sock == INVALID_SOCKET) { continue; }
  5083. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5084. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5085. close_socket(sock);
  5086. continue;
  5087. }
  5088. #endif
  5089. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5090. if (rp->ai_family == AF_INET6) {
  5091. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5092. }
  5093. if (socket_options) { socket_options(sock); }
  5094. // bind or connect
  5095. auto quit = false;
  5096. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5097. close_socket(sock);
  5098. if (quit) { break; }
  5099. }
  5100. return INVALID_SOCKET;
  5101. }
  5102. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5103. #ifdef _WIN32
  5104. auto flags = nonblocking ? 1UL : 0UL;
  5105. ioctlsocket(sock, FIONBIO, &flags);
  5106. #else
  5107. auto flags = fcntl(sock, F_GETFL, 0);
  5108. fcntl(sock, F_SETFL,
  5109. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5110. #endif
  5111. }
  5112. inline bool is_connection_error() {
  5113. #ifdef _WIN32
  5114. return WSAGetLastError() != WSAEWOULDBLOCK;
  5115. #else
  5116. return errno != EINPROGRESS;
  5117. #endif
  5118. }
  5119. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5120. struct addrinfo hints;
  5121. struct addrinfo *result;
  5122. memset(&hints, 0, sizeof(struct addrinfo));
  5123. hints.ai_family = AF_UNSPEC;
  5124. hints.ai_socktype = SOCK_STREAM;
  5125. hints.ai_protocol = 0;
  5126. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5127. return false;
  5128. }
  5129. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5130. auto ret = false;
  5131. for (auto rp = result; rp; rp = rp->ai_next) {
  5132. const auto &ai = *rp;
  5133. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5134. ret = true;
  5135. break;
  5136. }
  5137. }
  5138. return ret;
  5139. }
  5140. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5141. #define USE_IF2IP
  5142. #endif
  5143. #ifdef USE_IF2IP
  5144. inline std::string if2ip(int address_family, const std::string &ifn) {
  5145. struct ifaddrs *ifap;
  5146. getifaddrs(&ifap);
  5147. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5148. std::string addr_candidate;
  5149. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5150. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5151. (AF_UNSPEC == address_family ||
  5152. ifa->ifa_addr->sa_family == address_family)) {
  5153. if (ifa->ifa_addr->sa_family == AF_INET) {
  5154. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5155. char buf[INET_ADDRSTRLEN];
  5156. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5157. return std::string(buf, INET_ADDRSTRLEN);
  5158. }
  5159. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5160. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5161. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5162. char buf[INET6_ADDRSTRLEN] = {};
  5163. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5164. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5165. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5166. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5167. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5168. } else {
  5169. return std::string(buf, INET6_ADDRSTRLEN);
  5170. }
  5171. }
  5172. }
  5173. }
  5174. }
  5175. }
  5176. return addr_candidate;
  5177. }
  5178. #endif
  5179. inline socket_t create_client_socket(
  5180. const std::string &host, const std::string &ip, int port,
  5181. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5182. SocketOptions socket_options, time_t connection_timeout_sec,
  5183. time_t connection_timeout_usec, time_t read_timeout_sec,
  5184. time_t read_timeout_usec, time_t write_timeout_sec,
  5185. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5186. auto sock = create_socket(
  5187. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5188. std::move(socket_options),
  5189. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5190. if (!intf.empty()) {
  5191. #ifdef USE_IF2IP
  5192. auto ip_from_if = if2ip(address_family, intf);
  5193. if (ip_from_if.empty()) { ip_from_if = intf; }
  5194. if (!bind_ip_address(sock2, ip_from_if)) {
  5195. error = Error::BindIPAddress;
  5196. return false;
  5197. }
  5198. #endif
  5199. }
  5200. set_nonblocking(sock2, true);
  5201. auto ret =
  5202. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5203. if (ret < 0) {
  5204. if (is_connection_error()) {
  5205. error = Error::Connection;
  5206. return false;
  5207. }
  5208. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5209. connection_timeout_usec);
  5210. if (error != Error::Success) {
  5211. if (error == Error::ConnectionTimeout) { quit = true; }
  5212. return false;
  5213. }
  5214. }
  5215. set_nonblocking(sock2, false);
  5216. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5217. read_timeout_usec);
  5218. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5219. write_timeout_usec);
  5220. error = Error::Success;
  5221. return true;
  5222. },
  5223. connection_timeout_sec); // Pass DNS timeout
  5224. if (sock != INVALID_SOCKET) {
  5225. error = Error::Success;
  5226. } else {
  5227. if (error == Error::Success) { error = Error::Connection; }
  5228. }
  5229. return sock;
  5230. }
  5231. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5232. socklen_t addr_len, std::string &ip, int &port) {
  5233. if (addr.ss_family == AF_INET) {
  5234. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5235. } else if (addr.ss_family == AF_INET6) {
  5236. port =
  5237. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5238. } else {
  5239. return false;
  5240. }
  5241. std::array<char, NI_MAXHOST> ipstr{};
  5242. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5243. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5244. 0, NI_NUMERICHOST)) {
  5245. return false;
  5246. }
  5247. ip = ipstr.data();
  5248. return true;
  5249. }
  5250. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5251. struct sockaddr_storage addr;
  5252. socklen_t addr_len = sizeof(addr);
  5253. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5254. &addr_len)) {
  5255. get_ip_and_port(addr, addr_len, ip, port);
  5256. }
  5257. }
  5258. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5259. struct sockaddr_storage addr;
  5260. socklen_t addr_len = sizeof(addr);
  5261. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5262. &addr_len)) {
  5263. #ifndef _WIN32
  5264. if (addr.ss_family == AF_UNIX) {
  5265. #if defined(__linux__)
  5266. struct ucred ucred;
  5267. socklen_t len = sizeof(ucred);
  5268. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5269. port = ucred.pid;
  5270. }
  5271. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5272. pid_t pid;
  5273. socklen_t len = sizeof(pid);
  5274. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5275. port = pid;
  5276. }
  5277. #endif
  5278. return;
  5279. }
  5280. #endif
  5281. get_ip_and_port(addr, addr_len, ip, port);
  5282. }
  5283. }
  5284. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5285. unsigned int h) {
  5286. return (l == 0)
  5287. ? h
  5288. : str2tag_core(
  5289. s + 1, l - 1,
  5290. // Unsets the 6 high bits of h, therefore no overflow happens
  5291. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5292. h * 33) ^
  5293. static_cast<unsigned char>(*s));
  5294. }
  5295. inline unsigned int str2tag(const std::string &s) {
  5296. return str2tag_core(s.data(), s.size(), 0);
  5297. }
  5298. namespace udl {
  5299. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5300. return str2tag_core(s, l, 0);
  5301. }
  5302. } // namespace udl
  5303. inline std::string
  5304. find_content_type(const std::string &path,
  5305. const std::map<std::string, std::string> &user_data,
  5306. const std::string &default_content_type) {
  5307. auto ext = file_extension(path);
  5308. auto it = user_data.find(ext);
  5309. if (it != user_data.end()) { return it->second; }
  5310. using udl::operator""_t;
  5311. switch (str2tag(ext)) {
  5312. default: return default_content_type;
  5313. case "css"_t: return "text/css";
  5314. case "csv"_t: return "text/csv";
  5315. case "htm"_t:
  5316. case "html"_t: return "text/html";
  5317. case "js"_t:
  5318. case "mjs"_t: return "text/javascript";
  5319. case "txt"_t: return "text/plain";
  5320. case "vtt"_t: return "text/vtt";
  5321. case "apng"_t: return "image/apng";
  5322. case "avif"_t: return "image/avif";
  5323. case "bmp"_t: return "image/bmp";
  5324. case "gif"_t: return "image/gif";
  5325. case "png"_t: return "image/png";
  5326. case "svg"_t: return "image/svg+xml";
  5327. case "webp"_t: return "image/webp";
  5328. case "ico"_t: return "image/x-icon";
  5329. case "tif"_t: return "image/tiff";
  5330. case "tiff"_t: return "image/tiff";
  5331. case "jpg"_t:
  5332. case "jpeg"_t: return "image/jpeg";
  5333. case "mp4"_t: return "video/mp4";
  5334. case "mpeg"_t: return "video/mpeg";
  5335. case "webm"_t: return "video/webm";
  5336. case "mp3"_t: return "audio/mp3";
  5337. case "mpga"_t: return "audio/mpeg";
  5338. case "weba"_t: return "audio/webm";
  5339. case "wav"_t: return "audio/wave";
  5340. case "otf"_t: return "font/otf";
  5341. case "ttf"_t: return "font/ttf";
  5342. case "woff"_t: return "font/woff";
  5343. case "woff2"_t: return "font/woff2";
  5344. case "7z"_t: return "application/x-7z-compressed";
  5345. case "atom"_t: return "application/atom+xml";
  5346. case "pdf"_t: return "application/pdf";
  5347. case "json"_t: return "application/json";
  5348. case "rss"_t: return "application/rss+xml";
  5349. case "tar"_t: return "application/x-tar";
  5350. case "xht"_t:
  5351. case "xhtml"_t: return "application/xhtml+xml";
  5352. case "xslt"_t: return "application/xslt+xml";
  5353. case "xml"_t: return "application/xml";
  5354. case "gz"_t: return "application/gzip";
  5355. case "zip"_t: return "application/zip";
  5356. case "wasm"_t: return "application/wasm";
  5357. }
  5358. }
  5359. inline std::string
  5360. extract_media_type(const std::string &content_type,
  5361. std::map<std::string, std::string> *params = nullptr) {
  5362. // Extract type/subtype from Content-Type value (RFC 2045)
  5363. // e.g. "application/json; charset=utf-8" -> "application/json"
  5364. auto media_type = content_type;
  5365. auto semicolon_pos = media_type.find(';');
  5366. if (semicolon_pos != std::string::npos) {
  5367. auto param_str = media_type.substr(semicolon_pos + 1);
  5368. media_type = media_type.substr(0, semicolon_pos);
  5369. if (params) {
  5370. // Parse parameters: key=value pairs separated by ';'
  5371. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5372. [&](const char *b, const char *e) {
  5373. std::string key;
  5374. std::string val;
  5375. split(b, e, '=', [&](const char *b2, const char *e2) {
  5376. if (key.empty()) {
  5377. key.assign(b2, e2);
  5378. } else {
  5379. val.assign(b2, e2);
  5380. }
  5381. });
  5382. if (!key.empty()) {
  5383. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5384. }
  5385. });
  5386. }
  5387. }
  5388. // Trim whitespace from media type
  5389. return trim_copy(media_type);
  5390. }
  5391. inline bool can_compress_content_type(const std::string &content_type) {
  5392. using udl::operator""_t;
  5393. auto mime_type = extract_media_type(content_type);
  5394. auto tag = str2tag(mime_type);
  5395. switch (tag) {
  5396. case "image/svg+xml"_t:
  5397. case "application/javascript"_t:
  5398. case "application/x-javascript"_t:
  5399. case "application/json"_t:
  5400. case "application/ld+json"_t:
  5401. case "application/xml"_t:
  5402. case "application/xhtml+xml"_t:
  5403. case "application/rss+xml"_t:
  5404. case "application/atom+xml"_t:
  5405. case "application/xslt+xml"_t:
  5406. case "application/protobuf"_t: return true;
  5407. case "text/event-stream"_t: return false;
  5408. default: return !mime_type.rfind("text/", 0);
  5409. }
  5410. }
  5411. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5412. double &quality) {
  5413. quality = 1.0;
  5414. token.clear();
  5415. // Split on first ';': left = token name, right = parameters
  5416. const char *params_b = nullptr;
  5417. std::size_t params_len = 0;
  5418. divide(
  5419. b, static_cast<std::size_t>(e - b), ';',
  5420. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5421. auto r = trim(lb, lb + llen, 0, llen);
  5422. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5423. params_b = rb;
  5424. params_len = rlen;
  5425. });
  5426. if (token.empty()) { return false; }
  5427. if (params_len == 0) { return true; }
  5428. // Scan parameters for q= (stops on first match)
  5429. bool invalid = false;
  5430. split_find(params_b, params_b + params_len, ';',
  5431. (std::numeric_limits<size_t>::max)(),
  5432. [&](const char *pb, const char *pe) -> bool {
  5433. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5434. auto len = static_cast<size_t>(pe - pb);
  5435. if (len < 2) { return false; }
  5436. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5437. return false;
  5438. }
  5439. // Trim the value portion
  5440. auto r = trim(pb, pe, 2, len);
  5441. if (r.first >= r.second) {
  5442. invalid = true;
  5443. return true;
  5444. }
  5445. double v = 0.0;
  5446. auto res = from_chars(pb + r.first, pb + r.second, v);
  5447. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5448. invalid = true;
  5449. return true;
  5450. }
  5451. quality = v;
  5452. return true;
  5453. });
  5454. return !invalid;
  5455. }
  5456. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5457. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5458. return EncodingType::None;
  5459. }
  5460. const auto &s = req.get_header_value("Accept-Encoding");
  5461. if (s.empty()) { return EncodingType::None; }
  5462. // Single-pass: iterate tokens and track the best supported encoding.
  5463. // Server preference breaks ties (br > gzip > zstd).
  5464. EncodingType best = EncodingType::None;
  5465. double best_q = 0.0; // q=0 means "not acceptable"
  5466. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5467. auto priority = [](EncodingType t) -> int {
  5468. switch (t) {
  5469. case EncodingType::Brotli: return 0;
  5470. case EncodingType::Gzip: return 1;
  5471. case EncodingType::Zstd: return 2;
  5472. default: return 3;
  5473. }
  5474. };
  5475. std::string name;
  5476. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5477. double quality = 1.0;
  5478. if (!parse_quality(b, e, name, quality)) { return; }
  5479. if (quality <= 0.0) { return; }
  5480. EncodingType type = EncodingType::None;
  5481. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5482. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5483. #endif
  5484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5485. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5486. type = EncodingType::Gzip;
  5487. }
  5488. #endif
  5489. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5490. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5491. type = EncodingType::Zstd;
  5492. }
  5493. #endif
  5494. if (type == EncodingType::None) { return; }
  5495. // Higher q-value wins; for equal q, server preference breaks ties
  5496. if (quality > best_q ||
  5497. (quality == best_q && priority(type) < priority(best))) {
  5498. best_q = quality;
  5499. best = type;
  5500. }
  5501. });
  5502. return best;
  5503. }
  5504. inline bool nocompressor::compress(const char *data, size_t data_length,
  5505. bool /*last*/, Callback callback) {
  5506. if (!data_length) { return true; }
  5507. return callback(data, data_length);
  5508. }
  5509. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5510. inline gzip_compressor::gzip_compressor() {
  5511. std::memset(&strm_, 0, sizeof(strm_));
  5512. strm_.zalloc = Z_NULL;
  5513. strm_.zfree = Z_NULL;
  5514. strm_.opaque = Z_NULL;
  5515. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5516. Z_DEFAULT_STRATEGY) == Z_OK;
  5517. }
  5518. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5519. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5520. bool last, Callback callback) {
  5521. assert(is_valid_);
  5522. do {
  5523. constexpr size_t max_avail_in =
  5524. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5525. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5526. (std::min)(data_length, max_avail_in));
  5527. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5528. data_length -= strm_.avail_in;
  5529. data += strm_.avail_in;
  5530. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5531. auto ret = Z_OK;
  5532. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5533. do {
  5534. strm_.avail_out = static_cast<uInt>(buff.size());
  5535. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5536. ret = deflate(&strm_, flush);
  5537. if (ret == Z_STREAM_ERROR) { return false; }
  5538. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5539. return false;
  5540. }
  5541. } while (strm_.avail_out == 0);
  5542. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5543. (flush == Z_NO_FLUSH && ret == Z_OK));
  5544. assert(strm_.avail_in == 0);
  5545. } while (data_length > 0);
  5546. return true;
  5547. }
  5548. inline gzip_decompressor::gzip_decompressor() {
  5549. std::memset(&strm_, 0, sizeof(strm_));
  5550. strm_.zalloc = Z_NULL;
  5551. strm_.zfree = Z_NULL;
  5552. strm_.opaque = Z_NULL;
  5553. // 15 is the value of wbits, which should be at the maximum possible value
  5554. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5555. // that the stream type should be automatically detected either gzip or
  5556. // deflate.
  5557. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5558. }
  5559. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5560. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5561. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5562. Callback callback) {
  5563. assert(is_valid_);
  5564. auto ret = Z_OK;
  5565. do {
  5566. constexpr size_t max_avail_in =
  5567. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5568. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5569. (std::min)(data_length, max_avail_in));
  5570. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5571. data_length -= strm_.avail_in;
  5572. data += strm_.avail_in;
  5573. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5574. while (strm_.avail_in > 0 && ret == Z_OK) {
  5575. strm_.avail_out = static_cast<uInt>(buff.size());
  5576. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5577. ret = inflate(&strm_, Z_NO_FLUSH);
  5578. assert(ret != Z_STREAM_ERROR);
  5579. switch (ret) {
  5580. case Z_NEED_DICT:
  5581. case Z_DATA_ERROR:
  5582. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5583. }
  5584. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5585. return false;
  5586. }
  5587. }
  5588. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5589. } while (data_length > 0);
  5590. return true;
  5591. }
  5592. #endif
  5593. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5594. inline brotli_compressor::brotli_compressor() {
  5595. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5596. }
  5597. inline brotli_compressor::~brotli_compressor() {
  5598. BrotliEncoderDestroyInstance(state_);
  5599. }
  5600. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5601. bool last, Callback callback) {
  5602. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5603. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5604. auto available_in = data_length;
  5605. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5606. for (;;) {
  5607. if (last) {
  5608. if (BrotliEncoderIsFinished(state_)) { break; }
  5609. } else {
  5610. if (!available_in) { break; }
  5611. }
  5612. auto available_out = buff.size();
  5613. auto next_out = buff.data();
  5614. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5615. &available_out, &next_out, nullptr)) {
  5616. return false;
  5617. }
  5618. auto output_bytes = buff.size() - available_out;
  5619. if (output_bytes) {
  5620. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5621. }
  5622. }
  5623. return true;
  5624. }
  5625. inline brotli_decompressor::brotli_decompressor() {
  5626. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5627. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5628. : BROTLI_DECODER_RESULT_ERROR;
  5629. }
  5630. inline brotli_decompressor::~brotli_decompressor() {
  5631. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5632. }
  5633. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5634. inline bool brotli_decompressor::decompress(const char *data,
  5635. size_t data_length,
  5636. Callback callback) {
  5637. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5638. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5639. return 0;
  5640. }
  5641. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5642. size_t avail_in = data_length;
  5643. size_t total_out;
  5644. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5645. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5646. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5647. char *next_out = buff.data();
  5648. size_t avail_out = buff.size();
  5649. decoder_r = BrotliDecoderDecompressStream(
  5650. decoder_s, &avail_in, &next_in, &avail_out,
  5651. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5652. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5653. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5654. }
  5655. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5656. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5657. }
  5658. #endif
  5659. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5660. inline zstd_compressor::zstd_compressor() {
  5661. ctx_ = ZSTD_createCCtx();
  5662. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5663. }
  5664. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5665. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5666. bool last, Callback callback) {
  5667. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5668. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5669. ZSTD_inBuffer input = {data, data_length, 0};
  5670. bool finished;
  5671. do {
  5672. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5673. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5674. if (ZSTD_isError(remaining)) { return false; }
  5675. if (!callback(buff.data(), output.pos)) { return false; }
  5676. finished = last ? (remaining == 0) : (input.pos == input.size);
  5677. } while (!finished);
  5678. return true;
  5679. }
  5680. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5681. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5682. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5683. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5684. Callback callback) {
  5685. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5686. ZSTD_inBuffer input = {data, data_length, 0};
  5687. while (input.pos < input.size) {
  5688. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5689. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5690. if (ZSTD_isError(remaining)) { return false; }
  5691. if (!callback(buff.data(), output.pos)) { return false; }
  5692. }
  5693. return true;
  5694. }
  5695. #endif
  5696. inline std::unique_ptr<decompressor>
  5697. create_decompressor(const std::string &encoding) {
  5698. std::unique_ptr<decompressor> decompressor;
  5699. if (encoding == "gzip" || encoding == "deflate") {
  5700. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5701. decompressor = detail::make_unique<gzip_decompressor>();
  5702. #endif
  5703. } else if (encoding.find("br") != std::string::npos) {
  5704. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5705. decompressor = detail::make_unique<brotli_decompressor>();
  5706. #endif
  5707. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5708. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5709. decompressor = detail::make_unique<zstd_decompressor>();
  5710. #endif
  5711. }
  5712. return decompressor;
  5713. }
  5714. // Returns the best available compressor and its Content-Encoding name.
  5715. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5716. inline std::pair<std::unique_ptr<compressor>, const char *>
  5717. create_compressor() {
  5718. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5719. return {detail::make_unique<brotli_compressor>(), "br"};
  5720. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5721. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5722. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5723. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5724. #else
  5725. return {nullptr, nullptr};
  5726. #endif
  5727. }
  5728. inline bool is_prohibited_header_name(const std::string &name) {
  5729. using udl::operator""_t;
  5730. switch (str2tag(name)) {
  5731. case "REMOTE_ADDR"_t:
  5732. case "REMOTE_PORT"_t:
  5733. case "LOCAL_ADDR"_t:
  5734. case "LOCAL_PORT"_t: return true;
  5735. default: return false;
  5736. }
  5737. }
  5738. inline bool has_header(const Headers &headers, const std::string &key) {
  5739. if (is_prohibited_header_name(key)) { return false; }
  5740. return headers.find(key) != headers.end();
  5741. }
  5742. inline const char *get_header_value(const Headers &headers,
  5743. const std::string &key, const char *def,
  5744. size_t id) {
  5745. if (is_prohibited_header_name(key)) {
  5746. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5747. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5748. throw std::invalid_argument(msg);
  5749. #else
  5750. return "";
  5751. #endif
  5752. }
  5753. auto rng = headers.equal_range(key);
  5754. auto it = rng.first;
  5755. std::advance(it, static_cast<ssize_t>(id));
  5756. if (it != rng.second) { return it->second.c_str(); }
  5757. return def;
  5758. }
  5759. inline bool read_headers(Stream &strm, Headers &headers) {
  5760. const auto bufsiz = 2048;
  5761. char buf[bufsiz];
  5762. stream_line_reader line_reader(strm, buf, bufsiz);
  5763. size_t header_count = 0;
  5764. for (;;) {
  5765. if (!line_reader.getline()) { return false; }
  5766. // Check if the line ends with CRLF.
  5767. auto line_terminator_len = 2;
  5768. if (line_reader.end_with_crlf()) {
  5769. // Blank line indicates end of headers.
  5770. if (line_reader.size() == 2) { break; }
  5771. } else {
  5772. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5773. // Blank line indicates end of headers.
  5774. if (line_reader.size() == 1) { break; }
  5775. line_terminator_len = 1;
  5776. #else
  5777. continue; // Skip invalid line.
  5778. #endif
  5779. }
  5780. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5781. // Check header count limit
  5782. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5783. // Exclude line terminator
  5784. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5785. if (!parse_header(line_reader.ptr(), end,
  5786. [&](const std::string &key, const std::string &val) {
  5787. headers.emplace(key, val);
  5788. })) {
  5789. return false;
  5790. }
  5791. header_count++;
  5792. }
  5793. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5794. // headers that have different values to prevent request smuggling.
  5795. auto cl_range = headers.equal_range("Content-Length");
  5796. if (cl_range.first != cl_range.second) {
  5797. const auto &first_val = cl_range.first->second;
  5798. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5799. if (it->second != first_val) { return false; }
  5800. }
  5801. }
  5802. return true;
  5803. }
  5804. inline bool read_websocket_upgrade_response(Stream &strm,
  5805. const std::string &expected_accept,
  5806. std::string &selected_subprotocol) {
  5807. // Read status line
  5808. const auto bufsiz = 2048;
  5809. char buf[bufsiz];
  5810. stream_line_reader line_reader(strm, buf, bufsiz);
  5811. if (!line_reader.getline()) { return false; }
  5812. // Check for "HTTP/1.1 101"
  5813. auto line = std::string(line_reader.ptr(), line_reader.size());
  5814. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5815. // Parse headers using existing read_headers
  5816. Headers headers;
  5817. if (!read_headers(strm, headers)) { return false; }
  5818. // Verify Upgrade: websocket (case-insensitive)
  5819. auto upgrade_it = headers.find("Upgrade");
  5820. if (upgrade_it == headers.end()) { return false; }
  5821. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  5822. if (upgrade_val != "websocket") { return false; }
  5823. // Verify Connection header contains "Upgrade" (case-insensitive)
  5824. auto connection_it = headers.find("Connection");
  5825. if (connection_it == headers.end()) { return false; }
  5826. auto connection_val = case_ignore::to_lower(connection_it->second);
  5827. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  5828. // Verify Sec-WebSocket-Accept header value
  5829. auto it = headers.find("Sec-WebSocket-Accept");
  5830. if (it == headers.end() || it->second != expected_accept) { return false; }
  5831. // Extract negotiated subprotocol
  5832. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  5833. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  5834. return true;
  5835. }
  5836. enum class ReadContentResult {
  5837. Success, // Successfully read the content
  5838. PayloadTooLarge, // The content exceeds the specified payload limit
  5839. Error // An error occurred while reading the content
  5840. };
  5841. inline ReadContentResult read_content_with_length(
  5842. Stream &strm, size_t len, DownloadProgress progress,
  5843. ContentReceiverWithProgress out,
  5844. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  5845. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5846. detail::BodyReader br;
  5847. br.stream = &strm;
  5848. br.has_content_length = true;
  5849. br.content_length = len;
  5850. br.payload_max_length = payload_max_length;
  5851. br.chunked = false;
  5852. br.bytes_read = 0;
  5853. br.last_error = Error::Success;
  5854. size_t r = 0;
  5855. while (r < len) {
  5856. auto read_len = static_cast<size_t>(len - r);
  5857. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  5858. auto n = detail::read_body_content(&strm, br, buf, to_read);
  5859. if (n <= 0) {
  5860. // Check if it was a payload size error
  5861. if (br.last_error == Error::ExceedMaxPayloadSize) {
  5862. return ReadContentResult::PayloadTooLarge;
  5863. }
  5864. return ReadContentResult::Error;
  5865. }
  5866. if (!out(buf, static_cast<size_t>(n), r, len)) {
  5867. return ReadContentResult::Error;
  5868. }
  5869. r += static_cast<size_t>(n);
  5870. if (progress) {
  5871. if (!progress(r, len)) { return ReadContentResult::Error; }
  5872. }
  5873. }
  5874. return ReadContentResult::Success;
  5875. }
  5876. inline ReadContentResult
  5877. read_content_without_length(Stream &strm, size_t payload_max_length,
  5878. ContentReceiverWithProgress out) {
  5879. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5880. size_t r = 0;
  5881. for (;;) {
  5882. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  5883. if (n == 0) { return ReadContentResult::Success; }
  5884. if (n < 0) { return ReadContentResult::Error; }
  5885. // Check if adding this data would exceed the payload limit
  5886. if (r > payload_max_length ||
  5887. payload_max_length - r < static_cast<size_t>(n)) {
  5888. return ReadContentResult::PayloadTooLarge;
  5889. }
  5890. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  5891. return ReadContentResult::Error;
  5892. }
  5893. r += static_cast<size_t>(n);
  5894. }
  5895. return ReadContentResult::Success;
  5896. }
  5897. template <typename T>
  5898. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  5899. size_t payload_max_length,
  5900. ContentReceiverWithProgress out) {
  5901. detail::ChunkedDecoder dec(strm);
  5902. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5903. size_t total_len = 0;
  5904. for (;;) {
  5905. size_t chunk_offset = 0;
  5906. size_t chunk_total = 0;
  5907. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5908. if (n < 0) { return ReadContentResult::Error; }
  5909. if (n == 0) {
  5910. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5911. return ReadContentResult::Error;
  5912. }
  5913. return ReadContentResult::Success;
  5914. }
  5915. if (total_len > payload_max_length ||
  5916. payload_max_length - total_len < static_cast<size_t>(n)) {
  5917. return ReadContentResult::PayloadTooLarge;
  5918. }
  5919. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5920. return ReadContentResult::Error;
  5921. }
  5922. total_len += static_cast<size_t>(n);
  5923. }
  5924. }
  5925. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5926. return case_ignore::equal(
  5927. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5928. }
  5929. template <typename T, typename U>
  5930. bool prepare_content_receiver(T &x, int &status,
  5931. ContentReceiverWithProgress receiver,
  5932. bool decompress, size_t payload_max_length,
  5933. bool &exceed_payload_max_length, U callback) {
  5934. if (decompress) {
  5935. std::string encoding = x.get_header_value("Content-Encoding");
  5936. std::unique_ptr<decompressor> decompressor;
  5937. if (!encoding.empty()) {
  5938. decompressor = detail::create_decompressor(encoding);
  5939. if (!decompressor) {
  5940. // Unsupported encoding or no support compiled in
  5941. status = StatusCode::UnsupportedMediaType_415;
  5942. return false;
  5943. }
  5944. }
  5945. if (decompressor) {
  5946. if (decompressor->is_valid()) {
  5947. size_t decompressed_size = 0;
  5948. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5949. size_t off, size_t len) {
  5950. return decompressor->decompress(
  5951. buf, n, [&](const char *buf2, size_t n2) {
  5952. // Guard against zip-bomb: check
  5953. // decompressed size against limit.
  5954. if (payload_max_length > 0 &&
  5955. (decompressed_size >= payload_max_length ||
  5956. n2 > payload_max_length - decompressed_size)) {
  5957. exceed_payload_max_length = true;
  5958. return false;
  5959. }
  5960. decompressed_size += n2;
  5961. return receiver(buf2, n2, off, len);
  5962. });
  5963. };
  5964. return callback(std::move(out));
  5965. } else {
  5966. status = StatusCode::InternalServerError_500;
  5967. return false;
  5968. }
  5969. }
  5970. }
  5971. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5972. size_t len) {
  5973. return receiver(buf, n, off, len);
  5974. };
  5975. return callback(std::move(out));
  5976. }
  5977. template <typename T>
  5978. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5979. DownloadProgress progress,
  5980. ContentReceiverWithProgress receiver, bool decompress) {
  5981. bool exceed_payload_max_length = false;
  5982. return prepare_content_receiver(
  5983. x, status, std::move(receiver), decompress, payload_max_length,
  5984. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  5985. auto ret = true;
  5986. // Note: exceed_payload_max_length may also be set by the decompressor
  5987. // wrapper in prepare_content_receiver when the decompressed payload
  5988. // size exceeds the limit.
  5989. if (is_chunked_transfer_encoding(x.headers)) {
  5990. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5991. if (result == ReadContentResult::Success) {
  5992. ret = true;
  5993. } else if (result == ReadContentResult::PayloadTooLarge) {
  5994. exceed_payload_max_length = true;
  5995. ret = false;
  5996. } else {
  5997. ret = false;
  5998. }
  5999. } else if (!has_header(x.headers, "Content-Length")) {
  6000. auto result =
  6001. read_content_without_length(strm, payload_max_length, out);
  6002. if (result == ReadContentResult::Success) {
  6003. ret = true;
  6004. } else if (result == ReadContentResult::PayloadTooLarge) {
  6005. exceed_payload_max_length = true;
  6006. ret = false;
  6007. } else {
  6008. ret = false;
  6009. }
  6010. } else {
  6011. auto is_invalid_value = false;
  6012. auto len = get_header_value_u64(x.headers, "Content-Length",
  6013. (std::numeric_limits<size_t>::max)(),
  6014. 0, is_invalid_value);
  6015. if (is_invalid_value) {
  6016. ret = false;
  6017. } else if (len > 0) {
  6018. auto result = read_content_with_length(
  6019. strm, len, std::move(progress), out, payload_max_length);
  6020. ret = (result == ReadContentResult::Success);
  6021. if (result == ReadContentResult::PayloadTooLarge) {
  6022. exceed_payload_max_length = true;
  6023. }
  6024. }
  6025. }
  6026. if (!ret) {
  6027. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6028. : StatusCode::BadRequest_400;
  6029. }
  6030. return ret;
  6031. });
  6032. }
  6033. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6034. const std::string &path) {
  6035. std::string s = method;
  6036. s += ' ';
  6037. s += path;
  6038. s += " HTTP/1.1\r\n";
  6039. return strm.write(s.data(), s.size());
  6040. }
  6041. inline ssize_t write_response_line(Stream &strm, int status) {
  6042. std::string s = "HTTP/1.1 ";
  6043. s += std::to_string(status);
  6044. s += ' ';
  6045. s += httplib::status_message(status);
  6046. s += "\r\n";
  6047. return strm.write(s.data(), s.size());
  6048. }
  6049. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6050. ssize_t write_len = 0;
  6051. for (const auto &x : headers) {
  6052. std::string s;
  6053. s = x.first;
  6054. s += ": ";
  6055. s += x.second;
  6056. s += "\r\n";
  6057. auto len = strm.write(s.data(), s.size());
  6058. if (len < 0) { return len; }
  6059. write_len += len;
  6060. }
  6061. auto len = strm.write("\r\n");
  6062. if (len < 0) { return len; }
  6063. write_len += len;
  6064. return write_len;
  6065. }
  6066. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6067. size_t offset = 0;
  6068. while (offset < l) {
  6069. auto length = strm.write(d + offset, l - offset);
  6070. if (length < 0) { return false; }
  6071. offset += static_cast<size_t>(length);
  6072. }
  6073. return true;
  6074. }
  6075. template <typename T>
  6076. inline bool write_content_with_progress(Stream &strm,
  6077. const ContentProvider &content_provider,
  6078. size_t offset, size_t length,
  6079. T is_shutting_down,
  6080. const UploadProgress &upload_progress,
  6081. Error &error) {
  6082. size_t end_offset = offset + length;
  6083. size_t start_offset = offset;
  6084. auto ok = true;
  6085. DataSink data_sink;
  6086. data_sink.write = [&](const char *d, size_t l) -> bool {
  6087. if (ok) {
  6088. if (write_data(strm, d, l)) {
  6089. offset += l;
  6090. if (upload_progress && length > 0) {
  6091. size_t current_written = offset - start_offset;
  6092. if (!upload_progress(current_written, length)) {
  6093. ok = false;
  6094. return false;
  6095. }
  6096. }
  6097. } else {
  6098. ok = false;
  6099. }
  6100. }
  6101. return ok;
  6102. };
  6103. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6104. while (offset < end_offset && !is_shutting_down()) {
  6105. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6106. error = Error::Write;
  6107. return false;
  6108. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6109. error = Error::Canceled;
  6110. return false;
  6111. } else if (!ok) {
  6112. error = Error::Write;
  6113. return false;
  6114. }
  6115. }
  6116. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6117. error = Error::Write;
  6118. return false;
  6119. }
  6120. error = Error::Success;
  6121. return true;
  6122. }
  6123. template <typename T>
  6124. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6125. size_t offset, size_t length, T is_shutting_down,
  6126. Error &error) {
  6127. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6128. is_shutting_down, nullptr, error);
  6129. }
  6130. template <typename T>
  6131. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6132. size_t offset, size_t length,
  6133. const T &is_shutting_down) {
  6134. auto error = Error::Success;
  6135. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6136. error);
  6137. }
  6138. template <typename T>
  6139. inline bool
  6140. write_content_without_length(Stream &strm,
  6141. const ContentProvider &content_provider,
  6142. const T &is_shutting_down) {
  6143. size_t offset = 0;
  6144. auto data_available = true;
  6145. auto ok = true;
  6146. DataSink data_sink;
  6147. data_sink.write = [&](const char *d, size_t l) -> bool {
  6148. if (ok) {
  6149. offset += l;
  6150. if (!write_data(strm, d, l)) { ok = false; }
  6151. }
  6152. return ok;
  6153. };
  6154. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6155. data_sink.done = [&](void) { data_available = false; };
  6156. while (data_available && !is_shutting_down()) {
  6157. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6158. return false;
  6159. } else if (!content_provider(offset, 0, data_sink)) {
  6160. return false;
  6161. } else if (!ok) {
  6162. return false;
  6163. }
  6164. }
  6165. return !data_available; // true only if done() was called, false if shutting
  6166. // down
  6167. }
  6168. template <typename T, typename U>
  6169. inline bool
  6170. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6171. const T &is_shutting_down, U &compressor, Error &error) {
  6172. size_t offset = 0;
  6173. auto data_available = true;
  6174. auto ok = true;
  6175. DataSink data_sink;
  6176. data_sink.write = [&](const char *d, size_t l) -> bool {
  6177. if (ok) {
  6178. data_available = l > 0;
  6179. offset += l;
  6180. std::string payload;
  6181. if (compressor.compress(d, l, false,
  6182. [&](const char *data, size_t data_len) {
  6183. payload.append(data, data_len);
  6184. return true;
  6185. })) {
  6186. if (!payload.empty()) {
  6187. // Emit chunked response header and footer for each chunk
  6188. auto chunk =
  6189. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6190. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6191. }
  6192. } else {
  6193. ok = false;
  6194. }
  6195. }
  6196. return ok;
  6197. };
  6198. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6199. auto done_with_trailer = [&](const Headers *trailer) {
  6200. if (!ok) { return; }
  6201. data_available = false;
  6202. std::string payload;
  6203. if (!compressor.compress(nullptr, 0, true,
  6204. [&](const char *data, size_t data_len) {
  6205. payload.append(data, data_len);
  6206. return true;
  6207. })) {
  6208. ok = false;
  6209. return;
  6210. }
  6211. if (!payload.empty()) {
  6212. // Emit chunked response header and footer for each chunk
  6213. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6214. if (!write_data(strm, chunk.data(), chunk.size())) {
  6215. ok = false;
  6216. return;
  6217. }
  6218. }
  6219. constexpr const char done_marker[] = "0\r\n";
  6220. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6221. // Trailer
  6222. if (trailer) {
  6223. for (const auto &kv : *trailer) {
  6224. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6225. if (!write_data(strm, field_line.data(), field_line.size())) {
  6226. ok = false;
  6227. }
  6228. }
  6229. }
  6230. constexpr const char crlf[] = "\r\n";
  6231. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6232. };
  6233. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6234. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6235. done_with_trailer(&trailer);
  6236. };
  6237. while (data_available && !is_shutting_down()) {
  6238. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6239. error = Error::Write;
  6240. return false;
  6241. } else if (!content_provider(offset, 0, data_sink)) {
  6242. error = Error::Canceled;
  6243. return false;
  6244. } else if (!ok) {
  6245. error = Error::Write;
  6246. return false;
  6247. }
  6248. }
  6249. if (data_available) { // exited due to is_shutting_down(), not done()
  6250. error = Error::Write;
  6251. return false;
  6252. }
  6253. error = Error::Success;
  6254. return true;
  6255. }
  6256. template <typename T, typename U>
  6257. inline bool write_content_chunked(Stream &strm,
  6258. const ContentProvider &content_provider,
  6259. const T &is_shutting_down, U &compressor) {
  6260. auto error = Error::Success;
  6261. return write_content_chunked(strm, content_provider, is_shutting_down,
  6262. compressor, error);
  6263. }
  6264. template <typename T>
  6265. inline bool redirect(T &cli, Request &req, Response &res,
  6266. const std::string &path, const std::string &location,
  6267. Error &error) {
  6268. Request new_req = req;
  6269. new_req.path = path;
  6270. new_req.redirect_count_ -= 1;
  6271. if (res.status == StatusCode::SeeOther_303 &&
  6272. (req.method != "GET" && req.method != "HEAD")) {
  6273. new_req.method = "GET";
  6274. new_req.body.clear();
  6275. new_req.headers.clear();
  6276. }
  6277. Response new_res;
  6278. auto ret = cli.send(new_req, new_res, error);
  6279. if (ret) {
  6280. req = std::move(new_req);
  6281. res = std::move(new_res);
  6282. if (res.location.empty()) { res.location = location; }
  6283. }
  6284. return ret;
  6285. }
  6286. inline std::string params_to_query_str(const Params &params) {
  6287. std::string query;
  6288. for (auto it = params.begin(); it != params.end(); ++it) {
  6289. if (it != params.begin()) { query += '&'; }
  6290. query += encode_query_component(it->first);
  6291. query += '=';
  6292. query += encode_query_component(it->second);
  6293. }
  6294. return query;
  6295. }
  6296. inline void parse_query_text(const char *data, std::size_t size,
  6297. Params &params) {
  6298. std::set<std::string> cache;
  6299. split(data, data + size, '&', [&](const char *b, const char *e) {
  6300. std::string kv(b, e);
  6301. if (cache.find(kv) != cache.end()) { return; }
  6302. cache.insert(std::move(kv));
  6303. std::string key;
  6304. std::string val;
  6305. divide(b, static_cast<std::size_t>(e - b), '=',
  6306. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6307. std::size_t rhs_size) {
  6308. key.assign(lhs_data, lhs_size);
  6309. val.assign(rhs_data, rhs_size);
  6310. });
  6311. if (!key.empty()) {
  6312. params.emplace(decode_query_component(key), decode_query_component(val));
  6313. }
  6314. });
  6315. }
  6316. inline void parse_query_text(const std::string &s, Params &params) {
  6317. parse_query_text(s.data(), s.size(), params);
  6318. }
  6319. // Normalize a query string by decoding and re-encoding each key/value pair
  6320. // while preserving the original parameter order. This avoids double-encoding
  6321. // and ensures consistent encoding without reordering (unlike Params which
  6322. // uses std::multimap and sorts keys).
  6323. inline std::string normalize_query_string(const std::string &query) {
  6324. std::string result;
  6325. split(query.data(), query.data() + query.size(), '&',
  6326. [&](const char *b, const char *e) {
  6327. std::string key;
  6328. std::string val;
  6329. divide(b, static_cast<std::size_t>(e - b), '=',
  6330. [&](const char *lhs_data, std::size_t lhs_size,
  6331. const char *rhs_data, std::size_t rhs_size) {
  6332. key.assign(lhs_data, lhs_size);
  6333. val.assign(rhs_data, rhs_size);
  6334. });
  6335. if (!key.empty()) {
  6336. auto dec_key = decode_query_component(key);
  6337. auto dec_val = decode_query_component(val);
  6338. if (!result.empty()) { result += '&'; }
  6339. result += encode_query_component(dec_key);
  6340. if (!val.empty() || std::find(b, e, '=') != e) {
  6341. result += '=';
  6342. result += encode_query_component(dec_val);
  6343. }
  6344. }
  6345. });
  6346. return result;
  6347. }
  6348. inline bool parse_multipart_boundary(const std::string &content_type,
  6349. std::string &boundary) {
  6350. std::map<std::string, std::string> params;
  6351. extract_media_type(content_type, &params);
  6352. auto it = params.find("boundary");
  6353. if (it == params.end()) { return false; }
  6354. boundary = it->second;
  6355. return !boundary.empty();
  6356. }
  6357. inline void parse_disposition_params(const std::string &s, Params &params) {
  6358. std::set<std::string> cache;
  6359. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6360. std::string kv(b, e);
  6361. if (cache.find(kv) != cache.end()) { return; }
  6362. cache.insert(kv);
  6363. std::string key;
  6364. std::string val;
  6365. split(b, e, '=', [&](const char *b2, const char *e2) {
  6366. if (key.empty()) {
  6367. key.assign(b2, e2);
  6368. } else {
  6369. val.assign(b2, e2);
  6370. }
  6371. });
  6372. if (!key.empty()) {
  6373. params.emplace(trim_double_quotes_copy((key)),
  6374. trim_double_quotes_copy((val)));
  6375. }
  6376. });
  6377. }
  6378. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6379. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6380. #else
  6381. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6382. #endif
  6383. auto is_valid = [](const std::string &str) {
  6384. return std::all_of(str.cbegin(), str.cend(),
  6385. [](unsigned char c) { return std::isdigit(c); });
  6386. };
  6387. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6388. const auto pos = static_cast<size_t>(6);
  6389. const auto len = static_cast<size_t>(s.size() - 6);
  6390. auto all_valid_ranges = true;
  6391. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6392. if (!all_valid_ranges) { return; }
  6393. const auto it = std::find(b, e, '-');
  6394. if (it == e) {
  6395. all_valid_ranges = false;
  6396. return;
  6397. }
  6398. const auto lhs = std::string(b, it);
  6399. const auto rhs = std::string(it + 1, e);
  6400. if (!is_valid(lhs) || !is_valid(rhs)) {
  6401. all_valid_ranges = false;
  6402. return;
  6403. }
  6404. ssize_t first = -1;
  6405. if (!lhs.empty()) {
  6406. ssize_t v;
  6407. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6408. if (res.ec == std::errc{}) { first = v; }
  6409. }
  6410. ssize_t last = -1;
  6411. if (!rhs.empty()) {
  6412. ssize_t v;
  6413. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6414. if (res.ec == std::errc{}) { last = v; }
  6415. }
  6416. if ((first == -1 && last == -1) ||
  6417. (first != -1 && last != -1 && first > last)) {
  6418. all_valid_ranges = false;
  6419. return;
  6420. }
  6421. ranges.emplace_back(first, last);
  6422. });
  6423. return all_valid_ranges && !ranges.empty();
  6424. }
  6425. return false;
  6426. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6427. }
  6428. #else
  6429. } catch (...) { return false; }
  6430. #endif
  6431. inline bool parse_accept_header(const std::string &s,
  6432. std::vector<std::string> &content_types) {
  6433. content_types.clear();
  6434. // Empty string is considered valid (no preference)
  6435. if (s.empty()) { return true; }
  6436. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6437. if (s.front() == ',' || s.back() == ',' ||
  6438. s.find(",,") != std::string::npos) {
  6439. return false;
  6440. }
  6441. struct AcceptEntry {
  6442. std::string media_type;
  6443. double quality;
  6444. int order;
  6445. };
  6446. std::vector<AcceptEntry> entries;
  6447. int order = 0;
  6448. bool has_invalid_entry = false;
  6449. // Split by comma and parse each entry
  6450. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6451. std::string entry(b, e);
  6452. entry = trim_copy(entry);
  6453. if (entry.empty()) {
  6454. has_invalid_entry = true;
  6455. return;
  6456. }
  6457. AcceptEntry accept_entry;
  6458. accept_entry.order = order++;
  6459. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6460. accept_entry.media_type, accept_entry.quality)) {
  6461. has_invalid_entry = true;
  6462. return;
  6463. }
  6464. // Remove additional parameters from media type
  6465. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6466. // Basic validation of media type format
  6467. if (accept_entry.media_type.empty()) {
  6468. has_invalid_entry = true;
  6469. return;
  6470. }
  6471. // Check for basic media type format (should contain '/' or be '*')
  6472. if (accept_entry.media_type != "*" &&
  6473. accept_entry.media_type.find('/') == std::string::npos) {
  6474. has_invalid_entry = true;
  6475. return;
  6476. }
  6477. entries.push_back(std::move(accept_entry));
  6478. });
  6479. // Return false if any invalid entry was found
  6480. if (has_invalid_entry) { return false; }
  6481. // Sort by quality (descending), then by original order (ascending)
  6482. std::sort(entries.begin(), entries.end(),
  6483. [](const AcceptEntry &a, const AcceptEntry &b) {
  6484. if (a.quality != b.quality) {
  6485. return a.quality > b.quality; // Higher quality first
  6486. }
  6487. return a.order < b.order; // Earlier order first for same quality
  6488. });
  6489. // Extract sorted media types
  6490. content_types.reserve(entries.size());
  6491. for (auto &entry : entries) {
  6492. content_types.push_back(std::move(entry.media_type));
  6493. }
  6494. return true;
  6495. }
  6496. class FormDataParser {
  6497. public:
  6498. FormDataParser() = default;
  6499. void set_boundary(std::string &&boundary) {
  6500. boundary_ = std::move(boundary);
  6501. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6502. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6503. }
  6504. bool is_valid() const { return is_valid_; }
  6505. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6506. const ContentReceiver &content_callback) {
  6507. buf_append(buf, n);
  6508. while (buf_size() > 0) {
  6509. switch (state_) {
  6510. case 0: { // Initial boundary
  6511. auto pos = buf_find(dash_boundary_crlf_);
  6512. if (pos == buf_size()) { return true; }
  6513. buf_erase(pos + dash_boundary_crlf_.size());
  6514. state_ = 1;
  6515. break;
  6516. }
  6517. case 1: { // New entry
  6518. clear_file_info();
  6519. state_ = 2;
  6520. break;
  6521. }
  6522. case 2: { // Headers
  6523. auto pos = buf_find(crlf_);
  6524. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6525. while (pos < buf_size()) {
  6526. // Empty line
  6527. if (pos == 0) {
  6528. if (!header_callback(file_)) {
  6529. is_valid_ = false;
  6530. return false;
  6531. }
  6532. buf_erase(crlf_.size());
  6533. state_ = 3;
  6534. break;
  6535. }
  6536. const auto header = buf_head(pos);
  6537. if (!parse_header(header.data(), header.data() + header.size(),
  6538. [&](const std::string &, const std::string &) {})) {
  6539. is_valid_ = false;
  6540. return false;
  6541. }
  6542. // Parse and emplace space trimmed headers into a map
  6543. if (!parse_header(
  6544. header.data(), header.data() + header.size(),
  6545. [&](const std::string &key, const std::string &val) {
  6546. file_.headers.emplace(key, val);
  6547. })) {
  6548. is_valid_ = false;
  6549. return false;
  6550. }
  6551. constexpr const char header_content_type[] = "Content-Type:";
  6552. if (start_with_case_ignore(header, header_content_type)) {
  6553. file_.content_type =
  6554. trim_copy(header.substr(str_len(header_content_type)));
  6555. } else {
  6556. std::string disposition_params;
  6557. if (parse_content_disposition(header, disposition_params)) {
  6558. Params params;
  6559. parse_disposition_params(disposition_params, params);
  6560. auto it = params.find("name");
  6561. if (it != params.end()) {
  6562. file_.name = it->second;
  6563. } else {
  6564. is_valid_ = false;
  6565. return false;
  6566. }
  6567. it = params.find("filename");
  6568. if (it != params.end()) { file_.filename = it->second; }
  6569. it = params.find("filename*");
  6570. if (it != params.end()) {
  6571. // RFC 5987: only UTF-8 encoding is allowed
  6572. const auto &val = it->second;
  6573. constexpr const char utf8_prefix[] = "UTF-8''";
  6574. constexpr size_t prefix_len = str_len(utf8_prefix);
  6575. if (val.size() > prefix_len &&
  6576. start_with_case_ignore(val, utf8_prefix)) {
  6577. file_.filename = decode_path_component(
  6578. val.substr(prefix_len)); // override...
  6579. } else {
  6580. is_valid_ = false;
  6581. return false;
  6582. }
  6583. }
  6584. }
  6585. }
  6586. buf_erase(pos + crlf_.size());
  6587. pos = buf_find(crlf_);
  6588. }
  6589. if (state_ != 3) { return true; }
  6590. break;
  6591. }
  6592. case 3: { // Body
  6593. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6594. auto pos = buf_find(crlf_dash_boundary_);
  6595. if (pos < buf_size()) {
  6596. if (!content_callback(buf_data(), pos)) {
  6597. is_valid_ = false;
  6598. return false;
  6599. }
  6600. buf_erase(pos + crlf_dash_boundary_.size());
  6601. state_ = 4;
  6602. } else {
  6603. auto len = buf_size() - crlf_dash_boundary_.size();
  6604. if (len > 0) {
  6605. if (!content_callback(buf_data(), len)) {
  6606. is_valid_ = false;
  6607. return false;
  6608. }
  6609. buf_erase(len);
  6610. }
  6611. return true;
  6612. }
  6613. break;
  6614. }
  6615. case 4: { // Boundary
  6616. if (crlf_.size() > buf_size()) { return true; }
  6617. if (buf_start_with(crlf_)) {
  6618. buf_erase(crlf_.size());
  6619. state_ = 1;
  6620. } else {
  6621. if (dash_.size() > buf_size()) { return true; }
  6622. if (buf_start_with(dash_)) {
  6623. buf_erase(dash_.size());
  6624. is_valid_ = true;
  6625. buf_erase(buf_size()); // Remove epilogue
  6626. } else {
  6627. return true;
  6628. }
  6629. }
  6630. break;
  6631. }
  6632. }
  6633. }
  6634. return true;
  6635. }
  6636. private:
  6637. void clear_file_info() {
  6638. file_.name.clear();
  6639. file_.filename.clear();
  6640. file_.content_type.clear();
  6641. file_.headers.clear();
  6642. }
  6643. bool start_with_case_ignore(const std::string &a, const char *b,
  6644. size_t offset = 0) const {
  6645. const auto b_len = strlen(b);
  6646. if (a.size() < offset + b_len) { return false; }
  6647. for (size_t i = 0; i < b_len; i++) {
  6648. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6649. return false;
  6650. }
  6651. }
  6652. return true;
  6653. }
  6654. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6655. // Returns true if header matches, with the params portion in `params_out`.
  6656. bool parse_content_disposition(const std::string &header,
  6657. std::string &params_out) const {
  6658. constexpr const char prefix[] = "Content-Disposition:";
  6659. constexpr size_t prefix_len = str_len(prefix);
  6660. if (!start_with_case_ignore(header, prefix)) { return false; }
  6661. // Skip whitespace after "Content-Disposition:"
  6662. auto pos = prefix_len;
  6663. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6664. pos++;
  6665. }
  6666. // Match "form-data;" (case-insensitive)
  6667. constexpr const char form_data[] = "form-data;";
  6668. constexpr size_t form_data_len = str_len(form_data);
  6669. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6670. pos += form_data_len;
  6671. // Skip whitespace after "form-data;"
  6672. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6673. pos++;
  6674. }
  6675. params_out = header.substr(pos);
  6676. return true;
  6677. }
  6678. const std::string dash_ = "--";
  6679. const std::string crlf_ = "\r\n";
  6680. std::string boundary_;
  6681. std::string dash_boundary_crlf_;
  6682. std::string crlf_dash_boundary_;
  6683. size_t state_ = 0;
  6684. bool is_valid_ = false;
  6685. FormData file_;
  6686. // Buffer
  6687. bool start_with(const std::string &a, size_t spos, size_t epos,
  6688. const std::string &b) const {
  6689. if (epos - spos < b.size()) { return false; }
  6690. for (size_t i = 0; i < b.size(); i++) {
  6691. if (a[i + spos] != b[i]) { return false; }
  6692. }
  6693. return true;
  6694. }
  6695. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6696. const char *buf_data() const { return &buf_[buf_spos_]; }
  6697. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6698. bool buf_start_with(const std::string &s) const {
  6699. return start_with(buf_, buf_spos_, buf_epos_, s);
  6700. }
  6701. size_t buf_find(const std::string &s) const {
  6702. auto c = s.front();
  6703. size_t off = buf_spos_;
  6704. while (off < buf_epos_) {
  6705. auto pos = off;
  6706. while (true) {
  6707. if (pos == buf_epos_) { return buf_size(); }
  6708. if (buf_[pos] == c) { break; }
  6709. pos++;
  6710. }
  6711. auto remaining_size = buf_epos_ - pos;
  6712. if (s.size() > remaining_size) { return buf_size(); }
  6713. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6714. off = pos + 1;
  6715. }
  6716. return buf_size();
  6717. }
  6718. void buf_append(const char *data, size_t n) {
  6719. auto remaining_size = buf_size();
  6720. if (remaining_size > 0 && buf_spos_ > 0) {
  6721. for (size_t i = 0; i < remaining_size; i++) {
  6722. buf_[i] = buf_[buf_spos_ + i];
  6723. }
  6724. }
  6725. buf_spos_ = 0;
  6726. buf_epos_ = remaining_size;
  6727. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6728. for (size_t i = 0; i < n; i++) {
  6729. buf_[buf_epos_ + i] = data[i];
  6730. }
  6731. buf_epos_ += n;
  6732. }
  6733. void buf_erase(size_t size) { buf_spos_ += size; }
  6734. std::string buf_;
  6735. size_t buf_spos_ = 0;
  6736. size_t buf_epos_ = 0;
  6737. };
  6738. inline std::string random_string(size_t length) {
  6739. constexpr const char data[] =
  6740. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6741. thread_local auto engine([]() {
  6742. // std::random_device might actually be deterministic on some
  6743. // platforms, but due to lack of support in the c++ standard library,
  6744. // doing better requires either some ugly hacks or breaking portability.
  6745. std::random_device seed_gen;
  6746. // Request 128 bits of entropy for initialization
  6747. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6748. return std::mt19937(seed_sequence);
  6749. }());
  6750. std::string result;
  6751. for (size_t i = 0; i < length; i++) {
  6752. result += data[engine() % (sizeof(data) - 1)];
  6753. }
  6754. return result;
  6755. }
  6756. inline std::string make_multipart_data_boundary() {
  6757. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6758. }
  6759. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6760. auto valid = true;
  6761. for (size_t i = 0; i < boundary.size(); i++) {
  6762. auto c = boundary[i];
  6763. if (!std::isalnum(c) && c != '-' && c != '_') {
  6764. valid = false;
  6765. break;
  6766. }
  6767. }
  6768. return valid;
  6769. }
  6770. template <typename T>
  6771. inline std::string
  6772. serialize_multipart_formdata_item_begin(const T &item,
  6773. const std::string &boundary) {
  6774. std::string body = "--" + boundary + "\r\n";
  6775. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6776. if (!item.filename.empty()) {
  6777. body += "; filename=\"" + item.filename + "\"";
  6778. }
  6779. body += "\r\n";
  6780. if (!item.content_type.empty()) {
  6781. body += "Content-Type: " + item.content_type + "\r\n";
  6782. }
  6783. body += "\r\n";
  6784. return body;
  6785. }
  6786. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6787. inline std::string
  6788. serialize_multipart_formdata_finish(const std::string &boundary) {
  6789. return "--" + boundary + "--\r\n";
  6790. }
  6791. inline std::string
  6792. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  6793. return "multipart/form-data; boundary=" + boundary;
  6794. }
  6795. inline std::string
  6796. serialize_multipart_formdata(const UploadFormDataItems &items,
  6797. const std::string &boundary, bool finish = true) {
  6798. std::string body;
  6799. for (const auto &item : items) {
  6800. body += serialize_multipart_formdata_item_begin(item, boundary);
  6801. body += item.content + serialize_multipart_formdata_item_end();
  6802. }
  6803. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  6804. return body;
  6805. }
  6806. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  6807. const std::string &boundary) {
  6808. size_t total = 0;
  6809. for (const auto &item : items) {
  6810. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  6811. total += item.content.size();
  6812. total += serialize_multipart_formdata_item_end().size();
  6813. }
  6814. total += serialize_multipart_formdata_finish(boundary).size();
  6815. return total;
  6816. }
  6817. struct MultipartSegment {
  6818. const char *data;
  6819. size_t size;
  6820. };
  6821. // NOTE: items must outlive the returned ContentProvider
  6822. // (safe for synchronous use inside Post/Put/Patch)
  6823. inline ContentProvider
  6824. make_multipart_content_provider(const UploadFormDataItems &items,
  6825. const std::string &boundary) {
  6826. // Own the per-item header strings and the finish string
  6827. std::vector<std::string> owned;
  6828. owned.reserve(items.size() + 1);
  6829. for (const auto &item : items)
  6830. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  6831. owned.push_back(serialize_multipart_formdata_finish(boundary));
  6832. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  6833. std::vector<MultipartSegment> segs;
  6834. segs.reserve(items.size() * 3 + 1);
  6835. static const char crlf[] = "\r\n";
  6836. for (size_t i = 0; i < items.size(); i++) {
  6837. segs.push_back({owned[i].data(), owned[i].size()});
  6838. segs.push_back({items[i].content.data(), items[i].content.size()});
  6839. segs.push_back({crlf, 2});
  6840. }
  6841. segs.push_back({owned.back().data(), owned.back().size()});
  6842. struct MultipartState {
  6843. std::vector<std::string> owned;
  6844. std::vector<MultipartSegment> segs;
  6845. };
  6846. auto state = std::make_shared<MultipartState>();
  6847. state->owned = std::move(owned);
  6848. // `segs` holds raw pointers into owned strings; std::string move preserves
  6849. // the data pointer, so these pointers remain valid after the move above.
  6850. state->segs = std::move(segs);
  6851. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  6852. // Coalesce multiple small segments into fewer, larger writes to avoid
  6853. // excessive TCP packets when there are many form data items (#2410)
  6854. constexpr size_t kBufSize = 65536;
  6855. char buf[kBufSize];
  6856. size_t buf_len = 0;
  6857. size_t remaining = length;
  6858. // Find the first segment containing 'offset'
  6859. size_t pos = 0;
  6860. size_t seg_idx = 0;
  6861. for (; seg_idx < state->segs.size(); seg_idx++) {
  6862. const auto &seg = state->segs[seg_idx];
  6863. if (seg.size > 0 && offset - pos < seg.size) { break; }
  6864. pos += seg.size;
  6865. }
  6866. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  6867. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  6868. const auto &seg = state->segs[seg_idx];
  6869. size_t available = seg.size - seg_offset;
  6870. size_t to_copy = (std::min)(available, remaining);
  6871. const char *src = seg.data + seg_offset;
  6872. seg_offset = 0; // only the first segment has a non-zero offset
  6873. while (to_copy > 0) {
  6874. size_t space = kBufSize - buf_len;
  6875. size_t chunk = (std::min)(to_copy, space);
  6876. std::memcpy(buf + buf_len, src, chunk);
  6877. buf_len += chunk;
  6878. src += chunk;
  6879. to_copy -= chunk;
  6880. remaining -= chunk;
  6881. if (buf_len == kBufSize) {
  6882. if (!sink.write(buf, buf_len)) { return false; }
  6883. buf_len = 0;
  6884. }
  6885. }
  6886. }
  6887. if (buf_len > 0) { return sink.write(buf, buf_len); }
  6888. return true;
  6889. };
  6890. }
  6891. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  6892. if (ranges.size() <= 1) return;
  6893. // Sort ranges by start position
  6894. std::sort(ranges.begin(), ranges.end(),
  6895. [](const Range &a, const Range &b) { return a.first < b.first; });
  6896. Ranges coalesced;
  6897. coalesced.reserve(ranges.size());
  6898. for (auto &r : ranges) {
  6899. auto first_pos = r.first;
  6900. auto last_pos = r.second;
  6901. // Handle special cases like in range_error
  6902. if (first_pos == -1 && last_pos == -1) {
  6903. first_pos = 0;
  6904. last_pos = static_cast<ssize_t>(content_length);
  6905. }
  6906. if (first_pos == -1) {
  6907. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  6908. last_pos = static_cast<ssize_t>(content_length) - 1;
  6909. }
  6910. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  6911. last_pos = static_cast<ssize_t>(content_length) - 1;
  6912. }
  6913. // Skip invalid ranges
  6914. if (!(0 <= first_pos && first_pos <= last_pos &&
  6915. last_pos < static_cast<ssize_t>(content_length))) {
  6916. continue;
  6917. }
  6918. // Coalesce with previous range if overlapping or adjacent (but not
  6919. // identical)
  6920. if (!coalesced.empty()) {
  6921. auto &prev = coalesced.back();
  6922. // Check if current range overlaps or is adjacent to previous range
  6923. // but don't coalesce identical ranges (allow duplicates)
  6924. if (first_pos <= prev.second + 1 &&
  6925. !(first_pos == prev.first && last_pos == prev.second)) {
  6926. // Extend the previous range
  6927. prev.second = (std::max)(prev.second, last_pos);
  6928. continue;
  6929. }
  6930. }
  6931. // Add new range
  6932. coalesced.emplace_back(first_pos, last_pos);
  6933. }
  6934. ranges = std::move(coalesced);
  6935. }
  6936. inline bool range_error(Request &req, Response &res) {
  6937. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  6938. ssize_t content_len = static_cast<ssize_t>(
  6939. res.content_length_ ? res.content_length_ : res.body.size());
  6940. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  6941. size_t overwrapping_count = 0;
  6942. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  6943. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  6944. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  6945. // Too many ranges
  6946. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  6947. for (auto &r : req.ranges) {
  6948. auto &first_pos = r.first;
  6949. auto &last_pos = r.second;
  6950. if (first_pos == -1 && last_pos == -1) {
  6951. first_pos = 0;
  6952. last_pos = content_len;
  6953. }
  6954. if (first_pos == -1) {
  6955. first_pos = content_len - last_pos;
  6956. last_pos = content_len - 1;
  6957. }
  6958. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  6959. // A client can limit the number of bytes requested without knowing the
  6960. // size of the selected representation. If the last-pos value is absent,
  6961. // or if the value is greater than or equal to the current length of the
  6962. // representation data, the byte range is interpreted as the remainder of
  6963. // the representation (i.e., the server replaces the value of last-pos
  6964. // with a value that is one less than the current length of the selected
  6965. // representation).
  6966. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  6967. if (last_pos == -1 || last_pos >= content_len) {
  6968. last_pos = content_len - 1;
  6969. }
  6970. // Range must be within content length
  6971. if (!(0 <= first_pos && first_pos <= last_pos &&
  6972. last_pos <= content_len - 1)) {
  6973. return true;
  6974. }
  6975. // Request must not have more than two overlapping ranges
  6976. for (const auto &processed_range : processed_ranges) {
  6977. if (!(last_pos < processed_range.first ||
  6978. first_pos > processed_range.second)) {
  6979. overwrapping_count++;
  6980. if (overwrapping_count > 2) { return true; }
  6981. break; // Only count once per range
  6982. }
  6983. }
  6984. processed_ranges.emplace_back(first_pos, last_pos);
  6985. }
  6986. // After validation, coalesce overlapping ranges as per RFC 9110
  6987. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  6988. }
  6989. return false;
  6990. }
  6991. inline std::pair<size_t, size_t>
  6992. get_range_offset_and_length(Range r, size_t content_length) {
  6993. assert(r.first != -1 && r.second != -1);
  6994. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  6995. assert(r.first <= r.second &&
  6996. r.second < static_cast<ssize_t>(content_length));
  6997. (void)(content_length);
  6998. return std::make_pair(static_cast<size_t>(r.first),
  6999. static_cast<size_t>(r.second - r.first) + 1);
  7000. }
  7001. inline std::string make_content_range_header_field(
  7002. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7003. auto st = offset_and_length.first;
  7004. auto ed = st + offset_and_length.second - 1;
  7005. std::string field = "bytes ";
  7006. field += std::to_string(st);
  7007. field += '-';
  7008. field += std::to_string(ed);
  7009. field += '/';
  7010. field += std::to_string(content_length);
  7011. return field;
  7012. }
  7013. template <typename SToken, typename CToken, typename Content>
  7014. bool process_multipart_ranges_data(const Request &req,
  7015. const std::string &boundary,
  7016. const std::string &content_type,
  7017. size_t content_length, SToken stoken,
  7018. CToken ctoken, Content content) {
  7019. for (size_t i = 0; i < req.ranges.size(); i++) {
  7020. ctoken("--");
  7021. stoken(boundary);
  7022. ctoken("\r\n");
  7023. if (!content_type.empty()) {
  7024. ctoken("Content-Type: ");
  7025. stoken(content_type);
  7026. ctoken("\r\n");
  7027. }
  7028. auto offset_and_length =
  7029. get_range_offset_and_length(req.ranges[i], content_length);
  7030. ctoken("Content-Range: ");
  7031. stoken(make_content_range_header_field(offset_and_length, content_length));
  7032. ctoken("\r\n");
  7033. ctoken("\r\n");
  7034. if (!content(offset_and_length.first, offset_and_length.second)) {
  7035. return false;
  7036. }
  7037. ctoken("\r\n");
  7038. }
  7039. ctoken("--");
  7040. stoken(boundary);
  7041. ctoken("--");
  7042. return true;
  7043. }
  7044. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7045. const std::string &boundary,
  7046. const std::string &content_type,
  7047. size_t content_length,
  7048. std::string &data) {
  7049. process_multipart_ranges_data(
  7050. req, boundary, content_type, content_length,
  7051. [&](const std::string &token) { data += token; },
  7052. [&](const std::string &token) { data += token; },
  7053. [&](size_t offset, size_t length) {
  7054. assert(offset + length <= content_length);
  7055. data += res.body.substr(offset, length);
  7056. return true;
  7057. });
  7058. }
  7059. inline size_t get_multipart_ranges_data_length(const Request &req,
  7060. const std::string &boundary,
  7061. const std::string &content_type,
  7062. size_t content_length) {
  7063. size_t data_length = 0;
  7064. process_multipart_ranges_data(
  7065. req, boundary, content_type, content_length,
  7066. [&](const std::string &token) { data_length += token.size(); },
  7067. [&](const std::string &token) { data_length += token.size(); },
  7068. [&](size_t /*offset*/, size_t length) {
  7069. data_length += length;
  7070. return true;
  7071. });
  7072. return data_length;
  7073. }
  7074. template <typename T>
  7075. inline bool
  7076. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7077. const std::string &boundary,
  7078. const std::string &content_type,
  7079. size_t content_length, const T &is_shutting_down) {
  7080. return process_multipart_ranges_data(
  7081. req, boundary, content_type, content_length,
  7082. [&](const std::string &token) { strm.write(token); },
  7083. [&](const std::string &token) { strm.write(token); },
  7084. [&](size_t offset, size_t length) {
  7085. return write_content(strm, res.content_provider_, offset, length,
  7086. is_shutting_down);
  7087. });
  7088. }
  7089. inline bool expect_content(const Request &req) {
  7090. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7091. req.method == "DELETE") {
  7092. return true;
  7093. }
  7094. if (req.has_header("Content-Length") &&
  7095. req.get_header_value_u64("Content-Length") > 0) {
  7096. return true;
  7097. }
  7098. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  7099. return false;
  7100. }
  7101. #ifdef _WIN32
  7102. class WSInit {
  7103. public:
  7104. WSInit() {
  7105. WSADATA wsaData;
  7106. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7107. }
  7108. ~WSInit() {
  7109. if (is_valid_) WSACleanup();
  7110. }
  7111. bool is_valid_ = false;
  7112. };
  7113. static WSInit wsinit_;
  7114. #endif
  7115. inline bool parse_www_authenticate(const Response &res,
  7116. std::map<std::string, std::string> &auth,
  7117. bool is_proxy) {
  7118. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7119. if (res.has_header(auth_key)) {
  7120. thread_local auto re =
  7121. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7122. auto s = res.get_header_value(auth_key);
  7123. auto pos = s.find(' ');
  7124. if (pos != std::string::npos) {
  7125. auto type = s.substr(0, pos);
  7126. if (type == "Basic") {
  7127. return false;
  7128. } else if (type == "Digest") {
  7129. s = s.substr(pos + 1);
  7130. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7131. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7132. const auto &m = *i;
  7133. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7134. static_cast<size_t>(m.length(1)));
  7135. auto val = m.length(2) > 0
  7136. ? s.substr(static_cast<size_t>(m.position(2)),
  7137. static_cast<size_t>(m.length(2)))
  7138. : s.substr(static_cast<size_t>(m.position(3)),
  7139. static_cast<size_t>(m.length(3)));
  7140. auth[std::move(key)] = std::move(val);
  7141. }
  7142. return true;
  7143. }
  7144. }
  7145. }
  7146. return false;
  7147. }
  7148. class ContentProviderAdapter {
  7149. public:
  7150. explicit ContentProviderAdapter(
  7151. ContentProviderWithoutLength &&content_provider)
  7152. : content_provider_(std::move(content_provider)) {}
  7153. bool operator()(size_t offset, size_t, DataSink &sink) {
  7154. return content_provider_(offset, sink);
  7155. }
  7156. private:
  7157. ContentProviderWithoutLength content_provider_;
  7158. };
  7159. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7160. namespace fields {
  7161. inline bool is_token_char(char c) {
  7162. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7163. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7164. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7165. }
  7166. inline bool is_token(const std::string &s) {
  7167. if (s.empty()) { return false; }
  7168. for (auto c : s) {
  7169. if (!is_token_char(c)) { return false; }
  7170. }
  7171. return true;
  7172. }
  7173. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7174. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7175. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7176. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7177. inline bool is_field_content(const std::string &s) {
  7178. if (s.empty()) { return true; }
  7179. if (s.size() == 1) {
  7180. return is_field_vchar(s[0]);
  7181. } else if (s.size() == 2) {
  7182. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7183. } else {
  7184. size_t i = 0;
  7185. if (!is_field_vchar(s[i])) { return false; }
  7186. i++;
  7187. while (i < s.size() - 1) {
  7188. auto c = s[i++];
  7189. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7190. } else {
  7191. return false;
  7192. }
  7193. }
  7194. return is_field_vchar(s[i]);
  7195. }
  7196. }
  7197. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7198. } // namespace fields
  7199. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7200. int port, const std::string &path,
  7201. const Headers &headers,
  7202. std::string &selected_subprotocol) {
  7203. // Validate path and host
  7204. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7205. return false;
  7206. }
  7207. // Validate user-provided headers
  7208. for (const auto &h : headers) {
  7209. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7210. return false;
  7211. }
  7212. }
  7213. // Generate random Sec-WebSocket-Key
  7214. thread_local std::mt19937 rng(std::random_device{}());
  7215. std::string key_bytes(16, '\0');
  7216. for (size_t i = 0; i < 16; i += 4) {
  7217. auto r = rng();
  7218. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7219. }
  7220. auto client_key = base64_encode(key_bytes);
  7221. // Build upgrade request
  7222. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7223. req_str += "Host: " + host + ":" + std::to_string(port) + "\r\n";
  7224. req_str += "Upgrade: websocket\r\n";
  7225. req_str += "Connection: Upgrade\r\n";
  7226. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7227. req_str += "Sec-WebSocket-Version: 13\r\n";
  7228. for (const auto &h : headers) {
  7229. req_str += h.first + ": " + h.second + "\r\n";
  7230. }
  7231. req_str += "\r\n";
  7232. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7233. // Verify 101 response and Sec-WebSocket-Accept header
  7234. auto expected_accept = websocket_accept_key(client_key);
  7235. return read_websocket_upgrade_response(strm, expected_accept,
  7236. selected_subprotocol);
  7237. }
  7238. } // namespace detail
  7239. /*
  7240. * Group 2: detail namespace - SSL common utilities
  7241. */
  7242. #ifdef CPPHTTPLIB_SSL_ENABLED
  7243. namespace detail {
  7244. class SSLSocketStream final : public Stream {
  7245. public:
  7246. SSLSocketStream(
  7247. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7248. time_t read_timeout_usec, time_t write_timeout_sec,
  7249. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7250. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7251. (std::chrono::steady_clock::time_point::min)());
  7252. ~SSLSocketStream() override;
  7253. bool is_readable() const override;
  7254. bool wait_readable() const override;
  7255. bool wait_writable() const override;
  7256. bool is_peer_alive() const override;
  7257. ssize_t read(char *ptr, size_t size) override;
  7258. ssize_t write(const char *ptr, size_t size) override;
  7259. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7260. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7261. socket_t socket() const override;
  7262. time_t duration() const override;
  7263. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7264. private:
  7265. socket_t sock_;
  7266. tls::session_t session_;
  7267. time_t read_timeout_sec_;
  7268. time_t read_timeout_usec_;
  7269. time_t write_timeout_sec_;
  7270. time_t write_timeout_usec_;
  7271. time_t max_timeout_msec_;
  7272. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7273. };
  7274. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7275. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7276. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7277. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7278. unsigned int hash_length = 0;
  7279. unsigned char hash[EVP_MAX_MD_SIZE];
  7280. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7281. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7282. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7283. std::stringstream ss;
  7284. for (auto i = 0u; i < hash_length; ++i) {
  7285. ss << std::hex << std::setw(2) << std::setfill('0')
  7286. << static_cast<unsigned int>(hash[i]);
  7287. }
  7288. return ss.str();
  7289. }
  7290. inline std::string MD5(const std::string &s) {
  7291. return message_digest(s, EVP_md5());
  7292. }
  7293. inline std::string SHA_256(const std::string &s) {
  7294. return message_digest(s, EVP_sha256());
  7295. }
  7296. inline std::string SHA_512(const std::string &s) {
  7297. return message_digest(s, EVP_sha512());
  7298. }
  7299. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7300. namespace {
  7301. template <size_t N>
  7302. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7303. std::stringstream ss;
  7304. for (size_t i = 0; i < N; ++i) {
  7305. ss << std::hex << std::setw(2) << std::setfill('0')
  7306. << static_cast<unsigned int>(hash[i]);
  7307. }
  7308. return ss.str();
  7309. }
  7310. } // namespace
  7311. inline std::string MD5(const std::string &s) {
  7312. unsigned char hash[16];
  7313. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7314. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7315. hash);
  7316. #else
  7317. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7318. hash);
  7319. #endif
  7320. return hash_to_hex(hash);
  7321. }
  7322. inline std::string SHA_256(const std::string &s) {
  7323. unsigned char hash[32];
  7324. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7325. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7326. hash, 0);
  7327. #else
  7328. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7329. s.size(), hash, 0);
  7330. #endif
  7331. return hash_to_hex(hash);
  7332. }
  7333. inline std::string SHA_512(const std::string &s) {
  7334. unsigned char hash[64];
  7335. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7336. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7337. hash, 0);
  7338. #else
  7339. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7340. s.size(), hash, 0);
  7341. #endif
  7342. return hash_to_hex(hash);
  7343. }
  7344. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7345. namespace {
  7346. template <size_t N>
  7347. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7348. std::stringstream ss;
  7349. for (size_t i = 0; i < N; ++i) {
  7350. ss << std::hex << std::setw(2) << std::setfill('0')
  7351. << static_cast<unsigned int>(hash[i]);
  7352. }
  7353. return ss.str();
  7354. }
  7355. } // namespace
  7356. inline std::string MD5(const std::string &s) {
  7357. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7358. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7359. static_cast<word32>(s.size()), hash);
  7360. return hash_to_hex(hash);
  7361. }
  7362. inline std::string SHA_256(const std::string &s) {
  7363. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7364. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7365. static_cast<word32>(s.size()), hash);
  7366. return hash_to_hex(hash);
  7367. }
  7368. inline std::string SHA_512(const std::string &s) {
  7369. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7370. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7371. static_cast<word32>(s.size()), hash);
  7372. return hash_to_hex(hash);
  7373. }
  7374. #endif
  7375. inline bool is_ip_address(const std::string &host) {
  7376. struct in_addr addr4;
  7377. struct in6_addr addr6;
  7378. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7379. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7380. }
  7381. template <typename T>
  7382. inline bool process_server_socket_ssl(
  7383. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7384. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7385. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7386. time_t write_timeout_usec, T callback) {
  7387. return process_server_socket_core(
  7388. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7389. [&](bool close_connection, bool &connection_closed) {
  7390. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7391. write_timeout_sec, write_timeout_usec);
  7392. return callback(strm, close_connection, connection_closed);
  7393. });
  7394. }
  7395. template <typename T>
  7396. inline bool process_client_socket_ssl(
  7397. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7398. time_t read_timeout_usec, time_t write_timeout_sec,
  7399. time_t write_timeout_usec, time_t max_timeout_msec,
  7400. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7401. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7402. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7403. start_time);
  7404. return callback(strm);
  7405. }
  7406. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7407. const Request &req, const std::map<std::string, std::string> &auth,
  7408. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7409. const std::string &password, bool is_proxy = false) {
  7410. std::string nc;
  7411. {
  7412. std::stringstream ss;
  7413. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7414. nc = ss.str();
  7415. }
  7416. std::string qop;
  7417. if (auth.find("qop") != auth.end()) {
  7418. qop = auth.at("qop");
  7419. if (qop.find("auth-int") != std::string::npos) {
  7420. qop = "auth-int";
  7421. } else if (qop.find("auth") != std::string::npos) {
  7422. qop = "auth";
  7423. } else {
  7424. qop.clear();
  7425. }
  7426. }
  7427. std::string algo = "MD5";
  7428. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7429. std::string response;
  7430. {
  7431. auto H = algo == "SHA-256" ? detail::SHA_256
  7432. : algo == "SHA-512" ? detail::SHA_512
  7433. : detail::MD5;
  7434. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7435. auto A2 = req.method + ":" + req.path;
  7436. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7437. if (qop.empty()) {
  7438. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7439. } else {
  7440. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7441. ":" + qop + ":" + H(A2));
  7442. }
  7443. }
  7444. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7445. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7446. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7447. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7448. (qop.empty() ? ", response=\""
  7449. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7450. cnonce + "\", response=\"") +
  7451. response + "\"" +
  7452. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7453. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7454. return std::make_pair(key, field);
  7455. }
  7456. inline bool match_hostname(const std::string &pattern,
  7457. const std::string &hostname) {
  7458. // Exact match (case-insensitive)
  7459. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7460. // Split both pattern and hostname into components by '.'
  7461. std::vector<std::string> pattern_components;
  7462. if (!pattern.empty()) {
  7463. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7464. [&](const char *b, const char *e) {
  7465. pattern_components.emplace_back(b, e);
  7466. });
  7467. }
  7468. std::vector<std::string> host_components;
  7469. if (!hostname.empty()) {
  7470. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7471. [&](const char *b, const char *e) {
  7472. host_components.emplace_back(b, e);
  7473. });
  7474. }
  7475. // Component count must match
  7476. if (host_components.size() != pattern_components.size()) { return false; }
  7477. // Compare each component with wildcard support
  7478. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7479. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7480. auto itr = pattern_components.begin();
  7481. for (const auto &h : host_components) {
  7482. auto &p = *itr;
  7483. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7484. bool partial_match = false;
  7485. if (!p.empty() && p[p.size() - 1] == '*') {
  7486. const auto prefix_length = p.size() - 1;
  7487. if (prefix_length == 0) {
  7488. partial_match = true;
  7489. } else if (h.size() >= prefix_length) {
  7490. partial_match =
  7491. std::equal(p.begin(),
  7492. p.begin() + static_cast<std::string::difference_type>(
  7493. prefix_length),
  7494. h.begin(), [](const char ca, const char cb) {
  7495. return detail::case_ignore::to_lower(ca) ==
  7496. detail::case_ignore::to_lower(cb);
  7497. });
  7498. }
  7499. }
  7500. if (!partial_match) { return false; }
  7501. }
  7502. ++itr;
  7503. }
  7504. return true;
  7505. }
  7506. #ifdef _WIN32
  7507. // Verify certificate using Windows CertGetCertificateChain API.
  7508. // This provides real-time certificate validation with Windows Update
  7509. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7510. inline bool
  7511. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7512. const std::string &hostname,
  7513. bool verify_hostname, uint64_t &out_error) {
  7514. if (der_cert.empty()) { return false; }
  7515. out_error = 0;
  7516. // Create Windows certificate context from DER data
  7517. auto cert_context = CertCreateCertificateContext(
  7518. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7519. static_cast<DWORD>(der_cert.size()));
  7520. if (!cert_context) {
  7521. out_error = GetLastError();
  7522. return false;
  7523. }
  7524. auto cert_guard =
  7525. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7526. // Setup chain parameters
  7527. CERT_CHAIN_PARA chain_para = {};
  7528. chain_para.cbSize = sizeof(chain_para);
  7529. // Build certificate chain with revocation checking
  7530. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7531. auto chain_result = CertGetCertificateChain(
  7532. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7533. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7534. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7535. nullptr, &chain_context);
  7536. if (!chain_result || !chain_context) {
  7537. out_error = GetLastError();
  7538. return false;
  7539. }
  7540. auto chain_guard =
  7541. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7542. // Check if chain has errors
  7543. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7544. out_error = chain_context->TrustStatus.dwErrorStatus;
  7545. return false;
  7546. }
  7547. // Verify SSL policy
  7548. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7549. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7550. #ifdef AUTHTYPE_SERVER
  7551. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7552. #endif
  7553. std::wstring whost;
  7554. if (verify_hostname) {
  7555. whost = u8string_to_wstring(hostname.c_str());
  7556. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7557. }
  7558. CERT_CHAIN_POLICY_PARA policy_para = {};
  7559. policy_para.cbSize = sizeof(policy_para);
  7560. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7561. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7562. #else
  7563. policy_para.dwFlags = 0;
  7564. #endif
  7565. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7566. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7567. policy_status.cbSize = sizeof(policy_status);
  7568. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7569. &policy_para, &policy_status)) {
  7570. out_error = GetLastError();
  7571. return false;
  7572. }
  7573. if (policy_status.dwError != 0) {
  7574. out_error = policy_status.dwError;
  7575. return false;
  7576. }
  7577. return true;
  7578. }
  7579. #endif // _WIN32
  7580. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t &ctx,
  7581. tls::session_t &session, socket_t sock,
  7582. bool server_certificate_verification,
  7583. const std::string &ca_cert_file_path,
  7584. tls::ca_store_t ca_cert_store,
  7585. time_t timeout_sec, time_t timeout_usec) {
  7586. using namespace tls;
  7587. ctx = create_client_context();
  7588. if (!ctx) { return false; }
  7589. if (server_certificate_verification) {
  7590. if (!ca_cert_file_path.empty()) {
  7591. load_ca_file(ctx, ca_cert_file_path.c_str());
  7592. }
  7593. if (ca_cert_store) { set_ca_store(ctx, ca_cert_store); }
  7594. load_system_certs(ctx);
  7595. }
  7596. bool is_ip = is_ip_address(host);
  7597. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7598. if (is_ip && server_certificate_verification) {
  7599. set_verify_client(ctx, false);
  7600. } else {
  7601. set_verify_client(ctx, server_certificate_verification);
  7602. }
  7603. #endif
  7604. session = create_session(ctx, sock);
  7605. if (!session) { return false; }
  7606. // RFC 6066: SNI must not be set for IP addresses
  7607. if (!is_ip) { set_sni(session, host.c_str()); }
  7608. if (server_certificate_verification) { set_hostname(session, host.c_str()); }
  7609. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7610. return false;
  7611. }
  7612. if (server_certificate_verification) {
  7613. if (get_verify_result(session) != 0) { return false; }
  7614. }
  7615. return true;
  7616. }
  7617. } // namespace detail
  7618. #endif // CPPHTTPLIB_SSL_ENABLED
  7619. /*
  7620. * Group 3: httplib namespace - Non-SSL public API implementations
  7621. */
  7622. inline void default_socket_options(socket_t sock) {
  7623. set_socket_opt(sock, SOL_SOCKET,
  7624. #ifdef SO_REUSEPORT
  7625. SO_REUSEPORT,
  7626. #else
  7627. SO_REUSEADDR,
  7628. #endif
  7629. 1);
  7630. }
  7631. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7632. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7633. sizeof(optval));
  7634. }
  7635. inline std::string get_bearer_token_auth(const Request &req) {
  7636. if (req.has_header("Authorization")) {
  7637. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7638. return req.get_header_value("Authorization")
  7639. .substr(bearer_header_prefix_len);
  7640. }
  7641. return "";
  7642. }
  7643. inline const char *status_message(int status) {
  7644. switch (status) {
  7645. case StatusCode::Continue_100: return "Continue";
  7646. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7647. case StatusCode::Processing_102: return "Processing";
  7648. case StatusCode::EarlyHints_103: return "Early Hints";
  7649. case StatusCode::OK_200: return "OK";
  7650. case StatusCode::Created_201: return "Created";
  7651. case StatusCode::Accepted_202: return "Accepted";
  7652. case StatusCode::NonAuthoritativeInformation_203:
  7653. return "Non-Authoritative Information";
  7654. case StatusCode::NoContent_204: return "No Content";
  7655. case StatusCode::ResetContent_205: return "Reset Content";
  7656. case StatusCode::PartialContent_206: return "Partial Content";
  7657. case StatusCode::MultiStatus_207: return "Multi-Status";
  7658. case StatusCode::AlreadyReported_208: return "Already Reported";
  7659. case StatusCode::IMUsed_226: return "IM Used";
  7660. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7661. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7662. case StatusCode::Found_302: return "Found";
  7663. case StatusCode::SeeOther_303: return "See Other";
  7664. case StatusCode::NotModified_304: return "Not Modified";
  7665. case StatusCode::UseProxy_305: return "Use Proxy";
  7666. case StatusCode::unused_306: return "unused";
  7667. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7668. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7669. case StatusCode::BadRequest_400: return "Bad Request";
  7670. case StatusCode::Unauthorized_401: return "Unauthorized";
  7671. case StatusCode::PaymentRequired_402: return "Payment Required";
  7672. case StatusCode::Forbidden_403: return "Forbidden";
  7673. case StatusCode::NotFound_404: return "Not Found";
  7674. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7675. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7676. case StatusCode::ProxyAuthenticationRequired_407:
  7677. return "Proxy Authentication Required";
  7678. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7679. case StatusCode::Conflict_409: return "Conflict";
  7680. case StatusCode::Gone_410: return "Gone";
  7681. case StatusCode::LengthRequired_411: return "Length Required";
  7682. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7683. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7684. case StatusCode::UriTooLong_414: return "URI Too Long";
  7685. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7686. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7687. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7688. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7689. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7690. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7691. case StatusCode::Locked_423: return "Locked";
  7692. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7693. case StatusCode::TooEarly_425: return "Too Early";
  7694. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7695. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7696. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7697. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7698. return "Request Header Fields Too Large";
  7699. case StatusCode::UnavailableForLegalReasons_451:
  7700. return "Unavailable For Legal Reasons";
  7701. case StatusCode::NotImplemented_501: return "Not Implemented";
  7702. case StatusCode::BadGateway_502: return "Bad Gateway";
  7703. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7704. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7705. case StatusCode::HttpVersionNotSupported_505:
  7706. return "HTTP Version Not Supported";
  7707. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7708. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7709. case StatusCode::LoopDetected_508: return "Loop Detected";
  7710. case StatusCode::NotExtended_510: return "Not Extended";
  7711. case StatusCode::NetworkAuthenticationRequired_511:
  7712. return "Network Authentication Required";
  7713. default:
  7714. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7715. }
  7716. }
  7717. inline std::string to_string(const Error error) {
  7718. switch (error) {
  7719. case Error::Success: return "Success (no error)";
  7720. case Error::Unknown: return "Unknown";
  7721. case Error::Connection: return "Could not establish connection";
  7722. case Error::BindIPAddress: return "Failed to bind IP address";
  7723. case Error::Read: return "Failed to read connection";
  7724. case Error::Write: return "Failed to write connection";
  7725. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7726. case Error::Canceled: return "Connection handling canceled";
  7727. case Error::SSLConnection: return "SSL connection failed";
  7728. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7729. case Error::SSLServerVerification: return "SSL server verification failed";
  7730. case Error::SSLServerHostnameVerification:
  7731. return "SSL server hostname verification failed";
  7732. case Error::UnsupportedMultipartBoundaryChars:
  7733. return "Unsupported HTTP multipart boundary characters";
  7734. case Error::Compression: return "Compression failed";
  7735. case Error::ConnectionTimeout: return "Connection timed out";
  7736. case Error::ProxyConnection: return "Proxy connection failed";
  7737. case Error::ConnectionClosed: return "Connection closed by server";
  7738. case Error::Timeout: return "Read timeout";
  7739. case Error::ResourceExhaustion: return "Resource exhaustion";
  7740. case Error::TooManyFormDataFiles: return "Too many form data files";
  7741. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7742. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7743. case Error::ExceedMaxSocketDescriptorCount:
  7744. return "Exceeded maximum socket descriptor count";
  7745. case Error::InvalidRequestLine: return "Invalid request line";
  7746. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  7747. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  7748. case Error::InvalidHeaders: return "Invalid headers";
  7749. case Error::MultipartParsing: return "Multipart parsing failed";
  7750. case Error::OpenFile: return "Failed to open file";
  7751. case Error::Listen: return "Failed to listen on socket";
  7752. case Error::GetSockName: return "Failed to get socket name";
  7753. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  7754. case Error::HTTPParsing: return "HTTP parsing failed";
  7755. case Error::InvalidRangeHeader: return "Invalid Range header";
  7756. default: break;
  7757. }
  7758. return "Invalid";
  7759. }
  7760. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  7761. os << to_string(obj);
  7762. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  7763. return os;
  7764. }
  7765. inline std::string hosted_at(const std::string &hostname) {
  7766. std::vector<std::string> addrs;
  7767. hosted_at(hostname, addrs);
  7768. if (addrs.empty()) { return std::string(); }
  7769. return addrs[0];
  7770. }
  7771. inline void hosted_at(const std::string &hostname,
  7772. std::vector<std::string> &addrs) {
  7773. struct addrinfo hints;
  7774. struct addrinfo *result;
  7775. memset(&hints, 0, sizeof(struct addrinfo));
  7776. hints.ai_family = AF_UNSPEC;
  7777. hints.ai_socktype = SOCK_STREAM;
  7778. hints.ai_protocol = 0;
  7779. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  7780. &result, 0)) {
  7781. #if defined __linux__ && !defined __ANDROID__
  7782. res_init();
  7783. #endif
  7784. return;
  7785. }
  7786. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  7787. for (auto rp = result; rp; rp = rp->ai_next) {
  7788. const auto &addr =
  7789. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  7790. std::string ip;
  7791. auto dummy = -1;
  7792. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  7793. dummy)) {
  7794. addrs.emplace_back(std::move(ip));
  7795. }
  7796. }
  7797. }
  7798. inline std::string encode_uri_component(const std::string &value) {
  7799. std::ostringstream escaped;
  7800. escaped.fill('0');
  7801. escaped << std::hex;
  7802. for (auto c : value) {
  7803. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7804. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7805. c == ')') {
  7806. escaped << c;
  7807. } else {
  7808. escaped << std::uppercase;
  7809. escaped << '%' << std::setw(2)
  7810. << static_cast<int>(static_cast<unsigned char>(c));
  7811. escaped << std::nouppercase;
  7812. }
  7813. }
  7814. return escaped.str();
  7815. }
  7816. inline std::string encode_uri(const std::string &value) {
  7817. std::ostringstream escaped;
  7818. escaped.fill('0');
  7819. escaped << std::hex;
  7820. for (auto c : value) {
  7821. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7822. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7823. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  7824. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  7825. escaped << c;
  7826. } else {
  7827. escaped << std::uppercase;
  7828. escaped << '%' << std::setw(2)
  7829. << static_cast<int>(static_cast<unsigned char>(c));
  7830. escaped << std::nouppercase;
  7831. }
  7832. }
  7833. return escaped.str();
  7834. }
  7835. inline std::string decode_uri_component(const std::string &value) {
  7836. std::string result;
  7837. for (size_t i = 0; i < value.size(); i++) {
  7838. if (value[i] == '%' && i + 2 < value.size()) {
  7839. auto val = 0;
  7840. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7841. result += static_cast<char>(val);
  7842. i += 2;
  7843. } else {
  7844. result += value[i];
  7845. }
  7846. } else {
  7847. result += value[i];
  7848. }
  7849. }
  7850. return result;
  7851. }
  7852. inline std::string decode_uri(const std::string &value) {
  7853. std::string result;
  7854. for (size_t i = 0; i < value.size(); i++) {
  7855. if (value[i] == '%' && i + 2 < value.size()) {
  7856. auto val = 0;
  7857. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7858. result += static_cast<char>(val);
  7859. i += 2;
  7860. } else {
  7861. result += value[i];
  7862. }
  7863. } else {
  7864. result += value[i];
  7865. }
  7866. }
  7867. return result;
  7868. }
  7869. inline std::string encode_path_component(const std::string &component) {
  7870. std::string result;
  7871. result.reserve(component.size() * 3);
  7872. for (size_t i = 0; i < component.size(); i++) {
  7873. auto c = static_cast<unsigned char>(component[i]);
  7874. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  7875. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7876. result += static_cast<char>(c);
  7877. }
  7878. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  7879. // "," / ";" / "="
  7880. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  7881. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  7882. c == '=') {
  7883. result += static_cast<char>(c);
  7884. }
  7885. // Colon is allowed in path segments except first segment
  7886. else if (c == ':') {
  7887. result += static_cast<char>(c);
  7888. }
  7889. // @ is allowed in path
  7890. else if (c == '@') {
  7891. result += static_cast<char>(c);
  7892. } else {
  7893. result += '%';
  7894. char hex[3];
  7895. snprintf(hex, sizeof(hex), "%02X", c);
  7896. result.append(hex, 2);
  7897. }
  7898. }
  7899. return result;
  7900. }
  7901. inline std::string decode_path_component(const std::string &component) {
  7902. std::string result;
  7903. result.reserve(component.size());
  7904. for (size_t i = 0; i < component.size(); i++) {
  7905. if (component[i] == '%' && i + 1 < component.size()) {
  7906. if (component[i + 1] == 'u') {
  7907. // Unicode %uXXXX encoding
  7908. auto val = 0;
  7909. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  7910. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  7911. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  7912. char buff[4];
  7913. size_t len = detail::to_utf8(val, buff);
  7914. if (len > 0) { result.append(buff, len); }
  7915. i += 5; // 'u0000'
  7916. } else {
  7917. result += component[i];
  7918. }
  7919. } else {
  7920. // Standard %XX encoding
  7921. auto val = 0;
  7922. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  7923. // 2 digits hex codes
  7924. result += static_cast<char>(val);
  7925. i += 2; // 'XX'
  7926. } else {
  7927. result += component[i];
  7928. }
  7929. }
  7930. } else {
  7931. result += component[i];
  7932. }
  7933. }
  7934. return result;
  7935. }
  7936. inline std::string encode_query_component(const std::string &component,
  7937. bool space_as_plus) {
  7938. std::string result;
  7939. result.reserve(component.size() * 3);
  7940. for (size_t i = 0; i < component.size(); i++) {
  7941. auto c = static_cast<unsigned char>(component[i]);
  7942. // Unreserved characters per RFC 3986
  7943. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7944. result += static_cast<char>(c);
  7945. }
  7946. // Space handling
  7947. else if (c == ' ') {
  7948. if (space_as_plus) {
  7949. result += '+';
  7950. } else {
  7951. result += "%20";
  7952. }
  7953. }
  7954. // Plus sign handling
  7955. else if (c == '+') {
  7956. if (space_as_plus) {
  7957. result += "%2B";
  7958. } else {
  7959. result += static_cast<char>(c);
  7960. }
  7961. }
  7962. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  7963. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  7964. c == '*' || c == ',' || c == ';') {
  7965. result += static_cast<char>(c);
  7966. }
  7967. // Colon and @ are allowed in query
  7968. else if (c == ':' || c == '@') {
  7969. result += static_cast<char>(c);
  7970. }
  7971. // Forward slash is allowed in query values
  7972. else if (c == '/') {
  7973. result += static_cast<char>(c);
  7974. }
  7975. // Question mark is allowed in query values (after first ?)
  7976. else if (c == '?') {
  7977. result += static_cast<char>(c);
  7978. } else {
  7979. result += '%';
  7980. char hex[3];
  7981. snprintf(hex, sizeof(hex), "%02X", c);
  7982. result.append(hex, 2);
  7983. }
  7984. }
  7985. return result;
  7986. }
  7987. inline std::string decode_query_component(const std::string &component,
  7988. bool plus_as_space) {
  7989. std::string result;
  7990. result.reserve(component.size());
  7991. for (size_t i = 0; i < component.size(); i++) {
  7992. if (component[i] == '%' && i + 2 < component.size()) {
  7993. std::string hex = component.substr(i + 1, 2);
  7994. char *end;
  7995. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  7996. if (end == hex.c_str() + 2) {
  7997. result += static_cast<char>(value);
  7998. i += 2;
  7999. } else {
  8000. result += component[i];
  8001. }
  8002. } else if (component[i] == '+' && plus_as_space) {
  8003. result += ' '; // + becomes space in form-urlencoded
  8004. } else {
  8005. result += component[i];
  8006. }
  8007. }
  8008. return result;
  8009. }
  8010. inline std::string sanitize_filename(const std::string &filename) {
  8011. // Extract basename: find the last path separator (/ or \)
  8012. auto pos = filename.find_last_of("/\\");
  8013. auto result =
  8014. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8015. // Strip null bytes
  8016. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8017. // Trim whitespace
  8018. {
  8019. auto start = result.find_first_not_of(" \t");
  8020. auto end = result.find_last_not_of(" \t");
  8021. result = (start == std::string::npos)
  8022. ? ""
  8023. : result.substr(start, end - start + 1);
  8024. }
  8025. // Reject . and ..
  8026. if (result == "." || result == "..") { return ""; }
  8027. return result;
  8028. }
  8029. inline std::string append_query_params(const std::string &path,
  8030. const Params &params) {
  8031. std::string path_with_query = path;
  8032. thread_local const std::regex re("[^?]+\\?.*");
  8033. auto delm = std::regex_match(path, re) ? '&' : '?';
  8034. path_with_query += delm + detail::params_to_query_str(params);
  8035. return path_with_query;
  8036. }
  8037. // Header utilities
  8038. inline std::pair<std::string, std::string>
  8039. make_range_header(const Ranges &ranges) {
  8040. std::string field = "bytes=";
  8041. auto i = 0;
  8042. for (const auto &r : ranges) {
  8043. if (i != 0) { field += ", "; }
  8044. if (r.first != -1) { field += std::to_string(r.first); }
  8045. field += '-';
  8046. if (r.second != -1) { field += std::to_string(r.second); }
  8047. i++;
  8048. }
  8049. return std::make_pair("Range", std::move(field));
  8050. }
  8051. inline std::pair<std::string, std::string>
  8052. make_basic_authentication_header(const std::string &username,
  8053. const std::string &password, bool is_proxy) {
  8054. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8055. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8056. return std::make_pair(key, std::move(field));
  8057. }
  8058. inline std::pair<std::string, std::string>
  8059. make_bearer_token_authentication_header(const std::string &token,
  8060. bool is_proxy = false) {
  8061. auto field = "Bearer " + token;
  8062. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8063. return std::make_pair(key, std::move(field));
  8064. }
  8065. // Request implementation
  8066. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8067. size_t id) const {
  8068. return detail::get_header_value_u64(headers, key, def, id);
  8069. }
  8070. inline bool Request::has_header(const std::string &key) const {
  8071. return detail::has_header(headers, key);
  8072. }
  8073. inline std::string Request::get_header_value(const std::string &key,
  8074. const char *def, size_t id) const {
  8075. return detail::get_header_value(headers, key, def, id);
  8076. }
  8077. inline size_t Request::get_header_value_count(const std::string &key) const {
  8078. auto r = headers.equal_range(key);
  8079. return static_cast<size_t>(std::distance(r.first, r.second));
  8080. }
  8081. inline void Request::set_header(const std::string &key,
  8082. const std::string &val) {
  8083. if (detail::fields::is_field_name(key) &&
  8084. detail::fields::is_field_value(val)) {
  8085. headers.emplace(key, val);
  8086. }
  8087. }
  8088. inline bool Request::has_trailer(const std::string &key) const {
  8089. return trailers.find(key) != trailers.end();
  8090. }
  8091. inline std::string Request::get_trailer_value(const std::string &key,
  8092. size_t id) const {
  8093. auto rng = trailers.equal_range(key);
  8094. auto it = rng.first;
  8095. std::advance(it, static_cast<ssize_t>(id));
  8096. if (it != rng.second) { return it->second; }
  8097. return std::string();
  8098. }
  8099. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8100. auto r = trailers.equal_range(key);
  8101. return static_cast<size_t>(std::distance(r.first, r.second));
  8102. }
  8103. inline bool Request::has_param(const std::string &key) const {
  8104. return params.find(key) != params.end();
  8105. }
  8106. inline std::string Request::get_param_value(const std::string &key,
  8107. size_t id) const {
  8108. auto rng = params.equal_range(key);
  8109. auto it = rng.first;
  8110. std::advance(it, static_cast<ssize_t>(id));
  8111. if (it != rng.second) { return it->second; }
  8112. return std::string();
  8113. }
  8114. inline size_t Request::get_param_value_count(const std::string &key) const {
  8115. auto r = params.equal_range(key);
  8116. return static_cast<size_t>(std::distance(r.first, r.second));
  8117. }
  8118. inline bool Request::is_multipart_form_data() const {
  8119. const auto &content_type = get_header_value("Content-Type");
  8120. return detail::extract_media_type(content_type) == "multipart/form-data";
  8121. }
  8122. // Multipart FormData implementation
  8123. inline std::string MultipartFormData::get_field(const std::string &key,
  8124. size_t id) const {
  8125. auto rng = fields.equal_range(key);
  8126. auto it = rng.first;
  8127. std::advance(it, static_cast<ssize_t>(id));
  8128. if (it != rng.second) { return it->second.content; }
  8129. return std::string();
  8130. }
  8131. inline std::vector<std::string>
  8132. MultipartFormData::get_fields(const std::string &key) const {
  8133. std::vector<std::string> values;
  8134. auto rng = fields.equal_range(key);
  8135. for (auto it = rng.first; it != rng.second; it++) {
  8136. values.push_back(it->second.content);
  8137. }
  8138. return values;
  8139. }
  8140. inline bool MultipartFormData::has_field(const std::string &key) const {
  8141. return fields.find(key) != fields.end();
  8142. }
  8143. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8144. auto r = fields.equal_range(key);
  8145. return static_cast<size_t>(std::distance(r.first, r.second));
  8146. }
  8147. inline FormData MultipartFormData::get_file(const std::string &key,
  8148. size_t id) const {
  8149. auto rng = files.equal_range(key);
  8150. auto it = rng.first;
  8151. std::advance(it, static_cast<ssize_t>(id));
  8152. if (it != rng.second) { return it->second; }
  8153. return FormData();
  8154. }
  8155. inline std::vector<FormData>
  8156. MultipartFormData::get_files(const std::string &key) const {
  8157. std::vector<FormData> values;
  8158. auto rng = files.equal_range(key);
  8159. for (auto it = rng.first; it != rng.second; it++) {
  8160. values.push_back(it->second);
  8161. }
  8162. return values;
  8163. }
  8164. inline bool MultipartFormData::has_file(const std::string &key) const {
  8165. return files.find(key) != files.end();
  8166. }
  8167. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8168. auto r = files.equal_range(key);
  8169. return static_cast<size_t>(std::distance(r.first, r.second));
  8170. }
  8171. // Response implementation
  8172. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8173. size_t id) const {
  8174. return detail::get_header_value_u64(headers, key, def, id);
  8175. }
  8176. inline bool Response::has_header(const std::string &key) const {
  8177. return headers.find(key) != headers.end();
  8178. }
  8179. inline std::string Response::get_header_value(const std::string &key,
  8180. const char *def,
  8181. size_t id) const {
  8182. return detail::get_header_value(headers, key, def, id);
  8183. }
  8184. inline size_t Response::get_header_value_count(const std::string &key) const {
  8185. auto r = headers.equal_range(key);
  8186. return static_cast<size_t>(std::distance(r.first, r.second));
  8187. }
  8188. inline void Response::set_header(const std::string &key,
  8189. const std::string &val) {
  8190. if (detail::fields::is_field_name(key) &&
  8191. detail::fields::is_field_value(val)) {
  8192. headers.emplace(key, val);
  8193. }
  8194. }
  8195. inline bool Response::has_trailer(const std::string &key) const {
  8196. return trailers.find(key) != trailers.end();
  8197. }
  8198. inline std::string Response::get_trailer_value(const std::string &key,
  8199. size_t id) const {
  8200. auto rng = trailers.equal_range(key);
  8201. auto it = rng.first;
  8202. std::advance(it, static_cast<ssize_t>(id));
  8203. if (it != rng.second) { return it->second; }
  8204. return std::string();
  8205. }
  8206. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8207. auto r = trailers.equal_range(key);
  8208. return static_cast<size_t>(std::distance(r.first, r.second));
  8209. }
  8210. inline void Response::set_redirect(const std::string &url, int stat) {
  8211. if (detail::fields::is_field_value(url)) {
  8212. set_header("Location", url);
  8213. if (300 <= stat && stat < 400) {
  8214. this->status = stat;
  8215. } else {
  8216. this->status = StatusCode::Found_302;
  8217. }
  8218. }
  8219. }
  8220. inline void Response::set_content(const char *s, size_t n,
  8221. const std::string &content_type) {
  8222. body.assign(s, n);
  8223. auto rng = headers.equal_range("Content-Type");
  8224. headers.erase(rng.first, rng.second);
  8225. set_header("Content-Type", content_type);
  8226. }
  8227. inline void Response::set_content(const std::string &s,
  8228. const std::string &content_type) {
  8229. set_content(s.data(), s.size(), content_type);
  8230. }
  8231. inline void Response::set_content(std::string &&s,
  8232. const std::string &content_type) {
  8233. body = std::move(s);
  8234. auto rng = headers.equal_range("Content-Type");
  8235. headers.erase(rng.first, rng.second);
  8236. set_header("Content-Type", content_type);
  8237. }
  8238. inline void Response::set_content_provider(
  8239. size_t in_length, const std::string &content_type, ContentProvider provider,
  8240. ContentProviderResourceReleaser resource_releaser) {
  8241. set_header("Content-Type", content_type);
  8242. content_length_ = in_length;
  8243. if (in_length > 0) { content_provider_ = std::move(provider); }
  8244. content_provider_resource_releaser_ = std::move(resource_releaser);
  8245. is_chunked_content_provider_ = false;
  8246. }
  8247. inline void Response::set_content_provider(
  8248. const std::string &content_type, ContentProviderWithoutLength provider,
  8249. ContentProviderResourceReleaser resource_releaser) {
  8250. set_header("Content-Type", content_type);
  8251. content_length_ = 0;
  8252. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8253. content_provider_resource_releaser_ = std::move(resource_releaser);
  8254. is_chunked_content_provider_ = false;
  8255. }
  8256. inline void Response::set_chunked_content_provider(
  8257. const std::string &content_type, ContentProviderWithoutLength provider,
  8258. ContentProviderResourceReleaser resource_releaser) {
  8259. set_header("Content-Type", content_type);
  8260. content_length_ = 0;
  8261. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8262. content_provider_resource_releaser_ = std::move(resource_releaser);
  8263. is_chunked_content_provider_ = true;
  8264. }
  8265. inline void Response::set_file_content(const std::string &path,
  8266. const std::string &content_type) {
  8267. file_content_path_ = path;
  8268. file_content_content_type_ = content_type;
  8269. }
  8270. inline void Response::set_file_content(const std::string &path) {
  8271. file_content_path_ = path;
  8272. }
  8273. // Result implementation
  8274. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8275. size_t def,
  8276. size_t id) const {
  8277. return detail::get_header_value_u64(request_headers_, key, def, id);
  8278. }
  8279. inline bool Result::has_request_header(const std::string &key) const {
  8280. return request_headers_.find(key) != request_headers_.end();
  8281. }
  8282. inline std::string Result::get_request_header_value(const std::string &key,
  8283. const char *def,
  8284. size_t id) const {
  8285. return detail::get_header_value(request_headers_, key, def, id);
  8286. }
  8287. inline size_t
  8288. Result::get_request_header_value_count(const std::string &key) const {
  8289. auto r = request_headers_.equal_range(key);
  8290. return static_cast<size_t>(std::distance(r.first, r.second));
  8291. }
  8292. // Stream implementation
  8293. inline ssize_t Stream::write(const char *ptr) {
  8294. return write(ptr, strlen(ptr));
  8295. }
  8296. inline ssize_t Stream::write(const std::string &s) {
  8297. return write(s.data(), s.size());
  8298. }
  8299. // BodyReader implementation
  8300. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8301. if (!stream) {
  8302. last_error = Error::Connection;
  8303. return -1;
  8304. }
  8305. if (eof) { return 0; }
  8306. if (!chunked) {
  8307. // Content-Length based reading
  8308. if (has_content_length && bytes_read >= content_length) {
  8309. eof = true;
  8310. return 0;
  8311. }
  8312. auto to_read = len;
  8313. if (has_content_length) {
  8314. auto remaining = content_length - bytes_read;
  8315. to_read = (std::min)(len, remaining);
  8316. }
  8317. auto n = stream->read(buf, to_read);
  8318. if (n < 0) {
  8319. last_error = stream->get_error();
  8320. if (last_error == Error::Success) { last_error = Error::Read; }
  8321. eof = true;
  8322. return n;
  8323. }
  8324. if (n == 0) {
  8325. // Unexpected EOF before content_length
  8326. last_error = stream->get_error();
  8327. if (last_error == Error::Success) { last_error = Error::Read; }
  8328. eof = true;
  8329. return 0;
  8330. }
  8331. bytes_read += static_cast<size_t>(n);
  8332. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8333. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8334. last_error = Error::ExceedMaxPayloadSize;
  8335. eof = true;
  8336. return -1;
  8337. }
  8338. return n;
  8339. }
  8340. // Chunked transfer encoding: delegate to shared decoder instance.
  8341. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8342. size_t chunk_offset = 0;
  8343. size_t chunk_total = 0;
  8344. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8345. if (n < 0) {
  8346. last_error = stream->get_error();
  8347. if (last_error == Error::Success) { last_error = Error::Read; }
  8348. eof = true;
  8349. return n;
  8350. }
  8351. if (n == 0) {
  8352. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8353. eof = true;
  8354. return 0;
  8355. }
  8356. bytes_read += static_cast<size_t>(n);
  8357. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8358. last_error = Error::ExceedMaxPayloadSize;
  8359. eof = true;
  8360. return -1;
  8361. }
  8362. return n;
  8363. }
  8364. // ThreadPool implementation
  8365. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr)
  8366. : base_thread_count_(n), max_queued_requests_(mqr), idle_thread_count_(0),
  8367. shutdown_(false) {
  8368. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8369. if (max_n != 0 && max_n < n) {
  8370. std::string msg = "max_threads must be >= base_threads";
  8371. throw std::invalid_argument(msg);
  8372. }
  8373. #endif
  8374. max_thread_count_ = max_n == 0 ? n : max_n;
  8375. threads_.reserve(base_thread_count_);
  8376. for (size_t i = 0; i < base_thread_count_; i++) {
  8377. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8378. }
  8379. }
  8380. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8381. {
  8382. std::unique_lock<std::mutex> lock(mutex_);
  8383. if (shutdown_) { return false; }
  8384. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8385. return false;
  8386. }
  8387. jobs_.push_back(std::move(fn));
  8388. // Spawn a dynamic thread if no idle threads and under max
  8389. if (idle_thread_count_ == 0 &&
  8390. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8391. cleanup_finished_threads();
  8392. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8393. }
  8394. }
  8395. cond_.notify_one();
  8396. return true;
  8397. }
  8398. inline void ThreadPool::shutdown() {
  8399. {
  8400. std::unique_lock<std::mutex> lock(mutex_);
  8401. shutdown_ = true;
  8402. }
  8403. cond_.notify_all();
  8404. for (auto &t : threads_) {
  8405. if (t.joinable()) { t.join(); }
  8406. }
  8407. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8408. // with worker threads that call move_to_finished() concurrently.
  8409. std::list<std::thread> remaining_dynamic;
  8410. {
  8411. std::unique_lock<std::mutex> lock(mutex_);
  8412. remaining_dynamic = std::move(dynamic_threads_);
  8413. }
  8414. for (auto &t : remaining_dynamic) {
  8415. if (t.joinable()) { t.join(); }
  8416. }
  8417. std::unique_lock<std::mutex> lock(mutex_);
  8418. cleanup_finished_threads();
  8419. }
  8420. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8421. // Must be called with mutex_ held
  8422. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8423. if (it->get_id() == id) {
  8424. finished_threads_.push_back(std::move(*it));
  8425. dynamic_threads_.erase(it);
  8426. return;
  8427. }
  8428. }
  8429. }
  8430. inline void ThreadPool::cleanup_finished_threads() {
  8431. // Must be called with mutex_ held
  8432. for (auto &t : finished_threads_) {
  8433. if (t.joinable()) { t.join(); }
  8434. }
  8435. finished_threads_.clear();
  8436. }
  8437. inline void ThreadPool::worker(bool is_dynamic) {
  8438. for (;;) {
  8439. std::function<void()> fn;
  8440. {
  8441. std::unique_lock<std::mutex> lock(mutex_);
  8442. idle_thread_count_++;
  8443. if (is_dynamic) {
  8444. auto has_work = cond_.wait_for(
  8445. lock, std::chrono::seconds(CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT),
  8446. [&] { return !jobs_.empty() || shutdown_; });
  8447. if (!has_work) {
  8448. // Timed out with no work - exit this dynamic thread
  8449. idle_thread_count_--;
  8450. move_to_finished(std::this_thread::get_id());
  8451. break;
  8452. }
  8453. } else {
  8454. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8455. }
  8456. idle_thread_count_--;
  8457. if (shutdown_ && jobs_.empty()) { break; }
  8458. fn = std::move(jobs_.front());
  8459. jobs_.pop_front();
  8460. }
  8461. assert(true == static_cast<bool>(fn));
  8462. fn();
  8463. // Dynamic thread: exit if queue is empty after task completion
  8464. if (is_dynamic) {
  8465. std::unique_lock<std::mutex> lock(mutex_);
  8466. if (jobs_.empty()) {
  8467. move_to_finished(std::this_thread::get_id());
  8468. break;
  8469. }
  8470. }
  8471. }
  8472. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8473. !defined(LIBRESSL_VERSION_NUMBER)
  8474. OPENSSL_thread_stop();
  8475. #endif
  8476. }
  8477. /*
  8478. * Group 1 (continued): detail namespace - Stream implementations
  8479. */
  8480. namespace detail {
  8481. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8482. time_t timeout_sec, time_t timeout_usec,
  8483. time_t &actual_timeout_sec,
  8484. time_t &actual_timeout_usec) {
  8485. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8486. auto actual_timeout_msec =
  8487. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8488. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8489. actual_timeout_sec = actual_timeout_msec / 1000;
  8490. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8491. }
  8492. // Socket stream implementation
  8493. inline SocketStream::SocketStream(
  8494. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8495. time_t write_timeout_sec, time_t write_timeout_usec,
  8496. time_t max_timeout_msec,
  8497. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8498. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8499. read_timeout_usec_(read_timeout_usec),
  8500. write_timeout_sec_(write_timeout_sec),
  8501. write_timeout_usec_(write_timeout_usec),
  8502. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8503. read_buff_(read_buff_size_, 0) {}
  8504. inline SocketStream::~SocketStream() = default;
  8505. inline bool SocketStream::is_readable() const {
  8506. return read_buff_off_ < read_buff_content_size_;
  8507. }
  8508. inline bool SocketStream::wait_readable() const {
  8509. if (max_timeout_msec_ <= 0) {
  8510. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8511. }
  8512. time_t read_timeout_sec;
  8513. time_t read_timeout_usec;
  8514. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8515. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8516. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8517. }
  8518. inline bool SocketStream::wait_writable() const {
  8519. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8520. }
  8521. inline bool SocketStream::is_peer_alive() const {
  8522. return detail::is_socket_alive(sock_);
  8523. }
  8524. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8525. #ifdef _WIN32
  8526. size =
  8527. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8528. #else
  8529. size = (std::min)(size,
  8530. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8531. #endif
  8532. if (read_buff_off_ < read_buff_content_size_) {
  8533. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8534. if (size <= remaining_size) {
  8535. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8536. read_buff_off_ += size;
  8537. return static_cast<ssize_t>(size);
  8538. } else {
  8539. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8540. read_buff_off_ += remaining_size;
  8541. return static_cast<ssize_t>(remaining_size);
  8542. }
  8543. }
  8544. if (!wait_readable()) {
  8545. error_ = Error::Timeout;
  8546. return -1;
  8547. }
  8548. read_buff_off_ = 0;
  8549. read_buff_content_size_ = 0;
  8550. if (size < read_buff_size_) {
  8551. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8552. CPPHTTPLIB_RECV_FLAGS);
  8553. if (n <= 0) {
  8554. if (n == 0) {
  8555. error_ = Error::ConnectionClosed;
  8556. } else {
  8557. error_ = Error::Read;
  8558. }
  8559. return n;
  8560. } else if (n <= static_cast<ssize_t>(size)) {
  8561. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8562. return n;
  8563. } else {
  8564. memcpy(ptr, read_buff_.data(), size);
  8565. read_buff_off_ = size;
  8566. read_buff_content_size_ = static_cast<size_t>(n);
  8567. return static_cast<ssize_t>(size);
  8568. }
  8569. } else {
  8570. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8571. if (n <= 0) {
  8572. if (n == 0) {
  8573. error_ = Error::ConnectionClosed;
  8574. } else {
  8575. error_ = Error::Read;
  8576. }
  8577. }
  8578. return n;
  8579. }
  8580. }
  8581. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8582. if (!wait_writable()) { return -1; }
  8583. #if defined(_WIN32) && !defined(_WIN64)
  8584. size =
  8585. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8586. #endif
  8587. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8588. }
  8589. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8590. int &port) const {
  8591. return detail::get_remote_ip_and_port(sock_, ip, port);
  8592. }
  8593. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8594. int &port) const {
  8595. return detail::get_local_ip_and_port(sock_, ip, port);
  8596. }
  8597. inline socket_t SocketStream::socket() const { return sock_; }
  8598. inline time_t SocketStream::duration() const {
  8599. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8600. std::chrono::steady_clock::now() - start_time_)
  8601. .count();
  8602. }
  8603. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8604. read_timeout_sec_ = sec;
  8605. read_timeout_usec_ = usec;
  8606. }
  8607. // Buffer stream implementation
  8608. inline bool BufferStream::is_readable() const { return true; }
  8609. inline bool BufferStream::wait_readable() const { return true; }
  8610. inline bool BufferStream::wait_writable() const { return true; }
  8611. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8612. #if defined(_MSC_VER) && _MSC_VER < 1910
  8613. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8614. #else
  8615. auto len_read = buffer.copy(ptr, size, position);
  8616. #endif
  8617. position += static_cast<size_t>(len_read);
  8618. return static_cast<ssize_t>(len_read);
  8619. }
  8620. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8621. buffer.append(ptr, size);
  8622. return static_cast<ssize_t>(size);
  8623. }
  8624. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8625. int & /*port*/) const {}
  8626. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8627. int & /*port*/) const {}
  8628. inline socket_t BufferStream::socket() const { return 0; }
  8629. inline time_t BufferStream::duration() const { return 0; }
  8630. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8631. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8632. : MatcherBase(pattern) {
  8633. constexpr const char marker[] = "/:";
  8634. // One past the last ending position of a path param substring
  8635. std::size_t last_param_end = 0;
  8636. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8637. // Needed to ensure that parameter names are unique during matcher
  8638. // construction
  8639. // If exceptions are disabled, only last duplicate path
  8640. // parameter will be set
  8641. std::unordered_set<std::string> param_name_set;
  8642. #endif
  8643. while (true) {
  8644. const auto marker_pos = pattern.find(
  8645. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8646. if (marker_pos == std::string::npos) { break; }
  8647. static_fragments_.push_back(
  8648. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8649. const auto param_name_start = marker_pos + str_len(marker);
  8650. auto sep_pos = pattern.find(separator, param_name_start);
  8651. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8652. auto param_name =
  8653. pattern.substr(param_name_start, sep_pos - param_name_start);
  8654. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8655. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8656. std::string msg = "Encountered path parameter '" + param_name +
  8657. "' multiple times in route pattern '" + pattern + "'.";
  8658. throw std::invalid_argument(msg);
  8659. }
  8660. #endif
  8661. param_names_.push_back(std::move(param_name));
  8662. last_param_end = sep_pos + 1;
  8663. }
  8664. if (last_param_end < pattern.length()) {
  8665. static_fragments_.push_back(pattern.substr(last_param_end));
  8666. }
  8667. }
  8668. inline bool PathParamsMatcher::match(Request &request) const {
  8669. request.matches = std::smatch();
  8670. request.path_params.clear();
  8671. request.path_params.reserve(param_names_.size());
  8672. // One past the position at which the path matched the pattern last time
  8673. std::size_t starting_pos = 0;
  8674. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8675. const auto &fragment = static_fragments_[i];
  8676. if (starting_pos + fragment.length() > request.path.length()) {
  8677. return false;
  8678. }
  8679. // Avoid unnecessary allocation by using strncmp instead of substr +
  8680. // comparison
  8681. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8682. fragment.length()) != 0) {
  8683. return false;
  8684. }
  8685. starting_pos += fragment.length();
  8686. // Should only happen when we have a static fragment after a param
  8687. // Example: '/users/:id/subscriptions'
  8688. // The 'subscriptions' fragment here does not have a corresponding param
  8689. if (i >= param_names_.size()) { continue; }
  8690. auto sep_pos = request.path.find(separator, starting_pos);
  8691. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8692. const auto &param_name = param_names_[i];
  8693. request.path_params.emplace(
  8694. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8695. // Mark everything up to '/' as matched
  8696. starting_pos = sep_pos + 1;
  8697. }
  8698. // Returns false if the path is longer than the pattern
  8699. return starting_pos >= request.path.length();
  8700. }
  8701. inline bool RegexMatcher::match(Request &request) const {
  8702. request.path_params.clear();
  8703. return std::regex_match(request.path, request.matches, regex_);
  8704. }
  8705. // Enclose IPv6 address in brackets if needed
  8706. inline std::string prepare_host_string(const std::string &host) {
  8707. // Enclose IPv6 address in brackets (but not if already enclosed)
  8708. if (host.find(':') == std::string::npos ||
  8709. (!host.empty() && host[0] == '[')) {
  8710. // IPv4, hostname, or already bracketed IPv6
  8711. return host;
  8712. } else {
  8713. // IPv6 address without brackets
  8714. return "[" + host + "]";
  8715. }
  8716. }
  8717. inline std::string make_host_and_port_string(const std::string &host, int port,
  8718. bool is_ssl) {
  8719. auto result = prepare_host_string(host);
  8720. // Append port if not default
  8721. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  8722. ; // do nothing
  8723. } else {
  8724. result += ":" + std::to_string(port);
  8725. }
  8726. return result;
  8727. }
  8728. // Create "host:port" string always including port number (for CONNECT method)
  8729. inline std::string
  8730. make_host_and_port_string_always_port(const std::string &host, int port) {
  8731. return prepare_host_string(host) + ":" + std::to_string(port);
  8732. }
  8733. template <typename T>
  8734. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  8735. T header_writer, Error &error) {
  8736. for (const auto &h : headers) {
  8737. if (!detail::fields::is_field_name(h.first) ||
  8738. !detail::fields::is_field_value(h.second)) {
  8739. error = Error::InvalidHeaders;
  8740. return false;
  8741. }
  8742. }
  8743. if (header_writer(strm, headers) <= 0) {
  8744. error = Error::Write;
  8745. return false;
  8746. }
  8747. return true;
  8748. }
  8749. } // namespace detail
  8750. /*
  8751. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  8752. */
  8753. #ifdef CPPHTTPLIB_SSL_ENABLED
  8754. namespace detail {
  8755. // SSL socket stream implementation
  8756. inline SSLSocketStream::SSLSocketStream(
  8757. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8758. time_t read_timeout_usec, time_t write_timeout_sec,
  8759. time_t write_timeout_usec, time_t max_timeout_msec,
  8760. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8761. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  8762. read_timeout_usec_(read_timeout_usec),
  8763. write_timeout_sec_(write_timeout_sec),
  8764. write_timeout_usec_(write_timeout_usec),
  8765. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8766. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8767. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  8768. // Note: create_session() also clears this, but SSLClient currently
  8769. // uses ssl_new() which does not. Until full TLS API migration is complete,
  8770. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  8771. // SSL session was created.
  8772. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  8773. #endif
  8774. }
  8775. inline SSLSocketStream::~SSLSocketStream() = default;
  8776. inline bool SSLSocketStream::is_readable() const {
  8777. return tls::pending(session_) > 0;
  8778. }
  8779. inline bool SSLSocketStream::wait_readable() const {
  8780. if (max_timeout_msec_ <= 0) {
  8781. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8782. }
  8783. time_t read_timeout_sec;
  8784. time_t read_timeout_usec;
  8785. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8786. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8787. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8788. }
  8789. inline bool SSLSocketStream::wait_writable() const {
  8790. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8791. !tls::is_peer_closed(session_, sock_);
  8792. }
  8793. inline bool SSLSocketStream::is_peer_alive() const {
  8794. return !tls::is_peer_closed(session_, sock_);
  8795. }
  8796. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8797. if (tls::pending(session_) > 0) {
  8798. tls::TlsError err;
  8799. auto ret = tls::read(session_, ptr, size, err);
  8800. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8801. error_ = Error::ConnectionClosed;
  8802. }
  8803. return ret;
  8804. } else if (wait_readable()) {
  8805. tls::TlsError err;
  8806. auto ret = tls::read(session_, ptr, size, err);
  8807. if (ret < 0) {
  8808. auto n = 1000;
  8809. #ifdef _WIN32
  8810. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  8811. (err.code == tls::ErrorCode::SyscallError &&
  8812. WSAGetLastError() == WSAETIMEDOUT))) {
  8813. #else
  8814. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  8815. #endif
  8816. if (tls::pending(session_) > 0) {
  8817. return tls::read(session_, ptr, size, err);
  8818. } else if (wait_readable()) {
  8819. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8820. ret = tls::read(session_, ptr, size, err);
  8821. if (ret >= 0) { return ret; }
  8822. } else {
  8823. break;
  8824. }
  8825. }
  8826. assert(ret < 0);
  8827. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8828. error_ = Error::ConnectionClosed;
  8829. }
  8830. return ret;
  8831. } else {
  8832. error_ = Error::Timeout;
  8833. return -1;
  8834. }
  8835. }
  8836. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8837. if (wait_writable()) {
  8838. auto handle_size =
  8839. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  8840. tls::TlsError err;
  8841. auto ret = tls::write(session_, ptr, handle_size, err);
  8842. if (ret < 0) {
  8843. auto n = 1000;
  8844. #ifdef _WIN32
  8845. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  8846. (err.code == tls::ErrorCode::SyscallError &&
  8847. WSAGetLastError() == WSAETIMEDOUT))) {
  8848. #else
  8849. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  8850. #endif
  8851. if (wait_writable()) {
  8852. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8853. ret = tls::write(session_, ptr, handle_size, err);
  8854. if (ret >= 0) { return ret; }
  8855. } else {
  8856. break;
  8857. }
  8858. }
  8859. assert(ret < 0);
  8860. }
  8861. return ret;
  8862. }
  8863. return -1;
  8864. }
  8865. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  8866. int &port) const {
  8867. detail::get_remote_ip_and_port(sock_, ip, port);
  8868. }
  8869. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  8870. int &port) const {
  8871. detail::get_local_ip_and_port(sock_, ip, port);
  8872. }
  8873. inline socket_t SSLSocketStream::socket() const { return sock_; }
  8874. inline time_t SSLSocketStream::duration() const {
  8875. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8876. std::chrono::steady_clock::now() - start_time_)
  8877. .count();
  8878. }
  8879. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  8880. read_timeout_sec_ = sec;
  8881. read_timeout_usec_ = usec;
  8882. }
  8883. } // namespace detail
  8884. #endif // CPPHTTPLIB_SSL_ENABLED
  8885. /*
  8886. * Group 4: Server implementation
  8887. */
  8888. // HTTP server implementation
  8889. inline Server::Server()
  8890. : new_task_queue([] {
  8891. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  8892. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  8893. }) {
  8894. #ifndef _WIN32
  8895. signal(SIGPIPE, SIG_IGN);
  8896. #endif
  8897. }
  8898. inline Server::~Server() = default;
  8899. inline std::unique_ptr<detail::MatcherBase>
  8900. Server::make_matcher(const std::string &pattern) {
  8901. if (pattern.find("/:") != std::string::npos) {
  8902. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  8903. } else {
  8904. return detail::make_unique<detail::RegexMatcher>(pattern);
  8905. }
  8906. }
  8907. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  8908. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8909. return *this;
  8910. }
  8911. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  8912. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8913. return *this;
  8914. }
  8915. inline Server &Server::Post(const std::string &pattern,
  8916. HandlerWithContentReader handler) {
  8917. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8918. std::move(handler));
  8919. return *this;
  8920. }
  8921. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  8922. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8923. return *this;
  8924. }
  8925. inline Server &Server::Put(const std::string &pattern,
  8926. HandlerWithContentReader handler) {
  8927. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8928. std::move(handler));
  8929. return *this;
  8930. }
  8931. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  8932. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8933. return *this;
  8934. }
  8935. inline Server &Server::Patch(const std::string &pattern,
  8936. HandlerWithContentReader handler) {
  8937. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8938. std::move(handler));
  8939. return *this;
  8940. }
  8941. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  8942. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8943. return *this;
  8944. }
  8945. inline Server &Server::Delete(const std::string &pattern,
  8946. HandlerWithContentReader handler) {
  8947. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8948. std::move(handler));
  8949. return *this;
  8950. }
  8951. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  8952. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8953. return *this;
  8954. }
  8955. inline Server &Server::WebSocket(const std::string &pattern,
  8956. WebSocketHandler handler) {
  8957. websocket_handlers_.push_back(
  8958. {make_matcher(pattern), std::move(handler), nullptr});
  8959. return *this;
  8960. }
  8961. inline Server &Server::WebSocket(const std::string &pattern,
  8962. WebSocketHandler handler,
  8963. SubProtocolSelector sub_protocol_selector) {
  8964. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  8965. std::move(sub_protocol_selector)});
  8966. return *this;
  8967. }
  8968. inline bool Server::set_base_dir(const std::string &dir,
  8969. const std::string &mount_point) {
  8970. return set_mount_point(mount_point, dir);
  8971. }
  8972. inline bool Server::set_mount_point(const std::string &mount_point,
  8973. const std::string &dir, Headers headers) {
  8974. detail::FileStat stat(dir);
  8975. if (stat.is_dir()) {
  8976. std::string mnt = !mount_point.empty() ? mount_point : "/";
  8977. if (!mnt.empty() && mnt[0] == '/') {
  8978. std::string resolved_base;
  8979. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  8980. #if defined(_WIN32)
  8981. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  8982. resolved_base += '\\';
  8983. }
  8984. #else
  8985. if (resolved_base.back() != '/') { resolved_base += '/'; }
  8986. #endif
  8987. }
  8988. base_dirs_.push_back(
  8989. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  8990. return true;
  8991. }
  8992. }
  8993. return false;
  8994. }
  8995. inline bool Server::remove_mount_point(const std::string &mount_point) {
  8996. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  8997. if (it->mount_point == mount_point) {
  8998. base_dirs_.erase(it);
  8999. return true;
  9000. }
  9001. }
  9002. return false;
  9003. }
  9004. inline Server &
  9005. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9006. const std::string &mime) {
  9007. file_extension_and_mimetype_map_[ext] = mime;
  9008. return *this;
  9009. }
  9010. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9011. default_file_mimetype_ = mime;
  9012. return *this;
  9013. }
  9014. inline Server &Server::set_file_request_handler(Handler handler) {
  9015. file_request_handler_ = std::move(handler);
  9016. return *this;
  9017. }
  9018. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9019. std::true_type) {
  9020. error_handler_ = std::move(handler);
  9021. return *this;
  9022. }
  9023. inline Server &Server::set_error_handler_core(Handler handler,
  9024. std::false_type) {
  9025. error_handler_ = [handler](const Request &req, Response &res) {
  9026. handler(req, res);
  9027. return HandlerResponse::Handled;
  9028. };
  9029. return *this;
  9030. }
  9031. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9032. exception_handler_ = std::move(handler);
  9033. return *this;
  9034. }
  9035. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9036. pre_routing_handler_ = std::move(handler);
  9037. return *this;
  9038. }
  9039. inline Server &Server::set_post_routing_handler(Handler handler) {
  9040. post_routing_handler_ = std::move(handler);
  9041. return *this;
  9042. }
  9043. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9044. pre_request_handler_ = std::move(handler);
  9045. return *this;
  9046. }
  9047. inline Server &Server::set_logger(Logger logger) {
  9048. logger_ = std::move(logger);
  9049. return *this;
  9050. }
  9051. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9052. error_logger_ = std::move(error_logger);
  9053. return *this;
  9054. }
  9055. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9056. pre_compression_logger_ = std::move(logger);
  9057. return *this;
  9058. }
  9059. inline Server &
  9060. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9061. expect_100_continue_handler_ = std::move(handler);
  9062. return *this;
  9063. }
  9064. inline Server &Server::set_address_family(int family) {
  9065. address_family_ = family;
  9066. return *this;
  9067. }
  9068. inline Server &Server::set_tcp_nodelay(bool on) {
  9069. tcp_nodelay_ = on;
  9070. return *this;
  9071. }
  9072. inline Server &Server::set_ipv6_v6only(bool on) {
  9073. ipv6_v6only_ = on;
  9074. return *this;
  9075. }
  9076. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9077. socket_options_ = std::move(socket_options);
  9078. return *this;
  9079. }
  9080. inline Server &Server::set_default_headers(Headers headers) {
  9081. default_headers_ = std::move(headers);
  9082. return *this;
  9083. }
  9084. inline Server &Server::set_header_writer(
  9085. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9086. header_writer_ = writer;
  9087. return *this;
  9088. }
  9089. inline Server &
  9090. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9091. trusted_proxies_ = proxies;
  9092. return *this;
  9093. }
  9094. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9095. keep_alive_max_count_ = count;
  9096. return *this;
  9097. }
  9098. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9099. keep_alive_timeout_sec_ = sec;
  9100. return *this;
  9101. }
  9102. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9103. read_timeout_sec_ = sec;
  9104. read_timeout_usec_ = usec;
  9105. return *this;
  9106. }
  9107. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9108. write_timeout_sec_ = sec;
  9109. write_timeout_usec_ = usec;
  9110. return *this;
  9111. }
  9112. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9113. idle_interval_sec_ = sec;
  9114. idle_interval_usec_ = usec;
  9115. return *this;
  9116. }
  9117. inline Server &Server::set_payload_max_length(size_t length) {
  9118. payload_max_length_ = length;
  9119. return *this;
  9120. }
  9121. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9122. websocket_ping_interval_sec_ = sec;
  9123. return *this;
  9124. }
  9125. template <class Rep, class Period>
  9126. inline Server &Server::set_websocket_ping_interval(
  9127. const std::chrono::duration<Rep, Period> &duration) {
  9128. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9129. set_websocket_ping_interval(sec);
  9130. });
  9131. return *this;
  9132. }
  9133. inline bool Server::bind_to_port(const std::string &host, int port,
  9134. int socket_flags) {
  9135. auto ret = bind_internal(host, port, socket_flags);
  9136. if (ret == -1) { is_decommissioned = true; }
  9137. return ret >= 0;
  9138. }
  9139. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9140. auto ret = bind_internal(host, 0, socket_flags);
  9141. if (ret == -1) { is_decommissioned = true; }
  9142. return ret;
  9143. }
  9144. inline bool Server::listen_after_bind() { return listen_internal(); }
  9145. inline bool Server::listen(const std::string &host, int port,
  9146. int socket_flags) {
  9147. return bind_to_port(host, port, socket_flags) && listen_internal();
  9148. }
  9149. inline bool Server::is_running() const { return is_running_; }
  9150. inline void Server::wait_until_ready() const {
  9151. while (!is_running_ && !is_decommissioned) {
  9152. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9153. }
  9154. }
  9155. inline void Server::stop() {
  9156. if (is_running_) {
  9157. assert(svr_sock_ != INVALID_SOCKET);
  9158. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9159. detail::shutdown_socket(sock);
  9160. detail::close_socket(sock);
  9161. }
  9162. is_decommissioned = false;
  9163. }
  9164. inline void Server::decommission() { is_decommissioned = true; }
  9165. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9166. auto len = strlen(s);
  9167. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9168. len -= 2;
  9169. {
  9170. size_t count = 0;
  9171. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9172. switch (count) {
  9173. case 0: req.method = std::string(b, e); break;
  9174. case 1: req.target = std::string(b, e); break;
  9175. case 2: req.version = std::string(b, e); break;
  9176. default: break;
  9177. }
  9178. count++;
  9179. });
  9180. if (count != 3) { return false; }
  9181. }
  9182. thread_local const std::set<std::string> methods{
  9183. "GET", "HEAD", "POST", "PUT", "DELETE",
  9184. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9185. if (methods.find(req.method) == methods.end()) {
  9186. output_error_log(Error::InvalidHTTPMethod, &req);
  9187. return false;
  9188. }
  9189. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9190. output_error_log(Error::InvalidHTTPVersion, &req);
  9191. return false;
  9192. }
  9193. {
  9194. // Skip URL fragment
  9195. for (size_t i = 0; i < req.target.size(); i++) {
  9196. if (req.target[i] == '#') {
  9197. req.target.erase(i);
  9198. break;
  9199. }
  9200. }
  9201. detail::divide(req.target, '?',
  9202. [&](const char *lhs_data, std::size_t lhs_size,
  9203. const char *rhs_data, std::size_t rhs_size) {
  9204. req.path =
  9205. decode_path_component(std::string(lhs_data, lhs_size));
  9206. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9207. });
  9208. }
  9209. return true;
  9210. }
  9211. inline bool Server::write_response(Stream &strm, bool close_connection,
  9212. Request &req, Response &res) {
  9213. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9214. // incorrectly to the error content.
  9215. req.ranges.clear();
  9216. return write_response_core(strm, close_connection, req, res, false);
  9217. }
  9218. inline bool Server::write_response_with_content(Stream &strm,
  9219. bool close_connection,
  9220. const Request &req,
  9221. Response &res) {
  9222. return write_response_core(strm, close_connection, req, res, true);
  9223. }
  9224. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9225. const Request &req, Response &res,
  9226. bool need_apply_ranges) {
  9227. assert(res.status != -1);
  9228. if (400 <= res.status && error_handler_ &&
  9229. error_handler_(req, res) == HandlerResponse::Handled) {
  9230. need_apply_ranges = true;
  9231. }
  9232. std::string content_type;
  9233. std::string boundary;
  9234. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9235. // Prepare additional headers
  9236. if (close_connection || req.get_header_value("Connection") == "close" ||
  9237. 400 <= res.status) { // Don't leave connections open after errors
  9238. res.set_header("Connection", "close");
  9239. } else {
  9240. std::string s = "timeout=";
  9241. s += std::to_string(keep_alive_timeout_sec_);
  9242. s += ", max=";
  9243. s += std::to_string(keep_alive_max_count_);
  9244. res.set_header("Keep-Alive", s);
  9245. }
  9246. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9247. !res.has_header("Content-Type")) {
  9248. res.set_header("Content-Type", "text/plain");
  9249. }
  9250. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9251. !res.has_header("Content-Length")) {
  9252. res.set_header("Content-Length", "0");
  9253. }
  9254. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9255. res.set_header("Accept-Ranges", "bytes");
  9256. }
  9257. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9258. // Response line and headers
  9259. detail::BufferStream bstrm;
  9260. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9261. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9262. // Combine small body with headers to reduce write syscalls
  9263. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9264. bstrm.write(res.body.data(), res.body.size());
  9265. }
  9266. // Log before writing to avoid race condition with client-side code that
  9267. // accesses logger-captured data immediately after receiving the response.
  9268. output_log(req, res);
  9269. // Flush buffer
  9270. auto &data = bstrm.get_buffer();
  9271. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9272. // Streaming body
  9273. auto ret = true;
  9274. if (req.method != "HEAD" && res.content_provider_) {
  9275. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9276. res.content_provider_success_ = true;
  9277. } else {
  9278. ret = false;
  9279. }
  9280. }
  9281. return ret;
  9282. }
  9283. inline bool
  9284. Server::write_content_with_provider(Stream &strm, const Request &req,
  9285. Response &res, const std::string &boundary,
  9286. const std::string &content_type) {
  9287. auto is_shutting_down = [this]() {
  9288. return this->svr_sock_ == INVALID_SOCKET;
  9289. };
  9290. if (res.content_length_ > 0) {
  9291. if (req.ranges.empty()) {
  9292. return detail::write_content(strm, res.content_provider_, 0,
  9293. res.content_length_, is_shutting_down);
  9294. } else if (req.ranges.size() == 1) {
  9295. auto offset_and_length = detail::get_range_offset_and_length(
  9296. req.ranges[0], res.content_length_);
  9297. return detail::write_content(strm, res.content_provider_,
  9298. offset_and_length.first,
  9299. offset_and_length.second, is_shutting_down);
  9300. } else {
  9301. return detail::write_multipart_ranges_data(
  9302. strm, req, res, boundary, content_type, res.content_length_,
  9303. is_shutting_down);
  9304. }
  9305. } else {
  9306. if (res.is_chunked_content_provider_) {
  9307. auto type = detail::encoding_type(req, res);
  9308. std::unique_ptr<detail::compressor> compressor;
  9309. if (type == detail::EncodingType::Gzip) {
  9310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9311. compressor = detail::make_unique<detail::gzip_compressor>();
  9312. #endif
  9313. } else if (type == detail::EncodingType::Brotli) {
  9314. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9315. compressor = detail::make_unique<detail::brotli_compressor>();
  9316. #endif
  9317. } else if (type == detail::EncodingType::Zstd) {
  9318. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9319. compressor = detail::make_unique<detail::zstd_compressor>();
  9320. #endif
  9321. } else {
  9322. compressor = detail::make_unique<detail::nocompressor>();
  9323. }
  9324. assert(compressor != nullptr);
  9325. return detail::write_content_chunked(strm, res.content_provider_,
  9326. is_shutting_down, *compressor);
  9327. } else {
  9328. return detail::write_content_without_length(strm, res.content_provider_,
  9329. is_shutting_down);
  9330. }
  9331. }
  9332. }
  9333. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9334. FormFields::iterator cur_field;
  9335. FormFiles::iterator cur_file;
  9336. auto is_text_field = false;
  9337. size_t count = 0;
  9338. if (read_content_core(
  9339. strm, req, res,
  9340. // Regular
  9341. [&](const char *buf, size_t n) {
  9342. // Prevent arithmetic overflow when checking sizes.
  9343. // Avoid computing (req.body.size() + n) directly because
  9344. // adding two unsigned `size_t` values can wrap around and
  9345. // produce a small result instead of indicating overflow.
  9346. // Instead, check using subtraction: ensure `n` does not
  9347. // exceed the remaining capacity `max_size() - size()`.
  9348. if (req.body.size() >= req.body.max_size() ||
  9349. n > req.body.max_size() - req.body.size()) {
  9350. return false;
  9351. }
  9352. // Limit decompressed body size to payload_max_length_ to protect
  9353. // against "zip bomb" attacks where a small compressed payload
  9354. // decompresses to a massive size.
  9355. if (payload_max_length_ > 0 &&
  9356. (req.body.size() >= payload_max_length_ ||
  9357. n > payload_max_length_ - req.body.size())) {
  9358. return false;
  9359. }
  9360. req.body.append(buf, n);
  9361. return true;
  9362. },
  9363. // Multipart FormData
  9364. [&](const FormData &file) {
  9365. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9366. output_error_log(Error::TooManyFormDataFiles, &req);
  9367. return false;
  9368. }
  9369. if (file.filename.empty()) {
  9370. cur_field = req.form.fields.emplace(
  9371. file.name, FormField{file.name, file.content, file.headers});
  9372. is_text_field = true;
  9373. } else {
  9374. cur_file = req.form.files.emplace(file.name, file);
  9375. is_text_field = false;
  9376. }
  9377. return true;
  9378. },
  9379. [&](const char *buf, size_t n) {
  9380. if (is_text_field) {
  9381. auto &content = cur_field->second.content;
  9382. if (content.size() + n > content.max_size()) { return false; }
  9383. content.append(buf, n);
  9384. } else {
  9385. auto &content = cur_file->second.content;
  9386. if (content.size() + n > content.max_size()) { return false; }
  9387. content.append(buf, n);
  9388. }
  9389. return true;
  9390. })) {
  9391. const auto &content_type = req.get_header_value("Content-Type");
  9392. if (detail::extract_media_type(content_type) ==
  9393. "application/x-www-form-urlencoded") {
  9394. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9395. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9396. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9397. return false;
  9398. }
  9399. detail::parse_query_text(req.body, req.params);
  9400. }
  9401. return true;
  9402. }
  9403. return false;
  9404. }
  9405. inline bool Server::read_content_with_content_receiver(
  9406. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9407. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9408. return read_content_core(strm, req, res, std::move(receiver),
  9409. std::move(multipart_header),
  9410. std::move(multipart_receiver));
  9411. }
  9412. inline bool Server::read_content_core(
  9413. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9414. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9415. detail::FormDataParser multipart_form_data_parser;
  9416. ContentReceiverWithProgress out;
  9417. if (req.is_multipart_form_data()) {
  9418. const auto &content_type = req.get_header_value("Content-Type");
  9419. std::string boundary;
  9420. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9421. res.status = StatusCode::BadRequest_400;
  9422. output_error_log(Error::MultipartParsing, &req);
  9423. return false;
  9424. }
  9425. multipart_form_data_parser.set_boundary(std::move(boundary));
  9426. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9427. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9428. multipart_receiver);
  9429. };
  9430. } else {
  9431. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9432. size_t /*len*/) { return receiver(buf, n); };
  9433. }
  9434. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  9435. // are true (no Transfer-Encoding and no Content-Length), then the message
  9436. // body length is zero (no message body is present).
  9437. //
  9438. // For non-SSL builds, detect clients that send a body without a
  9439. // Content-Length header (raw HTTP over TCP). Check both the stream's
  9440. // internal read buffer (data already read from the socket during header
  9441. // parsing) and the socket itself for pending data. If data is found and
  9442. // exceeds the configured payload limit, reject with 413.
  9443. // For SSL builds we cannot reliably peek the decrypted application bytes,
  9444. // so keep the original behaviour.
  9445. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9446. if (!req.has_header("Content-Length") &&
  9447. !detail::is_chunked_transfer_encoding(req.headers)) {
  9448. // Only check if payload_max_length is set to a finite value
  9449. if (payload_max_length_ > 0 &&
  9450. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9451. // Check if there is data already buffered in the stream (read during
  9452. // header parsing) or pending on the socket. Use a non-blocking socket
  9453. // check to avoid deadlock when the client sends no body.
  9454. bool has_data = strm.is_readable();
  9455. if (!has_data) {
  9456. socket_t s = strm.socket();
  9457. if (s != INVALID_SOCKET) {
  9458. has_data = detail::select_read(s, 0, 0) > 0;
  9459. }
  9460. }
  9461. if (has_data) {
  9462. auto result =
  9463. detail::read_content_without_length(strm, payload_max_length_, out);
  9464. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9465. res.status = StatusCode::PayloadTooLarge_413;
  9466. return false;
  9467. } else if (result != detail::ReadContentResult::Success) {
  9468. return false;
  9469. }
  9470. return true;
  9471. }
  9472. }
  9473. return true;
  9474. }
  9475. #else
  9476. if (!req.has_header("Content-Length") &&
  9477. !detail::is_chunked_transfer_encoding(req.headers)) {
  9478. return true;
  9479. }
  9480. #endif
  9481. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9482. out, true)) {
  9483. return false;
  9484. }
  9485. req.body_consumed_ = true;
  9486. if (req.is_multipart_form_data()) {
  9487. if (!multipart_form_data_parser.is_valid()) {
  9488. res.status = StatusCode::BadRequest_400;
  9489. output_error_log(Error::MultipartParsing, &req);
  9490. return false;
  9491. }
  9492. }
  9493. return true;
  9494. }
  9495. inline bool Server::handle_file_request(Request &req, Response &res) {
  9496. for (const auto &entry : base_dirs_) {
  9497. // Prefix match
  9498. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9499. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9500. if (detail::is_valid_path(sub_path)) {
  9501. auto path = entry.base_dir + sub_path;
  9502. if (path.back() == '/') { path += "index.html"; }
  9503. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9504. // but symlinks/junctions can still escape the base directory.
  9505. if (!entry.resolved_base_dir.empty()) {
  9506. std::string resolved_path;
  9507. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9508. !detail::is_path_within_base(resolved_path,
  9509. entry.resolved_base_dir)) {
  9510. res.status = StatusCode::Forbidden_403;
  9511. return true;
  9512. }
  9513. }
  9514. detail::FileStat stat(path);
  9515. if (stat.is_dir()) {
  9516. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9517. return true;
  9518. }
  9519. if (stat.is_file()) {
  9520. for (const auto &kv : entry.headers) {
  9521. res.set_header(kv.first, kv.second);
  9522. }
  9523. auto etag = detail::compute_etag(stat);
  9524. if (!etag.empty()) { res.set_header("ETag", etag); }
  9525. auto mtime = stat.mtime();
  9526. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9527. if (!last_modified.empty()) {
  9528. res.set_header("Last-Modified", last_modified);
  9529. }
  9530. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9531. check_if_range(req, etag, mtime);
  9532. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9533. if (!mm->is_open()) {
  9534. output_error_log(Error::OpenFile, &req);
  9535. return false;
  9536. }
  9537. res.set_content_provider(
  9538. mm->size(),
  9539. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9540. default_file_mimetype_),
  9541. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9542. sink.write(mm->data() + offset, length);
  9543. return true;
  9544. });
  9545. if (req.method != "HEAD" && file_request_handler_) {
  9546. file_request_handler_(req, res);
  9547. }
  9548. return true;
  9549. } else {
  9550. output_error_log(Error::OpenFile, &req);
  9551. }
  9552. }
  9553. }
  9554. }
  9555. return false;
  9556. }
  9557. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9558. const std::string &etag,
  9559. time_t mtime) const {
  9560. // Handle conditional GET:
  9561. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9562. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9563. if (req.has_header("If-None-Match")) {
  9564. if (!etag.empty()) {
  9565. auto val = req.get_header_value("If-None-Match");
  9566. // NOTE: We use exact string matching here. This works correctly
  9567. // because our server always generates weak ETags (W/"..."), and
  9568. // clients typically send back the same ETag they received.
  9569. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9570. // If-None-Match, where W/"x" and "x" would match, but this
  9571. // simplified implementation requires exact matches.
  9572. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9573. [&](const char *b, const char *e) {
  9574. auto seg_len = static_cast<size_t>(e - b);
  9575. return (seg_len == 1 && *b == '*') ||
  9576. (seg_len == etag.size() &&
  9577. std::equal(b, e, etag.begin()));
  9578. });
  9579. if (ret) {
  9580. res.status = StatusCode::NotModified_304;
  9581. return true;
  9582. }
  9583. }
  9584. } else if (req.has_header("If-Modified-Since")) {
  9585. auto val = req.get_header_value("If-Modified-Since");
  9586. auto t = detail::parse_http_date(val);
  9587. if (t != static_cast<time_t>(-1) && mtime <= t) {
  9588. res.status = StatusCode::NotModified_304;
  9589. return true;
  9590. }
  9591. }
  9592. return false;
  9593. }
  9594. inline bool Server::check_if_range(Request &req, const std::string &etag,
  9595. time_t mtime) const {
  9596. // Handle If-Range for partial content requests (RFC 9110
  9597. // Section 13.1.5). If-Range is only evaluated when Range header is
  9598. // present. If the validator matches, serve partial content; otherwise
  9599. // serve full content.
  9600. if (!req.ranges.empty() && req.has_header("If-Range")) {
  9601. auto val = req.get_header_value("If-Range");
  9602. auto is_valid_range = [&]() {
  9603. if (detail::is_strong_etag(val)) {
  9604. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  9605. // comparison.
  9606. return (!etag.empty() && val == etag);
  9607. } else if (detail::is_weak_etag(val)) {
  9608. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  9609. return false;
  9610. } else {
  9611. // HTTP-date comparison
  9612. auto t = detail::parse_http_date(val);
  9613. return (t != static_cast<time_t>(-1) && mtime <= t);
  9614. }
  9615. };
  9616. if (!is_valid_range()) {
  9617. // Validator doesn't match: ignore Range and serve full content
  9618. req.ranges.clear();
  9619. return false;
  9620. }
  9621. }
  9622. return true;
  9623. }
  9624. inline socket_t
  9625. Server::create_server_socket(const std::string &host, int port,
  9626. int socket_flags,
  9627. SocketOptions socket_options) const {
  9628. return detail::create_socket(
  9629. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  9630. ipv6_v6only_, std::move(socket_options),
  9631. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  9632. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  9633. output_error_log(Error::BindIPAddress, nullptr);
  9634. return false;
  9635. }
  9636. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  9637. output_error_log(Error::Listen, nullptr);
  9638. return false;
  9639. }
  9640. return true;
  9641. });
  9642. }
  9643. inline int Server::bind_internal(const std::string &host, int port,
  9644. int socket_flags) {
  9645. if (is_decommissioned) { return -1; }
  9646. if (!is_valid()) { return -1; }
  9647. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  9648. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  9649. if (port == 0) {
  9650. struct sockaddr_storage addr;
  9651. socklen_t addr_len = sizeof(addr);
  9652. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  9653. &addr_len) == -1) {
  9654. output_error_log(Error::GetSockName, nullptr);
  9655. return -1;
  9656. }
  9657. if (addr.ss_family == AF_INET) {
  9658. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  9659. } else if (addr.ss_family == AF_INET6) {
  9660. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  9661. } else {
  9662. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  9663. return -1;
  9664. }
  9665. } else {
  9666. return port;
  9667. }
  9668. }
  9669. inline bool Server::listen_internal() {
  9670. if (is_decommissioned) { return false; }
  9671. auto ret = true;
  9672. is_running_ = true;
  9673. auto se = detail::scope_exit([&]() { is_running_ = false; });
  9674. {
  9675. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  9676. while (svr_sock_ != INVALID_SOCKET) {
  9677. #ifndef _WIN32
  9678. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  9679. #endif
  9680. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  9681. idle_interval_usec_);
  9682. if (val == 0) { // Timeout
  9683. task_queue->on_idle();
  9684. continue;
  9685. }
  9686. #ifndef _WIN32
  9687. }
  9688. #endif
  9689. #if defined _WIN32
  9690. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  9691. // OVERLAPPED
  9692. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  9693. #elif defined SOCK_CLOEXEC
  9694. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  9695. #else
  9696. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  9697. #endif
  9698. if (sock == INVALID_SOCKET) {
  9699. if (errno == EMFILE) {
  9700. // The per-process limit of open file descriptors has been reached.
  9701. // Try to accept new connections after a short sleep.
  9702. std::this_thread::sleep_for(std::chrono::microseconds{1});
  9703. continue;
  9704. } else if (errno == EINTR || errno == EAGAIN) {
  9705. continue;
  9706. }
  9707. if (svr_sock_ != INVALID_SOCKET) {
  9708. detail::close_socket(svr_sock_);
  9709. ret = false;
  9710. output_error_log(Error::Connection, nullptr);
  9711. } else {
  9712. ; // The server socket was closed by user.
  9713. }
  9714. break;
  9715. }
  9716. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  9717. read_timeout_sec_, read_timeout_usec_);
  9718. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  9719. write_timeout_sec_, write_timeout_usec_);
  9720. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  9721. if (!task_queue->enqueue(
  9722. [this, sock]() { process_and_close_socket(sock); })) {
  9723. output_error_log(Error::ResourceExhaustion, nullptr);
  9724. detail::shutdown_socket(sock);
  9725. detail::close_socket(sock);
  9726. }
  9727. }
  9728. task_queue->shutdown();
  9729. }
  9730. is_decommissioned = !ret;
  9731. return ret;
  9732. }
  9733. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  9734. if (pre_routing_handler_ &&
  9735. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  9736. return true;
  9737. }
  9738. // File handler
  9739. if ((req.method == "GET" || req.method == "HEAD") &&
  9740. handle_file_request(req, res)) {
  9741. return true;
  9742. }
  9743. if (detail::expect_content(req)) {
  9744. // Content reader handler
  9745. {
  9746. // Track whether the ContentReader was aborted due to the decompressed
  9747. // payload exceeding `payload_max_length_`.
  9748. // The user handler runs after the lambda returns, so we must restore the
  9749. // 413 status if the handler overwrites it.
  9750. bool content_reader_payload_too_large = false;
  9751. ContentReader reader(
  9752. [&](ContentReceiver receiver) {
  9753. auto result = read_content_with_content_receiver(
  9754. strm, req, res, std::move(receiver), nullptr, nullptr);
  9755. if (!result) {
  9756. output_error_log(Error::Read, &req);
  9757. if (res.status == StatusCode::PayloadTooLarge_413) {
  9758. content_reader_payload_too_large = true;
  9759. }
  9760. }
  9761. return result;
  9762. },
  9763. [&](FormDataHeader header, ContentReceiver receiver) {
  9764. auto result = read_content_with_content_receiver(
  9765. strm, req, res, nullptr, std::move(header),
  9766. std::move(receiver));
  9767. if (!result) {
  9768. output_error_log(Error::Read, &req);
  9769. if (res.status == StatusCode::PayloadTooLarge_413) {
  9770. content_reader_payload_too_large = true;
  9771. }
  9772. }
  9773. return result;
  9774. });
  9775. bool dispatched = false;
  9776. if (req.method == "POST") {
  9777. dispatched = dispatch_request_for_content_reader(
  9778. req, res, std::move(reader), post_handlers_for_content_reader_);
  9779. } else if (req.method == "PUT") {
  9780. dispatched = dispatch_request_for_content_reader(
  9781. req, res, std::move(reader), put_handlers_for_content_reader_);
  9782. } else if (req.method == "PATCH") {
  9783. dispatched = dispatch_request_for_content_reader(
  9784. req, res, std::move(reader), patch_handlers_for_content_reader_);
  9785. } else if (req.method == "DELETE") {
  9786. dispatched = dispatch_request_for_content_reader(
  9787. req, res, std::move(reader), delete_handlers_for_content_reader_);
  9788. }
  9789. if (dispatched) {
  9790. if (content_reader_payload_too_large) {
  9791. // Enforce the limit: override any status the handler may have set
  9792. // and return false so the error path sends a plain 413 response.
  9793. res.status = StatusCode::PayloadTooLarge_413;
  9794. res.body.clear();
  9795. res.content_length_ = 0;
  9796. res.content_provider_ = nullptr;
  9797. return false;
  9798. }
  9799. return true;
  9800. }
  9801. }
  9802. // Read content into `req.body`
  9803. if (!read_content(strm, req, res)) {
  9804. output_error_log(Error::Read, &req);
  9805. return false;
  9806. }
  9807. }
  9808. // Regular handler
  9809. if (req.method == "GET" || req.method == "HEAD") {
  9810. return dispatch_request(req, res, get_handlers_);
  9811. } else if (req.method == "POST") {
  9812. return dispatch_request(req, res, post_handlers_);
  9813. } else if (req.method == "PUT") {
  9814. return dispatch_request(req, res, put_handlers_);
  9815. } else if (req.method == "DELETE") {
  9816. return dispatch_request(req, res, delete_handlers_);
  9817. } else if (req.method == "OPTIONS") {
  9818. return dispatch_request(req, res, options_handlers_);
  9819. } else if (req.method == "PATCH") {
  9820. return dispatch_request(req, res, patch_handlers_);
  9821. }
  9822. res.status = StatusCode::BadRequest_400;
  9823. return false;
  9824. }
  9825. inline bool Server::dispatch_request(Request &req, Response &res,
  9826. const Handlers &handlers) const {
  9827. for (const auto &x : handlers) {
  9828. const auto &matcher = x.first;
  9829. const auto &handler = x.second;
  9830. if (matcher->match(req)) {
  9831. req.matched_route = matcher->pattern();
  9832. if (!pre_request_handler_ ||
  9833. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9834. handler(req, res);
  9835. }
  9836. return true;
  9837. }
  9838. }
  9839. return false;
  9840. }
  9841. inline void Server::apply_ranges(const Request &req, Response &res,
  9842. std::string &content_type,
  9843. std::string &boundary) const {
  9844. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  9845. auto it = res.headers.find("Content-Type");
  9846. if (it != res.headers.end()) {
  9847. content_type = it->second;
  9848. res.headers.erase(it);
  9849. }
  9850. boundary = detail::make_multipart_data_boundary();
  9851. res.set_header("Content-Type",
  9852. "multipart/byteranges; boundary=" + boundary);
  9853. }
  9854. auto type = detail::encoding_type(req, res);
  9855. if (res.body.empty()) {
  9856. if (res.content_length_ > 0) {
  9857. size_t length = 0;
  9858. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9859. length = res.content_length_;
  9860. } else if (req.ranges.size() == 1) {
  9861. auto offset_and_length = detail::get_range_offset_and_length(
  9862. req.ranges[0], res.content_length_);
  9863. length = offset_and_length.second;
  9864. auto content_range = detail::make_content_range_header_field(
  9865. offset_and_length, res.content_length_);
  9866. res.set_header("Content-Range", content_range);
  9867. } else {
  9868. length = detail::get_multipart_ranges_data_length(
  9869. req, boundary, content_type, res.content_length_);
  9870. }
  9871. res.set_header("Content-Length", std::to_string(length));
  9872. } else {
  9873. if (res.content_provider_) {
  9874. if (res.is_chunked_content_provider_) {
  9875. res.set_header("Transfer-Encoding", "chunked");
  9876. if (type == detail::EncodingType::Gzip) {
  9877. res.set_header("Content-Encoding", "gzip");
  9878. res.set_header("Vary", "Accept-Encoding");
  9879. } else if (type == detail::EncodingType::Brotli) {
  9880. res.set_header("Content-Encoding", "br");
  9881. res.set_header("Vary", "Accept-Encoding");
  9882. } else if (type == detail::EncodingType::Zstd) {
  9883. res.set_header("Content-Encoding", "zstd");
  9884. res.set_header("Vary", "Accept-Encoding");
  9885. }
  9886. }
  9887. }
  9888. }
  9889. } else {
  9890. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9891. ;
  9892. } else if (req.ranges.size() == 1) {
  9893. auto offset_and_length =
  9894. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  9895. auto offset = offset_and_length.first;
  9896. auto length = offset_and_length.second;
  9897. auto content_range = detail::make_content_range_header_field(
  9898. offset_and_length, res.body.size());
  9899. res.set_header("Content-Range", content_range);
  9900. assert(offset + length <= res.body.size());
  9901. res.body = res.body.substr(offset, length);
  9902. } else {
  9903. std::string data;
  9904. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  9905. res.body.size(), data);
  9906. res.body.swap(data);
  9907. }
  9908. if (type != detail::EncodingType::None) {
  9909. output_pre_compression_log(req, res);
  9910. std::unique_ptr<detail::compressor> compressor;
  9911. std::string content_encoding;
  9912. if (type == detail::EncodingType::Gzip) {
  9913. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9914. compressor = detail::make_unique<detail::gzip_compressor>();
  9915. content_encoding = "gzip";
  9916. #endif
  9917. } else if (type == detail::EncodingType::Brotli) {
  9918. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9919. compressor = detail::make_unique<detail::brotli_compressor>();
  9920. content_encoding = "br";
  9921. #endif
  9922. } else if (type == detail::EncodingType::Zstd) {
  9923. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9924. compressor = detail::make_unique<detail::zstd_compressor>();
  9925. content_encoding = "zstd";
  9926. #endif
  9927. }
  9928. if (compressor) {
  9929. std::string compressed;
  9930. if (compressor->compress(res.body.data(), res.body.size(), true,
  9931. [&](const char *data, size_t data_len) {
  9932. compressed.append(data, data_len);
  9933. return true;
  9934. })) {
  9935. res.body.swap(compressed);
  9936. res.set_header("Content-Encoding", content_encoding);
  9937. res.set_header("Vary", "Accept-Encoding");
  9938. }
  9939. }
  9940. }
  9941. auto length = std::to_string(res.body.size());
  9942. res.set_header("Content-Length", length);
  9943. }
  9944. }
  9945. inline bool Server::dispatch_request_for_content_reader(
  9946. Request &req, Response &res, ContentReader content_reader,
  9947. const HandlersForContentReader &handlers) const {
  9948. for (const auto &x : handlers) {
  9949. const auto &matcher = x.first;
  9950. const auto &handler = x.second;
  9951. if (matcher->match(req)) {
  9952. req.matched_route = matcher->pattern();
  9953. if (!pre_request_handler_ ||
  9954. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9955. handler(req, res, content_reader);
  9956. }
  9957. return true;
  9958. }
  9959. }
  9960. return false;
  9961. }
  9962. inline std::string
  9963. get_client_ip(const std::string &x_forwarded_for,
  9964. const std::vector<std::string> &trusted_proxies) {
  9965. // X-Forwarded-For is a comma-separated list per RFC 7239
  9966. std::vector<std::string> ip_list;
  9967. detail::split(x_forwarded_for.data(),
  9968. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  9969. [&](const char *b, const char *e) {
  9970. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  9971. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  9972. });
  9973. for (size_t i = 0; i < ip_list.size(); ++i) {
  9974. auto ip = ip_list[i];
  9975. auto is_trusted_proxy =
  9976. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  9977. [&](const std::string &proxy) { return ip == proxy; });
  9978. if (is_trusted_proxy) {
  9979. if (i == 0) {
  9980. // If the trusted proxy is the first IP, there's no preceding client IP
  9981. return ip;
  9982. } else {
  9983. // Return the IP immediately before the trusted proxy
  9984. return ip_list[i - 1];
  9985. }
  9986. }
  9987. }
  9988. // If no trusted proxy is found, return the first IP in the list
  9989. return ip_list.front();
  9990. }
  9991. inline bool
  9992. Server::process_request(Stream &strm, const std::string &remote_addr,
  9993. int remote_port, const std::string &local_addr,
  9994. int local_port, bool close_connection,
  9995. bool &connection_closed,
  9996. const std::function<void(Request &)> &setup_request,
  9997. bool *websocket_upgraded) {
  9998. std::array<char, 2048> buf{};
  9999. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10000. // Connection has been closed on client
  10001. if (!line_reader.getline()) { return false; }
  10002. Request req;
  10003. req.start_time_ = std::chrono::steady_clock::now();
  10004. req.remote_addr = remote_addr;
  10005. req.remote_port = remote_port;
  10006. req.local_addr = local_addr;
  10007. req.local_port = local_port;
  10008. Response res;
  10009. res.version = "HTTP/1.1";
  10010. res.headers = default_headers_;
  10011. // Request line and headers
  10012. if (!parse_request_line(line_reader.ptr(), req)) {
  10013. res.status = StatusCode::BadRequest_400;
  10014. output_error_log(Error::InvalidRequestLine, &req);
  10015. return write_response(strm, close_connection, req, res);
  10016. }
  10017. // Request headers
  10018. if (!detail::read_headers(strm, req.headers)) {
  10019. res.status = StatusCode::BadRequest_400;
  10020. output_error_log(Error::InvalidHeaders, &req);
  10021. return write_response(strm, close_connection, req, res);
  10022. }
  10023. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10024. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10025. // tolerated for compatibility with existing clients.
  10026. if (req.get_header_value_u64("Content-Length") > 0 &&
  10027. req.has_header("Transfer-Encoding")) {
  10028. connection_closed = true;
  10029. res.status = StatusCode::BadRequest_400;
  10030. return write_response(strm, close_connection, req, res);
  10031. }
  10032. // Check if the request URI doesn't exceed the limit
  10033. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10034. connection_closed = true;
  10035. res.status = StatusCode::UriTooLong_414;
  10036. output_error_log(Error::ExceedUriMaxLength, &req);
  10037. return write_response(strm, close_connection, req, res);
  10038. }
  10039. if (req.get_header_value("Connection") == "close") {
  10040. connection_closed = true;
  10041. }
  10042. if (req.version == "HTTP/1.0" &&
  10043. req.get_header_value("Connection") != "Keep-Alive") {
  10044. connection_closed = true;
  10045. }
  10046. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10047. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10048. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  10049. } else {
  10050. req.remote_addr = remote_addr;
  10051. }
  10052. req.remote_port = remote_port;
  10053. req.local_addr = local_addr;
  10054. req.local_port = local_port;
  10055. if (req.has_header("Accept")) {
  10056. const auto &accept_header = req.get_header_value("Accept");
  10057. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10058. connection_closed = true;
  10059. res.status = StatusCode::BadRequest_400;
  10060. output_error_log(Error::HTTPParsing, &req);
  10061. return write_response(strm, close_connection, req, res);
  10062. }
  10063. }
  10064. if (req.has_header("Range")) {
  10065. const auto &range_header_value = req.get_header_value("Range");
  10066. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10067. connection_closed = true;
  10068. res.status = StatusCode::RangeNotSatisfiable_416;
  10069. output_error_log(Error::InvalidRangeHeader, &req);
  10070. return write_response(strm, close_connection, req, res);
  10071. }
  10072. }
  10073. if (setup_request) { setup_request(req); }
  10074. if (req.get_header_value("Expect") == "100-continue") {
  10075. int status = StatusCode::Continue_100;
  10076. if (expect_100_continue_handler_) {
  10077. status = expect_100_continue_handler_(req, res);
  10078. }
  10079. switch (status) {
  10080. case StatusCode::Continue_100:
  10081. case StatusCode::ExpectationFailed_417:
  10082. detail::write_response_line(strm, status);
  10083. strm.write("\r\n");
  10084. break;
  10085. default:
  10086. connection_closed = true;
  10087. return write_response(strm, true, req, res);
  10088. }
  10089. }
  10090. // Setup `is_connection_closed` method
  10091. auto sock = strm.socket();
  10092. req.is_connection_closed = [sock]() {
  10093. return !detail::is_socket_alive(sock);
  10094. };
  10095. // WebSocket upgrade
  10096. // Check pre_routing_handler_ before upgrading so that authentication
  10097. // and other middleware can reject the request with an HTTP response
  10098. // (e.g., 401) before the protocol switches.
  10099. if (detail::is_websocket_upgrade(req)) {
  10100. if (pre_routing_handler_ &&
  10101. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10102. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10103. return write_response(strm, close_connection, req, res);
  10104. }
  10105. // Find matching WebSocket handler
  10106. for (const auto &entry : websocket_handlers_) {
  10107. if (entry.matcher->match(req)) {
  10108. // Compute accept key
  10109. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10110. auto accept_key = detail::websocket_accept_key(client_key);
  10111. // Negotiate subprotocol
  10112. std::string selected_subprotocol;
  10113. if (entry.sub_protocol_selector) {
  10114. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10115. if (!protocol_header.empty()) {
  10116. std::vector<std::string> protocols;
  10117. std::istringstream iss(protocol_header);
  10118. std::string token;
  10119. while (std::getline(iss, token, ',')) {
  10120. // Trim whitespace
  10121. auto start = token.find_first_not_of(' ');
  10122. auto end = token.find_last_not_of(' ');
  10123. if (start != std::string::npos) {
  10124. protocols.push_back(token.substr(start, end - start + 1));
  10125. }
  10126. }
  10127. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10128. }
  10129. }
  10130. // Send 101 Switching Protocols
  10131. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10132. "Upgrade: websocket\r\n"
  10133. "Connection: Upgrade\r\n"
  10134. "Sec-WebSocket-Accept: " +
  10135. accept_key + "\r\n";
  10136. if (!selected_subprotocol.empty()) {
  10137. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10138. return false;
  10139. }
  10140. handshake_response +=
  10141. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10142. }
  10143. handshake_response += "\r\n";
  10144. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10145. 0) {
  10146. return false;
  10147. }
  10148. connection_closed = true;
  10149. if (websocket_upgraded) { *websocket_upgraded = true; }
  10150. {
  10151. // Use WebSocket-specific read timeout instead of HTTP timeout
  10152. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10153. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_);
  10154. entry.handler(req, ws);
  10155. }
  10156. return true;
  10157. }
  10158. }
  10159. // No matching handler - fall through to 404
  10160. }
  10161. // Routing
  10162. auto routed = false;
  10163. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10164. routed = routing(req, res, strm);
  10165. #else
  10166. try {
  10167. routed = routing(req, res, strm);
  10168. } catch (std::exception &) {
  10169. if (exception_handler_) {
  10170. auto ep = std::current_exception();
  10171. exception_handler_(req, res, ep);
  10172. routed = true;
  10173. } else {
  10174. res.status = StatusCode::InternalServerError_500;
  10175. }
  10176. } catch (...) {
  10177. if (exception_handler_) {
  10178. auto ep = std::current_exception();
  10179. exception_handler_(req, res, ep);
  10180. routed = true;
  10181. } else {
  10182. res.status = StatusCode::InternalServerError_500;
  10183. }
  10184. }
  10185. #endif
  10186. auto ret = false;
  10187. if (routed) {
  10188. if (res.status == -1) {
  10189. res.status = req.ranges.empty() ? StatusCode::OK_200
  10190. : StatusCode::PartialContent_206;
  10191. }
  10192. // Serve file content by using a content provider
  10193. auto file_open_error = false;
  10194. if (!res.file_content_path_.empty()) {
  10195. const auto &path = res.file_content_path_;
  10196. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10197. if (!mm->is_open()) {
  10198. res.body.clear();
  10199. res.content_length_ = 0;
  10200. res.content_provider_ = nullptr;
  10201. res.status = StatusCode::NotFound_404;
  10202. output_error_log(Error::OpenFile, &req);
  10203. file_open_error = true;
  10204. } else {
  10205. auto content_type = res.file_content_content_type_;
  10206. if (content_type.empty()) {
  10207. content_type = detail::find_content_type(
  10208. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10209. }
  10210. res.set_content_provider(
  10211. mm->size(), content_type,
  10212. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10213. sink.write(mm->data() + offset, length);
  10214. return true;
  10215. });
  10216. }
  10217. }
  10218. if (file_open_error) {
  10219. ret = write_response(strm, close_connection, req, res);
  10220. } else if (detail::range_error(req, res)) {
  10221. res.body.clear();
  10222. res.content_length_ = 0;
  10223. res.content_provider_ = nullptr;
  10224. res.status = StatusCode::RangeNotSatisfiable_416;
  10225. ret = write_response(strm, close_connection, req, res);
  10226. } else {
  10227. ret = write_response_with_content(strm, close_connection, req, res);
  10228. }
  10229. } else {
  10230. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10231. ret = write_response(strm, close_connection, req, res);
  10232. }
  10233. // Drain any unconsumed request body to prevent request smuggling on
  10234. // keep-alive connections.
  10235. if (!req.body_consumed_ && detail::expect_content(req)) {
  10236. int drain_status = 200; // required by read_content signature
  10237. if (!detail::read_content(
  10238. strm, req, payload_max_length_, drain_status, nullptr,
  10239. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10240. // Body exceeds payload limit or read error — close the connection
  10241. // to prevent leftover bytes from being misinterpreted.
  10242. connection_closed = true;
  10243. }
  10244. }
  10245. return ret;
  10246. }
  10247. inline bool Server::is_valid() const { return true; }
  10248. inline bool Server::process_and_close_socket(socket_t sock) {
  10249. std::string remote_addr;
  10250. int remote_port = 0;
  10251. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10252. std::string local_addr;
  10253. int local_port = 0;
  10254. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10255. bool websocket_upgraded = false;
  10256. auto ret = detail::process_server_socket(
  10257. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10258. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10259. write_timeout_usec_,
  10260. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10261. return process_request(strm, remote_addr, remote_port, local_addr,
  10262. local_port, close_connection, connection_closed,
  10263. nullptr, &websocket_upgraded);
  10264. });
  10265. detail::shutdown_socket(sock);
  10266. detail::close_socket(sock);
  10267. return ret;
  10268. }
  10269. inline void Server::output_log(const Request &req, const Response &res) const {
  10270. if (logger_) {
  10271. std::lock_guard<std::mutex> guard(logger_mutex_);
  10272. logger_(req, res);
  10273. }
  10274. }
  10275. inline void Server::output_pre_compression_log(const Request &req,
  10276. const Response &res) const {
  10277. if (pre_compression_logger_) {
  10278. std::lock_guard<std::mutex> guard(logger_mutex_);
  10279. pre_compression_logger_(req, res);
  10280. }
  10281. }
  10282. inline void Server::output_error_log(const Error &err,
  10283. const Request *req) const {
  10284. if (error_logger_) {
  10285. std::lock_guard<std::mutex> guard(logger_mutex_);
  10286. error_logger_(err, req);
  10287. }
  10288. }
  10289. /*
  10290. * Group 5: ClientImpl and Client (Universal) implementation
  10291. */
  10292. // HTTP client implementation
  10293. inline ClientImpl::ClientImpl(const std::string &host)
  10294. : ClientImpl(host, 80, std::string(), std::string()) {}
  10295. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10296. : ClientImpl(host, port, std::string(), std::string()) {}
  10297. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10298. const std::string &client_cert_path,
  10299. const std::string &client_key_path)
  10300. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10301. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10302. inline ClientImpl::~ClientImpl() {
  10303. // Wait until all the requests in flight are handled.
  10304. size_t retry_count = 10;
  10305. while (retry_count-- > 0) {
  10306. {
  10307. std::lock_guard<std::mutex> guard(socket_mutex_);
  10308. if (socket_requests_in_flight_ == 0) { break; }
  10309. }
  10310. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10311. }
  10312. std::lock_guard<std::mutex> guard(socket_mutex_);
  10313. shutdown_socket(socket_);
  10314. close_socket(socket_);
  10315. }
  10316. inline bool ClientImpl::is_valid() const { return true; }
  10317. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10318. client_cert_path_ = rhs.client_cert_path_;
  10319. client_key_path_ = rhs.client_key_path_;
  10320. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10321. read_timeout_sec_ = rhs.read_timeout_sec_;
  10322. read_timeout_usec_ = rhs.read_timeout_usec_;
  10323. write_timeout_sec_ = rhs.write_timeout_sec_;
  10324. write_timeout_usec_ = rhs.write_timeout_usec_;
  10325. max_timeout_msec_ = rhs.max_timeout_msec_;
  10326. basic_auth_username_ = rhs.basic_auth_username_;
  10327. basic_auth_password_ = rhs.basic_auth_password_;
  10328. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10329. keep_alive_ = rhs.keep_alive_;
  10330. follow_location_ = rhs.follow_location_;
  10331. path_encode_ = rhs.path_encode_;
  10332. address_family_ = rhs.address_family_;
  10333. tcp_nodelay_ = rhs.tcp_nodelay_;
  10334. ipv6_v6only_ = rhs.ipv6_v6only_;
  10335. socket_options_ = rhs.socket_options_;
  10336. compress_ = rhs.compress_;
  10337. decompress_ = rhs.decompress_;
  10338. payload_max_length_ = rhs.payload_max_length_;
  10339. has_payload_max_length_ = rhs.has_payload_max_length_;
  10340. interface_ = rhs.interface_;
  10341. proxy_host_ = rhs.proxy_host_;
  10342. proxy_port_ = rhs.proxy_port_;
  10343. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10344. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10345. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10346. logger_ = rhs.logger_;
  10347. error_logger_ = rhs.error_logger_;
  10348. #ifdef CPPHTTPLIB_SSL_ENABLED
  10349. digest_auth_username_ = rhs.digest_auth_username_;
  10350. digest_auth_password_ = rhs.digest_auth_password_;
  10351. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10352. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10353. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10354. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10355. server_certificate_verification_ = rhs.server_certificate_verification_;
  10356. server_hostname_verification_ = rhs.server_hostname_verification_;
  10357. #endif
  10358. }
  10359. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10360. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10361. return detail::create_client_socket(
  10362. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10363. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10364. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10365. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10366. }
  10367. // Check is custom IP specified for host_
  10368. std::string ip;
  10369. auto it = addr_map_.find(host_);
  10370. if (it != addr_map_.end()) { ip = it->second; }
  10371. return detail::create_client_socket(
  10372. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10373. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10374. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10375. write_timeout_usec_, interface_, error);
  10376. }
  10377. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10378. Error &error) {
  10379. auto sock = create_client_socket(error);
  10380. if (sock == INVALID_SOCKET) { return false; }
  10381. socket.sock = sock;
  10382. return true;
  10383. }
  10384. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10385. return create_and_connect_socket(socket, error);
  10386. }
  10387. inline bool ClientImpl::setup_proxy_connection(
  10388. Socket & /*socket*/,
  10389. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10390. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10391. return true;
  10392. }
  10393. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10394. bool /*shutdown_gracefully*/) {
  10395. // If there are any requests in flight from threads other than us, then it's
  10396. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10397. assert(socket_requests_in_flight_ == 0 ||
  10398. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10399. }
  10400. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10401. if (socket.sock == INVALID_SOCKET) { return; }
  10402. detail::shutdown_socket(socket.sock);
  10403. }
  10404. inline void ClientImpl::close_socket(Socket &socket) {
  10405. // If there are requests in flight in another thread, usually closing
  10406. // the socket will be fine and they will simply receive an error when
  10407. // using the closed socket, but it is still a bug since rarely the OS
  10408. // may reassign the socket id to be used for a new socket, and then
  10409. // suddenly they will be operating on a live socket that is different
  10410. // than the one they intended!
  10411. assert(socket_requests_in_flight_ == 0 ||
  10412. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10413. // It is also a bug if this happens while SSL is still active
  10414. #ifdef CPPHTTPLIB_SSL_ENABLED
  10415. assert(socket.ssl == nullptr);
  10416. #endif
  10417. if (socket.sock == INVALID_SOCKET) { return; }
  10418. detail::close_socket(socket.sock);
  10419. socket.sock = INVALID_SOCKET;
  10420. }
  10421. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10422. Response &res,
  10423. bool skip_100_continue) const {
  10424. std::array<char, 2048> buf{};
  10425. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10426. if (!line_reader.getline()) { return false; }
  10427. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10428. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10429. #else
  10430. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10431. #endif
  10432. std::cmatch m;
  10433. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10434. return req.method == "CONNECT";
  10435. }
  10436. res.version = std::string(m[1]);
  10437. res.status = std::stoi(std::string(m[2]));
  10438. res.reason = std::string(m[3]);
  10439. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10440. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10441. if (!line_reader.getline()) { return false; } // CRLF
  10442. if (!line_reader.getline()) { return false; } // next response line
  10443. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10444. res.version = std::string(m[1]);
  10445. res.status = std::stoi(std::string(m[2]));
  10446. res.reason = std::string(m[3]);
  10447. }
  10448. return true;
  10449. }
  10450. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10451. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10452. auto ret = send_(req, res, error);
  10453. if (error == Error::SSLPeerCouldBeClosed_) {
  10454. assert(!ret);
  10455. ret = send_(req, res, error);
  10456. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10457. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10458. }
  10459. return ret;
  10460. }
  10461. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10462. {
  10463. std::lock_guard<std::mutex> guard(socket_mutex_);
  10464. // Set this to false immediately - if it ever gets set to true by the end
  10465. // of the request, we know another thread instructed us to close the
  10466. // socket.
  10467. socket_should_be_closed_when_request_is_done_ = false;
  10468. auto is_alive = false;
  10469. if (socket_.is_open()) {
  10470. is_alive = detail::is_socket_alive(socket_.sock);
  10471. #ifdef CPPHTTPLIB_SSL_ENABLED
  10472. if (is_alive && is_ssl()) {
  10473. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10474. is_alive = false;
  10475. }
  10476. }
  10477. #endif
  10478. if (!is_alive) {
  10479. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  10480. // seems like the other side has already closed the connection Also,
  10481. // there cannot be any requests in flight from other threads since we
  10482. // locked request_mutex_, so safe to close everything immediately
  10483. const bool shutdown_gracefully = false;
  10484. shutdown_ssl(socket_, shutdown_gracefully);
  10485. shutdown_socket(socket_);
  10486. close_socket(socket_);
  10487. }
  10488. }
  10489. if (!is_alive) {
  10490. if (!ensure_socket_connection(socket_, error)) {
  10491. output_error_log(error, &req);
  10492. return false;
  10493. }
  10494. {
  10495. auto success = true;
  10496. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10497. error)) {
  10498. if (!success) { output_error_log(error, &req); }
  10499. return success;
  10500. }
  10501. }
  10502. }
  10503. // Mark the current socket as being in use so that it cannot be closed by
  10504. // anyone else while this request is ongoing, even though we will be
  10505. // releasing the mutex.
  10506. if (socket_requests_in_flight_ > 1) {
  10507. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10508. }
  10509. socket_requests_in_flight_ += 1;
  10510. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10511. }
  10512. for (const auto &header : default_headers_) {
  10513. if (req.headers.find(header.first) == req.headers.end()) {
  10514. req.headers.insert(header);
  10515. }
  10516. }
  10517. auto ret = false;
  10518. auto close_connection = !keep_alive_;
  10519. auto se = detail::scope_exit([&]() {
  10520. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10521. std::lock_guard<std::mutex> guard(socket_mutex_);
  10522. socket_requests_in_flight_ -= 1;
  10523. if (socket_requests_in_flight_ <= 0) {
  10524. assert(socket_requests_in_flight_ == 0);
  10525. socket_requests_are_from_thread_ = std::thread::id();
  10526. }
  10527. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10528. !ret) {
  10529. shutdown_ssl(socket_, true);
  10530. shutdown_socket(socket_);
  10531. close_socket(socket_);
  10532. }
  10533. });
  10534. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10535. return handle_request(strm, req, res, close_connection, error);
  10536. });
  10537. if (!ret) {
  10538. if (error == Error::Success) {
  10539. error = Error::Unknown;
  10540. output_error_log(error, &req);
  10541. }
  10542. }
  10543. return ret;
  10544. }
  10545. inline Result ClientImpl::send(const Request &req) {
  10546. auto req2 = req;
  10547. return send_(std::move(req2));
  10548. }
  10549. inline Result ClientImpl::send_(Request &&req) {
  10550. auto res = detail::make_unique<Response>();
  10551. auto error = Error::Success;
  10552. auto ret = send(req, *res, error);
  10553. #ifdef CPPHTTPLIB_SSL_ENABLED
  10554. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10555. last_ssl_error_, last_backend_error_};
  10556. #else
  10557. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10558. #endif
  10559. }
  10560. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10561. const std::string &ct) {
  10562. (void)for_stream;
  10563. for (const auto &header : default_headers_) {
  10564. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10565. }
  10566. if (!r.has_header("Host")) {
  10567. if (address_family_ == AF_UNIX) {
  10568. r.headers.emplace("Host", "localhost");
  10569. } else {
  10570. r.headers.emplace(
  10571. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10572. }
  10573. }
  10574. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10575. if (!r.content_receiver) {
  10576. if (!r.has_header("Accept-Encoding")) {
  10577. std::string accept_encoding;
  10578. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10579. accept_encoding = "br";
  10580. #endif
  10581. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10582. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10583. accept_encoding += "gzip, deflate";
  10584. #endif
  10585. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10586. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10587. accept_encoding += "zstd";
  10588. #endif
  10589. r.set_header("Accept-Encoding", accept_encoding);
  10590. }
  10591. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10592. if (!r.has_header("User-Agent")) {
  10593. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  10594. r.set_header("User-Agent", agent);
  10595. }
  10596. #endif
  10597. }
  10598. if (!r.body.empty()) {
  10599. if (!ct.empty() && !r.has_header("Content-Type")) {
  10600. r.headers.emplace("Content-Type", ct);
  10601. }
  10602. if (!r.has_header("Content-Length")) {
  10603. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  10604. }
  10605. }
  10606. }
  10607. inline ClientImpl::StreamHandle
  10608. ClientImpl::open_stream(const std::string &method, const std::string &path,
  10609. const Params &params, const Headers &headers,
  10610. const std::string &body,
  10611. const std::string &content_type) {
  10612. StreamHandle handle;
  10613. handle.response = detail::make_unique<Response>();
  10614. handle.error = Error::Success;
  10615. auto query_path = params.empty() ? path : append_query_params(path, params);
  10616. handle.connection_ = detail::make_unique<ClientConnection>();
  10617. {
  10618. std::lock_guard<std::mutex> guard(socket_mutex_);
  10619. auto is_alive = false;
  10620. if (socket_.is_open()) {
  10621. is_alive = detail::is_socket_alive(socket_.sock);
  10622. #ifdef CPPHTTPLIB_SSL_ENABLED
  10623. if (is_alive && is_ssl()) {
  10624. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10625. is_alive = false;
  10626. }
  10627. }
  10628. #endif
  10629. if (!is_alive) {
  10630. shutdown_ssl(socket_, false);
  10631. shutdown_socket(socket_);
  10632. close_socket(socket_);
  10633. }
  10634. }
  10635. if (!is_alive) {
  10636. if (!ensure_socket_connection(socket_, handle.error)) {
  10637. handle.response.reset();
  10638. return handle;
  10639. }
  10640. {
  10641. auto success = true;
  10642. auto start_time = std::chrono::steady_clock::now();
  10643. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  10644. success, handle.error)) {
  10645. if (!success) { handle.response.reset(); }
  10646. return handle;
  10647. }
  10648. }
  10649. }
  10650. transfer_socket_ownership_to_handle(handle);
  10651. }
  10652. #ifdef CPPHTTPLIB_SSL_ENABLED
  10653. if (is_ssl() && handle.connection_->session) {
  10654. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  10655. handle.connection_->sock, handle.connection_->session,
  10656. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10657. write_timeout_usec_);
  10658. } else {
  10659. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10660. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10661. write_timeout_sec_, write_timeout_usec_);
  10662. }
  10663. #else
  10664. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10665. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10666. write_timeout_sec_, write_timeout_usec_);
  10667. #endif
  10668. handle.stream_ = handle.socket_stream_.get();
  10669. Request req;
  10670. req.method = method;
  10671. req.path = query_path;
  10672. req.headers = headers;
  10673. req.body = body;
  10674. prepare_default_headers(req, true, content_type);
  10675. auto &strm = *handle.stream_;
  10676. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  10677. handle.error = Error::Write;
  10678. handle.response.reset();
  10679. return handle;
  10680. }
  10681. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  10682. handle.error)) {
  10683. handle.response.reset();
  10684. return handle;
  10685. }
  10686. if (!body.empty()) {
  10687. if (strm.write(body.data(), body.size()) < 0) {
  10688. handle.error = Error::Write;
  10689. handle.response.reset();
  10690. return handle;
  10691. }
  10692. }
  10693. if (!read_response_line(strm, req, *handle.response) ||
  10694. !detail::read_headers(strm, handle.response->headers)) {
  10695. handle.error = Error::Read;
  10696. handle.response.reset();
  10697. return handle;
  10698. }
  10699. handle.body_reader_.stream = handle.stream_;
  10700. handle.body_reader_.payload_max_length = payload_max_length_;
  10701. if (handle.response->has_header("Content-Length")) {
  10702. bool is_invalid = false;
  10703. auto content_length = detail::get_header_value_u64(
  10704. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  10705. if (is_invalid) {
  10706. handle.error = Error::Read;
  10707. handle.response.reset();
  10708. return handle;
  10709. }
  10710. handle.body_reader_.has_content_length = true;
  10711. handle.body_reader_.content_length = content_length;
  10712. }
  10713. auto transfer_encoding =
  10714. handle.response->get_header_value("Transfer-Encoding");
  10715. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  10716. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  10717. if (!content_encoding.empty()) {
  10718. handle.decompressor_ = detail::create_decompressor(content_encoding);
  10719. }
  10720. return handle;
  10721. }
  10722. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  10723. if (!is_valid() || !response) { return -1; }
  10724. if (decompressor_) { return read_with_decompression(buf, len); }
  10725. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  10726. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  10727. trailers_parsed_ = true;
  10728. if (body_reader_.chunked_decoder) {
  10729. if (!body_reader_.chunked_decoder->parse_trailers_into(
  10730. response->trailers, response->headers)) {
  10731. return n;
  10732. }
  10733. } else {
  10734. detail::ChunkedDecoder dec(*stream_);
  10735. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  10736. return n;
  10737. }
  10738. }
  10739. }
  10740. return n;
  10741. }
  10742. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  10743. size_t len) {
  10744. if (decompress_offset_ < decompress_buffer_.size()) {
  10745. auto available = decompress_buffer_.size() - decompress_offset_;
  10746. auto to_copy = (std::min)(len, available);
  10747. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  10748. decompress_offset_ += to_copy;
  10749. decompressed_bytes_read_ += to_copy;
  10750. return static_cast<ssize_t>(to_copy);
  10751. }
  10752. decompress_buffer_.clear();
  10753. decompress_offset_ = 0;
  10754. constexpr size_t kDecompressionBufferSize = 8192;
  10755. char compressed_buf[kDecompressionBufferSize];
  10756. while (true) {
  10757. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  10758. sizeof(compressed_buf));
  10759. if (n <= 0) { return n; }
  10760. bool decompress_ok = decompressor_->decompress(
  10761. compressed_buf, static_cast<size_t>(n),
  10762. [this](const char *data, size_t data_len) {
  10763. decompress_buffer_.append(data, data_len);
  10764. auto limit = body_reader_.payload_max_length;
  10765. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  10766. return false;
  10767. }
  10768. return true;
  10769. });
  10770. if (!decompress_ok) {
  10771. body_reader_.last_error = Error::Read;
  10772. return -1;
  10773. }
  10774. if (!decompress_buffer_.empty()) { break; }
  10775. }
  10776. auto to_copy = (std::min)(len, decompress_buffer_.size());
  10777. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  10778. decompress_offset_ = to_copy;
  10779. decompressed_bytes_read_ += to_copy;
  10780. return static_cast<ssize_t>(to_copy);
  10781. }
  10782. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  10783. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  10784. return;
  10785. }
  10786. trailers_parsed_ = true;
  10787. const auto bufsiz = 128;
  10788. char line_buf[bufsiz];
  10789. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  10790. if (!line_reader.getline()) { return; }
  10791. if (!detail::parse_trailers(line_reader, response->trailers,
  10792. response->headers)) {
  10793. return;
  10794. }
  10795. }
  10796. namespace detail {
  10797. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  10798. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  10799. size_t &out_chunk_offset,
  10800. size_t &out_chunk_total) {
  10801. if (finished) { return 0; }
  10802. if (chunk_remaining == 0) {
  10803. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10804. if (!lr.getline()) { return -1; }
  10805. char *endptr = nullptr;
  10806. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  10807. if (endptr == lr.ptr()) { return -1; }
  10808. if (chunk_len == ULONG_MAX) { return -1; }
  10809. if (chunk_len == 0) {
  10810. chunk_remaining = 0;
  10811. finished = true;
  10812. out_chunk_offset = 0;
  10813. out_chunk_total = 0;
  10814. return 0;
  10815. }
  10816. chunk_remaining = static_cast<size_t>(chunk_len);
  10817. last_chunk_total = chunk_remaining;
  10818. last_chunk_offset = 0;
  10819. }
  10820. auto to_read = (std::min)(chunk_remaining, len);
  10821. auto n = strm.read(buf, to_read);
  10822. if (n <= 0) { return -1; }
  10823. auto offset_before = last_chunk_offset;
  10824. last_chunk_offset += static_cast<size_t>(n);
  10825. chunk_remaining -= static_cast<size_t>(n);
  10826. out_chunk_offset = offset_before;
  10827. out_chunk_total = last_chunk_total;
  10828. if (chunk_remaining == 0) {
  10829. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10830. if (!lr.getline()) { return -1; }
  10831. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  10832. }
  10833. return n;
  10834. }
  10835. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  10836. const Headers &src_headers) {
  10837. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10838. if (!lr.getline()) { return false; }
  10839. return parse_trailers(lr, dest, src_headers);
  10840. }
  10841. } // namespace detail
  10842. inline void
  10843. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  10844. handle.connection_->sock = socket_.sock;
  10845. #ifdef CPPHTTPLIB_SSL_ENABLED
  10846. handle.connection_->session = socket_.ssl;
  10847. socket_.ssl = nullptr;
  10848. #endif
  10849. socket_.sock = INVALID_SOCKET;
  10850. }
  10851. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  10852. Response &res, bool close_connection,
  10853. Error &error) {
  10854. if (req.path.empty()) {
  10855. error = Error::Connection;
  10856. output_error_log(error, &req);
  10857. return false;
  10858. }
  10859. auto req_save = req;
  10860. bool ret;
  10861. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  10862. auto req2 = req;
  10863. req2.path = "http://" +
  10864. detail::make_host_and_port_string(host_, port_, false) +
  10865. req.path;
  10866. ret = process_request(strm, req2, res, close_connection, error);
  10867. req = std::move(req2);
  10868. req.path = req_save.path;
  10869. } else {
  10870. ret = process_request(strm, req, res, close_connection, error);
  10871. }
  10872. if (!ret) { return false; }
  10873. if (res.get_header_value("Connection") == "close" ||
  10874. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  10875. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  10876. // for this to be safe.
  10877. // This is safe to call because handle_request is only called by send_
  10878. // which locks the request mutex during the process. It would be a bug
  10879. // to call it from a different thread since it's a thread-safety issue
  10880. // to do these things to the socket if another thread is using the socket.
  10881. std::lock_guard<std::mutex> guard(socket_mutex_);
  10882. shutdown_ssl(socket_, true);
  10883. shutdown_socket(socket_);
  10884. close_socket(socket_);
  10885. }
  10886. if (300 < res.status && res.status < 400 && follow_location_) {
  10887. req = std::move(req_save);
  10888. ret = redirect(req, res, error);
  10889. }
  10890. #ifdef CPPHTTPLIB_SSL_ENABLED
  10891. if ((res.status == StatusCode::Unauthorized_401 ||
  10892. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  10893. req.authorization_count_ < 5) {
  10894. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  10895. const auto &username =
  10896. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  10897. const auto &password =
  10898. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  10899. if (!username.empty() && !password.empty()) {
  10900. std::map<std::string, std::string> auth;
  10901. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  10902. Request new_req = req;
  10903. new_req.authorization_count_ += 1;
  10904. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  10905. : "Authorization");
  10906. new_req.headers.insert(detail::make_digest_authentication_header(
  10907. req, auth, new_req.authorization_count_, detail::random_string(10),
  10908. username, password, is_proxy));
  10909. Response new_res;
  10910. ret = send(new_req, new_res, error);
  10911. if (ret) { res = std::move(new_res); }
  10912. }
  10913. }
  10914. }
  10915. #endif
  10916. return ret;
  10917. }
  10918. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  10919. if (req.redirect_count_ == 0) {
  10920. error = Error::ExceedRedirectCount;
  10921. output_error_log(error, &req);
  10922. return false;
  10923. }
  10924. auto location = res.get_header_value("location");
  10925. if (location.empty()) { return false; }
  10926. thread_local const std::regex re(
  10927. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  10928. std::smatch m;
  10929. if (!std::regex_match(location, m, re)) { return false; }
  10930. auto scheme = is_ssl() ? "https" : "http";
  10931. auto next_scheme = m[1].str();
  10932. auto next_host = m[2].str();
  10933. if (next_host.empty()) { next_host = m[3].str(); }
  10934. auto port_str = m[4].str();
  10935. auto next_path = m[5].str();
  10936. auto next_query = m[6].str();
  10937. auto next_port = port_;
  10938. if (!port_str.empty()) {
  10939. if (!detail::parse_port(port_str, next_port)) { return false; }
  10940. } else if (!next_scheme.empty()) {
  10941. next_port = next_scheme == "https" ? 443 : 80;
  10942. }
  10943. if (next_scheme.empty()) { next_scheme = scheme; }
  10944. if (next_host.empty()) { next_host = host_; }
  10945. if (next_path.empty()) { next_path = "/"; }
  10946. auto path = decode_query_component(next_path, true) + next_query;
  10947. // Same host redirect - use current client
  10948. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  10949. return detail::redirect(*this, req, res, path, location, error);
  10950. }
  10951. // Cross-host/scheme redirect - create new client with robust setup
  10952. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  10953. path, location, error);
  10954. }
  10955. // New method for robust redirect client creation
  10956. inline bool ClientImpl::create_redirect_client(
  10957. const std::string &scheme, const std::string &host, int port, Request &req,
  10958. Response &res, const std::string &path, const std::string &location,
  10959. Error &error) {
  10960. // Determine if we need SSL
  10961. auto need_ssl = (scheme == "https");
  10962. // Clean up request headers that are host/client specific
  10963. // Remove headers that should not be carried over to new host
  10964. auto headers_to_remove =
  10965. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  10966. for (const auto &header_name : headers_to_remove) {
  10967. auto it = req.headers.find(header_name);
  10968. while (it != req.headers.end()) {
  10969. it = req.headers.erase(it);
  10970. it = req.headers.find(header_name);
  10971. }
  10972. }
  10973. // Create appropriate client type and handle redirect
  10974. if (need_ssl) {
  10975. #ifdef CPPHTTPLIB_SSL_ENABLED
  10976. // Create SSL client for HTTPS redirect
  10977. SSLClient redirect_client(host, port);
  10978. // Setup basic client configuration first
  10979. setup_redirect_client(redirect_client);
  10980. redirect_client.enable_server_certificate_verification(
  10981. server_certificate_verification_);
  10982. redirect_client.enable_server_hostname_verification(
  10983. server_hostname_verification_);
  10984. // Transfer CA certificate to redirect client
  10985. if (!ca_cert_pem_.empty()) {
  10986. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  10987. ca_cert_pem_.size());
  10988. }
  10989. if (!ca_cert_file_path_.empty()) {
  10990. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  10991. }
  10992. // Client certificates are set through constructor for SSLClient
  10993. // NOTE: SSLClient constructor already takes client_cert_path and
  10994. // client_key_path so we need to create it properly if client certs are
  10995. // needed
  10996. // Execute the redirect
  10997. return detail::redirect(redirect_client, req, res, path, location, error);
  10998. #else
  10999. // SSL not supported - set appropriate error
  11000. error = Error::SSLConnection;
  11001. output_error_log(error, &req);
  11002. return false;
  11003. #endif
  11004. } else {
  11005. // HTTP redirect
  11006. ClientImpl redirect_client(host, port);
  11007. // Setup client with robust configuration
  11008. setup_redirect_client(redirect_client);
  11009. // Execute the redirect
  11010. return detail::redirect(redirect_client, req, res, path, location, error);
  11011. }
  11012. }
  11013. // New method for robust client setup (based on basic_manual_redirect.cpp
  11014. // logic)
  11015. template <typename ClientType>
  11016. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11017. // Copy basic settings first
  11018. client.set_connection_timeout(connection_timeout_sec_);
  11019. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11020. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11021. client.set_keep_alive(keep_alive_);
  11022. client.set_follow_location(
  11023. true); // Enable redirects to handle multi-step redirects
  11024. client.set_path_encode(path_encode_);
  11025. client.set_compress(compress_);
  11026. client.set_decompress(decompress_);
  11027. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11028. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11029. // 15.4, credentials must not be forwarded when redirecting to a different
  11030. // host. This function is only called for cross-host redirects; same-host
  11031. // redirects are handled directly in ClientImpl::redirect().
  11032. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  11033. // before proxy auth)
  11034. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11035. // First set proxy host and port
  11036. client.set_proxy(proxy_host_, proxy_port_);
  11037. // Then set proxy authentication (order matters!)
  11038. if (!proxy_basic_auth_username_.empty()) {
  11039. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11040. proxy_basic_auth_password_);
  11041. }
  11042. if (!proxy_bearer_token_auth_token_.empty()) {
  11043. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11044. }
  11045. #ifdef CPPHTTPLIB_SSL_ENABLED
  11046. if (!proxy_digest_auth_username_.empty()) {
  11047. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11048. proxy_digest_auth_password_);
  11049. }
  11050. #endif
  11051. }
  11052. // Copy network and socket settings
  11053. client.set_address_family(address_family_);
  11054. client.set_tcp_nodelay(tcp_nodelay_);
  11055. client.set_ipv6_v6only(ipv6_v6only_);
  11056. if (socket_options_) { client.set_socket_options(socket_options_); }
  11057. if (!interface_.empty()) { client.set_interface(interface_); }
  11058. // Copy logging and headers
  11059. if (logger_) { client.set_logger(logger_); }
  11060. if (error_logger_) { client.set_error_logger(error_logger_); }
  11061. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11062. // Each new client should generate its own headers based on its target host
  11063. }
  11064. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11065. const Request &req,
  11066. Error &error) const {
  11067. auto is_shutting_down = []() { return false; };
  11068. if (req.is_chunked_content_provider_) {
  11069. auto compressor = compress_ ? detail::create_compressor().first
  11070. : std::unique_ptr<detail::compressor>();
  11071. if (!compressor) {
  11072. compressor = detail::make_unique<detail::nocompressor>();
  11073. }
  11074. return detail::write_content_chunked(strm, req.content_provider_,
  11075. is_shutting_down, *compressor, error);
  11076. } else {
  11077. return detail::write_content_with_progress(
  11078. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11079. req.upload_progress, error);
  11080. }
  11081. }
  11082. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11083. bool close_connection, Error &error,
  11084. bool skip_body) {
  11085. // Prepare additional headers
  11086. if (close_connection) {
  11087. if (!req.has_header("Connection")) {
  11088. req.set_header("Connection", "close");
  11089. }
  11090. }
  11091. std::string ct_for_defaults;
  11092. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11093. ct_for_defaults = "text/plain";
  11094. }
  11095. prepare_default_headers(req, false, ct_for_defaults);
  11096. if (req.body.empty()) {
  11097. if (req.content_provider_) {
  11098. if (!req.is_chunked_content_provider_) {
  11099. if (!req.has_header("Content-Length")) {
  11100. auto length = std::to_string(req.content_length_);
  11101. req.set_header("Content-Length", length);
  11102. }
  11103. }
  11104. } else {
  11105. if (req.method == "POST" || req.method == "PUT" ||
  11106. req.method == "PATCH") {
  11107. req.set_header("Content-Length", "0");
  11108. }
  11109. }
  11110. }
  11111. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11112. if (!req.has_header("Authorization")) {
  11113. req.headers.insert(make_basic_authentication_header(
  11114. basic_auth_username_, basic_auth_password_, false));
  11115. }
  11116. }
  11117. if (!proxy_basic_auth_username_.empty() &&
  11118. !proxy_basic_auth_password_.empty()) {
  11119. if (!req.has_header("Proxy-Authorization")) {
  11120. req.headers.insert(make_basic_authentication_header(
  11121. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11122. }
  11123. }
  11124. if (!bearer_token_auth_token_.empty()) {
  11125. if (!req.has_header("Authorization")) {
  11126. req.headers.insert(make_bearer_token_authentication_header(
  11127. bearer_token_auth_token_, false));
  11128. }
  11129. }
  11130. if (!proxy_bearer_token_auth_token_.empty()) {
  11131. if (!req.has_header("Proxy-Authorization")) {
  11132. req.headers.insert(make_bearer_token_authentication_header(
  11133. proxy_bearer_token_auth_token_, true));
  11134. }
  11135. }
  11136. // Request line and headers
  11137. {
  11138. detail::BufferStream bstrm;
  11139. // Extract path and query from req.path
  11140. std::string path_part, query_part;
  11141. auto query_pos = req.path.find('?');
  11142. if (query_pos != std::string::npos) {
  11143. path_part = req.path.substr(0, query_pos);
  11144. query_part = req.path.substr(query_pos + 1);
  11145. } else {
  11146. path_part = req.path;
  11147. query_part = "";
  11148. }
  11149. // Encode path part. If the original `req.path` already contained a
  11150. // query component, preserve its raw query string (including parameter
  11151. // order) instead of reparsing and reassembling it which may reorder
  11152. // parameters due to container ordering (e.g. `Params` uses
  11153. // `std::multimap`). When there is no query in `req.path`, fall back to
  11154. // building a query from `req.params` so existing callers that pass
  11155. // `Params` continue to work.
  11156. auto path_with_query =
  11157. path_encode_ ? detail::encode_path(path_part) : path_part;
  11158. if (!query_part.empty()) {
  11159. // Normalize the query string (decode then re-encode) while preserving
  11160. // the original parameter order.
  11161. auto normalized = detail::normalize_query_string(query_part);
  11162. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11163. // Still populate req.params for handlers/users who read them.
  11164. detail::parse_query_text(query_part, req.params);
  11165. } else {
  11166. // No query in path; parse any query_part (empty) and append params
  11167. // from `req.params` when present (preserves prior behavior for
  11168. // callers who provide Params separately).
  11169. detail::parse_query_text(query_part, req.params);
  11170. if (!req.params.empty()) {
  11171. path_with_query = append_query_params(path_with_query, req.params);
  11172. }
  11173. }
  11174. // Write request line and headers
  11175. detail::write_request_line(bstrm, req.method, path_with_query);
  11176. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11177. error)) {
  11178. output_error_log(error, &req);
  11179. return false;
  11180. }
  11181. // Flush buffer
  11182. auto &data = bstrm.get_buffer();
  11183. if (!detail::write_data(strm, data.data(), data.size())) {
  11184. error = Error::Write;
  11185. output_error_log(error, &req);
  11186. return false;
  11187. }
  11188. }
  11189. // After sending request line and headers, wait briefly for an early server
  11190. // response (e.g. 4xx) and avoid sending a potentially large request body
  11191. // unnecessarily. This workaround is only enabled on Windows because Unix
  11192. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11193. // buffering can accept large writes even when the peer already responded.
  11194. // Check the stream first (which covers SSL via `is_readable()`), then
  11195. // fall back to select on the socket. Only perform the wait for very large
  11196. // request bodies to avoid interfering with normal small requests and
  11197. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11198. // response. Skip this check when using Expect: 100-continue, as the protocol
  11199. // handles early responses properly.
  11200. #if defined(_WIN32)
  11201. if (!skip_body &&
  11202. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11203. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11204. auto start = std::chrono::high_resolution_clock::now();
  11205. for (;;) {
  11206. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11207. // from SSL internals. If the underlying socket is readable, assume an
  11208. // early response may be present.
  11209. auto sock = strm.socket();
  11210. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11211. return false;
  11212. }
  11213. // Fallback to stream-level check for non-socket streams or when the
  11214. // socket isn't reporting readable. Avoid using `is_readable()` for
  11215. // SSL, since `SSL_pending()` may report buffered records that do not
  11216. // indicate a complete application-level response yet.
  11217. if (!is_ssl() && strm.is_readable()) { return false; }
  11218. auto now = std::chrono::high_resolution_clock::now();
  11219. auto elapsed =
  11220. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11221. .count();
  11222. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11223. break;
  11224. }
  11225. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11226. }
  11227. }
  11228. #endif
  11229. // Body
  11230. if (skip_body) { return true; }
  11231. return write_request_body(strm, req, error);
  11232. }
  11233. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11234. Error &error) {
  11235. if (req.body.empty()) {
  11236. return write_content_with_provider(strm, req, error);
  11237. }
  11238. if (req.upload_progress) {
  11239. auto body_size = req.body.size();
  11240. size_t written = 0;
  11241. auto data = req.body.data();
  11242. while (written < body_size) {
  11243. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11244. if (!detail::write_data(strm, data + written, to_write)) {
  11245. error = Error::Write;
  11246. output_error_log(error, &req);
  11247. return false;
  11248. }
  11249. written += to_write;
  11250. if (!req.upload_progress(written, body_size)) {
  11251. error = Error::Canceled;
  11252. output_error_log(error, &req);
  11253. return false;
  11254. }
  11255. }
  11256. } else {
  11257. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11258. error = Error::Write;
  11259. output_error_log(error, &req);
  11260. return false;
  11261. }
  11262. }
  11263. return true;
  11264. }
  11265. inline std::unique_ptr<Response>
  11266. ClientImpl::send_with_content_provider_and_receiver(
  11267. Request &req, const char *body, size_t content_length,
  11268. ContentProvider content_provider,
  11269. ContentProviderWithoutLength content_provider_without_length,
  11270. const std::string &content_type, ContentReceiver content_receiver,
  11271. Error &error) {
  11272. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11273. auto enc = compress_
  11274. ? detail::create_compressor()
  11275. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11276. nullptr, nullptr);
  11277. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11278. if (enc.first && !content_provider_without_length) {
  11279. auto &compressor = enc.first;
  11280. if (content_provider) {
  11281. auto ok = true;
  11282. size_t offset = 0;
  11283. DataSink data_sink;
  11284. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11285. if (ok) {
  11286. auto last = offset + data_len == content_length;
  11287. auto ret = compressor->compress(
  11288. data, data_len, last,
  11289. [&](const char *compressed_data, size_t compressed_data_len) {
  11290. req.body.append(compressed_data, compressed_data_len);
  11291. return true;
  11292. });
  11293. if (ret) {
  11294. offset += data_len;
  11295. } else {
  11296. ok = false;
  11297. }
  11298. }
  11299. return ok;
  11300. };
  11301. while (ok && offset < content_length) {
  11302. if (!content_provider(offset, content_length - offset, data_sink)) {
  11303. error = Error::Canceled;
  11304. output_error_log(error, &req);
  11305. return nullptr;
  11306. }
  11307. }
  11308. } else {
  11309. if (!compressor->compress(body, content_length, true,
  11310. [&](const char *data, size_t data_len) {
  11311. req.body.append(data, data_len);
  11312. return true;
  11313. })) {
  11314. error = Error::Compression;
  11315. output_error_log(error, &req);
  11316. return nullptr;
  11317. }
  11318. }
  11319. } else {
  11320. if (content_provider) {
  11321. req.content_length_ = content_length;
  11322. req.content_provider_ = std::move(content_provider);
  11323. req.is_chunked_content_provider_ = false;
  11324. } else if (content_provider_without_length) {
  11325. req.content_length_ = 0;
  11326. req.content_provider_ = detail::ContentProviderAdapter(
  11327. std::move(content_provider_without_length));
  11328. req.is_chunked_content_provider_ = true;
  11329. req.set_header("Transfer-Encoding", "chunked");
  11330. } else {
  11331. req.body.assign(body, content_length);
  11332. }
  11333. }
  11334. if (content_receiver) {
  11335. req.content_receiver =
  11336. [content_receiver](const char *data, size_t data_length,
  11337. size_t /*offset*/, size_t /*total_length*/) {
  11338. return content_receiver(data, data_length);
  11339. };
  11340. }
  11341. auto res = detail::make_unique<Response>();
  11342. return send(req, *res, error) ? std::move(res) : nullptr;
  11343. }
  11344. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11345. const std::string &method, const std::string &path, const Headers &headers,
  11346. const char *body, size_t content_length, ContentProvider content_provider,
  11347. ContentProviderWithoutLength content_provider_without_length,
  11348. const std::string &content_type, ContentReceiver content_receiver,
  11349. UploadProgress progress) {
  11350. Request req;
  11351. req.method = method;
  11352. req.headers = headers;
  11353. req.path = path;
  11354. req.upload_progress = std::move(progress);
  11355. if (max_timeout_msec_ > 0) {
  11356. req.start_time_ = std::chrono::steady_clock::now();
  11357. }
  11358. auto error = Error::Success;
  11359. auto res = send_with_content_provider_and_receiver(
  11360. req, body, content_length, std::move(content_provider),
  11361. std::move(content_provider_without_length), content_type,
  11362. std::move(content_receiver), error);
  11363. #ifdef CPPHTTPLIB_SSL_ENABLED
  11364. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11365. last_backend_error_};
  11366. #else
  11367. return Result{std::move(res), error, std::move(req.headers)};
  11368. #endif
  11369. }
  11370. inline void ClientImpl::output_log(const Request &req,
  11371. const Response &res) const {
  11372. if (logger_) {
  11373. std::lock_guard<std::mutex> guard(logger_mutex_);
  11374. logger_(req, res);
  11375. }
  11376. }
  11377. inline void ClientImpl::output_error_log(const Error &err,
  11378. const Request *req) const {
  11379. if (error_logger_) {
  11380. std::lock_guard<std::mutex> guard(logger_mutex_);
  11381. error_logger_(err, req);
  11382. }
  11383. }
  11384. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11385. Response &res, bool close_connection,
  11386. Error &error) {
  11387. // Auto-add Expect: 100-continue for large bodies
  11388. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11389. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11390. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11391. req.set_header("Expect", "100-continue");
  11392. }
  11393. }
  11394. // Check for Expect: 100-continue
  11395. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11396. // Send request (skip body if using Expect: 100-continue)
  11397. auto write_request_success =
  11398. write_request(strm, req, close_connection, error, expect_100_continue);
  11399. #ifdef CPPHTTPLIB_SSL_ENABLED
  11400. if (is_ssl() && !expect_100_continue) {
  11401. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  11402. if (!is_proxy_enabled) {
  11403. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11404. error = Error::SSLPeerCouldBeClosed_;
  11405. output_error_log(error, &req);
  11406. return false;
  11407. }
  11408. }
  11409. }
  11410. #endif
  11411. // Handle Expect: 100-continue with timeout
  11412. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11413. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11414. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11415. auto ret = detail::select_read(strm.socket(), sec, usec);
  11416. if (ret <= 0) {
  11417. // Timeout or error: send body anyway (server didn't respond in time)
  11418. if (!write_request_body(strm, req, error)) { return false; }
  11419. expect_100_continue = false; // Switch to normal response handling
  11420. }
  11421. }
  11422. // Receive response and headers
  11423. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11424. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  11425. !detail::read_headers(strm, res.headers)) {
  11426. if (write_request_success) { error = Error::Read; }
  11427. output_error_log(error, &req);
  11428. return false;
  11429. }
  11430. if (!write_request_success) { return false; }
  11431. // Handle Expect: 100-continue response
  11432. if (expect_100_continue) {
  11433. if (res.status == StatusCode::Continue_100) {
  11434. // Server accepted, send the body
  11435. if (!write_request_body(strm, req, error)) { return false; }
  11436. // Read the actual response
  11437. res.headers.clear();
  11438. res.body.clear();
  11439. if (!read_response_line(strm, req, res) ||
  11440. !detail::read_headers(strm, res.headers)) {
  11441. error = Error::Read;
  11442. output_error_log(error, &req);
  11443. return false;
  11444. }
  11445. }
  11446. // If not 100 Continue, server returned an error; proceed with that response
  11447. }
  11448. // Body
  11449. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11450. req.method != "CONNECT") {
  11451. auto redirect = 300 < res.status && res.status < 400 &&
  11452. res.status != StatusCode::NotModified_304 &&
  11453. follow_location_;
  11454. if (req.response_handler && !redirect) {
  11455. if (!req.response_handler(res)) {
  11456. error = Error::Canceled;
  11457. output_error_log(error, &req);
  11458. return false;
  11459. }
  11460. }
  11461. auto out =
  11462. req.content_receiver
  11463. ? static_cast<ContentReceiverWithProgress>(
  11464. [&](const char *buf, size_t n, size_t off, size_t len) {
  11465. if (redirect) { return true; }
  11466. auto ret = req.content_receiver(buf, n, off, len);
  11467. if (!ret) {
  11468. error = Error::Canceled;
  11469. output_error_log(error, &req);
  11470. }
  11471. return ret;
  11472. })
  11473. : static_cast<ContentReceiverWithProgress>(
  11474. [&](const char *buf, size_t n, size_t /*off*/,
  11475. size_t /*len*/) {
  11476. assert(res.body.size() + n <= res.body.max_size());
  11477. if (payload_max_length_ > 0 &&
  11478. (res.body.size() >= payload_max_length_ ||
  11479. n > payload_max_length_ - res.body.size())) {
  11480. return false;
  11481. }
  11482. res.body.append(buf, n);
  11483. return true;
  11484. });
  11485. auto progress = [&](size_t current, size_t total) {
  11486. if (!req.download_progress || redirect) { return true; }
  11487. auto ret = req.download_progress(current, total);
  11488. if (!ret) {
  11489. error = Error::Canceled;
  11490. output_error_log(error, &req);
  11491. }
  11492. return ret;
  11493. };
  11494. if (res.has_header("Content-Length")) {
  11495. if (!req.content_receiver) {
  11496. auto len = res.get_header_value_u64("Content-Length");
  11497. if (len > res.body.max_size()) {
  11498. error = Error::Read;
  11499. output_error_log(error, &req);
  11500. return false;
  11501. }
  11502. res.body.reserve(static_cast<size_t>(len));
  11503. }
  11504. }
  11505. if (res.status != StatusCode::NotModified_304) {
  11506. int dummy_status;
  11507. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11508. ? (std::numeric_limits<size_t>::max)()
  11509. : payload_max_length_;
  11510. if (!detail::read_content(strm, res, max_length, dummy_status,
  11511. std::move(progress), std::move(out),
  11512. decompress_)) {
  11513. if (error != Error::Canceled) { error = Error::Read; }
  11514. output_error_log(error, &req);
  11515. return false;
  11516. }
  11517. }
  11518. }
  11519. // Log
  11520. output_log(req, res);
  11521. return true;
  11522. }
  11523. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11524. const std::string &boundary, const UploadFormDataItems &items,
  11525. const FormDataProviderItems &provider_items) const {
  11526. size_t cur_item = 0;
  11527. size_t cur_start = 0;
  11528. // cur_item and cur_start are copied to within the std::function and
  11529. // maintain state between successive calls
  11530. return [&, cur_item, cur_start](size_t offset,
  11531. DataSink &sink) mutable -> bool {
  11532. if (!offset && !items.empty()) {
  11533. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  11534. return true;
  11535. } else if (cur_item < provider_items.size()) {
  11536. if (!cur_start) {
  11537. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  11538. provider_items[cur_item], boundary);
  11539. offset += begin.size();
  11540. cur_start = offset;
  11541. sink.os << begin;
  11542. }
  11543. DataSink cur_sink;
  11544. auto has_data = true;
  11545. cur_sink.write = sink.write;
  11546. cur_sink.done = [&]() { has_data = false; };
  11547. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  11548. return false;
  11549. }
  11550. if (!has_data) {
  11551. sink.os << detail::serialize_multipart_formdata_item_end();
  11552. cur_item++;
  11553. cur_start = 0;
  11554. }
  11555. return true;
  11556. } else {
  11557. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  11558. sink.done();
  11559. return true;
  11560. }
  11561. };
  11562. }
  11563. inline bool ClientImpl::process_socket(
  11564. const Socket &socket,
  11565. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11566. std::function<bool(Stream &strm)> callback) {
  11567. return detail::process_client_socket(
  11568. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11569. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  11570. }
  11571. inline bool ClientImpl::is_ssl() const { return false; }
  11572. inline Result ClientImpl::Get(const std::string &path,
  11573. DownloadProgress progress) {
  11574. return Get(path, Headers(), std::move(progress));
  11575. }
  11576. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11577. const Headers &headers,
  11578. DownloadProgress progress) {
  11579. if (params.empty()) { return Get(path, headers); }
  11580. std::string path_with_query = append_query_params(path, params);
  11581. return Get(path_with_query, headers, std::move(progress));
  11582. }
  11583. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11584. DownloadProgress progress) {
  11585. Request req;
  11586. req.method = "GET";
  11587. req.path = path;
  11588. req.headers = headers;
  11589. req.download_progress = std::move(progress);
  11590. if (max_timeout_msec_ > 0) {
  11591. req.start_time_ = std::chrono::steady_clock::now();
  11592. }
  11593. return send_(std::move(req));
  11594. }
  11595. inline Result ClientImpl::Get(const std::string &path,
  11596. ContentReceiver content_receiver,
  11597. DownloadProgress progress) {
  11598. return Get(path, Headers(), nullptr, std::move(content_receiver),
  11599. std::move(progress));
  11600. }
  11601. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11602. ContentReceiver content_receiver,
  11603. DownloadProgress progress) {
  11604. return Get(path, headers, nullptr, std::move(content_receiver),
  11605. std::move(progress));
  11606. }
  11607. inline Result ClientImpl::Get(const std::string &path,
  11608. ResponseHandler response_handler,
  11609. ContentReceiver content_receiver,
  11610. DownloadProgress progress) {
  11611. return Get(path, Headers(), std::move(response_handler),
  11612. std::move(content_receiver), std::move(progress));
  11613. }
  11614. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11615. ResponseHandler response_handler,
  11616. ContentReceiver content_receiver,
  11617. DownloadProgress progress) {
  11618. Request req;
  11619. req.method = "GET";
  11620. req.path = path;
  11621. req.headers = headers;
  11622. req.response_handler = std::move(response_handler);
  11623. req.content_receiver =
  11624. [content_receiver](const char *data, size_t data_length,
  11625. size_t /*offset*/, size_t /*total_length*/) {
  11626. return content_receiver(data, data_length);
  11627. };
  11628. req.download_progress = std::move(progress);
  11629. if (max_timeout_msec_ > 0) {
  11630. req.start_time_ = std::chrono::steady_clock::now();
  11631. }
  11632. return send_(std::move(req));
  11633. }
  11634. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11635. const Headers &headers,
  11636. ContentReceiver content_receiver,
  11637. DownloadProgress progress) {
  11638. return Get(path, params, headers, nullptr, std::move(content_receiver),
  11639. std::move(progress));
  11640. }
  11641. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11642. const Headers &headers,
  11643. ResponseHandler response_handler,
  11644. ContentReceiver content_receiver,
  11645. DownloadProgress progress) {
  11646. if (params.empty()) {
  11647. return Get(path, headers, std::move(response_handler),
  11648. std::move(content_receiver), std::move(progress));
  11649. }
  11650. std::string path_with_query = append_query_params(path, params);
  11651. return Get(path_with_query, headers, std::move(response_handler),
  11652. std::move(content_receiver), std::move(progress));
  11653. }
  11654. inline Result ClientImpl::Head(const std::string &path) {
  11655. return Head(path, Headers());
  11656. }
  11657. inline Result ClientImpl::Head(const std::string &path,
  11658. const Headers &headers) {
  11659. Request req;
  11660. req.method = "HEAD";
  11661. req.headers = headers;
  11662. req.path = path;
  11663. if (max_timeout_msec_ > 0) {
  11664. req.start_time_ = std::chrono::steady_clock::now();
  11665. }
  11666. return send_(std::move(req));
  11667. }
  11668. inline Result ClientImpl::Post(const std::string &path) {
  11669. return Post(path, std::string(), std::string());
  11670. }
  11671. inline Result ClientImpl::Post(const std::string &path,
  11672. const Headers &headers) {
  11673. return Post(path, headers, nullptr, 0, std::string());
  11674. }
  11675. inline Result ClientImpl::Post(const std::string &path, const char *body,
  11676. size_t content_length,
  11677. const std::string &content_type,
  11678. UploadProgress progress) {
  11679. return Post(path, Headers(), body, content_length, content_type, progress);
  11680. }
  11681. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  11682. const std::string &content_type,
  11683. UploadProgress progress) {
  11684. return Post(path, Headers(), body, content_type, progress);
  11685. }
  11686. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  11687. return Post(path, Headers(), params);
  11688. }
  11689. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11690. ContentProvider content_provider,
  11691. const std::string &content_type,
  11692. UploadProgress progress) {
  11693. return Post(path, Headers(), content_length, std::move(content_provider),
  11694. content_type, progress);
  11695. }
  11696. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11697. ContentProvider content_provider,
  11698. const std::string &content_type,
  11699. ContentReceiver content_receiver,
  11700. UploadProgress progress) {
  11701. return Post(path, Headers(), content_length, std::move(content_provider),
  11702. content_type, std::move(content_receiver), progress);
  11703. }
  11704. inline Result ClientImpl::Post(const std::string &path,
  11705. ContentProviderWithoutLength content_provider,
  11706. const std::string &content_type,
  11707. UploadProgress progress) {
  11708. return Post(path, Headers(), std::move(content_provider), content_type,
  11709. progress);
  11710. }
  11711. inline Result ClientImpl::Post(const std::string &path,
  11712. ContentProviderWithoutLength content_provider,
  11713. const std::string &content_type,
  11714. ContentReceiver content_receiver,
  11715. UploadProgress progress) {
  11716. return Post(path, Headers(), std::move(content_provider), content_type,
  11717. std::move(content_receiver), progress);
  11718. }
  11719. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11720. const Params &params) {
  11721. auto query = detail::params_to_query_str(params);
  11722. return Post(path, headers, query, "application/x-www-form-urlencoded");
  11723. }
  11724. inline Result ClientImpl::Post(const std::string &path,
  11725. const UploadFormDataItems &items,
  11726. UploadProgress progress) {
  11727. return Post(path, Headers(), items, progress);
  11728. }
  11729. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11730. const UploadFormDataItems &items,
  11731. UploadProgress progress) {
  11732. const auto &boundary = detail::make_multipart_data_boundary();
  11733. const auto &content_type =
  11734. detail::serialize_multipart_formdata_get_content_type(boundary);
  11735. auto content_length = detail::get_multipart_content_length(items, boundary);
  11736. return Post(path, headers, content_length,
  11737. detail::make_multipart_content_provider(items, boundary),
  11738. content_type, progress);
  11739. }
  11740. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11741. const UploadFormDataItems &items,
  11742. const std::string &boundary,
  11743. UploadProgress progress) {
  11744. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11745. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11746. }
  11747. const auto &content_type =
  11748. detail::serialize_multipart_formdata_get_content_type(boundary);
  11749. auto content_length = detail::get_multipart_content_length(items, boundary);
  11750. return Post(path, headers, content_length,
  11751. detail::make_multipart_content_provider(items, boundary),
  11752. content_type, progress);
  11753. }
  11754. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11755. const char *body, size_t content_length,
  11756. const std::string &content_type,
  11757. UploadProgress progress) {
  11758. return send_with_content_provider_and_receiver(
  11759. "POST", path, headers, body, content_length, nullptr, nullptr,
  11760. content_type, nullptr, progress);
  11761. }
  11762. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11763. const std::string &body,
  11764. const std::string &content_type,
  11765. UploadProgress progress) {
  11766. return send_with_content_provider_and_receiver(
  11767. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  11768. content_type, nullptr, progress);
  11769. }
  11770. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11771. size_t content_length,
  11772. ContentProvider content_provider,
  11773. const std::string &content_type,
  11774. UploadProgress progress) {
  11775. return send_with_content_provider_and_receiver(
  11776. "POST", path, headers, nullptr, content_length,
  11777. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11778. }
  11779. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11780. size_t content_length,
  11781. ContentProvider content_provider,
  11782. const std::string &content_type,
  11783. ContentReceiver content_receiver,
  11784. DownloadProgress progress) {
  11785. return send_with_content_provider_and_receiver(
  11786. "POST", path, headers, nullptr, content_length,
  11787. std::move(content_provider), nullptr, content_type,
  11788. std::move(content_receiver), std::move(progress));
  11789. }
  11790. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11791. ContentProviderWithoutLength content_provider,
  11792. const std::string &content_type,
  11793. UploadProgress progress) {
  11794. return send_with_content_provider_and_receiver(
  11795. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11796. content_type, nullptr, progress);
  11797. }
  11798. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11799. ContentProviderWithoutLength content_provider,
  11800. const std::string &content_type,
  11801. ContentReceiver content_receiver,
  11802. DownloadProgress progress) {
  11803. return send_with_content_provider_and_receiver(
  11804. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11805. content_type, std::move(content_receiver), std::move(progress));
  11806. }
  11807. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11808. const UploadFormDataItems &items,
  11809. const FormDataProviderItems &provider_items,
  11810. UploadProgress progress) {
  11811. const auto &boundary = detail::make_multipart_data_boundary();
  11812. const auto &content_type =
  11813. detail::serialize_multipart_formdata_get_content_type(boundary);
  11814. return send_with_content_provider_and_receiver(
  11815. "POST", path, headers, nullptr, 0, nullptr,
  11816. get_multipart_content_provider(boundary, items, provider_items),
  11817. content_type, nullptr, progress);
  11818. }
  11819. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11820. const std::string &body,
  11821. const std::string &content_type,
  11822. ContentReceiver content_receiver,
  11823. DownloadProgress progress) {
  11824. Request req;
  11825. req.method = "POST";
  11826. req.path = path;
  11827. req.headers = headers;
  11828. req.body = body;
  11829. req.content_receiver =
  11830. [content_receiver](const char *data, size_t data_length,
  11831. size_t /*offset*/, size_t /*total_length*/) {
  11832. return content_receiver(data, data_length);
  11833. };
  11834. req.download_progress = std::move(progress);
  11835. if (max_timeout_msec_ > 0) {
  11836. req.start_time_ = std::chrono::steady_clock::now();
  11837. }
  11838. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11839. return send_(std::move(req));
  11840. }
  11841. inline Result ClientImpl::Put(const std::string &path) {
  11842. return Put(path, std::string(), std::string());
  11843. }
  11844. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  11845. return Put(path, headers, nullptr, 0, std::string());
  11846. }
  11847. inline Result ClientImpl::Put(const std::string &path, const char *body,
  11848. size_t content_length,
  11849. const std::string &content_type,
  11850. UploadProgress progress) {
  11851. return Put(path, Headers(), body, content_length, content_type, progress);
  11852. }
  11853. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  11854. const std::string &content_type,
  11855. UploadProgress progress) {
  11856. return Put(path, Headers(), body, content_type, progress);
  11857. }
  11858. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  11859. return Put(path, Headers(), params);
  11860. }
  11861. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11862. ContentProvider content_provider,
  11863. const std::string &content_type,
  11864. UploadProgress progress) {
  11865. return Put(path, Headers(), content_length, std::move(content_provider),
  11866. content_type, progress);
  11867. }
  11868. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11869. ContentProvider content_provider,
  11870. const std::string &content_type,
  11871. ContentReceiver content_receiver,
  11872. UploadProgress progress) {
  11873. return Put(path, Headers(), content_length, std::move(content_provider),
  11874. content_type, std::move(content_receiver), progress);
  11875. }
  11876. inline Result ClientImpl::Put(const std::string &path,
  11877. ContentProviderWithoutLength content_provider,
  11878. const std::string &content_type,
  11879. UploadProgress progress) {
  11880. return Put(path, Headers(), std::move(content_provider), content_type,
  11881. progress);
  11882. }
  11883. inline Result ClientImpl::Put(const std::string &path,
  11884. ContentProviderWithoutLength content_provider,
  11885. const std::string &content_type,
  11886. ContentReceiver content_receiver,
  11887. UploadProgress progress) {
  11888. return Put(path, Headers(), std::move(content_provider), content_type,
  11889. std::move(content_receiver), progress);
  11890. }
  11891. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11892. const Params &params) {
  11893. auto query = detail::params_to_query_str(params);
  11894. return Put(path, headers, query, "application/x-www-form-urlencoded");
  11895. }
  11896. inline Result ClientImpl::Put(const std::string &path,
  11897. const UploadFormDataItems &items,
  11898. UploadProgress progress) {
  11899. return Put(path, Headers(), items, progress);
  11900. }
  11901. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11902. const UploadFormDataItems &items,
  11903. UploadProgress progress) {
  11904. const auto &boundary = detail::make_multipart_data_boundary();
  11905. const auto &content_type =
  11906. detail::serialize_multipart_formdata_get_content_type(boundary);
  11907. auto content_length = detail::get_multipart_content_length(items, boundary);
  11908. return Put(path, headers, content_length,
  11909. detail::make_multipart_content_provider(items, boundary),
  11910. content_type, progress);
  11911. }
  11912. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11913. const UploadFormDataItems &items,
  11914. const std::string &boundary,
  11915. UploadProgress progress) {
  11916. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11917. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11918. }
  11919. const auto &content_type =
  11920. detail::serialize_multipart_formdata_get_content_type(boundary);
  11921. auto content_length = detail::get_multipart_content_length(items, boundary);
  11922. return Put(path, headers, content_length,
  11923. detail::make_multipart_content_provider(items, boundary),
  11924. content_type, progress);
  11925. }
  11926. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11927. const char *body, size_t content_length,
  11928. const std::string &content_type,
  11929. UploadProgress progress) {
  11930. return send_with_content_provider_and_receiver(
  11931. "PUT", path, headers, body, content_length, nullptr, nullptr,
  11932. content_type, nullptr, progress);
  11933. }
  11934. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11935. const std::string &body,
  11936. const std::string &content_type,
  11937. UploadProgress progress) {
  11938. return send_with_content_provider_and_receiver(
  11939. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  11940. content_type, nullptr, progress);
  11941. }
  11942. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11943. size_t content_length,
  11944. ContentProvider content_provider,
  11945. const std::string &content_type,
  11946. UploadProgress progress) {
  11947. return send_with_content_provider_and_receiver(
  11948. "PUT", path, headers, nullptr, content_length,
  11949. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11950. }
  11951. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11952. size_t content_length,
  11953. ContentProvider content_provider,
  11954. const std::string &content_type,
  11955. ContentReceiver content_receiver,
  11956. UploadProgress progress) {
  11957. return send_with_content_provider_and_receiver(
  11958. "PUT", path, headers, nullptr, content_length,
  11959. std::move(content_provider), nullptr, content_type,
  11960. std::move(content_receiver), progress);
  11961. }
  11962. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11963. ContentProviderWithoutLength content_provider,
  11964. const std::string &content_type,
  11965. UploadProgress progress) {
  11966. return send_with_content_provider_and_receiver(
  11967. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11968. content_type, nullptr, progress);
  11969. }
  11970. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11971. ContentProviderWithoutLength content_provider,
  11972. const std::string &content_type,
  11973. ContentReceiver content_receiver,
  11974. UploadProgress progress) {
  11975. return send_with_content_provider_and_receiver(
  11976. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11977. content_type, std::move(content_receiver), progress);
  11978. }
  11979. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11980. const UploadFormDataItems &items,
  11981. const FormDataProviderItems &provider_items,
  11982. UploadProgress progress) {
  11983. const auto &boundary = detail::make_multipart_data_boundary();
  11984. const auto &content_type =
  11985. detail::serialize_multipart_formdata_get_content_type(boundary);
  11986. return send_with_content_provider_and_receiver(
  11987. "PUT", path, headers, nullptr, 0, nullptr,
  11988. get_multipart_content_provider(boundary, items, provider_items),
  11989. content_type, nullptr, progress);
  11990. }
  11991. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11992. const std::string &body,
  11993. const std::string &content_type,
  11994. ContentReceiver content_receiver,
  11995. DownloadProgress progress) {
  11996. Request req;
  11997. req.method = "PUT";
  11998. req.path = path;
  11999. req.headers = headers;
  12000. req.body = body;
  12001. req.content_receiver =
  12002. [content_receiver](const char *data, size_t data_length,
  12003. size_t /*offset*/, size_t /*total_length*/) {
  12004. return content_receiver(data, data_length);
  12005. };
  12006. req.download_progress = std::move(progress);
  12007. if (max_timeout_msec_ > 0) {
  12008. req.start_time_ = std::chrono::steady_clock::now();
  12009. }
  12010. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12011. return send_(std::move(req));
  12012. }
  12013. inline Result ClientImpl::Patch(const std::string &path) {
  12014. return Patch(path, std::string(), std::string());
  12015. }
  12016. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12017. UploadProgress progress) {
  12018. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12019. }
  12020. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12021. size_t content_length,
  12022. const std::string &content_type,
  12023. UploadProgress progress) {
  12024. return Patch(path, Headers(), body, content_length, content_type, progress);
  12025. }
  12026. inline Result ClientImpl::Patch(const std::string &path,
  12027. const std::string &body,
  12028. const std::string &content_type,
  12029. UploadProgress progress) {
  12030. return Patch(path, Headers(), body, content_type, progress);
  12031. }
  12032. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12033. return Patch(path, Headers(), params);
  12034. }
  12035. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12036. ContentProvider content_provider,
  12037. const std::string &content_type,
  12038. UploadProgress progress) {
  12039. return Patch(path, Headers(), content_length, std::move(content_provider),
  12040. content_type, progress);
  12041. }
  12042. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12043. ContentProvider content_provider,
  12044. const std::string &content_type,
  12045. ContentReceiver content_receiver,
  12046. UploadProgress progress) {
  12047. return Patch(path, Headers(), content_length, std::move(content_provider),
  12048. content_type, std::move(content_receiver), progress);
  12049. }
  12050. inline Result ClientImpl::Patch(const std::string &path,
  12051. ContentProviderWithoutLength content_provider,
  12052. const std::string &content_type,
  12053. UploadProgress progress) {
  12054. return Patch(path, Headers(), std::move(content_provider), content_type,
  12055. progress);
  12056. }
  12057. inline Result ClientImpl::Patch(const std::string &path,
  12058. ContentProviderWithoutLength content_provider,
  12059. const std::string &content_type,
  12060. ContentReceiver content_receiver,
  12061. UploadProgress progress) {
  12062. return Patch(path, Headers(), std::move(content_provider), content_type,
  12063. std::move(content_receiver), progress);
  12064. }
  12065. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12066. const Params &params) {
  12067. auto query = detail::params_to_query_str(params);
  12068. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12069. }
  12070. inline Result ClientImpl::Patch(const std::string &path,
  12071. const UploadFormDataItems &items,
  12072. UploadProgress progress) {
  12073. return Patch(path, Headers(), items, progress);
  12074. }
  12075. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12076. const UploadFormDataItems &items,
  12077. UploadProgress progress) {
  12078. const auto &boundary = detail::make_multipart_data_boundary();
  12079. const auto &content_type =
  12080. detail::serialize_multipart_formdata_get_content_type(boundary);
  12081. auto content_length = detail::get_multipart_content_length(items, boundary);
  12082. return Patch(path, headers, content_length,
  12083. detail::make_multipart_content_provider(items, boundary),
  12084. content_type, progress);
  12085. }
  12086. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12087. const UploadFormDataItems &items,
  12088. const std::string &boundary,
  12089. UploadProgress progress) {
  12090. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12091. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12092. }
  12093. const auto &content_type =
  12094. detail::serialize_multipart_formdata_get_content_type(boundary);
  12095. auto content_length = detail::get_multipart_content_length(items, boundary);
  12096. return Patch(path, headers, content_length,
  12097. detail::make_multipart_content_provider(items, boundary),
  12098. content_type, progress);
  12099. }
  12100. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12101. const char *body, size_t content_length,
  12102. const std::string &content_type,
  12103. UploadProgress progress) {
  12104. return send_with_content_provider_and_receiver(
  12105. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12106. content_type, nullptr, progress);
  12107. }
  12108. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12109. const std::string &body,
  12110. const std::string &content_type,
  12111. UploadProgress progress) {
  12112. return send_with_content_provider_and_receiver(
  12113. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12114. content_type, nullptr, progress);
  12115. }
  12116. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12117. size_t content_length,
  12118. ContentProvider content_provider,
  12119. const std::string &content_type,
  12120. UploadProgress progress) {
  12121. return send_with_content_provider_and_receiver(
  12122. "PATCH", path, headers, nullptr, content_length,
  12123. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12124. }
  12125. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12126. size_t content_length,
  12127. ContentProvider content_provider,
  12128. const std::string &content_type,
  12129. ContentReceiver content_receiver,
  12130. UploadProgress progress) {
  12131. return send_with_content_provider_and_receiver(
  12132. "PATCH", path, headers, nullptr, content_length,
  12133. std::move(content_provider), nullptr, content_type,
  12134. std::move(content_receiver), progress);
  12135. }
  12136. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12137. ContentProviderWithoutLength content_provider,
  12138. const std::string &content_type,
  12139. UploadProgress progress) {
  12140. return send_with_content_provider_and_receiver(
  12141. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12142. content_type, nullptr, progress);
  12143. }
  12144. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12145. ContentProviderWithoutLength content_provider,
  12146. const std::string &content_type,
  12147. ContentReceiver content_receiver,
  12148. UploadProgress progress) {
  12149. return send_with_content_provider_and_receiver(
  12150. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12151. content_type, std::move(content_receiver), progress);
  12152. }
  12153. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12154. const UploadFormDataItems &items,
  12155. const FormDataProviderItems &provider_items,
  12156. UploadProgress progress) {
  12157. const auto &boundary = detail::make_multipart_data_boundary();
  12158. const auto &content_type =
  12159. detail::serialize_multipart_formdata_get_content_type(boundary);
  12160. return send_with_content_provider_and_receiver(
  12161. "PATCH", path, headers, nullptr, 0, nullptr,
  12162. get_multipart_content_provider(boundary, items, provider_items),
  12163. content_type, nullptr, progress);
  12164. }
  12165. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12166. const std::string &body,
  12167. const std::string &content_type,
  12168. ContentReceiver content_receiver,
  12169. DownloadProgress progress) {
  12170. Request req;
  12171. req.method = "PATCH";
  12172. req.path = path;
  12173. req.headers = headers;
  12174. req.body = body;
  12175. req.content_receiver =
  12176. [content_receiver](const char *data, size_t data_length,
  12177. size_t /*offset*/, size_t /*total_length*/) {
  12178. return content_receiver(data, data_length);
  12179. };
  12180. req.download_progress = std::move(progress);
  12181. if (max_timeout_msec_ > 0) {
  12182. req.start_time_ = std::chrono::steady_clock::now();
  12183. }
  12184. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12185. return send_(std::move(req));
  12186. }
  12187. inline Result ClientImpl::Delete(const std::string &path,
  12188. DownloadProgress progress) {
  12189. return Delete(path, Headers(), std::string(), std::string(), progress);
  12190. }
  12191. inline Result ClientImpl::Delete(const std::string &path,
  12192. const Headers &headers,
  12193. DownloadProgress progress) {
  12194. return Delete(path, headers, std::string(), std::string(), progress);
  12195. }
  12196. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12197. size_t content_length,
  12198. const std::string &content_type,
  12199. DownloadProgress progress) {
  12200. return Delete(path, Headers(), body, content_length, content_type, progress);
  12201. }
  12202. inline Result ClientImpl::Delete(const std::string &path,
  12203. const std::string &body,
  12204. const std::string &content_type,
  12205. DownloadProgress progress) {
  12206. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12207. progress);
  12208. }
  12209. inline Result ClientImpl::Delete(const std::string &path,
  12210. const Headers &headers,
  12211. const std::string &body,
  12212. const std::string &content_type,
  12213. DownloadProgress progress) {
  12214. return Delete(path, headers, body.data(), body.size(), content_type,
  12215. progress);
  12216. }
  12217. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12218. DownloadProgress progress) {
  12219. return Delete(path, Headers(), params, progress);
  12220. }
  12221. inline Result ClientImpl::Delete(const std::string &path,
  12222. const Headers &headers, const Params &params,
  12223. DownloadProgress progress) {
  12224. auto query = detail::params_to_query_str(params);
  12225. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12226. progress);
  12227. }
  12228. inline Result ClientImpl::Delete(const std::string &path,
  12229. const Headers &headers, const char *body,
  12230. size_t content_length,
  12231. const std::string &content_type,
  12232. DownloadProgress progress) {
  12233. Request req;
  12234. req.method = "DELETE";
  12235. req.headers = headers;
  12236. req.path = path;
  12237. req.download_progress = std::move(progress);
  12238. if (max_timeout_msec_ > 0) {
  12239. req.start_time_ = std::chrono::steady_clock::now();
  12240. }
  12241. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12242. req.body.assign(body, content_length);
  12243. return send_(std::move(req));
  12244. }
  12245. inline Result ClientImpl::Options(const std::string &path) {
  12246. return Options(path, Headers());
  12247. }
  12248. inline Result ClientImpl::Options(const std::string &path,
  12249. const Headers &headers) {
  12250. Request req;
  12251. req.method = "OPTIONS";
  12252. req.headers = headers;
  12253. req.path = path;
  12254. if (max_timeout_msec_ > 0) {
  12255. req.start_time_ = std::chrono::steady_clock::now();
  12256. }
  12257. return send_(std::move(req));
  12258. }
  12259. inline void ClientImpl::stop() {
  12260. std::lock_guard<std::mutex> guard(socket_mutex_);
  12261. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12262. // do is to shutdown_socket, so that threads using this socket suddenly
  12263. // discover they can't read/write any more and error out. Everything else
  12264. // (closing the socket, shutting ssl down) is unsafe because these actions
  12265. // are not thread-safe.
  12266. if (socket_requests_in_flight_ > 0) {
  12267. shutdown_socket(socket_);
  12268. // Aside from that, we set a flag for the socket to be closed when we're
  12269. // done.
  12270. socket_should_be_closed_when_request_is_done_ = true;
  12271. return;
  12272. }
  12273. // Otherwise, still holding the mutex, we can shut everything down ourselves
  12274. shutdown_ssl(socket_, true);
  12275. shutdown_socket(socket_);
  12276. close_socket(socket_);
  12277. }
  12278. inline std::string ClientImpl::host() const { return host_; }
  12279. inline int ClientImpl::port() const { return port_; }
  12280. inline size_t ClientImpl::is_socket_open() const {
  12281. std::lock_guard<std::mutex> guard(socket_mutex_);
  12282. return socket_.is_open();
  12283. }
  12284. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12285. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12286. connection_timeout_sec_ = sec;
  12287. connection_timeout_usec_ = usec;
  12288. }
  12289. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12290. read_timeout_sec_ = sec;
  12291. read_timeout_usec_ = usec;
  12292. }
  12293. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12294. write_timeout_sec_ = sec;
  12295. write_timeout_usec_ = usec;
  12296. }
  12297. inline void ClientImpl::set_max_timeout(time_t msec) {
  12298. max_timeout_msec_ = msec;
  12299. }
  12300. inline void ClientImpl::set_basic_auth(const std::string &username,
  12301. const std::string &password) {
  12302. basic_auth_username_ = username;
  12303. basic_auth_password_ = password;
  12304. }
  12305. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12306. bearer_token_auth_token_ = token;
  12307. }
  12308. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12309. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12310. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12311. inline void
  12312. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12313. addr_map_ = std::move(addr_map);
  12314. }
  12315. inline void ClientImpl::set_default_headers(Headers headers) {
  12316. default_headers_ = std::move(headers);
  12317. }
  12318. inline void ClientImpl::set_header_writer(
  12319. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12320. header_writer_ = writer;
  12321. }
  12322. inline void ClientImpl::set_address_family(int family) {
  12323. address_family_ = family;
  12324. }
  12325. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12326. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12327. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12328. socket_options_ = std::move(socket_options);
  12329. }
  12330. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12331. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12332. inline void ClientImpl::set_payload_max_length(size_t length) {
  12333. payload_max_length_ = length;
  12334. has_payload_max_length_ = true;
  12335. }
  12336. inline void ClientImpl::set_interface(const std::string &intf) {
  12337. interface_ = intf;
  12338. }
  12339. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12340. proxy_host_ = host;
  12341. proxy_port_ = port;
  12342. }
  12343. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12344. const std::string &password) {
  12345. proxy_basic_auth_username_ = username;
  12346. proxy_basic_auth_password_ = password;
  12347. }
  12348. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12349. proxy_bearer_token_auth_token_ = token;
  12350. }
  12351. #ifdef CPPHTTPLIB_SSL_ENABLED
  12352. inline void ClientImpl::set_digest_auth(const std::string &username,
  12353. const std::string &password) {
  12354. digest_auth_username_ = username;
  12355. digest_auth_password_ = password;
  12356. }
  12357. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12358. const std::string &ca_cert_dir_path) {
  12359. ca_cert_file_path_ = ca_cert_file_path;
  12360. ca_cert_dir_path_ = ca_cert_dir_path;
  12361. }
  12362. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12363. const std::string &password) {
  12364. proxy_digest_auth_username_ = username;
  12365. proxy_digest_auth_password_ = password;
  12366. }
  12367. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12368. server_certificate_verification_ = enabled;
  12369. }
  12370. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12371. server_hostname_verification_ = enabled;
  12372. }
  12373. #endif
  12374. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  12375. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12376. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  12377. std::size_t size) const {
  12378. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  12379. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  12380. if (!mem) { return nullptr; }
  12381. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  12382. if (!inf) { return nullptr; }
  12383. auto cts = X509_STORE_new();
  12384. if (cts) {
  12385. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  12386. auto itmp = sk_X509_INFO_value(inf, i);
  12387. if (!itmp) { continue; }
  12388. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  12389. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  12390. }
  12391. }
  12392. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  12393. return cts;
  12394. }
  12395. inline void ClientImpl::set_server_certificate_verifier(
  12396. std::function<SSLVerifierResponse(SSL *ssl)> /*verifier*/) {
  12397. // Base implementation does nothing - SSLClient overrides this
  12398. }
  12399. #endif
  12400. inline void ClientImpl::set_logger(Logger logger) {
  12401. logger_ = std::move(logger);
  12402. }
  12403. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12404. error_logger_ = std::move(error_logger);
  12405. }
  12406. /*
  12407. * SSL/TLS Common Implementation
  12408. */
  12409. inline ClientConnection::~ClientConnection() {
  12410. #ifdef CPPHTTPLIB_SSL_ENABLED
  12411. if (session) {
  12412. tls::shutdown(session, true);
  12413. tls::free_session(session);
  12414. session = nullptr;
  12415. }
  12416. #endif
  12417. if (sock != INVALID_SOCKET) {
  12418. detail::close_socket(sock);
  12419. sock = INVALID_SOCKET;
  12420. }
  12421. }
  12422. // Universal client implementation
  12423. inline Client::Client(const std::string &scheme_host_port)
  12424. : Client(scheme_host_port, std::string(), std::string()) {}
  12425. inline Client::Client(const std::string &scheme_host_port,
  12426. const std::string &client_cert_path,
  12427. const std::string &client_key_path) {
  12428. const static std::regex re(
  12429. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  12430. std::smatch m;
  12431. if (std::regex_match(scheme_host_port, m, re)) {
  12432. auto scheme = m[1].str();
  12433. #ifdef CPPHTTPLIB_SSL_ENABLED
  12434. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12435. #else
  12436. if (!scheme.empty() && scheme != "http") {
  12437. #endif
  12438. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12439. std::string msg = "'" + scheme + "' scheme is not supported.";
  12440. throw std::invalid_argument(msg);
  12441. #endif
  12442. return;
  12443. }
  12444. auto is_ssl = scheme == "https";
  12445. auto host = m[2].str();
  12446. if (host.empty()) { host = m[3].str(); }
  12447. auto port_str = m[4].str();
  12448. auto port = is_ssl ? 443 : 80;
  12449. if (!port_str.empty() && !detail::parse_port(port_str, port)) { return; }
  12450. if (is_ssl) {
  12451. #ifdef CPPHTTPLIB_SSL_ENABLED
  12452. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12453. client_key_path);
  12454. is_ssl_ = is_ssl;
  12455. #endif
  12456. } else {
  12457. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12458. client_key_path);
  12459. }
  12460. } else {
  12461. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12462. // if port param below changes.
  12463. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12464. client_cert_path, client_key_path);
  12465. }
  12466. } // namespace detail
  12467. inline Client::Client(const std::string &host, int port)
  12468. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  12469. inline Client::Client(const std::string &host, int port,
  12470. const std::string &client_cert_path,
  12471. const std::string &client_key_path)
  12472. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12473. client_key_path)) {}
  12474. inline Client::~Client() = default;
  12475. inline bool Client::is_valid() const {
  12476. return cli_ != nullptr && cli_->is_valid();
  12477. }
  12478. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12479. return cli_->Get(path, std::move(progress));
  12480. }
  12481. inline Result Client::Get(const std::string &path, const Headers &headers,
  12482. DownloadProgress progress) {
  12483. return cli_->Get(path, headers, std::move(progress));
  12484. }
  12485. inline Result Client::Get(const std::string &path,
  12486. ContentReceiver content_receiver,
  12487. DownloadProgress progress) {
  12488. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12489. }
  12490. inline Result Client::Get(const std::string &path, const Headers &headers,
  12491. ContentReceiver content_receiver,
  12492. DownloadProgress progress) {
  12493. return cli_->Get(path, headers, std::move(content_receiver),
  12494. std::move(progress));
  12495. }
  12496. inline Result Client::Get(const std::string &path,
  12497. ResponseHandler response_handler,
  12498. ContentReceiver content_receiver,
  12499. DownloadProgress progress) {
  12500. return cli_->Get(path, std::move(response_handler),
  12501. std::move(content_receiver), std::move(progress));
  12502. }
  12503. inline Result Client::Get(const std::string &path, const Headers &headers,
  12504. ResponseHandler response_handler,
  12505. ContentReceiver content_receiver,
  12506. DownloadProgress progress) {
  12507. return cli_->Get(path, headers, std::move(response_handler),
  12508. std::move(content_receiver), std::move(progress));
  12509. }
  12510. inline Result Client::Get(const std::string &path, const Params &params,
  12511. const Headers &headers, DownloadProgress progress) {
  12512. return cli_->Get(path, params, headers, std::move(progress));
  12513. }
  12514. inline Result Client::Get(const std::string &path, const Params &params,
  12515. const Headers &headers,
  12516. ContentReceiver content_receiver,
  12517. DownloadProgress progress) {
  12518. return cli_->Get(path, params, headers, std::move(content_receiver),
  12519. std::move(progress));
  12520. }
  12521. inline Result Client::Get(const std::string &path, const Params &params,
  12522. const Headers &headers,
  12523. ResponseHandler response_handler,
  12524. ContentReceiver content_receiver,
  12525. DownloadProgress progress) {
  12526. return cli_->Get(path, params, headers, std::move(response_handler),
  12527. std::move(content_receiver), std::move(progress));
  12528. }
  12529. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12530. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12531. return cli_->Head(path, headers);
  12532. }
  12533. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12534. inline Result Client::Post(const std::string &path, const Headers &headers) {
  12535. return cli_->Post(path, headers);
  12536. }
  12537. inline Result Client::Post(const std::string &path, const char *body,
  12538. size_t content_length,
  12539. const std::string &content_type,
  12540. UploadProgress progress) {
  12541. return cli_->Post(path, body, content_length, content_type, progress);
  12542. }
  12543. inline Result Client::Post(const std::string &path, const Headers &headers,
  12544. const char *body, size_t content_length,
  12545. const std::string &content_type,
  12546. UploadProgress progress) {
  12547. return cli_->Post(path, headers, body, content_length, content_type,
  12548. progress);
  12549. }
  12550. inline Result Client::Post(const std::string &path, const std::string &body,
  12551. const std::string &content_type,
  12552. UploadProgress progress) {
  12553. return cli_->Post(path, body, content_type, progress);
  12554. }
  12555. inline Result Client::Post(const std::string &path, const Headers &headers,
  12556. const std::string &body,
  12557. const std::string &content_type,
  12558. UploadProgress progress) {
  12559. return cli_->Post(path, headers, body, content_type, progress);
  12560. }
  12561. inline Result Client::Post(const std::string &path, size_t content_length,
  12562. ContentProvider content_provider,
  12563. const std::string &content_type,
  12564. UploadProgress progress) {
  12565. return cli_->Post(path, content_length, std::move(content_provider),
  12566. content_type, progress);
  12567. }
  12568. inline Result Client::Post(const std::string &path, size_t content_length,
  12569. ContentProvider content_provider,
  12570. const std::string &content_type,
  12571. ContentReceiver content_receiver,
  12572. UploadProgress progress) {
  12573. return cli_->Post(path, content_length, std::move(content_provider),
  12574. content_type, std::move(content_receiver), progress);
  12575. }
  12576. inline Result Client::Post(const std::string &path,
  12577. ContentProviderWithoutLength content_provider,
  12578. const std::string &content_type,
  12579. UploadProgress progress) {
  12580. return cli_->Post(path, std::move(content_provider), content_type, progress);
  12581. }
  12582. inline Result Client::Post(const std::string &path,
  12583. ContentProviderWithoutLength content_provider,
  12584. const std::string &content_type,
  12585. ContentReceiver content_receiver,
  12586. UploadProgress progress) {
  12587. return cli_->Post(path, std::move(content_provider), content_type,
  12588. std::move(content_receiver), progress);
  12589. }
  12590. inline Result Client::Post(const std::string &path, const Headers &headers,
  12591. size_t content_length,
  12592. ContentProvider content_provider,
  12593. const std::string &content_type,
  12594. UploadProgress progress) {
  12595. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12596. content_type, progress);
  12597. }
  12598. inline Result Client::Post(const std::string &path, const Headers &headers,
  12599. size_t content_length,
  12600. ContentProvider content_provider,
  12601. const std::string &content_type,
  12602. ContentReceiver content_receiver,
  12603. DownloadProgress progress) {
  12604. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12605. content_type, std::move(content_receiver), progress);
  12606. }
  12607. inline Result Client::Post(const std::string &path, const Headers &headers,
  12608. ContentProviderWithoutLength content_provider,
  12609. const std::string &content_type,
  12610. UploadProgress progress) {
  12611. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12612. progress);
  12613. }
  12614. inline Result Client::Post(const std::string &path, const Headers &headers,
  12615. ContentProviderWithoutLength content_provider,
  12616. const std::string &content_type,
  12617. ContentReceiver content_receiver,
  12618. DownloadProgress progress) {
  12619. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12620. std::move(content_receiver), progress);
  12621. }
  12622. inline Result Client::Post(const std::string &path, const Params &params) {
  12623. return cli_->Post(path, params);
  12624. }
  12625. inline Result Client::Post(const std::string &path, const Headers &headers,
  12626. const Params &params) {
  12627. return cli_->Post(path, headers, params);
  12628. }
  12629. inline Result Client::Post(const std::string &path,
  12630. const UploadFormDataItems &items,
  12631. UploadProgress progress) {
  12632. return cli_->Post(path, items, progress);
  12633. }
  12634. inline Result Client::Post(const std::string &path, const Headers &headers,
  12635. const UploadFormDataItems &items,
  12636. UploadProgress progress) {
  12637. return cli_->Post(path, headers, items, progress);
  12638. }
  12639. inline Result Client::Post(const std::string &path, const Headers &headers,
  12640. const UploadFormDataItems &items,
  12641. const std::string &boundary,
  12642. UploadProgress progress) {
  12643. return cli_->Post(path, headers, items, boundary, progress);
  12644. }
  12645. inline Result Client::Post(const std::string &path, const Headers &headers,
  12646. const UploadFormDataItems &items,
  12647. const FormDataProviderItems &provider_items,
  12648. UploadProgress progress) {
  12649. return cli_->Post(path, headers, items, provider_items, progress);
  12650. }
  12651. inline Result Client::Post(const std::string &path, const Headers &headers,
  12652. const std::string &body,
  12653. const std::string &content_type,
  12654. ContentReceiver content_receiver,
  12655. DownloadProgress progress) {
  12656. return cli_->Post(path, headers, body, content_type,
  12657. std::move(content_receiver), progress);
  12658. }
  12659. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  12660. inline Result Client::Put(const std::string &path, const Headers &headers) {
  12661. return cli_->Put(path, headers);
  12662. }
  12663. inline Result Client::Put(const std::string &path, const char *body,
  12664. size_t content_length,
  12665. const std::string &content_type,
  12666. UploadProgress progress) {
  12667. return cli_->Put(path, body, content_length, content_type, progress);
  12668. }
  12669. inline Result Client::Put(const std::string &path, const Headers &headers,
  12670. const char *body, size_t content_length,
  12671. const std::string &content_type,
  12672. UploadProgress progress) {
  12673. return cli_->Put(path, headers, body, content_length, content_type, progress);
  12674. }
  12675. inline Result Client::Put(const std::string &path, const std::string &body,
  12676. const std::string &content_type,
  12677. UploadProgress progress) {
  12678. return cli_->Put(path, body, content_type, progress);
  12679. }
  12680. inline Result Client::Put(const std::string &path, const Headers &headers,
  12681. const std::string &body,
  12682. const std::string &content_type,
  12683. UploadProgress progress) {
  12684. return cli_->Put(path, headers, body, content_type, progress);
  12685. }
  12686. inline Result Client::Put(const std::string &path, size_t content_length,
  12687. ContentProvider content_provider,
  12688. const std::string &content_type,
  12689. UploadProgress progress) {
  12690. return cli_->Put(path, content_length, std::move(content_provider),
  12691. content_type, progress);
  12692. }
  12693. inline Result Client::Put(const std::string &path, size_t content_length,
  12694. ContentProvider content_provider,
  12695. const std::string &content_type,
  12696. ContentReceiver content_receiver,
  12697. UploadProgress progress) {
  12698. return cli_->Put(path, content_length, std::move(content_provider),
  12699. content_type, std::move(content_receiver), progress);
  12700. }
  12701. inline Result Client::Put(const std::string &path,
  12702. ContentProviderWithoutLength content_provider,
  12703. const std::string &content_type,
  12704. UploadProgress progress) {
  12705. return cli_->Put(path, std::move(content_provider), content_type, progress);
  12706. }
  12707. inline Result Client::Put(const std::string &path,
  12708. ContentProviderWithoutLength content_provider,
  12709. const std::string &content_type,
  12710. ContentReceiver content_receiver,
  12711. UploadProgress progress) {
  12712. return cli_->Put(path, std::move(content_provider), content_type,
  12713. std::move(content_receiver), progress);
  12714. }
  12715. inline Result Client::Put(const std::string &path, const Headers &headers,
  12716. size_t content_length,
  12717. ContentProvider content_provider,
  12718. const std::string &content_type,
  12719. UploadProgress progress) {
  12720. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12721. content_type, progress);
  12722. }
  12723. inline Result Client::Put(const std::string &path, const Headers &headers,
  12724. size_t content_length,
  12725. ContentProvider content_provider,
  12726. const std::string &content_type,
  12727. ContentReceiver content_receiver,
  12728. UploadProgress progress) {
  12729. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12730. content_type, std::move(content_receiver), progress);
  12731. }
  12732. inline Result Client::Put(const std::string &path, const Headers &headers,
  12733. ContentProviderWithoutLength content_provider,
  12734. const std::string &content_type,
  12735. UploadProgress progress) {
  12736. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12737. progress);
  12738. }
  12739. inline Result Client::Put(const std::string &path, const Headers &headers,
  12740. ContentProviderWithoutLength content_provider,
  12741. const std::string &content_type,
  12742. ContentReceiver content_receiver,
  12743. UploadProgress progress) {
  12744. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12745. std::move(content_receiver), progress);
  12746. }
  12747. inline Result Client::Put(const std::string &path, const Params &params) {
  12748. return cli_->Put(path, params);
  12749. }
  12750. inline Result Client::Put(const std::string &path, const Headers &headers,
  12751. const Params &params) {
  12752. return cli_->Put(path, headers, params);
  12753. }
  12754. inline Result Client::Put(const std::string &path,
  12755. const UploadFormDataItems &items,
  12756. UploadProgress progress) {
  12757. return cli_->Put(path, items, progress);
  12758. }
  12759. inline Result Client::Put(const std::string &path, const Headers &headers,
  12760. const UploadFormDataItems &items,
  12761. UploadProgress progress) {
  12762. return cli_->Put(path, headers, items, progress);
  12763. }
  12764. inline Result Client::Put(const std::string &path, const Headers &headers,
  12765. const UploadFormDataItems &items,
  12766. const std::string &boundary,
  12767. UploadProgress progress) {
  12768. return cli_->Put(path, headers, items, boundary, progress);
  12769. }
  12770. inline Result Client::Put(const std::string &path, const Headers &headers,
  12771. const UploadFormDataItems &items,
  12772. const FormDataProviderItems &provider_items,
  12773. UploadProgress progress) {
  12774. return cli_->Put(path, headers, items, provider_items, progress);
  12775. }
  12776. inline Result Client::Put(const std::string &path, const Headers &headers,
  12777. const std::string &body,
  12778. const std::string &content_type,
  12779. ContentReceiver content_receiver,
  12780. DownloadProgress progress) {
  12781. return cli_->Put(path, headers, body, content_type, content_receiver,
  12782. progress);
  12783. }
  12784. inline Result Client::Patch(const std::string &path) {
  12785. return cli_->Patch(path);
  12786. }
  12787. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  12788. return cli_->Patch(path, headers);
  12789. }
  12790. inline Result Client::Patch(const std::string &path, const char *body,
  12791. size_t content_length,
  12792. const std::string &content_type,
  12793. UploadProgress progress) {
  12794. return cli_->Patch(path, body, content_length, content_type, progress);
  12795. }
  12796. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12797. const char *body, size_t content_length,
  12798. const std::string &content_type,
  12799. UploadProgress progress) {
  12800. return cli_->Patch(path, headers, body, content_length, content_type,
  12801. progress);
  12802. }
  12803. inline Result Client::Patch(const std::string &path, const std::string &body,
  12804. const std::string &content_type,
  12805. UploadProgress progress) {
  12806. return cli_->Patch(path, body, content_type, progress);
  12807. }
  12808. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12809. const std::string &body,
  12810. const std::string &content_type,
  12811. UploadProgress progress) {
  12812. return cli_->Patch(path, headers, body, content_type, progress);
  12813. }
  12814. inline Result Client::Patch(const std::string &path, size_t content_length,
  12815. ContentProvider content_provider,
  12816. const std::string &content_type,
  12817. UploadProgress progress) {
  12818. return cli_->Patch(path, content_length, std::move(content_provider),
  12819. content_type, progress);
  12820. }
  12821. inline Result Client::Patch(const std::string &path, size_t content_length,
  12822. ContentProvider content_provider,
  12823. const std::string &content_type,
  12824. ContentReceiver content_receiver,
  12825. UploadProgress progress) {
  12826. return cli_->Patch(path, content_length, std::move(content_provider),
  12827. content_type, std::move(content_receiver), progress);
  12828. }
  12829. inline Result Client::Patch(const std::string &path,
  12830. ContentProviderWithoutLength content_provider,
  12831. const std::string &content_type,
  12832. UploadProgress progress) {
  12833. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  12834. }
  12835. inline Result Client::Patch(const std::string &path,
  12836. ContentProviderWithoutLength content_provider,
  12837. const std::string &content_type,
  12838. ContentReceiver content_receiver,
  12839. UploadProgress progress) {
  12840. return cli_->Patch(path, std::move(content_provider), content_type,
  12841. std::move(content_receiver), progress);
  12842. }
  12843. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12844. size_t content_length,
  12845. ContentProvider content_provider,
  12846. const std::string &content_type,
  12847. UploadProgress progress) {
  12848. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12849. content_type, progress);
  12850. }
  12851. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12852. size_t content_length,
  12853. ContentProvider content_provider,
  12854. const std::string &content_type,
  12855. ContentReceiver content_receiver,
  12856. UploadProgress progress) {
  12857. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12858. content_type, std::move(content_receiver), progress);
  12859. }
  12860. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12861. ContentProviderWithoutLength content_provider,
  12862. const std::string &content_type,
  12863. UploadProgress progress) {
  12864. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12865. progress);
  12866. }
  12867. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12868. ContentProviderWithoutLength content_provider,
  12869. const std::string &content_type,
  12870. ContentReceiver content_receiver,
  12871. UploadProgress progress) {
  12872. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12873. std::move(content_receiver), progress);
  12874. }
  12875. inline Result Client::Patch(const std::string &path, const Params &params) {
  12876. return cli_->Patch(path, params);
  12877. }
  12878. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12879. const Params &params) {
  12880. return cli_->Patch(path, headers, params);
  12881. }
  12882. inline Result Client::Patch(const std::string &path,
  12883. const UploadFormDataItems &items,
  12884. UploadProgress progress) {
  12885. return cli_->Patch(path, items, progress);
  12886. }
  12887. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12888. const UploadFormDataItems &items,
  12889. UploadProgress progress) {
  12890. return cli_->Patch(path, headers, items, progress);
  12891. }
  12892. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12893. const UploadFormDataItems &items,
  12894. const std::string &boundary,
  12895. UploadProgress progress) {
  12896. return cli_->Patch(path, headers, items, boundary, progress);
  12897. }
  12898. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12899. const UploadFormDataItems &items,
  12900. const FormDataProviderItems &provider_items,
  12901. UploadProgress progress) {
  12902. return cli_->Patch(path, headers, items, provider_items, progress);
  12903. }
  12904. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12905. const std::string &body,
  12906. const std::string &content_type,
  12907. ContentReceiver content_receiver,
  12908. DownloadProgress progress) {
  12909. return cli_->Patch(path, headers, body, content_type, content_receiver,
  12910. progress);
  12911. }
  12912. inline Result Client::Delete(const std::string &path,
  12913. DownloadProgress progress) {
  12914. return cli_->Delete(path, progress);
  12915. }
  12916. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12917. DownloadProgress progress) {
  12918. return cli_->Delete(path, headers, progress);
  12919. }
  12920. inline Result Client::Delete(const std::string &path, const char *body,
  12921. size_t content_length,
  12922. const std::string &content_type,
  12923. DownloadProgress progress) {
  12924. return cli_->Delete(path, body, content_length, content_type, progress);
  12925. }
  12926. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12927. const char *body, size_t content_length,
  12928. const std::string &content_type,
  12929. DownloadProgress progress) {
  12930. return cli_->Delete(path, headers, body, content_length, content_type,
  12931. progress);
  12932. }
  12933. inline Result Client::Delete(const std::string &path, const std::string &body,
  12934. const std::string &content_type,
  12935. DownloadProgress progress) {
  12936. return cli_->Delete(path, body, content_type, progress);
  12937. }
  12938. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12939. const std::string &body,
  12940. const std::string &content_type,
  12941. DownloadProgress progress) {
  12942. return cli_->Delete(path, headers, body, content_type, progress);
  12943. }
  12944. inline Result Client::Delete(const std::string &path, const Params &params,
  12945. DownloadProgress progress) {
  12946. return cli_->Delete(path, params, progress);
  12947. }
  12948. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12949. const Params &params, DownloadProgress progress) {
  12950. return cli_->Delete(path, headers, params, progress);
  12951. }
  12952. inline Result Client::Options(const std::string &path) {
  12953. return cli_->Options(path);
  12954. }
  12955. inline Result Client::Options(const std::string &path, const Headers &headers) {
  12956. return cli_->Options(path, headers);
  12957. }
  12958. inline ClientImpl::StreamHandle
  12959. Client::open_stream(const std::string &method, const std::string &path,
  12960. const Params &params, const Headers &headers,
  12961. const std::string &body, const std::string &content_type) {
  12962. return cli_->open_stream(method, path, params, headers, body, content_type);
  12963. }
  12964. inline bool Client::send(Request &req, Response &res, Error &error) {
  12965. return cli_->send(req, res, error);
  12966. }
  12967. inline Result Client::send(const Request &req) { return cli_->send(req); }
  12968. inline void Client::stop() { cli_->stop(); }
  12969. inline std::string Client::host() const { return cli_->host(); }
  12970. inline int Client::port() const { return cli_->port(); }
  12971. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  12972. inline socket_t Client::socket() const { return cli_->socket(); }
  12973. inline void
  12974. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12975. cli_->set_hostname_addr_map(std::move(addr_map));
  12976. }
  12977. inline void Client::set_default_headers(Headers headers) {
  12978. cli_->set_default_headers(std::move(headers));
  12979. }
  12980. inline void Client::set_header_writer(
  12981. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12982. cli_->set_header_writer(writer);
  12983. }
  12984. inline void Client::set_address_family(int family) {
  12985. cli_->set_address_family(family);
  12986. }
  12987. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  12988. inline void Client::set_socket_options(SocketOptions socket_options) {
  12989. cli_->set_socket_options(std::move(socket_options));
  12990. }
  12991. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  12992. cli_->set_connection_timeout(sec, usec);
  12993. }
  12994. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  12995. cli_->set_read_timeout(sec, usec);
  12996. }
  12997. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  12998. cli_->set_write_timeout(sec, usec);
  12999. }
  13000. inline void Client::set_basic_auth(const std::string &username,
  13001. const std::string &password) {
  13002. cli_->set_basic_auth(username, password);
  13003. }
  13004. inline void Client::set_bearer_token_auth(const std::string &token) {
  13005. cli_->set_bearer_token_auth(token);
  13006. }
  13007. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13008. inline void Client::set_follow_location(bool on) {
  13009. cli_->set_follow_location(on);
  13010. }
  13011. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13012. [[deprecated("Use set_path_encode() instead. "
  13013. "This function will be removed by v1.0.0.")]]
  13014. inline void Client::set_url_encode(bool on) {
  13015. cli_->set_path_encode(on);
  13016. }
  13017. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13018. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13019. inline void Client::set_payload_max_length(size_t length) {
  13020. cli_->set_payload_max_length(length);
  13021. }
  13022. inline void Client::set_interface(const std::string &intf) {
  13023. cli_->set_interface(intf);
  13024. }
  13025. inline void Client::set_proxy(const std::string &host, int port) {
  13026. cli_->set_proxy(host, port);
  13027. }
  13028. inline void Client::set_proxy_basic_auth(const std::string &username,
  13029. const std::string &password) {
  13030. cli_->set_proxy_basic_auth(username, password);
  13031. }
  13032. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13033. cli_->set_proxy_bearer_token_auth(token);
  13034. }
  13035. inline void Client::set_logger(Logger logger) {
  13036. cli_->set_logger(std::move(logger));
  13037. }
  13038. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13039. cli_->set_error_logger(std::move(error_logger));
  13040. }
  13041. /*
  13042. * Group 6: SSL Server and Client implementation
  13043. */
  13044. #ifdef CPPHTTPLIB_SSL_ENABLED
  13045. // SSL HTTP server implementation
  13046. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13047. const char *client_ca_cert_file_path,
  13048. const char *client_ca_cert_dir_path,
  13049. const char *private_key_password) {
  13050. using namespace tls;
  13051. ctx_ = create_server_context();
  13052. if (!ctx_) { return; }
  13053. // Load server certificate and private key
  13054. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13055. private_key_password)) {
  13056. last_ssl_error_ = static_cast<int>(get_error());
  13057. free_context(ctx_);
  13058. ctx_ = nullptr;
  13059. return;
  13060. }
  13061. // Load client CA certificates for client authentication
  13062. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13063. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13064. client_ca_cert_dir_path)) {
  13065. last_ssl_error_ = static_cast<int>(get_error());
  13066. free_context(ctx_);
  13067. ctx_ = nullptr;
  13068. return;
  13069. }
  13070. // Enable client certificate verification
  13071. set_verify_client(ctx_, true);
  13072. }
  13073. }
  13074. inline SSLServer::SSLServer(const PemMemory &pem) {
  13075. using namespace tls;
  13076. ctx_ = create_server_context();
  13077. if (ctx_) {
  13078. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13079. pem.private_key_password)) {
  13080. last_ssl_error_ = static_cast<int>(get_error());
  13081. free_context(ctx_);
  13082. ctx_ = nullptr;
  13083. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13084. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13085. last_ssl_error_ = static_cast<int>(get_error());
  13086. free_context(ctx_);
  13087. ctx_ = nullptr;
  13088. } else {
  13089. set_verify_client(ctx_, true);
  13090. }
  13091. }
  13092. }
  13093. }
  13094. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13095. using namespace tls;
  13096. ctx_ = create_server_context();
  13097. if (ctx_) {
  13098. if (!setup_callback(ctx_)) {
  13099. free_context(ctx_);
  13100. ctx_ = nullptr;
  13101. }
  13102. }
  13103. }
  13104. inline SSLServer::~SSLServer() {
  13105. if (ctx_) { tls::free_context(ctx_); }
  13106. }
  13107. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13108. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13109. using namespace tls;
  13110. // Create TLS session with mutex protection
  13111. session_t session = nullptr;
  13112. {
  13113. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13114. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13115. }
  13116. if (!session) {
  13117. last_ssl_error_ = static_cast<int>(get_error());
  13118. detail::shutdown_socket(sock);
  13119. detail::close_socket(sock);
  13120. return false;
  13121. }
  13122. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13123. bool handshake_done = false;
  13124. bool ret = false;
  13125. bool websocket_upgraded = false;
  13126. auto cleanup = detail::scope_exit([&] {
  13127. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13128. free_session(session);
  13129. detail::shutdown_socket(sock);
  13130. detail::close_socket(sock);
  13131. });
  13132. // Perform TLS accept handshake with timeout
  13133. TlsError tls_err;
  13134. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13135. &tls_err)) {
  13136. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13137. // Map TlsError to legacy ssl_error for backward compatibility
  13138. if (tls_err.code == ErrorCode::WantRead) {
  13139. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13140. } else if (tls_err.code == ErrorCode::WantWrite) {
  13141. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13142. } else {
  13143. last_ssl_error_ = SSL_ERROR_SSL;
  13144. }
  13145. #else
  13146. last_ssl_error_ = static_cast<int>(get_error());
  13147. #endif
  13148. return false;
  13149. }
  13150. handshake_done = true;
  13151. std::string remote_addr;
  13152. int remote_port = 0;
  13153. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13154. std::string local_addr;
  13155. int local_port = 0;
  13156. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13157. ret = detail::process_server_socket_ssl(
  13158. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13159. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13160. write_timeout_usec_,
  13161. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13162. return process_request(
  13163. strm, remote_addr, remote_port, local_addr, local_port,
  13164. close_connection, connection_closed,
  13165. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13166. });
  13167. return ret;
  13168. }
  13169. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13170. const char *key_pem,
  13171. const char *client_ca_pem,
  13172. const char *password) {
  13173. if (!ctx_) { return false; }
  13174. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13175. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13176. return false;
  13177. }
  13178. if (client_ca_pem) {
  13179. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13180. }
  13181. return true;
  13182. }
  13183. // SSL HTTP client implementation
  13184. inline SSLClient::~SSLClient() {
  13185. if (ctx_) { tls::free_context(ctx_); }
  13186. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13187. // base function rather than the derived function once we get to the
  13188. // base class destructor, and won't free the SSL (causing a leak).
  13189. shutdown_ssl_impl(socket_, true);
  13190. }
  13191. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13192. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13193. shutdown_ssl_impl(socket, shutdown_gracefully);
  13194. }
  13195. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13196. bool shutdown_gracefully) {
  13197. if (socket.sock == INVALID_SOCKET) {
  13198. assert(socket.ssl == nullptr);
  13199. return;
  13200. }
  13201. if (socket.ssl) {
  13202. tls::shutdown(socket.ssl, shutdown_gracefully);
  13203. {
  13204. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13205. tls::free_session(socket.ssl);
  13206. }
  13207. socket.ssl = nullptr;
  13208. }
  13209. assert(socket.ssl == nullptr);
  13210. }
  13211. inline bool SSLClient::process_socket(
  13212. const Socket &socket,
  13213. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13214. std::function<bool(Stream &strm)> callback) {
  13215. assert(socket.ssl);
  13216. return detail::process_client_socket_ssl(
  13217. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13218. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13219. std::move(callback));
  13220. }
  13221. inline bool SSLClient::is_ssl() const { return true; }
  13222. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13223. if (!is_valid()) {
  13224. error = Error::SSLConnection;
  13225. return false;
  13226. }
  13227. return ClientImpl::create_and_connect_socket(socket, error);
  13228. }
  13229. inline bool SSLClient::setup_proxy_connection(
  13230. Socket &socket,
  13231. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13232. Response &res, bool &success, Error &error) {
  13233. if (proxy_host_.empty() || proxy_port_ == -1) { return true; }
  13234. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13235. return false;
  13236. }
  13237. if (!initialize_ssl(socket, error)) {
  13238. success = false;
  13239. return false;
  13240. }
  13241. return true;
  13242. }
  13243. // Assumes that socket_mutex_ is locked and that there are no requests in
  13244. // flight
  13245. inline bool SSLClient::connect_with_proxy(
  13246. Socket &socket,
  13247. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13248. Response &res, bool &success, Error &error) {
  13249. success = true;
  13250. Response proxy_res;
  13251. if (!detail::process_client_socket(
  13252. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13253. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13254. start_time, [&](Stream &strm) {
  13255. Request req2;
  13256. req2.method = "CONNECT";
  13257. req2.path =
  13258. detail::make_host_and_port_string_always_port(host_, port_);
  13259. if (max_timeout_msec_ > 0) {
  13260. req2.start_time_ = std::chrono::steady_clock::now();
  13261. }
  13262. return process_request(strm, req2, proxy_res, false, error);
  13263. })) {
  13264. // Thread-safe to close everything because we are assuming there are no
  13265. // requests in flight
  13266. shutdown_ssl(socket, true);
  13267. shutdown_socket(socket);
  13268. close_socket(socket);
  13269. success = false;
  13270. return false;
  13271. }
  13272. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13273. if (!proxy_digest_auth_username_.empty() &&
  13274. !proxy_digest_auth_password_.empty()) {
  13275. std::map<std::string, std::string> auth;
  13276. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13277. // Close the current socket and create a new one for the authenticated
  13278. // request
  13279. shutdown_ssl(socket, true);
  13280. shutdown_socket(socket);
  13281. close_socket(socket);
  13282. // Create a new socket for the authenticated CONNECT request
  13283. if (!ensure_socket_connection(socket, error)) {
  13284. success = false;
  13285. output_error_log(error, nullptr);
  13286. return false;
  13287. }
  13288. proxy_res = Response();
  13289. if (!detail::process_client_socket(
  13290. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13291. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13292. start_time, [&](Stream &strm) {
  13293. Request req3;
  13294. req3.method = "CONNECT";
  13295. req3.path = detail::make_host_and_port_string_always_port(
  13296. host_, port_);
  13297. req3.headers.insert(detail::make_digest_authentication_header(
  13298. req3, auth, 1, detail::random_string(10),
  13299. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13300. true));
  13301. if (max_timeout_msec_ > 0) {
  13302. req3.start_time_ = std::chrono::steady_clock::now();
  13303. }
  13304. return process_request(strm, req3, proxy_res, false, error);
  13305. })) {
  13306. // Thread-safe to close everything because we are assuming there are
  13307. // no requests in flight
  13308. shutdown_ssl(socket, true);
  13309. shutdown_socket(socket);
  13310. close_socket(socket);
  13311. success = false;
  13312. return false;
  13313. }
  13314. }
  13315. }
  13316. }
  13317. // If status code is not 200, proxy request is failed.
  13318. // Set error to ProxyConnection and return proxy response
  13319. // as the response of the request
  13320. if (proxy_res.status != StatusCode::OK_200) {
  13321. error = Error::ProxyConnection;
  13322. output_error_log(error, nullptr);
  13323. res = std::move(proxy_res);
  13324. // Thread-safe to close everything because we are assuming there are
  13325. // no requests in flight
  13326. shutdown_ssl(socket, true);
  13327. shutdown_socket(socket);
  13328. close_socket(socket);
  13329. return false;
  13330. }
  13331. return true;
  13332. }
  13333. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13334. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13335. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  13336. if (!initialize_ssl(socket, error)) {
  13337. shutdown_socket(socket);
  13338. close_socket(socket);
  13339. return false;
  13340. }
  13341. return true;
  13342. }
  13343. // SSL HTTP client implementation
  13344. inline SSLClient::SSLClient(const std::string &host)
  13345. : SSLClient(host, 443, std::string(), std::string()) {}
  13346. inline SSLClient::SSLClient(const std::string &host, int port)
  13347. : SSLClient(host, port, std::string(), std::string()) {}
  13348. inline SSLClient::SSLClient(const std::string &host, int port,
  13349. const std::string &client_cert_path,
  13350. const std::string &client_key_path,
  13351. const std::string &private_key_password)
  13352. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13353. ctx_ = tls::create_client_context();
  13354. if (!ctx_) { return; }
  13355. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  13356. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13357. const char *password =
  13358. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13359. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13360. client_key_path.c_str(), password)) {
  13361. last_backend_error_ = tls::get_error();
  13362. tls::free_context(ctx_);
  13363. ctx_ = nullptr;
  13364. }
  13365. }
  13366. }
  13367. inline SSLClient::SSLClient(const std::string &host, int port,
  13368. const PemMemory &pem)
  13369. : ClientImpl(host, port) {
  13370. ctx_ = tls::create_client_context();
  13371. if (!ctx_) { return; }
  13372. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  13373. if (pem.cert_pem && pem.key_pem) {
  13374. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13375. pem.private_key_password)) {
  13376. last_backend_error_ = tls::get_error();
  13377. tls::free_context(ctx_);
  13378. ctx_ = nullptr;
  13379. }
  13380. }
  13381. }
  13382. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13383. if (ca_cert_store && ctx_) {
  13384. // set_ca_store takes ownership of ca_cert_store
  13385. tls::set_ca_store(ctx_, ca_cert_store);
  13386. } else if (ca_cert_store) {
  13387. tls::free_ca_store(ca_cert_store);
  13388. }
  13389. }
  13390. inline void
  13391. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13392. if (!ctx_) { return; }
  13393. tls::set_verify_callback(ctx_, verifier);
  13394. }
  13395. inline void SSLClient::set_session_verifier(
  13396. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13397. session_verifier_ = std::move(verifier);
  13398. }
  13399. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13400. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13401. enable_windows_cert_verification_ = enabled;
  13402. }
  13403. #endif
  13404. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13405. std::size_t size) {
  13406. if (ctx_ && ca_cert && size > 0) {
  13407. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13408. tls::load_ca_pem(ctx_, ca_cert, size);
  13409. }
  13410. }
  13411. inline bool SSLClient::load_certs() {
  13412. auto ret = true;
  13413. std::call_once(initialize_cert_, [&]() {
  13414. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13415. if (!ca_cert_file_path_.empty()) {
  13416. if (!tls::load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13417. last_backend_error_ = tls::get_error();
  13418. ret = false;
  13419. }
  13420. } else if (!ca_cert_dir_path_.empty()) {
  13421. if (!tls::load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13422. last_backend_error_ = tls::get_error();
  13423. ret = false;
  13424. }
  13425. } else if (ca_cert_pem_.empty()) {
  13426. if (!tls::load_system_certs(ctx_)) {
  13427. last_backend_error_ = tls::get_error();
  13428. }
  13429. }
  13430. });
  13431. return ret;
  13432. }
  13433. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13434. using namespace tls;
  13435. // Load CA certificates if server verification is enabled
  13436. if (server_certificate_verification_) {
  13437. if (!load_certs()) {
  13438. error = Error::SSLLoadingCerts;
  13439. output_error_log(error, nullptr);
  13440. return false;
  13441. }
  13442. }
  13443. bool is_ip = detail::is_ip_address(host_);
  13444. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13445. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13446. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13447. // For IP addresses with verification enabled, use OPTIONAL mode since
  13448. // these backends require hostname for strict verification.
  13449. if (is_ip && server_certificate_verification_) {
  13450. set_verify_client(ctx_, false);
  13451. } else {
  13452. set_verify_client(ctx_, server_certificate_verification_);
  13453. }
  13454. #endif
  13455. // Create TLS session
  13456. session_t session = nullptr;
  13457. {
  13458. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13459. session = create_session(ctx_, socket.sock);
  13460. }
  13461. if (!session) {
  13462. error = Error::SSLConnection;
  13463. last_backend_error_ = get_error();
  13464. return false;
  13465. }
  13466. // Use scope_exit to ensure session is freed on error paths
  13467. bool success = false;
  13468. auto session_guard = detail::scope_exit([&] {
  13469. if (!success) { free_session(session); }
  13470. });
  13471. // Set SNI extension (skip for IP addresses per RFC 6066).
  13472. // On MbedTLS, set_sni also enables hostname verification internally.
  13473. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13474. if (!is_ip) {
  13475. if (!set_sni(session, host_.c_str())) {
  13476. error = Error::SSLConnection;
  13477. last_backend_error_ = get_error();
  13478. return false;
  13479. }
  13480. }
  13481. // Perform non-blocking TLS handshake with timeout
  13482. TlsError tls_err;
  13483. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13484. connection_timeout_usec_, &tls_err)) {
  13485. last_ssl_error_ = static_cast<int>(tls_err.code);
  13486. last_backend_error_ = tls_err.backend_code;
  13487. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13488. error = Error::SSLServerVerification;
  13489. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13490. error = Error::SSLServerHostnameVerification;
  13491. } else {
  13492. error = Error::SSLConnection;
  13493. }
  13494. output_error_log(error, nullptr);
  13495. return false;
  13496. }
  13497. // Post-handshake session verifier callback
  13498. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13499. if (session_verifier_) { verification_status = session_verifier_(session); }
  13500. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13501. last_backend_error_ = get_error();
  13502. error = Error::SSLServerVerification;
  13503. output_error_log(error, nullptr);
  13504. return false;
  13505. }
  13506. // Default server certificate verification
  13507. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13508. server_certificate_verification_) {
  13509. verify_result_ = tls::get_verify_result(session);
  13510. if (verify_result_ != 0) {
  13511. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13512. error = Error::SSLServerVerification;
  13513. output_error_log(error, nullptr);
  13514. return false;
  13515. }
  13516. auto server_cert = get_peer_cert(session);
  13517. if (!server_cert) {
  13518. last_backend_error_ = get_error();
  13519. error = Error::SSLServerVerification;
  13520. output_error_log(error, nullptr);
  13521. return false;
  13522. }
  13523. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13524. // Hostname verification (post-handshake for all cases).
  13525. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13526. // On MbedTLS, set_sni already enabled hostname verification during
  13527. // handshake for non-IP hosts, but this check is still needed for IP
  13528. // addresses where SNI is not set.
  13529. if (server_hostname_verification_) {
  13530. if (!verify_hostname(server_cert, host_.c_str())) {
  13531. last_backend_error_ = hostname_mismatch_code();
  13532. error = Error::SSLServerHostnameVerification;
  13533. output_error_log(error, nullptr);
  13534. return false;
  13535. }
  13536. }
  13537. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13538. // Additional Windows Schannel verification.
  13539. // This provides real-time certificate validation with Windows Update
  13540. // integration, working with both OpenSSL and MbedTLS backends.
  13541. // Skip when a custom CA cert is specified, as the Windows certificate
  13542. // store would not know about user-provided CA certificates.
  13543. if (enable_windows_cert_verification_ && ca_cert_file_path_.empty() &&
  13544. ca_cert_dir_path_.empty() && ca_cert_pem_.empty()) {
  13545. std::vector<unsigned char> der;
  13546. if (get_cert_der(server_cert, der)) {
  13547. uint64_t wincrypt_error = 0;
  13548. if (!detail::verify_cert_with_windows_schannel(
  13549. der, host_, server_hostname_verification_, wincrypt_error)) {
  13550. last_backend_error_ = wincrypt_error;
  13551. error = Error::SSLServerVerification;
  13552. output_error_log(error, nullptr);
  13553. return false;
  13554. }
  13555. }
  13556. }
  13557. #endif
  13558. }
  13559. success = true;
  13560. socket.ssl = session;
  13561. return true;
  13562. }
  13563. inline void Client::set_digest_auth(const std::string &username,
  13564. const std::string &password) {
  13565. cli_->set_digest_auth(username, password);
  13566. }
  13567. inline void Client::set_proxy_digest_auth(const std::string &username,
  13568. const std::string &password) {
  13569. cli_->set_proxy_digest_auth(username, password);
  13570. }
  13571. inline void Client::enable_server_certificate_verification(bool enabled) {
  13572. cli_->enable_server_certificate_verification(enabled);
  13573. }
  13574. inline void Client::enable_server_hostname_verification(bool enabled) {
  13575. cli_->enable_server_hostname_verification(enabled);
  13576. }
  13577. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13578. inline void Client::enable_windows_certificate_verification(bool enabled) {
  13579. if (is_ssl_) {
  13580. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  13581. enabled);
  13582. }
  13583. }
  13584. #endif
  13585. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  13586. const std::string &ca_cert_dir_path) {
  13587. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  13588. }
  13589. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13590. if (is_ssl_) {
  13591. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  13592. } else if (ca_cert_store) {
  13593. tls::free_ca_store(ca_cert_store);
  13594. }
  13595. }
  13596. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  13597. set_ca_cert_store(tls::create_ca_store(ca_cert, size));
  13598. }
  13599. inline void
  13600. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13601. if (is_ssl_) {
  13602. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  13603. std::move(verifier));
  13604. }
  13605. }
  13606. inline void Client::set_session_verifier(
  13607. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13608. if (is_ssl_) {
  13609. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  13610. }
  13611. }
  13612. inline tls::ctx_t Client::tls_context() const {
  13613. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  13614. return nullptr;
  13615. }
  13616. #endif // CPPHTTPLIB_SSL_ENABLED
  13617. /*
  13618. * Group 7: TLS abstraction layer - Common API
  13619. */
  13620. #ifdef CPPHTTPLIB_SSL_ENABLED
  13621. namespace tls {
  13622. // Helper for PeerCert construction
  13623. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  13624. return PeerCert(get_peer_cert(session));
  13625. }
  13626. namespace impl {
  13627. inline VerifyCallback &get_verify_callback() {
  13628. static thread_local VerifyCallback callback;
  13629. return callback;
  13630. }
  13631. inline VerifyCallback &get_mbedtls_verify_callback() {
  13632. static thread_local VerifyCallback callback;
  13633. return callback;
  13634. }
  13635. // Check if a string is an IPv4 address
  13636. inline bool is_ipv4_address(const std::string &str) {
  13637. int dots = 0;
  13638. for (char c : str) {
  13639. if (c == '.') {
  13640. dots++;
  13641. } else if (!isdigit(static_cast<unsigned char>(c))) {
  13642. return false;
  13643. }
  13644. }
  13645. return dots == 3;
  13646. }
  13647. // Parse IPv4 address string to bytes
  13648. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  13649. const char *p = str.c_str();
  13650. for (int i = 0; i < 4; i++) {
  13651. if (i > 0) {
  13652. if (*p != '.') { return false; }
  13653. p++;
  13654. }
  13655. int val = 0;
  13656. int digits = 0;
  13657. while (*p >= '0' && *p <= '9') {
  13658. val = val * 10 + (*p - '0');
  13659. if (val > 255) { return false; }
  13660. p++;
  13661. digits++;
  13662. }
  13663. if (digits == 0) { return false; }
  13664. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  13665. if (digits > 1 && *(p - digits) == '0') { return false; }
  13666. out[i] = static_cast<unsigned char>(val);
  13667. }
  13668. return *p == '\0';
  13669. }
  13670. #ifdef _WIN32
  13671. // Enumerate Windows system certificates and call callback with DER data
  13672. template <typename Callback>
  13673. inline bool enumerate_windows_system_certs(Callback cb) {
  13674. bool loaded = false;
  13675. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13676. for (auto store_name : store_names) {
  13677. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  13678. if (hStore) {
  13679. PCCERT_CONTEXT pContext = nullptr;
  13680. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13681. nullptr) {
  13682. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  13683. loaded = true;
  13684. }
  13685. }
  13686. CertCloseStore(hStore, 0);
  13687. }
  13688. }
  13689. return loaded;
  13690. }
  13691. #endif
  13692. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  13693. // Enumerate macOS Keychain certificates and call callback with DER data
  13694. template <typename Callback>
  13695. inline bool enumerate_macos_keychain_certs(Callback cb) {
  13696. bool loaded = false;
  13697. CFArrayRef certs = nullptr;
  13698. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  13699. if (status == errSecSuccess && certs) {
  13700. CFIndex count = CFArrayGetCount(certs);
  13701. for (CFIndex i = 0; i < count; i++) {
  13702. SecCertificateRef cert =
  13703. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  13704. CFDataRef data = SecCertificateCopyData(cert);
  13705. if (data) {
  13706. if (cb(CFDataGetBytePtr(data),
  13707. static_cast<size_t>(CFDataGetLength(data)))) {
  13708. loaded = true;
  13709. }
  13710. CFRelease(data);
  13711. }
  13712. }
  13713. CFRelease(certs);
  13714. }
  13715. return loaded;
  13716. }
  13717. #endif
  13718. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  13719. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  13720. // Common CA certificate file paths on Linux/Unix
  13721. inline const char **system_ca_paths() {
  13722. static const char *paths[] = {
  13723. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  13724. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  13725. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  13726. "/etc/pki/tls/cacert.pem", // OpenELEC
  13727. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  13728. nullptr};
  13729. return paths;
  13730. }
  13731. // Common CA certificate directory paths on Linux/Unix
  13732. inline const char **system_ca_dirs() {
  13733. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  13734. "/etc/pki/tls/certs", // RHEL/CentOS
  13735. "/usr/share/ca-certificates", // Other
  13736. nullptr};
  13737. return dirs;
  13738. }
  13739. #endif
  13740. } // namespace impl
  13741. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  13742. const char *ca_dir) {
  13743. if (!ctx) { return false; }
  13744. bool success = true;
  13745. if (ca_file && *ca_file) {
  13746. if (!load_ca_file(ctx, ca_file)) { success = false; }
  13747. }
  13748. if (ca_dir && *ca_dir) {
  13749. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  13750. }
  13751. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13752. // Set CA list for client certificate request (CertificateRequest message)
  13753. if (ca_file && *ca_file) {
  13754. auto list = SSL_load_client_CA_file(ca_file);
  13755. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  13756. }
  13757. #endif
  13758. return success;
  13759. }
  13760. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13761. const char *password) {
  13762. return set_client_cert_pem(ctx, cert, key, password);
  13763. }
  13764. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  13765. const char *key_path, const char *password) {
  13766. return set_client_cert_file(ctx, cert_path, key_path, password);
  13767. }
  13768. // PeerCert implementation
  13769. inline PeerCert::PeerCert() = default;
  13770. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  13771. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  13772. other.cert_ = nullptr;
  13773. }
  13774. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  13775. if (this != &other) {
  13776. if (cert_) { free_cert(cert_); }
  13777. cert_ = other.cert_;
  13778. other.cert_ = nullptr;
  13779. }
  13780. return *this;
  13781. }
  13782. inline PeerCert::~PeerCert() {
  13783. if (cert_) { free_cert(cert_); }
  13784. }
  13785. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  13786. inline std::string PeerCert::subject_cn() const {
  13787. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  13788. }
  13789. inline std::string PeerCert::issuer_name() const {
  13790. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  13791. }
  13792. inline bool PeerCert::check_hostname(const char *hostname) const {
  13793. return cert_ ? verify_hostname(cert_, hostname) : false;
  13794. }
  13795. inline std::vector<SanEntry> PeerCert::sans() const {
  13796. std::vector<SanEntry> result;
  13797. if (cert_) { get_cert_sans(cert_, result); }
  13798. return result;
  13799. }
  13800. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  13801. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  13802. }
  13803. inline std::string PeerCert::serial() const {
  13804. return cert_ ? get_cert_serial(cert_) : std::string();
  13805. }
  13806. // VerifyContext method implementations
  13807. inline std::string VerifyContext::subject_cn() const {
  13808. return cert ? get_cert_subject_cn(cert) : std::string();
  13809. }
  13810. inline std::string VerifyContext::issuer_name() const {
  13811. return cert ? get_cert_issuer_name(cert) : std::string();
  13812. }
  13813. inline bool VerifyContext::check_hostname(const char *hostname) const {
  13814. return cert ? verify_hostname(cert, hostname) : false;
  13815. }
  13816. inline std::vector<SanEntry> VerifyContext::sans() const {
  13817. std::vector<SanEntry> result;
  13818. if (cert) { get_cert_sans(cert, result); }
  13819. return result;
  13820. }
  13821. inline bool VerifyContext::validity(time_t &not_before,
  13822. time_t &not_after) const {
  13823. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  13824. }
  13825. inline std::string VerifyContext::serial() const {
  13826. return cert ? get_cert_serial(cert) : std::string();
  13827. }
  13828. // TlsError static method implementation
  13829. inline std::string TlsError::verify_error_to_string(long error_code) {
  13830. return verify_error_string(error_code);
  13831. }
  13832. } // namespace tls
  13833. // Request::peer_cert() implementation
  13834. inline tls::PeerCert Request::peer_cert() const {
  13835. return tls::get_peer_cert_from_session(ssl);
  13836. }
  13837. // Request::sni() implementation
  13838. inline std::string Request::sni() const {
  13839. if (!ssl) { return std::string(); }
  13840. const char *s = tls::get_sni(ssl);
  13841. return s ? std::string(s) : std::string();
  13842. }
  13843. #endif // CPPHTTPLIB_SSL_ENABLED
  13844. /*
  13845. * Group 8: TLS abstraction layer - OpenSSL backend
  13846. */
  13847. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13848. inline SSL_CTX *Client::ssl_context() const {
  13849. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  13850. return nullptr;
  13851. }
  13852. inline void Client::set_server_certificate_verifier(
  13853. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  13854. cli_->set_server_certificate_verifier(verifier);
  13855. }
  13856. inline long Client::get_verify_result() const {
  13857. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).get_verify_result(); }
  13858. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  13859. }
  13860. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  13861. /*
  13862. * OpenSSL Backend Implementation
  13863. */
  13864. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13865. namespace tls {
  13866. namespace impl {
  13867. // OpenSSL-specific helpers for converting native types to PEM
  13868. inline std::string x509_to_pem(X509 *cert) {
  13869. if (!cert) return {};
  13870. BIO *bio = BIO_new(BIO_s_mem());
  13871. if (!bio) return {};
  13872. if (PEM_write_bio_X509(bio, cert) != 1) {
  13873. BIO_free(bio);
  13874. return {};
  13875. }
  13876. char *data = nullptr;
  13877. long len = BIO_get_mem_data(bio, &data);
  13878. std::string pem(data, static_cast<size_t>(len));
  13879. BIO_free(bio);
  13880. return pem;
  13881. }
  13882. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  13883. if (!key) return {};
  13884. BIO *bio = BIO_new(BIO_s_mem());
  13885. if (!bio) return {};
  13886. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  13887. nullptr) != 1) {
  13888. BIO_free(bio);
  13889. return {};
  13890. }
  13891. char *data = nullptr;
  13892. long len = BIO_get_mem_data(bio, &data);
  13893. std::string pem(data, static_cast<size_t>(len));
  13894. BIO_free(bio);
  13895. return pem;
  13896. }
  13897. inline std::string x509_store_to_pem(X509_STORE *store) {
  13898. if (!store) return {};
  13899. std::string pem;
  13900. auto objs = X509_STORE_get0_objects(store);
  13901. if (!objs) return {};
  13902. auto count = sk_X509_OBJECT_num(objs);
  13903. for (decltype(count) i = 0; i < count; i++) {
  13904. auto obj = sk_X509_OBJECT_value(objs, i);
  13905. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13906. auto cert = X509_OBJECT_get0_X509(obj);
  13907. if (cert) { pem += x509_to_pem(cert); }
  13908. }
  13909. }
  13910. return pem;
  13911. }
  13912. // Helper to map OpenSSL SSL_get_error to ErrorCode
  13913. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  13914. switch (ssl_error) {
  13915. case SSL_ERROR_NONE: return ErrorCode::Success;
  13916. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  13917. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  13918. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  13919. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  13920. case SSL_ERROR_SSL:
  13921. default: return ErrorCode::Fatal;
  13922. }
  13923. }
  13924. // Helper: Create client CA list from PEM string
  13925. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  13926. // Caller takes ownership of returned list
  13927. inline STACK_OF(X509_NAME) *
  13928. create_client_ca_list_from_pem(const char *ca_pem) {
  13929. if (!ca_pem) { return nullptr; }
  13930. auto ca_list = sk_X509_NAME_new_null();
  13931. if (!ca_list) { return nullptr; }
  13932. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  13933. if (!bio) {
  13934. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  13935. return nullptr;
  13936. }
  13937. X509 *cert = nullptr;
  13938. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  13939. nullptr) {
  13940. X509_NAME *name = X509_get_subject_name(cert);
  13941. if (name) { sk_X509_NAME_push(ca_list, X509_NAME_dup(name)); }
  13942. X509_free(cert);
  13943. }
  13944. BIO_free(bio);
  13945. return ca_list;
  13946. }
  13947. // Helper: Extract CA names from X509_STORE
  13948. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  13949. // Caller takes ownership of returned list
  13950. inline STACK_OF(X509_NAME) *
  13951. extract_client_ca_list_from_store(X509_STORE *store) {
  13952. if (!store) { return nullptr; }
  13953. auto ca_list = sk_X509_NAME_new_null();
  13954. if (!ca_list) { return nullptr; }
  13955. auto objs = X509_STORE_get0_objects(store);
  13956. if (!objs) {
  13957. sk_X509_NAME_free(ca_list);
  13958. return nullptr;
  13959. }
  13960. auto count = sk_X509_OBJECT_num(objs);
  13961. for (decltype(count) i = 0; i < count; i++) {
  13962. auto obj = sk_X509_OBJECT_value(objs, i);
  13963. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13964. auto cert = X509_OBJECT_get0_X509(obj);
  13965. if (cert) {
  13966. auto subject = X509_get_subject_name(cert);
  13967. if (subject) {
  13968. auto name_dup = X509_NAME_dup(subject);
  13969. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  13970. }
  13971. }
  13972. }
  13973. }
  13974. if (sk_X509_NAME_num(ca_list) == 0) {
  13975. sk_X509_NAME_free(ca_list);
  13976. return nullptr;
  13977. }
  13978. return ca_list;
  13979. }
  13980. // OpenSSL verify callback wrapper
  13981. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  13982. auto &callback = get_verify_callback();
  13983. if (!callback) { return preverify_ok; }
  13984. // Get SSL object from X509_STORE_CTX
  13985. auto ssl = static_cast<SSL *>(
  13986. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  13987. if (!ssl) { return preverify_ok; }
  13988. // Get current certificate and depth
  13989. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  13990. int depth = X509_STORE_CTX_get_error_depth(ctx);
  13991. int error = X509_STORE_CTX_get_error(ctx);
  13992. // Build context
  13993. VerifyContext verify_ctx;
  13994. verify_ctx.session = static_cast<session_t>(ssl);
  13995. verify_ctx.cert = static_cast<cert_t>(cert);
  13996. verify_ctx.depth = depth;
  13997. verify_ctx.preverify_ok = (preverify_ok != 0);
  13998. verify_ctx.error_code = error;
  13999. verify_ctx.error_string =
  14000. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14001. return callback(verify_ctx) ? 1 : 0;
  14002. }
  14003. } // namespace impl
  14004. inline ctx_t create_client_context() {
  14005. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14006. if (ctx) {
  14007. // Disable auto-retry to properly handle non-blocking I/O
  14008. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14009. // Set minimum TLS version
  14010. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14011. }
  14012. return static_cast<ctx_t>(ctx);
  14013. }
  14014. inline void free_context(ctx_t ctx) {
  14015. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14016. }
  14017. inline bool set_min_version(ctx_t ctx, Version version) {
  14018. if (!ctx) return false;
  14019. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14020. static_cast<int>(version)) == 1;
  14021. }
  14022. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14023. if (!ctx || !pem || len == 0) return false;
  14024. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14025. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14026. if (!store) return false;
  14027. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14028. if (!bio) return false;
  14029. bool ok = true;
  14030. X509 *cert = nullptr;
  14031. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14032. nullptr) {
  14033. if (X509_STORE_add_cert(store, cert) != 1) {
  14034. // Ignore duplicate errors
  14035. auto err = ERR_peek_last_error();
  14036. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14037. ok = false;
  14038. }
  14039. }
  14040. X509_free(cert);
  14041. if (!ok) break;
  14042. }
  14043. BIO_free(bio);
  14044. // Clear any "no more certificates" errors
  14045. ERR_clear_error();
  14046. return ok;
  14047. }
  14048. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14049. if (!ctx || !file_path) return false;
  14050. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14051. nullptr) == 1;
  14052. }
  14053. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14054. if (!ctx || !dir_path) return false;
  14055. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14056. dir_path) == 1;
  14057. }
  14058. inline bool load_system_certs(ctx_t ctx) {
  14059. if (!ctx) return false;
  14060. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14061. #ifdef _WIN32
  14062. // Windows: Load from system certificate store (ROOT and CA)
  14063. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14064. if (!store) return false;
  14065. bool loaded_any = false;
  14066. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14067. for (auto store_name : store_names) {
  14068. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14069. if (!hStore) continue;
  14070. PCCERT_CONTEXT pContext = nullptr;
  14071. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14072. nullptr) {
  14073. const unsigned char *data = pContext->pbCertEncoded;
  14074. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14075. if (x509) {
  14076. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14077. X509_free(x509);
  14078. }
  14079. }
  14080. CertCloseStore(hStore, 0);
  14081. }
  14082. return loaded_any;
  14083. #elif defined(__APPLE__)
  14084. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14085. // macOS: Load from Keychain
  14086. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14087. if (!store) return false;
  14088. CFArrayRef certs = nullptr;
  14089. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  14090. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14091. }
  14092. bool loaded_any = false;
  14093. auto count = CFArrayGetCount(certs);
  14094. for (CFIndex i = 0; i < count; i++) {
  14095. auto cert = reinterpret_cast<SecCertificateRef>(
  14096. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14097. CFDataRef der = SecCertificateCopyData(cert);
  14098. if (der) {
  14099. const unsigned char *data = CFDataGetBytePtr(der);
  14100. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14101. if (x509) {
  14102. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14103. X509_free(x509);
  14104. }
  14105. CFRelease(der);
  14106. }
  14107. }
  14108. CFRelease(certs);
  14109. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14110. #else
  14111. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14112. #endif
  14113. #else
  14114. // Other Unix: use default verify paths
  14115. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14116. #endif
  14117. }
  14118. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14119. const char *password) {
  14120. if (!ctx || !cert || !key) return false;
  14121. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14122. // Load certificate
  14123. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14124. if (!cert_bio) return false;
  14125. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14126. BIO_free(cert_bio);
  14127. if (!x509) return false;
  14128. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14129. X509_free(x509);
  14130. if (!cert_ok) return false;
  14131. // Load private key
  14132. auto key_bio = BIO_new_mem_buf(key, -1);
  14133. if (!key_bio) return false;
  14134. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14135. password ? const_cast<char *>(password)
  14136. : nullptr);
  14137. BIO_free(key_bio);
  14138. if (!pkey) return false;
  14139. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14140. EVP_PKEY_free(pkey);
  14141. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14142. }
  14143. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14144. const char *key_path, const char *password) {
  14145. if (!ctx || !cert_path || !key_path) return false;
  14146. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14147. if (password && password[0] != '\0') {
  14148. SSL_CTX_set_default_passwd_cb_userdata(
  14149. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14150. }
  14151. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14152. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14153. }
  14154. inline ctx_t create_server_context() {
  14155. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14156. if (ctx) {
  14157. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14158. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14159. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14160. }
  14161. return static_cast<ctx_t>(ctx);
  14162. }
  14163. inline void set_verify_client(ctx_t ctx, bool require) {
  14164. if (!ctx) return;
  14165. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14166. require
  14167. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14168. : SSL_VERIFY_NONE,
  14169. nullptr);
  14170. }
  14171. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14172. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14173. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14174. SSL *ssl = SSL_new(ssl_ctx);
  14175. if (!ssl) return nullptr;
  14176. // Disable auto-retry for proper non-blocking I/O handling
  14177. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14178. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14179. if (!bio) {
  14180. SSL_free(ssl);
  14181. return nullptr;
  14182. }
  14183. SSL_set_bio(ssl, bio, bio);
  14184. return static_cast<session_t>(ssl);
  14185. }
  14186. inline void free_session(session_t session) {
  14187. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14188. }
  14189. inline bool set_sni(session_t session, const char *hostname) {
  14190. if (!session || !hostname) return false;
  14191. auto ssl = static_cast<SSL *>(session);
  14192. // Set SNI (Server Name Indication) only - does not enable verification
  14193. #if defined(OPENSSL_IS_BORINGSSL)
  14194. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14195. #else
  14196. // Direct call instead of macro to suppress -Wold-style-cast warning
  14197. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14198. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14199. #endif
  14200. }
  14201. inline bool set_hostname(session_t session, const char *hostname) {
  14202. if (!session || !hostname) return false;
  14203. auto ssl = static_cast<SSL *>(session);
  14204. // Set SNI (Server Name Indication)
  14205. if (!set_sni(session, hostname)) { return false; }
  14206. // Enable hostname verification
  14207. auto param = SSL_get0_param(ssl);
  14208. if (!param) return false;
  14209. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14210. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14211. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14212. return true;
  14213. }
  14214. inline TlsError connect(session_t session) {
  14215. if (!session) { return TlsError(); }
  14216. auto ssl = static_cast<SSL *>(session);
  14217. auto ret = SSL_connect(ssl);
  14218. TlsError err;
  14219. if (ret == 1) {
  14220. err.code = ErrorCode::Success;
  14221. } else {
  14222. auto ssl_err = SSL_get_error(ssl, ret);
  14223. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14224. err.backend_code = ERR_get_error();
  14225. }
  14226. return err;
  14227. }
  14228. inline TlsError accept(session_t session) {
  14229. if (!session) { return TlsError(); }
  14230. auto ssl = static_cast<SSL *>(session);
  14231. auto ret = SSL_accept(ssl);
  14232. TlsError err;
  14233. if (ret == 1) {
  14234. err.code = ErrorCode::Success;
  14235. } else {
  14236. auto ssl_err = SSL_get_error(ssl, ret);
  14237. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14238. err.backend_code = ERR_get_error();
  14239. }
  14240. return err;
  14241. }
  14242. inline bool connect_nonblocking(session_t session, socket_t sock,
  14243. time_t timeout_sec, time_t timeout_usec,
  14244. TlsError *err) {
  14245. if (!session) {
  14246. if (err) { err->code = ErrorCode::Fatal; }
  14247. return false;
  14248. }
  14249. auto ssl = static_cast<SSL *>(session);
  14250. auto bio = SSL_get_rbio(ssl);
  14251. // Set non-blocking mode for handshake
  14252. detail::set_nonblocking(sock, true);
  14253. if (bio) { BIO_set_nbio(bio, 1); }
  14254. auto cleanup = detail::scope_exit([&]() {
  14255. // Restore blocking mode after handshake
  14256. if (bio) { BIO_set_nbio(bio, 0); }
  14257. detail::set_nonblocking(sock, false);
  14258. });
  14259. auto res = 0;
  14260. while ((res = SSL_connect(ssl)) != 1) {
  14261. auto ssl_err = SSL_get_error(ssl, res);
  14262. switch (ssl_err) {
  14263. case SSL_ERROR_WANT_READ:
  14264. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14265. continue;
  14266. }
  14267. break;
  14268. case SSL_ERROR_WANT_WRITE:
  14269. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14270. continue;
  14271. }
  14272. break;
  14273. default: break;
  14274. }
  14275. if (err) {
  14276. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14277. err->backend_code = ERR_get_error();
  14278. }
  14279. return false;
  14280. }
  14281. if (err) { err->code = ErrorCode::Success; }
  14282. return true;
  14283. }
  14284. inline bool accept_nonblocking(session_t session, socket_t sock,
  14285. time_t timeout_sec, time_t timeout_usec,
  14286. TlsError *err) {
  14287. if (!session) {
  14288. if (err) { err->code = ErrorCode::Fatal; }
  14289. return false;
  14290. }
  14291. auto ssl = static_cast<SSL *>(session);
  14292. auto bio = SSL_get_rbio(ssl);
  14293. // Set non-blocking mode for handshake
  14294. detail::set_nonblocking(sock, true);
  14295. if (bio) { BIO_set_nbio(bio, 1); }
  14296. auto cleanup = detail::scope_exit([&]() {
  14297. // Restore blocking mode after handshake
  14298. if (bio) { BIO_set_nbio(bio, 0); }
  14299. detail::set_nonblocking(sock, false);
  14300. });
  14301. auto res = 0;
  14302. while ((res = SSL_accept(ssl)) != 1) {
  14303. auto ssl_err = SSL_get_error(ssl, res);
  14304. switch (ssl_err) {
  14305. case SSL_ERROR_WANT_READ:
  14306. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14307. continue;
  14308. }
  14309. break;
  14310. case SSL_ERROR_WANT_WRITE:
  14311. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14312. continue;
  14313. }
  14314. break;
  14315. default: break;
  14316. }
  14317. if (err) {
  14318. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14319. err->backend_code = ERR_get_error();
  14320. }
  14321. return false;
  14322. }
  14323. if (err) { err->code = ErrorCode::Success; }
  14324. return true;
  14325. }
  14326. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14327. if (!session || !buf) {
  14328. err.code = ErrorCode::Fatal;
  14329. return -1;
  14330. }
  14331. auto ssl = static_cast<SSL *>(session);
  14332. constexpr auto max_len =
  14333. static_cast<size_t>((std::numeric_limits<int>::max)());
  14334. if (len > max_len) { len = max_len; }
  14335. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14336. if (ret > 0) {
  14337. err.code = ErrorCode::Success;
  14338. return ret;
  14339. }
  14340. auto ssl_err = SSL_get_error(ssl, ret);
  14341. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14342. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14343. return -1;
  14344. }
  14345. inline ssize_t write(session_t session, const void *buf, size_t len,
  14346. TlsError &err) {
  14347. if (!session || !buf) {
  14348. err.code = ErrorCode::Fatal;
  14349. return -1;
  14350. }
  14351. auto ssl = static_cast<SSL *>(session);
  14352. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14353. if (ret > 0) {
  14354. err.code = ErrorCode::Success;
  14355. return ret;
  14356. }
  14357. auto ssl_err = SSL_get_error(ssl, ret);
  14358. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14359. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14360. return -1;
  14361. }
  14362. inline int pending(const_session_t session) {
  14363. if (!session) return 0;
  14364. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14365. }
  14366. inline void shutdown(session_t session, bool graceful) {
  14367. if (!session) return;
  14368. auto ssl = static_cast<SSL *>(session);
  14369. if (graceful) {
  14370. // First call sends close_notify
  14371. if (SSL_shutdown(ssl) == 0) {
  14372. // Second call waits for peer's close_notify
  14373. SSL_shutdown(ssl);
  14374. }
  14375. }
  14376. }
  14377. inline bool is_peer_closed(session_t session, socket_t sock) {
  14378. if (!session) return true;
  14379. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14380. detail::set_nonblocking(sock, true);
  14381. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14382. auto ssl = static_cast<SSL *>(session);
  14383. char buf;
  14384. auto ret = SSL_peek(ssl, &buf, 1);
  14385. if (ret > 0) return false;
  14386. auto err = SSL_get_error(ssl, ret);
  14387. return err == SSL_ERROR_ZERO_RETURN;
  14388. }
  14389. inline cert_t get_peer_cert(const_session_t session) {
  14390. if (!session) return nullptr;
  14391. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14392. static_cast<SSL *>(const_cast<void *>(session))));
  14393. }
  14394. inline void free_cert(cert_t cert) {
  14395. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14396. }
  14397. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14398. if (!cert || !hostname) return false;
  14399. auto x509 = static_cast<X509 *>(cert);
  14400. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14401. if (detail::is_ip_address(hostname)) {
  14402. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14403. }
  14404. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14405. }
  14406. inline uint64_t hostname_mismatch_code() {
  14407. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14408. }
  14409. inline long get_verify_result(const_session_t session) {
  14410. if (!session) return X509_V_ERR_UNSPECIFIED;
  14411. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14412. }
  14413. inline std::string get_cert_subject_cn(cert_t cert) {
  14414. if (!cert) return "";
  14415. auto x509 = static_cast<X509 *>(cert);
  14416. auto subject_name = X509_get_subject_name(x509);
  14417. if (!subject_name) return "";
  14418. char buf[256];
  14419. auto len =
  14420. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  14421. if (len < 0) return "";
  14422. return std::string(buf, static_cast<size_t>(len));
  14423. }
  14424. inline std::string get_cert_issuer_name(cert_t cert) {
  14425. if (!cert) return "";
  14426. auto x509 = static_cast<X509 *>(cert);
  14427. auto issuer_name = X509_get_issuer_name(x509);
  14428. if (!issuer_name) return "";
  14429. char buf[256];
  14430. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14431. return std::string(buf);
  14432. }
  14433. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14434. sans.clear();
  14435. if (!cert) return false;
  14436. auto x509 = static_cast<X509 *>(cert);
  14437. auto names = static_cast<GENERAL_NAMES *>(
  14438. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14439. if (!names) return true; // No SANs is valid
  14440. auto count = sk_GENERAL_NAME_num(names);
  14441. for (decltype(count) i = 0; i < count; i++) {
  14442. auto gen = sk_GENERAL_NAME_value(names, i);
  14443. if (!gen) continue;
  14444. SanEntry entry;
  14445. switch (gen->type) {
  14446. case GEN_DNS:
  14447. entry.type = SanType::DNS;
  14448. if (gen->d.dNSName) {
  14449. entry.value = std::string(
  14450. reinterpret_cast<const char *>(
  14451. ASN1_STRING_get0_data(gen->d.dNSName)),
  14452. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14453. }
  14454. break;
  14455. case GEN_IPADD:
  14456. entry.type = SanType::IP;
  14457. if (gen->d.iPAddress) {
  14458. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14459. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14460. if (len == 4) {
  14461. // IPv4
  14462. char buf[INET_ADDRSTRLEN];
  14463. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14464. entry.value = buf;
  14465. } else if (len == 16) {
  14466. // IPv6
  14467. char buf[INET6_ADDRSTRLEN];
  14468. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14469. entry.value = buf;
  14470. }
  14471. }
  14472. break;
  14473. case GEN_EMAIL:
  14474. entry.type = SanType::EMAIL;
  14475. if (gen->d.rfc822Name) {
  14476. entry.value = std::string(
  14477. reinterpret_cast<const char *>(
  14478. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14479. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14480. }
  14481. break;
  14482. case GEN_URI:
  14483. entry.type = SanType::URI;
  14484. if (gen->d.uniformResourceIdentifier) {
  14485. entry.value = std::string(
  14486. reinterpret_cast<const char *>(
  14487. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14488. static_cast<size_t>(
  14489. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14490. }
  14491. break;
  14492. default: entry.type = SanType::OTHER; break;
  14493. }
  14494. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14495. }
  14496. GENERAL_NAMES_free(names);
  14497. return true;
  14498. }
  14499. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14500. time_t &not_after) {
  14501. if (!cert) return false;
  14502. auto x509 = static_cast<X509 *>(cert);
  14503. auto nb = X509_get0_notBefore(x509);
  14504. auto na = X509_get0_notAfter(x509);
  14505. if (!nb || !na) return false;
  14506. ASN1_TIME *epoch = ASN1_TIME_new();
  14507. if (!epoch) return false;
  14508. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14509. if (!ASN1_TIME_set(epoch, 0)) return false;
  14510. int pday, psec;
  14511. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14512. not_before = 86400 * (time_t)pday + psec;
  14513. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14514. not_after = 86400 * (time_t)pday + psec;
  14515. return true;
  14516. }
  14517. inline std::string get_cert_serial(cert_t cert) {
  14518. if (!cert) return "";
  14519. auto x509 = static_cast<X509 *>(cert);
  14520. auto serial = X509_get_serialNumber(x509);
  14521. if (!serial) return "";
  14522. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14523. if (!bn) return "";
  14524. auto hex = BN_bn2hex(bn);
  14525. BN_free(bn);
  14526. if (!hex) return "";
  14527. std::string result(hex);
  14528. OPENSSL_free(hex);
  14529. return result;
  14530. }
  14531. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14532. if (!cert) return false;
  14533. auto x509 = static_cast<X509 *>(cert);
  14534. auto len = i2d_X509(x509, nullptr);
  14535. if (len < 0) return false;
  14536. der.resize(static_cast<size_t>(len));
  14537. auto p = der.data();
  14538. i2d_X509(x509, &p);
  14539. return true;
  14540. }
  14541. inline const char *get_sni(const_session_t session) {
  14542. if (!session) return nullptr;
  14543. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14544. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14545. }
  14546. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14547. inline uint64_t get_error() { return ERR_get_error(); }
  14548. inline std::string error_string(uint64_t code) {
  14549. char buf[256];
  14550. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14551. return std::string(buf);
  14552. }
  14553. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14554. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14555. if (!mem) { return nullptr; }
  14556. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14557. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14558. if (!inf) { return nullptr; }
  14559. auto store = X509_STORE_new();
  14560. if (store) {
  14561. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  14562. auto itmp = sk_X509_INFO_value(inf, i);
  14563. if (!itmp) { continue; }
  14564. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  14565. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  14566. }
  14567. }
  14568. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  14569. return static_cast<ca_store_t>(store);
  14570. }
  14571. inline void free_ca_store(ca_store_t store) {
  14572. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  14573. }
  14574. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14575. if (!ctx || !store) { return false; }
  14576. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14577. auto x509_store = static_cast<X509_STORE *>(store);
  14578. // Check if same store is already set
  14579. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  14580. // SSL_CTX_set_cert_store takes ownership and frees the old store
  14581. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  14582. return true;
  14583. }
  14584. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14585. certs.clear();
  14586. if (!ctx) { return 0; }
  14587. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14588. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14589. if (!store) { return 0; }
  14590. auto objs = X509_STORE_get0_objects(store);
  14591. if (!objs) { return 0; }
  14592. auto count = sk_X509_OBJECT_num(objs);
  14593. for (decltype(count) i = 0; i < count; i++) {
  14594. auto obj = sk_X509_OBJECT_value(objs, i);
  14595. if (!obj) { continue; }
  14596. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14597. auto x509 = X509_OBJECT_get0_X509(obj);
  14598. if (x509) {
  14599. // Increment reference count so caller can free it
  14600. X509_up_ref(x509);
  14601. certs.push_back(static_cast<cert_t>(x509));
  14602. }
  14603. }
  14604. }
  14605. return certs.size();
  14606. }
  14607. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  14608. std::vector<std::string> names;
  14609. if (!ctx) { return names; }
  14610. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14611. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14612. if (!store) { return names; }
  14613. auto objs = X509_STORE_get0_objects(store);
  14614. if (!objs) { return names; }
  14615. auto count = sk_X509_OBJECT_num(objs);
  14616. for (decltype(count) i = 0; i < count; i++) {
  14617. auto obj = sk_X509_OBJECT_value(objs, i);
  14618. if (!obj) { continue; }
  14619. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14620. auto x509 = X509_OBJECT_get0_X509(obj);
  14621. if (x509) {
  14622. auto subject = X509_get_subject_name(x509);
  14623. if (subject) {
  14624. char buf[512];
  14625. X509_NAME_oneline(subject, buf, sizeof(buf));
  14626. names.push_back(buf);
  14627. }
  14628. }
  14629. }
  14630. }
  14631. return names;
  14632. }
  14633. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  14634. const char *key_pem, const char *password) {
  14635. if (!ctx || !cert_pem || !key_pem) { return false; }
  14636. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14637. // Load certificate from PEM
  14638. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  14639. if (!cert_bio) { return false; }
  14640. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14641. BIO_free(cert_bio);
  14642. if (!cert) { return false; }
  14643. // Load private key from PEM
  14644. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  14645. if (!key_bio) {
  14646. X509_free(cert);
  14647. return false;
  14648. }
  14649. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14650. password ? const_cast<char *>(password)
  14651. : nullptr);
  14652. BIO_free(key_bio);
  14653. if (!key) {
  14654. X509_free(cert);
  14655. return false;
  14656. }
  14657. // Update certificate and key
  14658. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  14659. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  14660. X509_free(cert);
  14661. EVP_PKEY_free(key);
  14662. return ret;
  14663. }
  14664. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  14665. if (!ctx || !ca_pem) { return false; }
  14666. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14667. // Create new X509_STORE from PEM
  14668. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  14669. if (!store) { return false; }
  14670. // SSL_CTX_set_cert_store takes ownership
  14671. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  14672. // Set client CA list for client certificate request
  14673. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  14674. if (ca_list) {
  14675. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  14676. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  14677. }
  14678. return true;
  14679. }
  14680. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  14681. if (!ctx) { return false; }
  14682. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14683. impl::get_verify_callback() = std::move(callback);
  14684. if (impl::get_verify_callback()) {
  14685. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  14686. } else {
  14687. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  14688. }
  14689. return true;
  14690. }
  14691. inline long get_verify_error(const_session_t session) {
  14692. if (!session) { return -1; }
  14693. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14694. return SSL_get_verify_result(ssl);
  14695. }
  14696. inline std::string verify_error_string(long error_code) {
  14697. if (error_code == X509_V_OK) { return ""; }
  14698. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  14699. return str ? str : "unknown error";
  14700. }
  14701. namespace impl {
  14702. // OpenSSL-specific helpers for public API wrappers
  14703. inline ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  14704. X509_STORE *client_ca_store,
  14705. int &out_error) {
  14706. out_error = 0;
  14707. auto cert_pem = x509_to_pem(cert);
  14708. auto key_pem = evp_pkey_to_pem(key);
  14709. if (cert_pem.empty() || key_pem.empty()) {
  14710. out_error = static_cast<int>(ERR_get_error());
  14711. return nullptr;
  14712. }
  14713. auto ctx = create_server_context();
  14714. if (!ctx) {
  14715. out_error = static_cast<int>(get_error());
  14716. return nullptr;
  14717. }
  14718. if (!set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr)) {
  14719. out_error = static_cast<int>(get_error());
  14720. free_context(ctx);
  14721. return nullptr;
  14722. }
  14723. if (client_ca_store) {
  14724. // Set cert store for verification (SSL_CTX_set_cert_store takes ownership)
  14725. SSL_CTX_set_cert_store(static_cast<SSL_CTX *>(ctx), client_ca_store);
  14726. // Extract and set client CA list directly from store (more efficient than
  14727. // PEM conversion)
  14728. auto ca_list = extract_client_ca_list_from_store(client_ca_store);
  14729. if (ca_list) {
  14730. SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), ca_list);
  14731. }
  14732. set_verify_client(ctx, true);
  14733. }
  14734. return ctx;
  14735. }
  14736. inline void update_server_certs_from_x509(ctx_t ctx, X509 *cert, EVP_PKEY *key,
  14737. X509_STORE *client_ca_store) {
  14738. auto cert_pem = x509_to_pem(cert);
  14739. auto key_pem = evp_pkey_to_pem(key);
  14740. if (!cert_pem.empty() && !key_pem.empty()) {
  14741. update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  14742. }
  14743. if (client_ca_store) {
  14744. auto ca_pem = x509_store_to_pem(client_ca_store);
  14745. if (!ca_pem.empty()) { update_server_client_ca(ctx, ca_pem.c_str()); }
  14746. X509_STORE_free(client_ca_store);
  14747. }
  14748. }
  14749. inline ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  14750. const char *password,
  14751. uint64_t &out_error) {
  14752. out_error = 0;
  14753. auto ctx = create_client_context();
  14754. if (!ctx) {
  14755. out_error = get_error();
  14756. return nullptr;
  14757. }
  14758. if (cert && key) {
  14759. auto cert_pem = x509_to_pem(cert);
  14760. auto key_pem = evp_pkey_to_pem(key);
  14761. if (cert_pem.empty() || key_pem.empty()) {
  14762. out_error = ERR_get_error();
  14763. free_context(ctx);
  14764. return nullptr;
  14765. }
  14766. if (!set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  14767. password)) {
  14768. out_error = get_error();
  14769. free_context(ctx);
  14770. return nullptr;
  14771. }
  14772. }
  14773. return ctx;
  14774. }
  14775. } // namespace impl
  14776. } // namespace tls
  14777. // ClientImpl::set_ca_cert_store - defined here to use
  14778. // tls::impl::x509_store_to_pem Deprecated: converts X509_STORE to PEM and
  14779. // stores for redirect transfer
  14780. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  14781. if (ca_cert_store) {
  14782. ca_cert_pem_ = tls::impl::x509_store_to_pem(ca_cert_store);
  14783. }
  14784. }
  14785. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  14786. X509_STORE *client_ca_cert_store) {
  14787. ctx_ = tls::impl::create_server_context_from_x509(
  14788. cert, private_key, client_ca_cert_store, last_ssl_error_);
  14789. }
  14790. inline SSLServer::SSLServer(
  14791. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  14792. // Use abstract API to create context
  14793. ctx_ = tls::create_server_context();
  14794. if (ctx_) {
  14795. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  14796. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  14797. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  14798. tls::free_context(ctx_);
  14799. ctx_ = nullptr;
  14800. }
  14801. }
  14802. }
  14803. inline SSL_CTX *SSLServer::ssl_context() const {
  14804. return static_cast<SSL_CTX *>(ctx_);
  14805. }
  14806. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  14807. X509_STORE *client_ca_cert_store) {
  14808. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14809. tls::impl::update_server_certs_from_x509(ctx_, cert, private_key,
  14810. client_ca_cert_store);
  14811. }
  14812. inline SSLClient::SSLClient(const std::string &host, int port,
  14813. X509 *client_cert, EVP_PKEY *client_key,
  14814. const std::string &private_key_password)
  14815. : ClientImpl(host, port) {
  14816. const char *password =
  14817. private_key_password.empty() ? nullptr : private_key_password.c_str();
  14818. ctx_ = tls::impl::create_client_context_from_x509(
  14819. client_cert, client_key, password, last_backend_error_);
  14820. }
  14821. inline long SSLClient::get_verify_result() const { return verify_result_; }
  14822. inline void SSLClient::set_server_certificate_verifier(
  14823. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  14824. // Wrap SSL* callback into backend-independent session_verifier_
  14825. auto v = std::make_shared<std::function<SSLVerifierResponse(SSL *)>>(
  14826. std::move(verifier));
  14827. session_verifier_ = [v](tls::session_t session) {
  14828. return (*v)(static_cast<SSL *>(session));
  14829. };
  14830. }
  14831. inline SSL_CTX *SSLClient::ssl_context() const {
  14832. return static_cast<SSL_CTX *>(ctx_);
  14833. }
  14834. inline bool SSLClient::verify_host(X509 *server_cert) const {
  14835. /* Quote from RFC2818 section 3.1 "Server Identity"
  14836. If a subjectAltName extension of type dNSName is present, that MUST
  14837. be used as the identity. Otherwise, the (most specific) Common Name
  14838. field in the Subject field of the certificate MUST be used. Although
  14839. the use of the Common Name is existing practice, it is deprecated and
  14840. Certification Authorities are encouraged to use the dNSName instead.
  14841. Matching is performed using the matching rules specified by
  14842. [RFC2459]. If more than one identity of a given type is present in
  14843. the certificate (e.g., more than one dNSName name, a match in any one
  14844. of the set is considered acceptable.) Names may contain the wildcard
  14845. character * which is considered to match any single domain name
  14846. component or component fragment. E.g., *.a.com matches foo.a.com but
  14847. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  14848. In some cases, the URI is specified as an IP address rather than a
  14849. hostname. In this case, the iPAddress subjectAltName must be present
  14850. in the certificate and must exactly match the IP in the URI.
  14851. */
  14852. return verify_host_with_subject_alt_name(server_cert) ||
  14853. verify_host_with_common_name(server_cert);
  14854. }
  14855. inline bool
  14856. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  14857. auto ret = false;
  14858. auto type = GEN_DNS;
  14859. struct in6_addr addr6 = {};
  14860. struct in_addr addr = {};
  14861. size_t addr_len = 0;
  14862. #ifndef __MINGW32__
  14863. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  14864. type = GEN_IPADD;
  14865. addr_len = sizeof(struct in6_addr);
  14866. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  14867. type = GEN_IPADD;
  14868. addr_len = sizeof(struct in_addr);
  14869. }
  14870. #endif
  14871. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  14872. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  14873. if (alt_names) {
  14874. auto dsn_matched = false;
  14875. auto ip_matched = false;
  14876. auto count = sk_GENERAL_NAME_num(alt_names);
  14877. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  14878. auto val = sk_GENERAL_NAME_value(alt_names, i);
  14879. if (!val || val->type != type) { continue; }
  14880. auto name =
  14881. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  14882. if (name == nullptr) { continue; }
  14883. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  14884. switch (type) {
  14885. case GEN_DNS:
  14886. dsn_matched =
  14887. detail::match_hostname(std::string(name, name_len), host_);
  14888. break;
  14889. case GEN_IPADD:
  14890. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  14891. ip_matched = true;
  14892. }
  14893. break;
  14894. }
  14895. }
  14896. if (dsn_matched || ip_matched) { ret = true; }
  14897. }
  14898. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  14899. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  14900. return ret;
  14901. }
  14902. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  14903. const auto subject_name = X509_get_subject_name(server_cert);
  14904. if (subject_name != nullptr) {
  14905. char name[BUFSIZ];
  14906. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  14907. name, sizeof(name));
  14908. if (name_len != -1) {
  14909. return detail::match_hostname(
  14910. std::string(name, static_cast<size_t>(name_len)), host_);
  14911. }
  14912. }
  14913. return false;
  14914. }
  14915. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  14916. /*
  14917. * Group 9: TLS abstraction layer - Mbed TLS backend
  14918. */
  14919. /*
  14920. * Mbed TLS Backend Implementation
  14921. */
  14922. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14923. namespace tls {
  14924. namespace impl {
  14925. // Mbed TLS session wrapper
  14926. struct MbedTlsSession {
  14927. mbedtls_ssl_context ssl;
  14928. socket_t sock = INVALID_SOCKET;
  14929. std::string hostname; // For client: set via set_sni
  14930. std::string sni_hostname; // For server: received from client via SNI callback
  14931. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  14932. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  14933. MbedTlsSession(const MbedTlsSession &) = delete;
  14934. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  14935. };
  14936. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  14937. // queue)
  14938. inline int &mbedtls_last_error() {
  14939. static thread_local int err = 0;
  14940. return err;
  14941. }
  14942. // Helper to map Mbed TLS error to ErrorCode
  14943. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  14944. if (ret == 0) { return ErrorCode::Success; }
  14945. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  14946. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  14947. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  14948. return ErrorCode::PeerClosed;
  14949. }
  14950. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  14951. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  14952. out_errno = errno;
  14953. return ErrorCode::SyscallError;
  14954. }
  14955. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  14956. return ErrorCode::CertVerifyFailed;
  14957. }
  14958. return ErrorCode::Fatal;
  14959. }
  14960. // BIO-like send callback for Mbed TLS
  14961. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  14962. size_t len) {
  14963. auto sock = *static_cast<socket_t *>(ctx);
  14964. #ifdef _WIN32
  14965. auto ret =
  14966. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  14967. if (ret == SOCKET_ERROR) {
  14968. int err = WSAGetLastError();
  14969. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  14970. return MBEDTLS_ERR_NET_SEND_FAILED;
  14971. }
  14972. #else
  14973. auto ret = send(sock, buf, len, 0);
  14974. if (ret < 0) {
  14975. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14976. return MBEDTLS_ERR_SSL_WANT_WRITE;
  14977. }
  14978. return MBEDTLS_ERR_NET_SEND_FAILED;
  14979. }
  14980. #endif
  14981. return static_cast<int>(ret);
  14982. }
  14983. // BIO-like recv callback for Mbed TLS
  14984. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  14985. auto sock = *static_cast<socket_t *>(ctx);
  14986. #ifdef _WIN32
  14987. auto ret =
  14988. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  14989. if (ret == SOCKET_ERROR) {
  14990. int err = WSAGetLastError();
  14991. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  14992. return MBEDTLS_ERR_NET_RECV_FAILED;
  14993. }
  14994. #else
  14995. auto ret = recv(sock, buf, len, 0);
  14996. if (ret < 0) {
  14997. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14998. return MBEDTLS_ERR_SSL_WANT_READ;
  14999. }
  15000. return MBEDTLS_ERR_NET_RECV_FAILED;
  15001. }
  15002. #endif
  15003. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15004. return static_cast<int>(ret);
  15005. }
  15006. // MbedTlsContext constructor/destructor implementations
  15007. inline MbedTlsContext::MbedTlsContext() {
  15008. mbedtls_ssl_config_init(&conf);
  15009. mbedtls_entropy_init(&entropy);
  15010. mbedtls_ctr_drbg_init(&ctr_drbg);
  15011. mbedtls_x509_crt_init(&ca_chain);
  15012. mbedtls_x509_crt_init(&own_cert);
  15013. mbedtls_pk_init(&own_key);
  15014. }
  15015. inline MbedTlsContext::~MbedTlsContext() {
  15016. mbedtls_pk_free(&own_key);
  15017. mbedtls_x509_crt_free(&own_cert);
  15018. mbedtls_x509_crt_free(&ca_chain);
  15019. mbedtls_ctr_drbg_free(&ctr_drbg);
  15020. mbedtls_entropy_free(&entropy);
  15021. mbedtls_ssl_config_free(&conf);
  15022. }
  15023. // Thread-local storage for SNI captured during handshake
  15024. // This is needed because the SNI callback doesn't have a way to pass
  15025. // session-specific data before the session is fully set up
  15026. inline std::string &mbedpending_sni() {
  15027. static thread_local std::string sni;
  15028. return sni;
  15029. }
  15030. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15031. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15032. const unsigned char *name, size_t name_len) {
  15033. (void)p_ctx;
  15034. (void)ssl;
  15035. // Store SNI name in thread-local storage
  15036. // It will be retrieved and stored in the session after handshake
  15037. if (name && name_len > 0) {
  15038. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15039. } else {
  15040. mbedpending_sni().clear();
  15041. }
  15042. return 0; // Accept any SNI
  15043. }
  15044. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15045. int cert_depth, uint32_t *flags);
  15046. // MbedTLS verify callback wrapper
  15047. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15048. int cert_depth, uint32_t *flags) {
  15049. auto &callback = get_verify_callback();
  15050. if (!callback) { return 0; } // Continue with default verification
  15051. // data points to the MbedTlsSession
  15052. auto *session = static_cast<MbedTlsSession *>(data);
  15053. // Build context
  15054. VerifyContext verify_ctx;
  15055. verify_ctx.session = static_cast<session_t>(session);
  15056. verify_ctx.cert = static_cast<cert_t>(crt);
  15057. verify_ctx.depth = cert_depth;
  15058. verify_ctx.preverify_ok = (*flags == 0);
  15059. verify_ctx.error_code = static_cast<long>(*flags);
  15060. // Convert Mbed TLS flags to error string
  15061. static thread_local char error_buf[256];
  15062. if (*flags != 0) {
  15063. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15064. verify_ctx.error_string = error_buf;
  15065. } else {
  15066. verify_ctx.error_string = nullptr;
  15067. }
  15068. bool accepted = callback(verify_ctx);
  15069. if (accepted) {
  15070. *flags = 0; // Clear all error flags
  15071. return 0;
  15072. }
  15073. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15074. }
  15075. } // namespace impl
  15076. inline ctx_t create_client_context() {
  15077. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15078. if (!ctx) { return nullptr; }
  15079. ctx->is_server = false;
  15080. // Seed the random number generator
  15081. const char *pers = "httplib_client";
  15082. int ret = mbedtls_ctr_drbg_seed(
  15083. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15084. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15085. if (ret != 0) {
  15086. impl::mbedtls_last_error() = ret;
  15087. delete ctx;
  15088. return nullptr;
  15089. }
  15090. // Set up SSL config for client
  15091. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15092. MBEDTLS_SSL_TRANSPORT_STREAM,
  15093. MBEDTLS_SSL_PRESET_DEFAULT);
  15094. if (ret != 0) {
  15095. impl::mbedtls_last_error() = ret;
  15096. delete ctx;
  15097. return nullptr;
  15098. }
  15099. // Set random number generator
  15100. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15101. // Default: verify peer certificate
  15102. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15103. // Set minimum TLS version to 1.2
  15104. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15105. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15106. #else
  15107. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15108. MBEDTLS_SSL_MINOR_VERSION_3);
  15109. #endif
  15110. return static_cast<ctx_t>(ctx);
  15111. }
  15112. inline ctx_t create_server_context() {
  15113. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15114. if (!ctx) { return nullptr; }
  15115. ctx->is_server = true;
  15116. // Seed the random number generator
  15117. const char *pers = "httplib_server";
  15118. int ret = mbedtls_ctr_drbg_seed(
  15119. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15120. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15121. if (ret != 0) {
  15122. impl::mbedtls_last_error() = ret;
  15123. delete ctx;
  15124. return nullptr;
  15125. }
  15126. // Set up SSL config for server
  15127. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15128. MBEDTLS_SSL_TRANSPORT_STREAM,
  15129. MBEDTLS_SSL_PRESET_DEFAULT);
  15130. if (ret != 0) {
  15131. impl::mbedtls_last_error() = ret;
  15132. delete ctx;
  15133. return nullptr;
  15134. }
  15135. // Set random number generator
  15136. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15137. // Default: don't verify client
  15138. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15139. // Set minimum TLS version to 1.2
  15140. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15141. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15142. #else
  15143. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15144. MBEDTLS_SSL_MINOR_VERSION_3);
  15145. #endif
  15146. // Set SNI callback to capture client's SNI hostname
  15147. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15148. return static_cast<ctx_t>(ctx);
  15149. }
  15150. inline void free_context(ctx_t ctx) {
  15151. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15152. }
  15153. inline bool set_min_version(ctx_t ctx, Version version) {
  15154. if (!ctx) { return false; }
  15155. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15156. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15157. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15158. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15159. if (version >= Version::TLS1_3) {
  15160. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15161. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15162. #endif
  15163. }
  15164. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15165. #else
  15166. // Mbed TLS 2.x uses major/minor version numbers
  15167. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15168. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15169. if (version >= Version::TLS1_3) {
  15170. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15171. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15172. #else
  15173. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15174. #endif
  15175. }
  15176. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15177. #endif
  15178. return true;
  15179. }
  15180. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15181. if (!ctx || !pem) { return false; }
  15182. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15183. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15184. // Add null terminator if not present
  15185. std::string pem_str(pem, len);
  15186. int ret = mbedtls_x509_crt_parse(
  15187. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15188. pem_str.size() + 1);
  15189. if (ret != 0) {
  15190. impl::mbedtls_last_error() = ret;
  15191. return false;
  15192. }
  15193. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15194. return true;
  15195. }
  15196. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15197. if (!ctx || !file_path) { return false; }
  15198. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15199. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15200. if (ret != 0) {
  15201. impl::mbedtls_last_error() = ret;
  15202. return false;
  15203. }
  15204. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15205. return true;
  15206. }
  15207. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15208. if (!ctx || !dir_path) { return false; }
  15209. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15210. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15211. if (ret < 0) { // Returns number of certs on success, negative on error
  15212. impl::mbedtls_last_error() = ret;
  15213. return false;
  15214. }
  15215. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15216. return true;
  15217. }
  15218. inline bool load_system_certs(ctx_t ctx) {
  15219. if (!ctx) { return false; }
  15220. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15221. bool loaded = false;
  15222. #ifdef _WIN32
  15223. loaded = impl::enumerate_windows_system_certs(
  15224. [&](const unsigned char *data, size_t len) {
  15225. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15226. });
  15227. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15228. loaded = impl::enumerate_macos_keychain_certs(
  15229. [&](const unsigned char *data, size_t len) {
  15230. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15231. });
  15232. #else
  15233. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15234. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15235. loaded = true;
  15236. break;
  15237. }
  15238. }
  15239. if (!loaded) {
  15240. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15241. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15242. loaded = true;
  15243. break;
  15244. }
  15245. }
  15246. }
  15247. #endif
  15248. if (loaded) {
  15249. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15250. }
  15251. return loaded;
  15252. }
  15253. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15254. const char *password) {
  15255. if (!ctx || !cert || !key) { return false; }
  15256. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15257. // Parse certificate
  15258. std::string cert_str(cert);
  15259. int ret = mbedtls_x509_crt_parse(
  15260. &mctx->own_cert,
  15261. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15262. cert_str.size() + 1);
  15263. if (ret != 0) {
  15264. impl::mbedtls_last_error() = ret;
  15265. return false;
  15266. }
  15267. // Parse private key
  15268. std::string key_str(key);
  15269. const unsigned char *pwd =
  15270. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15271. size_t pwd_len = password ? strlen(password) : 0;
  15272. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15273. ret = mbedtls_pk_parse_key(
  15274. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15275. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15276. &mctx->ctr_drbg);
  15277. #else
  15278. ret = mbedtls_pk_parse_key(
  15279. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15280. key_str.size() + 1, pwd, pwd_len);
  15281. #endif
  15282. if (ret != 0) {
  15283. impl::mbedtls_last_error() = ret;
  15284. return false;
  15285. }
  15286. // Verify that the certificate and private key match
  15287. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15288. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15289. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15290. #else
  15291. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15292. #endif
  15293. if (ret != 0) {
  15294. impl::mbedtls_last_error() = ret;
  15295. return false;
  15296. }
  15297. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15298. if (ret != 0) {
  15299. impl::mbedtls_last_error() = ret;
  15300. return false;
  15301. }
  15302. return true;
  15303. }
  15304. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15305. const char *key_path, const char *password) {
  15306. if (!ctx || !cert_path || !key_path) { return false; }
  15307. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15308. // Parse certificate file
  15309. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15310. if (ret != 0) {
  15311. impl::mbedtls_last_error() = ret;
  15312. return false;
  15313. }
  15314. // Parse private key file
  15315. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15316. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15317. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15318. #else
  15319. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15320. #endif
  15321. if (ret != 0) {
  15322. impl::mbedtls_last_error() = ret;
  15323. return false;
  15324. }
  15325. // Verify that the certificate and private key match
  15326. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15327. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15328. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15329. #else
  15330. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15331. #endif
  15332. if (ret != 0) {
  15333. impl::mbedtls_last_error() = ret;
  15334. return false;
  15335. }
  15336. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15337. if (ret != 0) {
  15338. impl::mbedtls_last_error() = ret;
  15339. return false;
  15340. }
  15341. return true;
  15342. }
  15343. inline void set_verify_client(ctx_t ctx, bool require) {
  15344. if (!ctx) { return; }
  15345. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15346. mctx->verify_client = require;
  15347. if (require) {
  15348. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15349. } else {
  15350. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15351. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15352. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15353. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15354. : MBEDTLS_SSL_VERIFY_NONE);
  15355. }
  15356. }
  15357. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15358. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15359. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15360. auto session = new (std::nothrow) impl::MbedTlsSession();
  15361. if (!session) { return nullptr; }
  15362. session->sock = sock;
  15363. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15364. if (ret != 0) {
  15365. impl::mbedtls_last_error() = ret;
  15366. delete session;
  15367. return nullptr;
  15368. }
  15369. // Set BIO callbacks
  15370. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15371. impl::mbedtls_net_recv_cb, nullptr);
  15372. // Set per-session verify callback with session pointer if callback is
  15373. // registered
  15374. if (mctx->has_verify_callback) {
  15375. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15376. session);
  15377. }
  15378. return static_cast<session_t>(session);
  15379. }
  15380. inline void free_session(session_t session) {
  15381. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15382. }
  15383. inline bool set_sni(session_t session, const char *hostname) {
  15384. if (!session || !hostname) { return false; }
  15385. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15386. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15387. if (ret != 0) {
  15388. impl::mbedtls_last_error() = ret;
  15389. return false;
  15390. }
  15391. msession->hostname = hostname;
  15392. return true;
  15393. }
  15394. inline bool set_hostname(session_t session, const char *hostname) {
  15395. // In Mbed TLS, set_hostname also sets up hostname verification
  15396. return set_sni(session, hostname);
  15397. }
  15398. inline TlsError connect(session_t session) {
  15399. TlsError err;
  15400. if (!session) {
  15401. err.code = ErrorCode::Fatal;
  15402. return err;
  15403. }
  15404. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15405. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15406. if (ret == 0) {
  15407. err.code = ErrorCode::Success;
  15408. } else {
  15409. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15410. err.backend_code = static_cast<uint64_t>(-ret);
  15411. impl::mbedtls_last_error() = ret;
  15412. }
  15413. return err;
  15414. }
  15415. inline TlsError accept(session_t session) {
  15416. // Same as connect for Mbed TLS - handshake works for both client and server
  15417. auto result = connect(session);
  15418. // After successful handshake, capture SNI from thread-local storage
  15419. if (result.code == ErrorCode::Success && session) {
  15420. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15421. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15422. impl::mbedpending_sni().clear();
  15423. }
  15424. return result;
  15425. }
  15426. inline bool connect_nonblocking(session_t session, socket_t sock,
  15427. time_t timeout_sec, time_t timeout_usec,
  15428. TlsError *err) {
  15429. if (!session) {
  15430. if (err) { err->code = ErrorCode::Fatal; }
  15431. return false;
  15432. }
  15433. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15434. // Set socket to non-blocking mode
  15435. detail::set_nonblocking(sock, true);
  15436. auto cleanup =
  15437. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15438. int ret;
  15439. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15440. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15441. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15442. continue;
  15443. }
  15444. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15445. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15446. continue;
  15447. }
  15448. }
  15449. // TlsError or timeout
  15450. if (err) {
  15451. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15452. err->backend_code = static_cast<uint64_t>(-ret);
  15453. }
  15454. impl::mbedtls_last_error() = ret;
  15455. return false;
  15456. }
  15457. if (err) { err->code = ErrorCode::Success; }
  15458. return true;
  15459. }
  15460. inline bool accept_nonblocking(session_t session, socket_t sock,
  15461. time_t timeout_sec, time_t timeout_usec,
  15462. TlsError *err) {
  15463. // Same implementation as connect for Mbed TLS
  15464. bool result =
  15465. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15466. // After successful handshake, capture SNI from thread-local storage
  15467. if (result && session) {
  15468. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15469. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15470. impl::mbedpending_sni().clear();
  15471. }
  15472. return result;
  15473. }
  15474. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15475. if (!session || !buf) {
  15476. err.code = ErrorCode::Fatal;
  15477. return -1;
  15478. }
  15479. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15480. int ret =
  15481. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15482. if (ret > 0) {
  15483. err.code = ErrorCode::Success;
  15484. return static_cast<ssize_t>(ret);
  15485. }
  15486. if (ret == 0) {
  15487. err.code = ErrorCode::PeerClosed;
  15488. return 0;
  15489. }
  15490. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15491. err.backend_code = static_cast<uint64_t>(-ret);
  15492. impl::mbedtls_last_error() = ret;
  15493. return -1;
  15494. }
  15495. inline ssize_t write(session_t session, const void *buf, size_t len,
  15496. TlsError &err) {
  15497. if (!session || !buf) {
  15498. err.code = ErrorCode::Fatal;
  15499. return -1;
  15500. }
  15501. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15502. int ret = mbedtls_ssl_write(&msession->ssl,
  15503. static_cast<const unsigned char *>(buf), len);
  15504. if (ret > 0) {
  15505. err.code = ErrorCode::Success;
  15506. return static_cast<ssize_t>(ret);
  15507. }
  15508. if (ret == 0) {
  15509. err.code = ErrorCode::PeerClosed;
  15510. return 0;
  15511. }
  15512. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15513. err.backend_code = static_cast<uint64_t>(-ret);
  15514. impl::mbedtls_last_error() = ret;
  15515. return -1;
  15516. }
  15517. inline int pending(const_session_t session) {
  15518. if (!session) { return 0; }
  15519. auto msession =
  15520. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15521. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15522. }
  15523. inline void shutdown(session_t session, bool graceful) {
  15524. if (!session) { return; }
  15525. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15526. if (graceful) {
  15527. // Try to send close_notify, but don't block forever
  15528. int ret;
  15529. int attempts = 0;
  15530. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15531. attempts < 3) {
  15532. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15533. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15534. break;
  15535. }
  15536. attempts++;
  15537. }
  15538. }
  15539. }
  15540. inline bool is_peer_closed(session_t session, socket_t sock) {
  15541. if (!session || sock == INVALID_SOCKET) { return true; }
  15542. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15543. // Check if there's already decrypted data available in the TLS buffer
  15544. // If so, the connection is definitely alive
  15545. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15546. // Set socket to non-blocking to avoid blocking on read
  15547. detail::set_nonblocking(sock, true);
  15548. auto cleanup =
  15549. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15550. // Try a 1-byte read to check connection status
  15551. // Note: This will consume the byte if data is available, but for the
  15552. // purpose of checking if peer is closed, this should be acceptable
  15553. // since we're only called when we expect the connection might be closing
  15554. unsigned char buf;
  15555. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15556. // If we got data or WANT_READ (would block), connection is alive
  15557. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15558. // If we get a peer close notify or a connection reset, the peer is closed
  15559. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15560. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15561. }
  15562. inline cert_t get_peer_cert(const_session_t session) {
  15563. if (!session) { return nullptr; }
  15564. auto msession =
  15565. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15566. // Mbed TLS returns a pointer to the internal peer cert chain.
  15567. // WARNING: This pointer is only valid while the session is active.
  15568. // Do not use the certificate after calling free_session().
  15569. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15570. return const_cast<mbedtls_x509_crt *>(cert);
  15571. }
  15572. inline void free_cert(cert_t cert) {
  15573. // Mbed TLS: peer certificate is owned by the SSL context.
  15574. // No-op here, but callers should still call this for cross-backend
  15575. // portability.
  15576. (void)cert;
  15577. }
  15578. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15579. if (!cert || !hostname) { return false; }
  15580. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15581. std::string host_str(hostname);
  15582. // Check if hostname is an IP address
  15583. bool is_ip = impl::is_ipv4_address(host_str);
  15584. unsigned char ip_bytes[4];
  15585. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  15586. // Check Subject Alternative Names (SAN)
  15587. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15588. // - DNS names: raw string bytes
  15589. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15590. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15591. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15592. const unsigned char *p = san->buf.p;
  15593. size_t len = san->buf.len;
  15594. if (is_ip) {
  15595. // Check if this SAN is an IPv4 address (4 bytes)
  15596. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  15597. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  15598. } else {
  15599. // Check if this SAN is a DNS name (printable ASCII string)
  15600. bool is_dns = len > 0;
  15601. for (size_t i = 0; i < len && is_dns; i++) {
  15602. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15603. }
  15604. if (is_dns) {
  15605. std::string san_name(reinterpret_cast<const char *>(p), len);
  15606. if (detail::match_hostname(san_name, host_str)) { return true; }
  15607. }
  15608. }
  15609. san = san->next;
  15610. }
  15611. // Fallback: Check Common Name (CN) in subject
  15612. char cn[256];
  15613. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15614. if (ret > 0) {
  15615. std::string cn_str(cn);
  15616. // Look for "CN=" in the DN string
  15617. size_t cn_pos = cn_str.find("CN=");
  15618. if (cn_pos != std::string::npos) {
  15619. size_t start = cn_pos + 3;
  15620. size_t end = cn_str.find(',', start);
  15621. std::string cn_value =
  15622. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15623. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15624. }
  15625. }
  15626. return false;
  15627. }
  15628. inline uint64_t hostname_mismatch_code() {
  15629. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15630. }
  15631. inline long get_verify_result(const_session_t session) {
  15632. if (!session) { return -1; }
  15633. auto msession =
  15634. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15635. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15636. // Return 0 (X509_V_OK equivalent) if verification passed
  15637. return flags == 0 ? 0 : static_cast<long>(flags);
  15638. }
  15639. inline std::string get_cert_subject_cn(cert_t cert) {
  15640. if (!cert) return "";
  15641. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15642. // Find the CN in the subject
  15643. const mbedtls_x509_name *name = &x509->subject;
  15644. while (name != nullptr) {
  15645. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15646. return std::string(reinterpret_cast<const char *>(name->val.p),
  15647. name->val.len);
  15648. }
  15649. name = name->next;
  15650. }
  15651. return "";
  15652. }
  15653. inline std::string get_cert_issuer_name(cert_t cert) {
  15654. if (!cert) return "";
  15655. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15656. // Build a human-readable issuer name string
  15657. char buf[512];
  15658. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15659. if (ret < 0) return "";
  15660. return std::string(buf);
  15661. }
  15662. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15663. sans.clear();
  15664. if (!cert) return false;
  15665. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15666. // Parse the Subject Alternative Name extension
  15667. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15668. while (cur != nullptr) {
  15669. if (cur->buf.len > 0) {
  15670. // Mbed TLS stores SAN as ASN.1 sequences
  15671. // The tag byte indicates the type
  15672. const unsigned char *p = cur->buf.p;
  15673. size_t len = cur->buf.len;
  15674. // First byte is the tag
  15675. unsigned char tag = *p;
  15676. p++;
  15677. len--;
  15678. // Parse length (simple single-byte length assumed)
  15679. if (len > 0 && *p < 0x80) {
  15680. size_t value_len = *p;
  15681. p++;
  15682. len--;
  15683. if (value_len <= len) {
  15684. SanEntry entry;
  15685. // ASN.1 context tags for GeneralName
  15686. switch (tag & 0x1F) {
  15687. case 2: // dNSName
  15688. entry.type = SanType::DNS;
  15689. entry.value =
  15690. std::string(reinterpret_cast<const char *>(p), value_len);
  15691. break;
  15692. case 7: // iPAddress
  15693. entry.type = SanType::IP;
  15694. if (value_len == 4) {
  15695. // IPv4
  15696. char buf[16];
  15697. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15698. entry.value = buf;
  15699. } else if (value_len == 16) {
  15700. // IPv6
  15701. char buf[64];
  15702. snprintf(buf, sizeof(buf),
  15703. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15704. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15705. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15706. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15707. entry.value = buf;
  15708. }
  15709. break;
  15710. case 1: // rfc822Name (email)
  15711. entry.type = SanType::EMAIL;
  15712. entry.value =
  15713. std::string(reinterpret_cast<const char *>(p), value_len);
  15714. break;
  15715. case 6: // uniformResourceIdentifier
  15716. entry.type = SanType::URI;
  15717. entry.value =
  15718. std::string(reinterpret_cast<const char *>(p), value_len);
  15719. break;
  15720. default: entry.type = SanType::OTHER; break;
  15721. }
  15722. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15723. }
  15724. }
  15725. }
  15726. cur = cur->next;
  15727. }
  15728. return true;
  15729. }
  15730. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15731. time_t &not_after) {
  15732. if (!cert) return false;
  15733. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15734. // Convert mbedtls_x509_time to time_t
  15735. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15736. struct tm tm_time = {};
  15737. tm_time.tm_year = t.year - 1900;
  15738. tm_time.tm_mon = t.mon - 1;
  15739. tm_time.tm_mday = t.day;
  15740. tm_time.tm_hour = t.hour;
  15741. tm_time.tm_min = t.min;
  15742. tm_time.tm_sec = t.sec;
  15743. #ifdef _WIN32
  15744. return _mkgmtime(&tm_time);
  15745. #else
  15746. return timegm(&tm_time);
  15747. #endif
  15748. };
  15749. not_before = to_time_t(x509->valid_from);
  15750. not_after = to_time_t(x509->valid_to);
  15751. return true;
  15752. }
  15753. inline std::string get_cert_serial(cert_t cert) {
  15754. if (!cert) return "";
  15755. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15756. // Convert serial number to hex string
  15757. std::string result;
  15758. result.reserve(x509->serial.len * 2);
  15759. for (size_t i = 0; i < x509->serial.len; i++) {
  15760. char hex[3];
  15761. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  15762. result += hex;
  15763. }
  15764. return result;
  15765. }
  15766. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15767. if (!cert) return false;
  15768. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  15769. if (!crt->raw.p || crt->raw.len == 0) return false;
  15770. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  15771. return true;
  15772. }
  15773. inline const char *get_sni(const_session_t session) {
  15774. if (!session) return nullptr;
  15775. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  15776. // For server: return SNI received from client during handshake
  15777. if (!msession->sni_hostname.empty()) {
  15778. return msession->sni_hostname.c_str();
  15779. }
  15780. // For client: return the hostname set via set_sni
  15781. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  15782. return nullptr;
  15783. }
  15784. inline uint64_t peek_error() {
  15785. // Mbed TLS doesn't have an error queue, return the last error
  15786. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  15787. }
  15788. inline uint64_t get_error() {
  15789. // Mbed TLS doesn't have an error queue, return and clear the last error
  15790. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  15791. impl::mbedtls_last_error() = 0;
  15792. return err;
  15793. }
  15794. inline std::string error_string(uint64_t code) {
  15795. char buf[256];
  15796. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  15797. return std::string(buf);
  15798. }
  15799. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15800. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  15801. if (!ca_chain) { return nullptr; }
  15802. mbedtls_x509_crt_init(ca_chain);
  15803. // mbedtls_x509_crt_parse expects null-terminated PEM
  15804. int ret = mbedtls_x509_crt_parse(ca_chain,
  15805. reinterpret_cast<const unsigned char *>(pem),
  15806. len + 1); // +1 for null terminator
  15807. if (ret != 0) {
  15808. // Try without +1 in case PEM is already null-terminated
  15809. ret = mbedtls_x509_crt_parse(
  15810. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  15811. if (ret != 0) {
  15812. mbedtls_x509_crt_free(ca_chain);
  15813. delete ca_chain;
  15814. return nullptr;
  15815. }
  15816. }
  15817. return static_cast<ca_store_t>(ca_chain);
  15818. }
  15819. inline void free_ca_store(ca_store_t store) {
  15820. if (store) {
  15821. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15822. mbedtls_x509_crt_free(ca_chain);
  15823. delete ca_chain;
  15824. }
  15825. }
  15826. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15827. if (!ctx || !store) { return false; }
  15828. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15829. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15830. // Free existing CA chain
  15831. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15832. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15833. // Copy the CA chain (deep copy)
  15834. // Parse from the raw data of the source cert
  15835. mbedtls_x509_crt *src = ca_chain;
  15836. while (src != nullptr) {
  15837. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  15838. src->raw.len);
  15839. if (ret != 0) { return false; }
  15840. src = src->next;
  15841. }
  15842. // Update the SSL config to use the new CA chain
  15843. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15844. return true;
  15845. }
  15846. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15847. certs.clear();
  15848. if (!ctx) { return 0; }
  15849. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15850. // Iterate through the CA chain
  15851. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15852. while (cert != nullptr && cert->raw.len > 0) {
  15853. // Create a copy of the certificate for the caller
  15854. auto *copy = new mbedtls_x509_crt;
  15855. mbedtls_x509_crt_init(copy);
  15856. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  15857. if (ret == 0) {
  15858. certs.push_back(static_cast<cert_t>(copy));
  15859. } else {
  15860. mbedtls_x509_crt_free(copy);
  15861. delete copy;
  15862. }
  15863. cert = cert->next;
  15864. }
  15865. return certs.size();
  15866. }
  15867. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15868. std::vector<std::string> names;
  15869. if (!ctx) { return names; }
  15870. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15871. // Iterate through the CA chain
  15872. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15873. while (cert != nullptr && cert->raw.len > 0) {
  15874. char buf[512];
  15875. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  15876. if (ret > 0) { names.push_back(buf); }
  15877. cert = cert->next;
  15878. }
  15879. return names;
  15880. }
  15881. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15882. const char *key_pem, const char *password) {
  15883. if (!ctx || !cert_pem || !key_pem) { return false; }
  15884. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15885. // Free existing certificate and key
  15886. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  15887. mbedtls_pk_free(&mbed_ctx->own_key);
  15888. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  15889. mbedtls_pk_init(&mbed_ctx->own_key);
  15890. // Parse certificate PEM
  15891. int ret = mbedtls_x509_crt_parse(
  15892. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  15893. strlen(cert_pem) + 1);
  15894. if (ret != 0) {
  15895. impl::mbedtls_last_error() = ret;
  15896. return false;
  15897. }
  15898. // Parse private key PEM
  15899. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15900. ret = mbedtls_pk_parse_key(
  15901. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15902. strlen(key_pem) + 1,
  15903. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15904. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  15905. &mbed_ctx->ctr_drbg);
  15906. #else
  15907. ret = mbedtls_pk_parse_key(
  15908. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15909. strlen(key_pem) + 1,
  15910. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15911. password ? strlen(password) : 0);
  15912. #endif
  15913. if (ret != 0) {
  15914. impl::mbedtls_last_error() = ret;
  15915. return false;
  15916. }
  15917. // Configure SSL to use the new certificate and key
  15918. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  15919. &mbed_ctx->own_key);
  15920. if (ret != 0) {
  15921. impl::mbedtls_last_error() = ret;
  15922. return false;
  15923. }
  15924. return true;
  15925. }
  15926. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15927. if (!ctx || !ca_pem) { return false; }
  15928. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15929. // Free existing CA chain
  15930. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15931. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15932. // Parse CA PEM
  15933. int ret = mbedtls_x509_crt_parse(
  15934. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  15935. strlen(ca_pem) + 1);
  15936. if (ret != 0) {
  15937. impl::mbedtls_last_error() = ret;
  15938. return false;
  15939. }
  15940. // Update SSL config to use new CA chain
  15941. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15942. return true;
  15943. }
  15944. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15945. if (!ctx) { return false; }
  15946. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15947. impl::get_verify_callback() = std::move(callback);
  15948. mbed_ctx->has_verify_callback =
  15949. static_cast<bool>(impl::get_verify_callback());
  15950. if (mbed_ctx->has_verify_callback) {
  15951. // Set OPTIONAL mode to ensure callback is called even when verification
  15952. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  15953. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  15954. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  15955. nullptr);
  15956. } else {
  15957. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  15958. }
  15959. return true;
  15960. }
  15961. inline long get_verify_error(const_session_t session) {
  15962. if (!session) { return -1; }
  15963. auto *msession =
  15964. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15965. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  15966. }
  15967. inline std::string verify_error_string(long error_code) {
  15968. if (error_code == 0) { return ""; }
  15969. char buf[256];
  15970. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  15971. static_cast<uint32_t>(error_code));
  15972. // Remove trailing newline if present
  15973. std::string result(buf);
  15974. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  15975. result.pop_back();
  15976. }
  15977. return result;
  15978. }
  15979. } // namespace tls
  15980. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  15981. /*
  15982. * Group 10: TLS abstraction layer - wolfSSL backend
  15983. */
  15984. /*
  15985. * wolfSSL Backend Implementation
  15986. */
  15987. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  15988. namespace tls {
  15989. namespace impl {
  15990. // wolfSSL session wrapper
  15991. struct WolfSSLSession {
  15992. WOLFSSL *ssl = nullptr;
  15993. socket_t sock = INVALID_SOCKET;
  15994. std::string hostname; // For client: set via set_sni
  15995. std::string sni_hostname; // For server: received from client via SNI callback
  15996. WolfSSLSession() = default;
  15997. ~WolfSSLSession() {
  15998. if (ssl) { wolfSSL_free(ssl); }
  15999. }
  16000. WolfSSLSession(const WolfSSLSession &) = delete;
  16001. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16002. };
  16003. // Thread-local error code accessor for wolfSSL
  16004. inline uint64_t &wolfssl_last_error() {
  16005. static thread_local uint64_t err = 0;
  16006. return err;
  16007. }
  16008. // Helper to map wolfSSL error to ErrorCode.
  16009. // ssl_error is the value from wolfSSL_get_error().
  16010. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16011. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16012. int &out_errno) {
  16013. switch (ssl_error) {
  16014. case SSL_ERROR_NONE: return ErrorCode::Success;
  16015. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16016. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16017. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16018. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16019. default:
  16020. if (ssl) {
  16021. // wolfSSL stores the low-level error code as a negative value.
  16022. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16023. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16024. if (low_err == DOMAIN_NAME_MISMATCH) {
  16025. return ErrorCode::HostnameMismatch;
  16026. }
  16027. // Check verify result to distinguish cert verification from generic SSL
  16028. // errors.
  16029. long vr = wolfSSL_get_verify_result(ssl);
  16030. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16031. }
  16032. return ErrorCode::Fatal;
  16033. }
  16034. }
  16035. // WolfSSLContext constructor/destructor implementations
  16036. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16037. inline WolfSSLContext::~WolfSSLContext() {
  16038. if (ctx) { wolfSSL_CTX_free(ctx); }
  16039. }
  16040. // Thread-local storage for SNI captured during handshake
  16041. inline std::string &wolfssl_pending_sni() {
  16042. static thread_local std::string sni;
  16043. return sni;
  16044. }
  16045. // SNI callback for wolfSSL server to capture client's SNI hostname
  16046. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16047. (void)ret;
  16048. (void)exArg;
  16049. void *name_data = nullptr;
  16050. unsigned short name_len =
  16051. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16052. if (name_data && name_len > 0) {
  16053. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16054. name_len);
  16055. } else {
  16056. wolfssl_pending_sni().clear();
  16057. }
  16058. return 0; // Continue regardless
  16059. }
  16060. // wolfSSL verify callback wrapper
  16061. inline int wolfssl_verify_callback(int preverify_ok,
  16062. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16063. auto &callback = get_verify_callback();
  16064. if (!callback) { return preverify_ok; }
  16065. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16066. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16067. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16068. // Get the WOLFSSL object from the X509_STORE_CTX
  16069. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16070. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16071. VerifyContext verify_ctx;
  16072. verify_ctx.session = static_cast<session_t>(ssl);
  16073. verify_ctx.cert = static_cast<cert_t>(cert);
  16074. verify_ctx.depth = depth;
  16075. verify_ctx.preverify_ok = (preverify_ok != 0);
  16076. verify_ctx.error_code = static_cast<long>(err);
  16077. if (err != 0) {
  16078. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16079. } else {
  16080. verify_ctx.error_string = nullptr;
  16081. }
  16082. bool accepted = callback(verify_ctx);
  16083. return accepted ? 1 : 0;
  16084. }
  16085. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16086. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16087. wolfSSL_CTX_set_default_passwd_cb(
  16088. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16089. auto *pwd = static_cast<const char *>(userdata);
  16090. if (!pwd) return 0;
  16091. auto len = static_cast<int>(strlen(pwd));
  16092. if (len > size) len = size;
  16093. memcpy(buf, pwd, static_cast<size_t>(len));
  16094. return len;
  16095. });
  16096. }
  16097. } // namespace impl
  16098. inline ctx_t create_client_context() {
  16099. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16100. if (!ctx) { return nullptr; }
  16101. ctx->is_server = false;
  16102. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16103. if (!method) {
  16104. delete ctx;
  16105. return nullptr;
  16106. }
  16107. ctx->ctx = wolfSSL_CTX_new(method);
  16108. if (!ctx->ctx) {
  16109. delete ctx;
  16110. return nullptr;
  16111. }
  16112. // Default: verify peer certificate
  16113. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16114. return static_cast<ctx_t>(ctx);
  16115. }
  16116. inline ctx_t create_server_context() {
  16117. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16118. if (!ctx) { return nullptr; }
  16119. ctx->is_server = true;
  16120. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16121. if (!method) {
  16122. delete ctx;
  16123. return nullptr;
  16124. }
  16125. ctx->ctx = wolfSSL_CTX_new(method);
  16126. if (!ctx->ctx) {
  16127. delete ctx;
  16128. return nullptr;
  16129. }
  16130. // Default: don't verify client
  16131. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16132. // Enable SNI on server
  16133. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16134. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16135. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16136. return static_cast<ctx_t>(ctx);
  16137. }
  16138. inline void free_context(ctx_t ctx) {
  16139. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16140. }
  16141. inline bool set_min_version(ctx_t ctx, Version version) {
  16142. if (!ctx) { return false; }
  16143. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16144. int min_ver = WOLFSSL_TLSV1_2;
  16145. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16146. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16147. }
  16148. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16149. if (!ctx || !pem) { return false; }
  16150. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16151. int ret = wolfSSL_CTX_load_verify_buffer(
  16152. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16153. static_cast<long>(len), SSL_FILETYPE_PEM);
  16154. if (ret != SSL_SUCCESS) {
  16155. impl::wolfssl_last_error() =
  16156. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16157. return false;
  16158. }
  16159. wctx->ca_pem_data_.append(pem, len);
  16160. return true;
  16161. }
  16162. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16163. if (!ctx || !file_path) { return false; }
  16164. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16165. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16166. if (ret != SSL_SUCCESS) {
  16167. impl::wolfssl_last_error() =
  16168. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16169. return false;
  16170. }
  16171. return true;
  16172. }
  16173. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16174. if (!ctx || !dir_path) { return false; }
  16175. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16176. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16177. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16178. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16179. // immediately. Return true even on failure since the CA file may have
  16180. // already been loaded, matching OpenSSL's lenient behavior.
  16181. (void)ret;
  16182. return true;
  16183. }
  16184. inline bool load_system_certs(ctx_t ctx) {
  16185. if (!ctx) { return false; }
  16186. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16187. bool loaded = false;
  16188. #ifdef _WIN32
  16189. loaded = impl::enumerate_windows_system_certs(
  16190. [&](const unsigned char *data, size_t len) {
  16191. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16192. static_cast<long>(len),
  16193. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16194. });
  16195. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16196. loaded = impl::enumerate_macos_keychain_certs(
  16197. [&](const unsigned char *data, size_t len) {
  16198. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16199. static_cast<long>(len),
  16200. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16201. });
  16202. #else
  16203. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16204. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16205. SSL_SUCCESS) {
  16206. loaded = true;
  16207. break;
  16208. }
  16209. }
  16210. if (!loaded) {
  16211. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16212. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16213. SSL_SUCCESS) {
  16214. loaded = true;
  16215. break;
  16216. }
  16217. }
  16218. }
  16219. #endif
  16220. return loaded;
  16221. }
  16222. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16223. const char *password) {
  16224. if (!ctx || !cert || !key) { return false; }
  16225. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16226. // Load certificate
  16227. int ret = wolfSSL_CTX_use_certificate_buffer(
  16228. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16229. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16230. if (ret != SSL_SUCCESS) {
  16231. impl::wolfssl_last_error() =
  16232. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16233. return false;
  16234. }
  16235. // Set password callback if password is provided
  16236. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16237. // Load private key
  16238. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16239. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16240. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16241. if (ret != SSL_SUCCESS) {
  16242. impl::wolfssl_last_error() =
  16243. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16244. return false;
  16245. }
  16246. // Verify that the certificate and private key match
  16247. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16248. }
  16249. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16250. const char *key_path, const char *password) {
  16251. if (!ctx || !cert_path || !key_path) { return false; }
  16252. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16253. // Load certificate file
  16254. int ret =
  16255. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16256. if (ret != SSL_SUCCESS) {
  16257. impl::wolfssl_last_error() =
  16258. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16259. return false;
  16260. }
  16261. // Set password callback if password is provided
  16262. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16263. // Load private key file
  16264. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16265. if (ret != SSL_SUCCESS) {
  16266. impl::wolfssl_last_error() =
  16267. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16268. return false;
  16269. }
  16270. // Verify that the certificate and private key match
  16271. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16272. }
  16273. inline void set_verify_client(ctx_t ctx, bool require) {
  16274. if (!ctx) { return; }
  16275. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16276. wctx->verify_client = require;
  16277. if (require) {
  16278. wolfSSL_CTX_set_verify(
  16279. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16280. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16281. } else {
  16282. if (wctx->has_verify_callback) {
  16283. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16284. impl::wolfssl_verify_callback);
  16285. } else {
  16286. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16287. }
  16288. }
  16289. }
  16290. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16291. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16292. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16293. auto session = new (std::nothrow) impl::WolfSSLSession();
  16294. if (!session) { return nullptr; }
  16295. session->sock = sock;
  16296. session->ssl = wolfSSL_new(wctx->ctx);
  16297. if (!session->ssl) {
  16298. impl::wolfssl_last_error() =
  16299. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16300. delete session;
  16301. return nullptr;
  16302. }
  16303. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16304. return static_cast<session_t>(session);
  16305. }
  16306. inline void free_session(session_t session) {
  16307. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16308. }
  16309. inline bool set_sni(session_t session, const char *hostname) {
  16310. if (!session || !hostname) { return false; }
  16311. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16312. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16313. static_cast<word16>(strlen(hostname)));
  16314. if (ret != WOLFSSL_SUCCESS) {
  16315. impl::wolfssl_last_error() =
  16316. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16317. return false;
  16318. }
  16319. // Also set hostname for verification
  16320. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16321. wsession->hostname = hostname;
  16322. return true;
  16323. }
  16324. inline bool set_hostname(session_t session, const char *hostname) {
  16325. // In wolfSSL, set_hostname also sets up hostname verification
  16326. return set_sni(session, hostname);
  16327. }
  16328. inline TlsError connect(session_t session) {
  16329. TlsError err;
  16330. if (!session) {
  16331. err.code = ErrorCode::Fatal;
  16332. return err;
  16333. }
  16334. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16335. int ret = wolfSSL_connect(wsession->ssl);
  16336. if (ret == SSL_SUCCESS) {
  16337. err.code = ErrorCode::Success;
  16338. } else {
  16339. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16340. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16341. err.backend_code = static_cast<uint64_t>(ssl_error);
  16342. impl::wolfssl_last_error() = err.backend_code;
  16343. }
  16344. return err;
  16345. }
  16346. inline TlsError accept(session_t session) {
  16347. TlsError err;
  16348. if (!session) {
  16349. err.code = ErrorCode::Fatal;
  16350. return err;
  16351. }
  16352. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16353. int ret = wolfSSL_accept(wsession->ssl);
  16354. if (ret == SSL_SUCCESS) {
  16355. err.code = ErrorCode::Success;
  16356. // Capture SNI from thread-local storage after successful handshake
  16357. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16358. impl::wolfssl_pending_sni().clear();
  16359. } else {
  16360. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16361. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16362. err.backend_code = static_cast<uint64_t>(ssl_error);
  16363. impl::wolfssl_last_error() = err.backend_code;
  16364. }
  16365. return err;
  16366. }
  16367. inline bool connect_nonblocking(session_t session, socket_t sock,
  16368. time_t timeout_sec, time_t timeout_usec,
  16369. TlsError *err) {
  16370. if (!session) {
  16371. if (err) { err->code = ErrorCode::Fatal; }
  16372. return false;
  16373. }
  16374. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16375. // Set socket to non-blocking mode
  16376. detail::set_nonblocking(sock, true);
  16377. auto cleanup =
  16378. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16379. int ret;
  16380. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16381. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16382. if (ssl_error == SSL_ERROR_WANT_READ) {
  16383. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16384. continue;
  16385. }
  16386. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16387. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16388. continue;
  16389. }
  16390. }
  16391. // Error or timeout
  16392. if (err) {
  16393. err->code =
  16394. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16395. err->backend_code = static_cast<uint64_t>(ssl_error);
  16396. }
  16397. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16398. return false;
  16399. }
  16400. if (err) { err->code = ErrorCode::Success; }
  16401. return true;
  16402. }
  16403. inline bool accept_nonblocking(session_t session, socket_t sock,
  16404. time_t timeout_sec, time_t timeout_usec,
  16405. TlsError *err) {
  16406. if (!session) {
  16407. if (err) { err->code = ErrorCode::Fatal; }
  16408. return false;
  16409. }
  16410. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16411. // Set socket to non-blocking mode
  16412. detail::set_nonblocking(sock, true);
  16413. auto cleanup =
  16414. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16415. int ret;
  16416. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16417. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16418. if (ssl_error == SSL_ERROR_WANT_READ) {
  16419. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16420. continue;
  16421. }
  16422. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16423. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16424. continue;
  16425. }
  16426. }
  16427. // Error or timeout
  16428. if (err) {
  16429. err->code =
  16430. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16431. err->backend_code = static_cast<uint64_t>(ssl_error);
  16432. }
  16433. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16434. return false;
  16435. }
  16436. if (err) { err->code = ErrorCode::Success; }
  16437. // Capture SNI from thread-local storage after successful handshake
  16438. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16439. impl::wolfssl_pending_sni().clear();
  16440. return true;
  16441. }
  16442. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16443. if (!session || !buf) {
  16444. err.code = ErrorCode::Fatal;
  16445. return -1;
  16446. }
  16447. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16448. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16449. if (ret > 0) {
  16450. err.code = ErrorCode::Success;
  16451. return static_cast<ssize_t>(ret);
  16452. }
  16453. if (ret == 0) {
  16454. err.code = ErrorCode::PeerClosed;
  16455. return 0;
  16456. }
  16457. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16458. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16459. err.backend_code = static_cast<uint64_t>(ssl_error);
  16460. impl::wolfssl_last_error() = err.backend_code;
  16461. return -1;
  16462. }
  16463. inline ssize_t write(session_t session, const void *buf, size_t len,
  16464. TlsError &err) {
  16465. if (!session || !buf) {
  16466. err.code = ErrorCode::Fatal;
  16467. return -1;
  16468. }
  16469. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16470. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16471. if (ret > 0) {
  16472. err.code = ErrorCode::Success;
  16473. return static_cast<ssize_t>(ret);
  16474. }
  16475. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16476. // Treat this as an error (return -1) so callers don't spin in a
  16477. // write loop adding zero to the offset.
  16478. if (ret == 0) {
  16479. err.code = ErrorCode::PeerClosed;
  16480. return -1;
  16481. }
  16482. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16483. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16484. err.backend_code = static_cast<uint64_t>(ssl_error);
  16485. impl::wolfssl_last_error() = err.backend_code;
  16486. return -1;
  16487. }
  16488. inline int pending(const_session_t session) {
  16489. if (!session) { return 0; }
  16490. auto wsession =
  16491. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16492. return wolfSSL_pending(wsession->ssl);
  16493. }
  16494. inline void shutdown(session_t session, bool graceful) {
  16495. if (!session) { return; }
  16496. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16497. if (graceful) {
  16498. int ret;
  16499. int attempts = 0;
  16500. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16501. attempts < 3) {
  16502. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16503. if (ssl_error != SSL_ERROR_WANT_READ &&
  16504. ssl_error != SSL_ERROR_WANT_WRITE) {
  16505. break;
  16506. }
  16507. attempts++;
  16508. }
  16509. } else {
  16510. wolfSSL_shutdown(wsession->ssl);
  16511. }
  16512. }
  16513. inline bool is_peer_closed(session_t session, socket_t sock) {
  16514. if (!session || sock == INVALID_SOCKET) { return true; }
  16515. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16516. // Check if there's already decrypted data available
  16517. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16518. // Set socket to non-blocking to avoid blocking on read
  16519. detail::set_nonblocking(sock, true);
  16520. auto cleanup =
  16521. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16522. // Peek 1 byte to check connection status without consuming data
  16523. unsigned char buf;
  16524. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16525. // If we got data or WANT_READ (would block), connection is alive
  16526. if (ret > 0) { return false; }
  16527. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16528. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16529. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16530. ret == 0;
  16531. }
  16532. inline cert_t get_peer_cert(const_session_t session) {
  16533. if (!session) { return nullptr; }
  16534. auto wsession =
  16535. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16536. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16537. return static_cast<cert_t>(cert);
  16538. }
  16539. inline void free_cert(cert_t cert) {
  16540. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16541. }
  16542. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16543. if (!cert || !hostname) { return false; }
  16544. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16545. std::string host_str(hostname);
  16546. // Check if hostname is an IP address
  16547. bool is_ip = impl::is_ipv4_address(host_str);
  16548. unsigned char ip_bytes[4];
  16549. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  16550. // Check Subject Alternative Names
  16551. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16552. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16553. if (san_names) {
  16554. int san_count = wolfSSL_sk_num(san_names);
  16555. for (int i = 0; i < san_count; i++) {
  16556. auto *names =
  16557. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16558. if (!names) continue;
  16559. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16560. // DNS name
  16561. unsigned char *dns_name = nullptr;
  16562. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16563. if (dns_name && dns_len > 0) {
  16564. std::string san_name(reinterpret_cast<char *>(dns_name),
  16565. static_cast<size_t>(dns_len));
  16566. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16567. if (detail::match_hostname(san_name, host_str)) {
  16568. wolfSSL_sk_free(san_names);
  16569. return true;
  16570. }
  16571. }
  16572. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16573. // IP address
  16574. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16575. int ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16576. if (ip_data && ip_len == 4 && memcmp(ip_data, ip_bytes, 4) == 0) {
  16577. wolfSSL_sk_free(san_names);
  16578. return true;
  16579. }
  16580. }
  16581. }
  16582. wolfSSL_sk_free(san_names);
  16583. }
  16584. // Fallback: Check Common Name (CN) in subject
  16585. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16586. if (subject) {
  16587. char cn[256] = {};
  16588. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16589. sizeof(cn));
  16590. if (cn_len > 0) {
  16591. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16592. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16593. }
  16594. }
  16595. return false;
  16596. }
  16597. inline uint64_t hostname_mismatch_code() {
  16598. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16599. }
  16600. inline long get_verify_result(const_session_t session) {
  16601. if (!session) { return -1; }
  16602. auto wsession =
  16603. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16604. long result = wolfSSL_get_verify_result(wsession->ssl);
  16605. return result;
  16606. }
  16607. inline std::string get_cert_subject_cn(cert_t cert) {
  16608. if (!cert) return "";
  16609. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16610. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16611. if (!subject) return "";
  16612. char cn[256] = {};
  16613. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16614. sizeof(cn));
  16615. if (cn_len <= 0) return "";
  16616. return std::string(cn, static_cast<size_t>(cn_len));
  16617. }
  16618. inline std::string get_cert_issuer_name(cert_t cert) {
  16619. if (!cert) return "";
  16620. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16621. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16622. if (!issuer) return "";
  16623. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16624. if (!name_str) return "";
  16625. std::string result(name_str);
  16626. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16627. return result;
  16628. }
  16629. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16630. sans.clear();
  16631. if (!cert) return false;
  16632. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16633. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16634. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16635. if (!san_names) return true; // No SANs is not an error
  16636. int count = wolfSSL_sk_num(san_names);
  16637. for (int i = 0; i < count; i++) {
  16638. auto *name =
  16639. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16640. if (!name) continue;
  16641. SanEntry entry;
  16642. switch (name->type) {
  16643. case WOLFSSL_GEN_DNS: {
  16644. entry.type = SanType::DNS;
  16645. unsigned char *dns_name = nullptr;
  16646. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16647. if (dns_name && dns_len > 0) {
  16648. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16649. static_cast<size_t>(dns_len));
  16650. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16651. }
  16652. break;
  16653. }
  16654. case WOLFSSL_GEN_IPADD: {
  16655. entry.type = SanType::IP;
  16656. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16657. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16658. if (ip_data && ip_len == 4) {
  16659. char buf[16];
  16660. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16661. ip_data[2], ip_data[3]);
  16662. entry.value = buf;
  16663. } else if (ip_data && ip_len == 16) {
  16664. char buf[64];
  16665. snprintf(buf, sizeof(buf),
  16666. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16667. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16668. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16669. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16670. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16671. ip_data[14], ip_data[15]);
  16672. entry.value = buf;
  16673. }
  16674. break;
  16675. }
  16676. case WOLFSSL_GEN_EMAIL:
  16677. entry.type = SanType::EMAIL;
  16678. {
  16679. unsigned char *email = nullptr;
  16680. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16681. if (email && email_len > 0) {
  16682. entry.value = std::string(reinterpret_cast<char *>(email),
  16683. static_cast<size_t>(email_len));
  16684. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16685. }
  16686. }
  16687. break;
  16688. case WOLFSSL_GEN_URI:
  16689. entry.type = SanType::URI;
  16690. {
  16691. unsigned char *uri = nullptr;
  16692. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16693. &uri, name->d.uniformResourceIdentifier);
  16694. if (uri && uri_len > 0) {
  16695. entry.value = std::string(reinterpret_cast<char *>(uri),
  16696. static_cast<size_t>(uri_len));
  16697. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16698. }
  16699. }
  16700. break;
  16701. default: entry.type = SanType::OTHER; break;
  16702. }
  16703. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16704. }
  16705. wolfSSL_sk_free(san_names);
  16706. return true;
  16707. }
  16708. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16709. time_t &not_after) {
  16710. if (!cert) return false;
  16711. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16712. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16713. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16714. if (!nb || !na) return false;
  16715. // wolfSSL_ASN1_TIME_to_tm is available
  16716. struct tm tm_nb = {}, tm_na = {};
  16717. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16718. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16719. #ifdef _WIN32
  16720. not_before = _mkgmtime(&tm_nb);
  16721. not_after = _mkgmtime(&tm_na);
  16722. #else
  16723. not_before = timegm(&tm_nb);
  16724. not_after = timegm(&tm_na);
  16725. #endif
  16726. return true;
  16727. }
  16728. inline std::string get_cert_serial(cert_t cert) {
  16729. if (!cert) return "";
  16730. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16731. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16732. if (!serial_asn1) return "";
  16733. // Get the serial number data
  16734. int len = serial_asn1->length;
  16735. unsigned char *data = serial_asn1->data;
  16736. if (!data || len <= 0) return "";
  16737. std::string result;
  16738. result.reserve(static_cast<size_t>(len) * 2);
  16739. for (int i = 0; i < len; i++) {
  16740. char hex[3];
  16741. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16742. result += hex;
  16743. }
  16744. return result;
  16745. }
  16746. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16747. if (!cert) return false;
  16748. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16749. int der_len = 0;
  16750. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  16751. if (!der_data || der_len <= 0) return false;
  16752. der.assign(der_data, der_data + der_len);
  16753. return true;
  16754. }
  16755. inline const char *get_sni(const_session_t session) {
  16756. if (!session) return nullptr;
  16757. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  16758. // For server: return SNI received from client during handshake
  16759. if (!wsession->sni_hostname.empty()) {
  16760. return wsession->sni_hostname.c_str();
  16761. }
  16762. // For client: return the hostname set via set_sni
  16763. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  16764. return nullptr;
  16765. }
  16766. inline uint64_t peek_error() {
  16767. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16768. }
  16769. inline uint64_t get_error() {
  16770. uint64_t err = impl::wolfssl_last_error();
  16771. impl::wolfssl_last_error() = 0;
  16772. return err;
  16773. }
  16774. inline std::string error_string(uint64_t code) {
  16775. char buf[256];
  16776. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  16777. return std::string(buf);
  16778. }
  16779. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16780. if (!pem || len == 0) { return nullptr; }
  16781. // Validate by attempting to load into a temporary ctx
  16782. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  16783. if (!tmp_ctx) { return nullptr; }
  16784. int ret = wolfSSL_CTX_load_verify_buffer(
  16785. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  16786. static_cast<long>(len), SSL_FILETYPE_PEM);
  16787. wolfSSL_CTX_free(tmp_ctx);
  16788. if (ret != SSL_SUCCESS) { return nullptr; }
  16789. return static_cast<ca_store_t>(
  16790. new impl::WolfSSLCAStore{std::string(pem, len)});
  16791. }
  16792. inline void free_ca_store(ca_store_t store) {
  16793. delete static_cast<impl::WolfSSLCAStore *>(store);
  16794. }
  16795. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16796. if (!ctx || !store) { return false; }
  16797. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16798. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  16799. int ret = wolfSSL_CTX_load_verify_buffer(
  16800. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  16801. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  16802. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  16803. return ret == SSL_SUCCESS;
  16804. }
  16805. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16806. certs.clear();
  16807. if (!ctx) { return 0; }
  16808. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16809. if (wctx->ca_pem_data_.empty()) { return 0; }
  16810. const std::string &pem = wctx->ca_pem_data_;
  16811. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16812. const std::string end_marker = "-----END CERTIFICATE-----";
  16813. size_t pos = 0;
  16814. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16815. size_t end_pos = pem.find(end_marker, pos);
  16816. if (end_pos == std::string::npos) { break; }
  16817. end_pos += end_marker.size();
  16818. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16819. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16820. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16821. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16822. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  16823. pos = end_pos;
  16824. }
  16825. return certs.size();
  16826. }
  16827. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16828. std::vector<std::string> names;
  16829. if (!ctx) { return names; }
  16830. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16831. if (wctx->ca_pem_data_.empty()) { return names; }
  16832. const std::string &pem = wctx->ca_pem_data_;
  16833. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16834. const std::string end_marker = "-----END CERTIFICATE-----";
  16835. size_t pos = 0;
  16836. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16837. size_t end_pos = pem.find(end_marker, pos);
  16838. if (end_pos == std::string::npos) { break; }
  16839. end_pos += end_marker.size();
  16840. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16841. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16842. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16843. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16844. if (x509) {
  16845. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16846. if (subject) {
  16847. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  16848. if (name_str) {
  16849. names.push_back(name_str);
  16850. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16851. }
  16852. }
  16853. wolfSSL_X509_free(x509);
  16854. }
  16855. pos = end_pos;
  16856. }
  16857. return names;
  16858. }
  16859. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16860. const char *key_pem, const char *password) {
  16861. if (!ctx || !cert_pem || !key_pem) { return false; }
  16862. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16863. // Load new certificate
  16864. int ret = wolfSSL_CTX_use_certificate_buffer(
  16865. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  16866. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  16867. if (ret != SSL_SUCCESS) {
  16868. impl::wolfssl_last_error() =
  16869. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16870. return false;
  16871. }
  16872. // Set password if provided
  16873. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16874. // Load new private key
  16875. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16876. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  16877. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  16878. if (ret != SSL_SUCCESS) {
  16879. impl::wolfssl_last_error() =
  16880. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16881. return false;
  16882. }
  16883. return true;
  16884. }
  16885. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16886. if (!ctx || !ca_pem) { return false; }
  16887. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16888. int ret = wolfSSL_CTX_load_verify_buffer(
  16889. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  16890. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  16891. if (ret != SSL_SUCCESS) {
  16892. impl::wolfssl_last_error() =
  16893. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16894. return false;
  16895. }
  16896. return true;
  16897. }
  16898. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16899. if (!ctx) { return false; }
  16900. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16901. impl::get_verify_callback() = std::move(callback);
  16902. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  16903. if (wctx->has_verify_callback) {
  16904. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16905. impl::wolfssl_verify_callback);
  16906. } else {
  16907. wolfSSL_CTX_set_verify(
  16908. wctx->ctx,
  16909. wctx->verify_client
  16910. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  16911. : SSL_VERIFY_NONE,
  16912. nullptr);
  16913. }
  16914. return true;
  16915. }
  16916. inline long get_verify_error(const_session_t session) {
  16917. if (!session) { return -1; }
  16918. auto *wsession =
  16919. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16920. return wolfSSL_get_verify_result(wsession->ssl);
  16921. }
  16922. inline std::string verify_error_string(long error_code) {
  16923. if (error_code == 0) { return ""; }
  16924. const char *str =
  16925. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  16926. return str ? std::string(str) : std::string();
  16927. }
  16928. } // namespace tls
  16929. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  16930. // WebSocket implementation
  16931. namespace ws {
  16932. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  16933. bool fin) {
  16934. std::lock_guard<std::mutex> lock(write_mutex_);
  16935. if (closed_) { return false; }
  16936. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  16937. }
  16938. inline ReadResult WebSocket::read(std::string &msg) {
  16939. while (!closed_) {
  16940. Opcode opcode;
  16941. std::string payload;
  16942. bool fin;
  16943. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  16944. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16945. closed_ = true;
  16946. return Fail;
  16947. }
  16948. switch (opcode) {
  16949. case Opcode::Ping: {
  16950. std::lock_guard<std::mutex> lock(write_mutex_);
  16951. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  16952. payload.size(), true, !is_server_);
  16953. continue;
  16954. }
  16955. case Opcode::Pong: continue;
  16956. case Opcode::Close: {
  16957. if (!closed_.exchange(true)) {
  16958. // Echo close frame back
  16959. std::lock_guard<std::mutex> lock(write_mutex_);
  16960. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  16961. payload.size(), true, !is_server_);
  16962. }
  16963. return Fail;
  16964. }
  16965. case Opcode::Text:
  16966. case Opcode::Binary: {
  16967. auto result = opcode == Opcode::Text ? Text : Binary;
  16968. msg = std::move(payload);
  16969. // Handle fragmentation
  16970. if (!fin) {
  16971. while (true) {
  16972. Opcode cont_opcode;
  16973. std::string cont_payload;
  16974. bool cont_fin;
  16975. if (!impl::read_websocket_frame(
  16976. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  16977. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16978. closed_ = true;
  16979. return Fail;
  16980. }
  16981. if (cont_opcode == Opcode::Ping) {
  16982. std::lock_guard<std::mutex> lock(write_mutex_);
  16983. detail::write_websocket_frame(
  16984. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  16985. true, !is_server_);
  16986. continue;
  16987. }
  16988. if (cont_opcode == Opcode::Pong) { continue; }
  16989. if (cont_opcode == Opcode::Close) {
  16990. if (!closed_.exchange(true)) {
  16991. std::lock_guard<std::mutex> lock(write_mutex_);
  16992. detail::write_websocket_frame(
  16993. strm_, Opcode::Close, cont_payload.data(),
  16994. cont_payload.size(), true, !is_server_);
  16995. }
  16996. return Fail;
  16997. }
  16998. // RFC 6455: continuation frames must use opcode 0x0
  16999. if (cont_opcode != Opcode::Continuation) {
  17000. closed_ = true;
  17001. return Fail;
  17002. }
  17003. msg += cont_payload;
  17004. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17005. closed_ = true;
  17006. return Fail;
  17007. }
  17008. if (cont_fin) { break; }
  17009. }
  17010. }
  17011. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17012. if (result == Text && !impl::is_valid_utf8(msg)) {
  17013. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17014. return Fail;
  17015. }
  17016. return result;
  17017. }
  17018. default: closed_ = true; return Fail;
  17019. }
  17020. }
  17021. return Fail;
  17022. }
  17023. inline bool WebSocket::send(const std::string &data) {
  17024. return send_frame(Opcode::Text, data.data(), data.size());
  17025. }
  17026. inline bool WebSocket::send(const char *data, size_t len) {
  17027. return send_frame(Opcode::Binary, data, len);
  17028. }
  17029. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17030. if (closed_.exchange(true)) { return; }
  17031. ping_cv_.notify_all();
  17032. std::string payload;
  17033. auto code = static_cast<uint16_t>(status);
  17034. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17035. payload.push_back(static_cast<char>(code & 0xFF));
  17036. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17037. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17038. payload += reason.substr(0, 123);
  17039. {
  17040. std::lock_guard<std::mutex> lock(write_mutex_);
  17041. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17042. payload.size(), true, !is_server_);
  17043. }
  17044. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17045. // Close response before closing the TCP connection. Use a short timeout to
  17046. // avoid hanging if the peer doesn't respond.
  17047. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17048. Opcode op;
  17049. std::string resp;
  17050. bool fin;
  17051. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17052. if (op == Opcode::Close) { break; }
  17053. }
  17054. }
  17055. inline WebSocket::~WebSocket() {
  17056. {
  17057. std::lock_guard<std::mutex> lock(ping_mutex_);
  17058. closed_ = true;
  17059. }
  17060. ping_cv_.notify_all();
  17061. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17062. }
  17063. inline void WebSocket::start_heartbeat() {
  17064. if (ping_interval_sec_ == 0) { return; }
  17065. ping_thread_ = std::thread([this]() {
  17066. std::unique_lock<std::mutex> lock(ping_mutex_);
  17067. while (!closed_) {
  17068. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17069. if (closed_) { break; }
  17070. lock.unlock();
  17071. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17072. closed_ = true;
  17073. break;
  17074. }
  17075. lock.lock();
  17076. }
  17077. });
  17078. }
  17079. inline const Request &WebSocket::request() const { return req_; }
  17080. inline bool WebSocket::is_open() const { return !closed_; }
  17081. // WebSocketClient implementation
  17082. inline WebSocketClient::WebSocketClient(
  17083. const std::string &scheme_host_port_path, const Headers &headers)
  17084. : headers_(headers) {
  17085. const static std::regex re(
  17086. R"(([a-z]+):\/\/(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?(\/.*))");
  17087. std::smatch m;
  17088. if (std::regex_match(scheme_host_port_path, m, re)) {
  17089. auto scheme = m[1].str();
  17090. #ifdef CPPHTTPLIB_SSL_ENABLED
  17091. if (scheme != "ws" && scheme != "wss") {
  17092. #else
  17093. if (scheme != "ws") {
  17094. #endif
  17095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17096. std::string msg = "'" + scheme + "' scheme is not supported.";
  17097. throw std::invalid_argument(msg);
  17098. #endif
  17099. return;
  17100. }
  17101. auto is_ssl = scheme == "wss";
  17102. host_ = m[2].str();
  17103. if (host_.empty()) { host_ = m[3].str(); }
  17104. auto port_str = m[4].str();
  17105. port_ = is_ssl ? 443 : 80;
  17106. if (!port_str.empty() && !detail::parse_port(port_str, port_)) { return; }
  17107. path_ = m[5].str();
  17108. #ifdef CPPHTTPLIB_SSL_ENABLED
  17109. is_ssl_ = is_ssl;
  17110. #else
  17111. if (is_ssl) { return; }
  17112. #endif
  17113. is_valid_ = true;
  17114. }
  17115. }
  17116. inline WebSocketClient::~WebSocketClient() { shutdown_and_close(); }
  17117. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17118. inline void WebSocketClient::shutdown_and_close() {
  17119. #ifdef CPPHTTPLIB_SSL_ENABLED
  17120. if (is_ssl_) {
  17121. if (tls_session_) {
  17122. tls::shutdown(tls_session_, true);
  17123. tls::free_session(tls_session_);
  17124. tls_session_ = nullptr;
  17125. }
  17126. if (tls_ctx_) {
  17127. tls::free_context(tls_ctx_);
  17128. tls_ctx_ = nullptr;
  17129. }
  17130. }
  17131. #endif
  17132. if (ws_ && ws_->is_open()) { ws_->close(); }
  17133. ws_.reset();
  17134. if (sock_ != INVALID_SOCKET) {
  17135. detail::shutdown_socket(sock_);
  17136. detail::close_socket(sock_);
  17137. sock_ = INVALID_SOCKET;
  17138. }
  17139. }
  17140. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17141. #ifdef CPPHTTPLIB_SSL_ENABLED
  17142. if (is_ssl_) {
  17143. if (!detail::setup_client_tls_session(
  17144. host_, tls_ctx_, tls_session_, sock_,
  17145. server_certificate_verification_, ca_cert_file_path_,
  17146. ca_cert_store_, read_timeout_sec_, read_timeout_usec_)) {
  17147. return false;
  17148. }
  17149. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17150. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17151. write_timeout_sec_, write_timeout_usec_));
  17152. return true;
  17153. }
  17154. #endif
  17155. strm = std::unique_ptr<Stream>(
  17156. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17157. write_timeout_sec_, write_timeout_usec_));
  17158. return true;
  17159. }
  17160. inline bool WebSocketClient::connect() {
  17161. if (!is_valid_) { return false; }
  17162. shutdown_and_close();
  17163. Error error;
  17164. sock_ = detail::create_client_socket(
  17165. host_, std::string(), port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17166. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17167. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17168. write_timeout_usec_, interface_, error);
  17169. if (sock_ == INVALID_SOCKET) { return false; }
  17170. std::unique_ptr<Stream> strm;
  17171. if (!create_stream(strm)) {
  17172. shutdown_and_close();
  17173. return false;
  17174. }
  17175. std::string selected_subprotocol;
  17176. if (!detail::perform_websocket_handshake(*strm, host_, port_, path_, headers_,
  17177. selected_subprotocol)) {
  17178. shutdown_and_close();
  17179. return false;
  17180. }
  17181. subprotocol_ = std::move(selected_subprotocol);
  17182. Request req;
  17183. req.method = "GET";
  17184. req.path = path_;
  17185. ws_ = std::unique_ptr<WebSocket>(
  17186. new WebSocket(std::move(strm), req, false, websocket_ping_interval_sec_));
  17187. return true;
  17188. }
  17189. inline ReadResult WebSocketClient::read(std::string &msg) {
  17190. if (!ws_) { return Fail; }
  17191. return ws_->read(msg);
  17192. }
  17193. inline bool WebSocketClient::send(const std::string &data) {
  17194. if (!ws_) { return false; }
  17195. return ws_->send(data);
  17196. }
  17197. inline bool WebSocketClient::send(const char *data, size_t len) {
  17198. if (!ws_) { return false; }
  17199. return ws_->send(data, len);
  17200. }
  17201. inline void WebSocketClient::close(CloseStatus status,
  17202. const std::string &reason) {
  17203. if (ws_) { ws_->close(status, reason); }
  17204. }
  17205. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17206. inline const std::string &WebSocketClient::subprotocol() const {
  17207. return subprotocol_;
  17208. }
  17209. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17210. read_timeout_sec_ = sec;
  17211. read_timeout_usec_ = usec;
  17212. }
  17213. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17214. write_timeout_sec_ = sec;
  17215. write_timeout_usec_ = usec;
  17216. }
  17217. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17218. websocket_ping_interval_sec_ = sec;
  17219. }
  17220. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17221. inline void WebSocketClient::set_address_family(int family) {
  17222. address_family_ = family;
  17223. }
  17224. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17225. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17226. socket_options_ = std::move(socket_options);
  17227. }
  17228. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17229. connection_timeout_sec_ = sec;
  17230. connection_timeout_usec_ = usec;
  17231. }
  17232. inline void WebSocketClient::set_interface(const std::string &intf) {
  17233. interface_ = intf;
  17234. }
  17235. #ifdef CPPHTTPLIB_SSL_ENABLED
  17236. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17237. ca_cert_file_path_ = path;
  17238. }
  17239. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17240. ca_cert_store_ = store;
  17241. }
  17242. inline void
  17243. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17244. server_certificate_verification_ = enabled;
  17245. }
  17246. #endif // CPPHTTPLIB_SSL_ENABLED
  17247. } // namespace ws
  17248. // ----------------------------------------------------------------------------
  17249. } // namespace httplib
  17250. #endif // CPPHTTPLIB_HTTPLIB_H