httplib.h 685 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741
  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.49.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003100"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. #ifndef CPPHTTPLIB_TCP_NODELAY
  109. #define CPPHTTPLIB_TCP_NODELAY false
  110. #endif
  111. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  112. #define CPPHTTPLIB_IPV6_V6ONLY false
  113. #endif
  114. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  115. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  116. #endif
  117. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  118. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  119. #endif
  120. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  121. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  124. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  125. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  126. ? std::thread::hardware_concurrency() - 1 \
  127. : 0))
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  131. #endif
  132. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  133. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  148. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  149. #endif
  150. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  151. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  152. #endif
  153. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  154. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  155. #endif
  156. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  157. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  158. #endif
  159. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  160. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  161. #endif
  162. /*
  163. * Headers
  164. */
  165. #ifdef _WIN32
  166. #ifndef _CRT_SECURE_NO_WARNINGS
  167. #define _CRT_SECURE_NO_WARNINGS
  168. #endif //_CRT_SECURE_NO_WARNINGS
  169. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  170. #define _CRT_NONSTDC_NO_DEPRECATE
  171. #endif //_CRT_NONSTDC_NO_DEPRECATE
  172. #if defined(_MSC_VER)
  173. #if _MSC_VER < 1900
  174. #error Sorry, Visual Studio versions prior to 2015 are not supported
  175. #endif
  176. #pragma comment(lib, "ws2_32.lib")
  177. #ifndef _SSIZE_T_DEFINED
  178. using ssize_t = __int64;
  179. #define _SSIZE_T_DEFINED
  180. #endif
  181. #endif // _MSC_VER
  182. #ifndef S_ISREG
  183. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  184. #endif // S_ISREG
  185. #ifndef S_ISDIR
  186. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  187. #endif // S_ISDIR
  188. #ifndef NOMINMAX
  189. #define NOMINMAX
  190. #endif // NOMINMAX
  191. #include <io.h>
  192. #include <winsock2.h>
  193. #include <ws2tcpip.h>
  194. #if defined(__has_include)
  195. #if __has_include(<afunix.h>)
  196. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  197. #include <afunix.h>
  198. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  199. #endif
  200. #endif
  201. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  202. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  203. #endif
  204. using nfds_t = unsigned long;
  205. using socket_t = SOCKET;
  206. using socklen_t = int;
  207. #else // not _WIN32
  208. #include <arpa/inet.h>
  209. #if !defined(_AIX) && !defined(__MVS__)
  210. #include <ifaddrs.h>
  211. #endif
  212. #ifdef __MVS__
  213. #include <strings.h>
  214. #ifndef NI_MAXHOST
  215. #define NI_MAXHOST 1025
  216. #endif
  217. #endif
  218. #include <net/if.h>
  219. #include <netdb.h>
  220. #include <netinet/in.h>
  221. #ifdef __linux__
  222. #include <resolv.h>
  223. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  224. #endif
  225. #include <csignal>
  226. #include <netinet/tcp.h>
  227. #include <poll.h>
  228. #include <pthread.h>
  229. #include <sys/mman.h>
  230. #include <sys/socket.h>
  231. #include <sys/un.h>
  232. #include <unistd.h>
  233. using socket_t = int;
  234. #ifndef INVALID_SOCKET
  235. #define INVALID_SOCKET (-1)
  236. #endif
  237. #endif //_WIN32
  238. #if defined(__APPLE__)
  239. #include <TargetConditionals.h>
  240. #endif
  241. #include <algorithm>
  242. #include <array>
  243. #include <atomic>
  244. #include <cassert>
  245. #include <chrono>
  246. #include <climits>
  247. #include <condition_variable>
  248. #include <cstdlib>
  249. #include <cstring>
  250. #include <errno.h>
  251. #include <exception>
  252. #include <fcntl.h>
  253. #include <fstream>
  254. #include <functional>
  255. #include <iomanip>
  256. #include <iostream>
  257. #include <list>
  258. #include <map>
  259. #include <memory>
  260. #include <mutex>
  261. #include <random>
  262. #include <regex>
  263. #include <set>
  264. #include <sstream>
  265. #include <string>
  266. #include <sys/stat.h>
  267. #include <system_error>
  268. #include <thread>
  269. #include <unordered_map>
  270. #include <unordered_set>
  271. #include <utility>
  272. // On macOS with a TLS backend, enable Keychain root certificates by default
  273. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  274. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  275. // only; on those platforms the user must provide a CA bundle explicitly.
  276. #if defined(__APPLE__) && defined(__clang__) && \
  277. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  278. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  279. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  280. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  281. #if TARGET_OS_OSX
  282. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  283. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  284. #endif
  285. #endif
  286. #endif
  287. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  288. defined(__APPLE__) && !TARGET_OS_OSX
  289. #error \
  290. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  291. #endif
  292. // On Windows, enable Schannel certificate verification by default
  293. // unless the user explicitly opts out.
  294. #if defined(_WIN32) && \
  295. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  296. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  297. #endif
  298. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  299. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  300. #if TARGET_OS_MAC && defined(__clang__)
  301. #include <CFNetwork/CFHost.h>
  302. #include <CoreFoundation/CoreFoundation.h>
  303. #endif
  304. #endif
  305. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  306. #ifdef _WIN32
  307. #include <wincrypt.h>
  308. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  309. // used
  310. #undef X509_NAME
  311. #undef X509_CERT_PAIR
  312. #undef X509_EXTENSIONS
  313. #undef PKCS7_SIGNER_INFO
  314. #ifdef _MSC_VER
  315. #pragma comment(lib, "crypt32.lib")
  316. #endif
  317. #endif // _WIN32
  318. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  319. #if TARGET_OS_OSX
  320. #include <Security/Security.h>
  321. #endif
  322. #endif
  323. #include <openssl/err.h>
  324. #include <openssl/evp.h>
  325. #include <openssl/ssl.h>
  326. #include <openssl/x509v3.h>
  327. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  328. #include <openssl/applink.c>
  329. #endif
  330. #include <iostream>
  331. #include <sstream>
  332. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  333. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  334. #error Please use OpenSSL or a current version of BoringSSL
  335. #endif
  336. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  337. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  338. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  339. #endif
  340. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  341. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  342. #include <mbedtls/ctr_drbg.h>
  343. #include <mbedtls/entropy.h>
  344. #include <mbedtls/error.h>
  345. #include <mbedtls/md5.h>
  346. #include <mbedtls/net_sockets.h>
  347. #include <mbedtls/oid.h>
  348. #include <mbedtls/pk.h>
  349. #include <mbedtls/sha1.h>
  350. #include <mbedtls/sha256.h>
  351. #include <mbedtls/sha512.h>
  352. #include <mbedtls/ssl.h>
  353. #include <mbedtls/x509_crt.h>
  354. #ifdef _WIN32
  355. #include <wincrypt.h>
  356. #ifdef _MSC_VER
  357. #pragma comment(lib, "crypt32.lib")
  358. #endif
  359. #endif // _WIN32
  360. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  361. #if TARGET_OS_OSX
  362. #include <Security/Security.h>
  363. #endif
  364. #endif
  365. // Mbed TLS 3.x API compatibility
  366. #if MBEDTLS_VERSION_MAJOR >= 3
  367. #define CPPHTTPLIB_MBEDTLS_V3
  368. #endif
  369. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  370. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  371. #include <wolfssl/options.h>
  372. #include <wolfssl/openssl/x509v3.h>
  373. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  374. #ifndef WOLFSSL_GEN_EMAIL
  375. #define WOLFSSL_GEN_EMAIL 1
  376. #endif
  377. #ifndef WOLFSSL_GEN_DNS
  378. #define WOLFSSL_GEN_DNS 2
  379. #endif
  380. #ifndef WOLFSSL_GEN_URI
  381. #define WOLFSSL_GEN_URI 6
  382. #endif
  383. #ifndef WOLFSSL_GEN_IPADD
  384. #define WOLFSSL_GEN_IPADD 7
  385. #endif
  386. #include <wolfssl/ssl.h>
  387. #include <wolfssl/wolfcrypt/hash.h>
  388. #include <wolfssl/wolfcrypt/md5.h>
  389. #include <wolfssl/wolfcrypt/sha256.h>
  390. #include <wolfssl/wolfcrypt/sha512.h>
  391. #ifdef _WIN32
  392. #include <wincrypt.h>
  393. #ifdef _MSC_VER
  394. #pragma comment(lib, "crypt32.lib")
  395. #endif
  396. #endif // _WIN32
  397. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  398. #if TARGET_OS_OSX
  399. #include <Security/Security.h>
  400. #endif
  401. #endif
  402. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  403. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  404. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  405. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  406. #define CPPHTTPLIB_SSL_ENABLED
  407. #endif
  408. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  409. #include <zlib.h>
  410. #endif
  411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  412. #include <brotli/decode.h>
  413. #include <brotli/encode.h>
  414. #endif
  415. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  416. #include <zstd.h>
  417. #endif
  418. /*
  419. * Declaration
  420. */
  421. namespace httplib {
  422. namespace ws {
  423. class WebSocket;
  424. } // namespace ws
  425. namespace detail {
  426. /*
  427. * Backport std::make_unique from C++14.
  428. *
  429. * NOTE: This code came up with the following stackoverflow post:
  430. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  431. *
  432. */
  433. template <class T, class... Args>
  434. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  435. make_unique(Args &&...args) {
  436. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  437. }
  438. template <class T>
  439. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  440. make_unique(std::size_t n) {
  441. typedef typename std::remove_extent<T>::type RT;
  442. return std::unique_ptr<T>(new RT[n]);
  443. }
  444. // Locale-independent ASCII character classification. The <cctype>
  445. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  446. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  447. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  448. // classified without regard to the locale.
  449. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  450. inline bool is_ascii_alpha(char c) {
  451. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  452. }
  453. inline bool is_ascii_alnum(char c) {
  454. return is_ascii_digit(c) || is_ascii_alpha(c);
  455. }
  456. namespace case_ignore {
  457. inline unsigned char to_lower(int c) {
  458. const static unsigned char table[256] = {
  459. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  460. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  461. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  462. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  463. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  464. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  465. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  466. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  467. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  468. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  469. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  470. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  471. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  472. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  473. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  474. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  475. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  476. 255,
  477. };
  478. return table[(unsigned char)(char)c];
  479. }
  480. inline std::string to_lower(const std::string &s) {
  481. std::string result = s;
  482. std::transform(
  483. result.begin(), result.end(), result.begin(),
  484. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  485. return result;
  486. }
  487. inline bool equal(const std::string &a, const std::string &b) {
  488. return a.size() == b.size() &&
  489. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  490. return to_lower(ca) == to_lower(cb);
  491. });
  492. }
  493. struct equal_to {
  494. bool operator()(const std::string &a, const std::string &b) const {
  495. return equal(a, b);
  496. }
  497. };
  498. struct hash {
  499. size_t operator()(const std::string &key) const {
  500. return hash_core(key.data(), key.size(), 0);
  501. }
  502. size_t hash_core(const char *s, size_t l, size_t h) const {
  503. return (l == 0) ? h
  504. : hash_core(s + 1, l - 1,
  505. // Unsets the 6 high bits of h, therefore no
  506. // overflow happens
  507. (((std::numeric_limits<size_t>::max)() >> 6) &
  508. h * 33) ^
  509. static_cast<unsigned char>(to_lower(*s)));
  510. }
  511. };
  512. template <typename T>
  513. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  514. detail::case_ignore::equal_to>;
  515. } // namespace case_ignore
  516. // This is based on
  517. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  518. struct scope_exit {
  519. explicit scope_exit(std::function<void(void)> &&f)
  520. : exit_function(std::move(f)), execute_on_destruction{true} {}
  521. scope_exit(scope_exit &&rhs) noexcept
  522. : exit_function(std::move(rhs.exit_function)),
  523. execute_on_destruction{rhs.execute_on_destruction} {
  524. rhs.release();
  525. }
  526. ~scope_exit() {
  527. if (execute_on_destruction) { this->exit_function(); }
  528. }
  529. void release() { this->execute_on_destruction = false; }
  530. private:
  531. scope_exit(const scope_exit &) = delete;
  532. void operator=(const scope_exit &) = delete;
  533. scope_exit &operator=(scope_exit &&) = delete;
  534. std::function<void(void)> exit_function;
  535. bool execute_on_destruction;
  536. };
  537. // Simple from_chars implementation for integer and double types (C++17
  538. // substitute)
  539. template <typename T> struct from_chars_result {
  540. const char *ptr;
  541. std::errc ec;
  542. };
  543. template <typename T>
  544. inline from_chars_result<T> from_chars(const char *first, const char *last,
  545. T &value, int base = 10) {
  546. value = 0;
  547. const char *p = first;
  548. bool negative = false;
  549. if (p != last && *p == '-') {
  550. negative = true;
  551. ++p;
  552. }
  553. if (p == last) { return {first, std::errc::invalid_argument}; }
  554. T result = 0;
  555. for (; p != last; ++p) {
  556. char c = *p;
  557. int digit = -1;
  558. if (is_ascii_digit(c)) {
  559. digit = c - '0';
  560. } else if ('a' <= c && c <= 'z') {
  561. digit = c - 'a' + 10;
  562. } else if ('A' <= c && c <= 'Z') {
  563. digit = c - 'A' + 10;
  564. } else {
  565. break;
  566. }
  567. if (digit < 0 || digit >= base) { break; }
  568. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  569. return {p, std::errc::result_out_of_range};
  570. }
  571. result = result * base + digit;
  572. }
  573. if (p == first || (negative && p == first + 1)) {
  574. return {first, std::errc::invalid_argument};
  575. }
  576. value = negative ? -result : result;
  577. return {p, std::errc{}};
  578. }
  579. // from_chars for double (hand-written, locale-independent)
  580. //
  581. // The only double consumed by this library is the HTTP quality value, whose
  582. // grammar is (RFC 9110 12.4.2):
  583. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  584. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  585. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  586. // '.' always the decimal separator (std::strtod would instead read it from the
  587. // global C locale, mis-parsing q-values once an embedder calls
  588. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  589. // the result to [0, 1], so inputs outside that range need not be distinguished
  590. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  591. // cases that exponent and wide-range handling would introduce.
  592. inline from_chars_result<double> from_chars(const char *first, const char *last,
  593. double &value) {
  594. value = 0.0;
  595. const char *p = first;
  596. // Each 1eN is exactly representable, so a single final division by the
  597. // matching entry yields a correctly-rounded result.
  598. static const double powers_of_ten[] = {
  599. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  600. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  601. const int max_frac_digits =
  602. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  603. // Accumulate digits into a 64-bit integer and remember how many were
  604. // fractional. Two independent caps keep this bounded and safe:
  605. // * accumulation saturates before mantissa could overflow uint64_t, and
  606. // * frac_digits is capped at max_frac_digits so it is always a valid index
  607. // into powers_of_ten (without this an input like "0.000...0" would never
  608. // grow mantissa, so the saturation cap alone would not bound it).
  609. // Both caps only drop digits far beyond the precision a q-value needs; any
  610. // value they would change is well outside [0, 1] and rejected by the caller.
  611. uint64_t mantissa = 0;
  612. int frac_digits = 0;
  613. bool seen_digit = false;
  614. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  615. auto accumulate = [&](char c) {
  616. if (mantissa <= limit) {
  617. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  618. return true;
  619. }
  620. return false;
  621. };
  622. for (; p != last && is_ascii_digit(*p); ++p) {
  623. seen_digit = true;
  624. accumulate(*p);
  625. }
  626. if (p != last && *p == '.') {
  627. ++p;
  628. for (; p != last && is_ascii_digit(*p); ++p) {
  629. seen_digit = true;
  630. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  631. }
  632. }
  633. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  634. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  635. return {p, std::errc{}};
  636. }
  637. inline bool parse_port(const char *s, size_t len, int &port) {
  638. int val = 0;
  639. auto r = from_chars(s, s + len, val);
  640. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  641. port = val;
  642. return true;
  643. }
  644. inline bool parse_port(const std::string &s, int &port) {
  645. return parse_port(s.data(), s.size(), port);
  646. }
  647. struct UrlComponents {
  648. std::string scheme;
  649. std::string host;
  650. std::string port;
  651. std::string path;
  652. std::string query;
  653. };
  654. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  655. uc = {};
  656. size_t pos = 0;
  657. auto sep = url.find("://");
  658. if (sep != std::string::npos) {
  659. uc.scheme = url.substr(0, sep);
  660. // Scheme must be [a-z]+ only
  661. if (uc.scheme.empty()) { return false; }
  662. for (auto c : uc.scheme) {
  663. if (c < 'a' || c > 'z') { return false; }
  664. }
  665. pos = sep + 3;
  666. } else if (url.compare(0, 2, "//") == 0) {
  667. pos = 2;
  668. }
  669. auto has_authority_prefix = pos > 0;
  670. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  671. url[0] != '?' && url[0] != '#');
  672. if (has_authority) {
  673. if (pos < url.size() && url[pos] == '[') {
  674. auto close = url.find(']', pos);
  675. if (close == std::string::npos) { return false; }
  676. uc.host = url.substr(pos + 1, close - pos - 1);
  677. // IPv6 host must be [a-fA-F0-9:]+ only
  678. if (uc.host.empty()) { return false; }
  679. for (auto c : uc.host) {
  680. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  681. (c >= 'A' && c <= 'F') || c == ':')) {
  682. return false;
  683. }
  684. }
  685. pos = close + 1;
  686. } else {
  687. auto end = url.find_first_of(":/?#", pos);
  688. if (end == std::string::npos) { end = url.size(); }
  689. uc.host = url.substr(pos, end - pos);
  690. pos = end;
  691. }
  692. if (pos < url.size() && url[pos] == ':') {
  693. ++pos;
  694. auto end = url.find_first_of("/?#", pos);
  695. if (end == std::string::npos) { end = url.size(); }
  696. uc.port = url.substr(pos, end - pos);
  697. pos = end;
  698. }
  699. // Without :// or //, the entire input must be consumed as host[:port].
  700. // If there is leftover (path, query, etc.), this is not a valid
  701. // host[:port] string — clear and reparse as a plain path.
  702. if (!has_authority_prefix && pos < url.size()) {
  703. uc.host.clear();
  704. uc.port.clear();
  705. pos = 0;
  706. }
  707. }
  708. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  709. auto end = url.find_first_of("?#", pos);
  710. if (end == std::string::npos) { end = url.size(); }
  711. uc.path = url.substr(pos, end - pos);
  712. pos = end;
  713. }
  714. if (pos < url.size() && url[pos] == '?') {
  715. auto end = url.find('#', pos);
  716. if (end == std::string::npos) { end = url.size(); }
  717. uc.query = url.substr(pos, end - pos);
  718. }
  719. return true;
  720. }
  721. } // namespace detail
  722. enum class SSLVerifierResponse {
  723. // no decision has been made, use the built-in certificate verifier
  724. NoDecisionMade,
  725. // connection certificate is verified and accepted
  726. CertificateAccepted,
  727. // connection certificate was processed but is rejected
  728. CertificateRejected
  729. };
  730. // System CA loading policy for SSL clients. Auto (the default) loads system
  731. // CA certs only when no custom CA is configured; enable_system_ca() switches
  732. // to an explicit policy.
  733. enum class SystemCAMode { Auto, Enabled, Disabled };
  734. enum StatusCode {
  735. // Information responses
  736. Continue_100 = 100,
  737. SwitchingProtocol_101 = 101,
  738. Processing_102 = 102,
  739. EarlyHints_103 = 103,
  740. // Successful responses
  741. OK_200 = 200,
  742. Created_201 = 201,
  743. Accepted_202 = 202,
  744. NonAuthoritativeInformation_203 = 203,
  745. NoContent_204 = 204,
  746. ResetContent_205 = 205,
  747. PartialContent_206 = 206,
  748. MultiStatus_207 = 207,
  749. AlreadyReported_208 = 208,
  750. IMUsed_226 = 226,
  751. // Redirection messages
  752. MultipleChoices_300 = 300,
  753. MovedPermanently_301 = 301,
  754. Found_302 = 302,
  755. SeeOther_303 = 303,
  756. NotModified_304 = 304,
  757. UseProxy_305 = 305,
  758. unused_306 = 306,
  759. TemporaryRedirect_307 = 307,
  760. PermanentRedirect_308 = 308,
  761. // Client error responses
  762. BadRequest_400 = 400,
  763. Unauthorized_401 = 401,
  764. PaymentRequired_402 = 402,
  765. Forbidden_403 = 403,
  766. NotFound_404 = 404,
  767. MethodNotAllowed_405 = 405,
  768. NotAcceptable_406 = 406,
  769. ProxyAuthenticationRequired_407 = 407,
  770. RequestTimeout_408 = 408,
  771. Conflict_409 = 409,
  772. Gone_410 = 410,
  773. LengthRequired_411 = 411,
  774. PreconditionFailed_412 = 412,
  775. PayloadTooLarge_413 = 413,
  776. UriTooLong_414 = 414,
  777. UnsupportedMediaType_415 = 415,
  778. RangeNotSatisfiable_416 = 416,
  779. ExpectationFailed_417 = 417,
  780. ImATeapot_418 = 418,
  781. MisdirectedRequest_421 = 421,
  782. UnprocessableContent_422 = 422,
  783. Locked_423 = 423,
  784. FailedDependency_424 = 424,
  785. TooEarly_425 = 425,
  786. UpgradeRequired_426 = 426,
  787. PreconditionRequired_428 = 428,
  788. TooManyRequests_429 = 429,
  789. RequestHeaderFieldsTooLarge_431 = 431,
  790. UnavailableForLegalReasons_451 = 451,
  791. // Server error responses
  792. InternalServerError_500 = 500,
  793. NotImplemented_501 = 501,
  794. BadGateway_502 = 502,
  795. ServiceUnavailable_503 = 503,
  796. GatewayTimeout_504 = 504,
  797. HttpVersionNotSupported_505 = 505,
  798. VariantAlsoNegotiates_506 = 506,
  799. InsufficientStorage_507 = 507,
  800. LoopDetected_508 = 508,
  801. NotExtended_510 = 510,
  802. NetworkAuthenticationRequired_511 = 511,
  803. };
  804. using Headers =
  805. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  806. detail::case_ignore::equal_to>;
  807. using Params = std::multimap<std::string, std::string>;
  808. using Match = std::smatch;
  809. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  810. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  811. /*
  812. * detail: type-erased storage used by UserData.
  813. * ABI-stable regardless of C++ standard — always uses this custom
  814. * implementation instead of std::any.
  815. */
  816. namespace detail {
  817. using any_type_id = const void *;
  818. template <typename T> any_type_id any_typeid() noexcept {
  819. static const char id = 0;
  820. return &id;
  821. }
  822. struct any_storage {
  823. virtual ~any_storage() = default;
  824. virtual std::unique_ptr<any_storage> clone() const = 0;
  825. virtual any_type_id type_id() const noexcept = 0;
  826. };
  827. template <typename T> struct any_value final : any_storage {
  828. T value;
  829. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  830. std::unique_ptr<any_storage> clone() const override {
  831. return std::unique_ptr<any_storage>(new any_value<T>(value));
  832. }
  833. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  834. };
  835. } // namespace detail
  836. class UserData {
  837. public:
  838. UserData() = default;
  839. UserData(UserData &&) noexcept = default;
  840. UserData &operator=(UserData &&) noexcept = default;
  841. UserData(const UserData &o) {
  842. for (const auto &e : o.entries_) {
  843. if (e.second) { entries_[e.first] = e.second->clone(); }
  844. }
  845. }
  846. UserData &operator=(const UserData &o) {
  847. if (this != &o) {
  848. entries_.clear();
  849. for (const auto &e : o.entries_) {
  850. if (e.second) { entries_[e.first] = e.second->clone(); }
  851. }
  852. }
  853. return *this;
  854. }
  855. template <typename T> void set(const std::string &key, T &&value) {
  856. using D = typename std::decay<T>::type;
  857. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  858. }
  859. template <typename T> T *get(const std::string &key) noexcept {
  860. auto it = entries_.find(key);
  861. if (it == entries_.end() || !it->second) { return nullptr; }
  862. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  863. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  864. }
  865. template <typename T> const T *get(const std::string &key) const noexcept {
  866. auto it = entries_.find(key);
  867. if (it == entries_.end() || !it->second) { return nullptr; }
  868. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  869. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  870. }
  871. bool has(const std::string &key) const noexcept {
  872. return entries_.find(key) != entries_.end();
  873. }
  874. void erase(const std::string &key) { entries_.erase(key); }
  875. void clear() noexcept { entries_.clear(); }
  876. private:
  877. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  878. entries_;
  879. };
  880. struct Response;
  881. using ResponseHandler = std::function<bool(const Response &response)>;
  882. struct FormData {
  883. std::string name;
  884. std::string content;
  885. std::string filename;
  886. std::string content_type;
  887. Headers headers;
  888. };
  889. struct FormField {
  890. std::string name;
  891. std::string content;
  892. Headers headers;
  893. };
  894. using FormFields = std::multimap<std::string, FormField>;
  895. using FormFiles = std::multimap<std::string, FormData>;
  896. struct MultipartFormData {
  897. FormFields fields; // Text fields from multipart
  898. FormFiles files; // Files from multipart
  899. // Text field access
  900. std::string get_field(const std::string &key, size_t id = 0) const;
  901. std::vector<std::string> get_fields(const std::string &key) const;
  902. bool has_field(const std::string &key) const;
  903. size_t get_field_count(const std::string &key) const;
  904. // File access
  905. FormData get_file(const std::string &key, size_t id = 0) const;
  906. std::vector<FormData> get_files(const std::string &key) const;
  907. bool has_file(const std::string &key) const;
  908. size_t get_file_count(const std::string &key) const;
  909. };
  910. struct UploadFormData {
  911. std::string name;
  912. std::string content;
  913. std::string filename;
  914. std::string content_type;
  915. };
  916. using UploadFormDataItems = std::vector<UploadFormData>;
  917. class DataSink {
  918. public:
  919. DataSink() : os(&sb_), sb_(*this) {}
  920. DataSink(const DataSink &) = delete;
  921. DataSink &operator=(const DataSink &) = delete;
  922. DataSink(DataSink &&) = delete;
  923. DataSink &operator=(DataSink &&) = delete;
  924. std::function<bool(const char *data, size_t data_len)> write;
  925. std::function<bool()> is_writable;
  926. std::function<void()> done;
  927. std::function<void(const Headers &trailer)> done_with_trailer;
  928. std::ostream os;
  929. private:
  930. class data_sink_streambuf final : public std::streambuf {
  931. public:
  932. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  933. protected:
  934. std::streamsize xsputn(const char *s, std::streamsize n) override {
  935. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  936. return 0;
  937. }
  938. private:
  939. DataSink &sink_;
  940. };
  941. data_sink_streambuf sb_;
  942. };
  943. using ContentProvider =
  944. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  945. using ContentProviderWithoutLength =
  946. std::function<bool(size_t offset, DataSink &sink)>;
  947. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  948. struct FormDataProvider {
  949. std::string name;
  950. ContentProviderWithoutLength provider;
  951. std::string filename;
  952. std::string content_type;
  953. };
  954. using FormDataProviderItems = std::vector<FormDataProvider>;
  955. inline FormDataProvider
  956. make_file_provider(const std::string &name, const std::string &filepath,
  957. const std::string &filename = std::string(),
  958. const std::string &content_type = std::string()) {
  959. FormDataProvider fdp;
  960. fdp.name = name;
  961. fdp.filename = filename.empty() ? filepath : filename;
  962. fdp.content_type = content_type;
  963. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  964. std::ifstream f(filepath, std::ios::binary);
  965. if (!f) { return false; }
  966. if (offset > 0) {
  967. f.seekg(static_cast<std::streamoff>(offset));
  968. if (!f.good()) {
  969. sink.done();
  970. return true;
  971. }
  972. }
  973. char buf[8192];
  974. f.read(buf, sizeof(buf));
  975. auto n = static_cast<size_t>(f.gcount());
  976. if (n > 0) { return sink.write(buf, n); }
  977. sink.done(); // EOF
  978. return true;
  979. };
  980. return fdp;
  981. }
  982. inline std::pair<size_t, ContentProvider>
  983. make_file_body(const std::string &filepath) {
  984. size_t size = 0;
  985. {
  986. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  987. if (!f) { return {0, ContentProvider{}}; }
  988. size = static_cast<size_t>(f.tellg());
  989. }
  990. ContentProvider provider = [filepath](size_t offset, size_t length,
  991. DataSink &sink) -> bool {
  992. std::ifstream f(filepath, std::ios::binary);
  993. if (!f) { return false; }
  994. f.seekg(static_cast<std::streamoff>(offset));
  995. if (!f.good()) { return false; }
  996. char buf[8192];
  997. while (length > 0) {
  998. auto to_read = (std::min)(sizeof(buf), length);
  999. f.read(buf, static_cast<std::streamsize>(to_read));
  1000. auto n = static_cast<size_t>(f.gcount());
  1001. if (n == 0) { break; }
  1002. if (!sink.write(buf, n)) { return false; }
  1003. length -= n;
  1004. }
  1005. return true;
  1006. };
  1007. return {size, std::move(provider)};
  1008. }
  1009. using ContentReceiverWithProgress = std::function<bool(
  1010. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1011. using ContentReceiver =
  1012. std::function<bool(const char *data, size_t data_length)>;
  1013. using FormDataHeader = std::function<bool(const FormData &file)>;
  1014. class ContentReader {
  1015. public:
  1016. using Reader = std::function<bool(ContentReceiver receiver)>;
  1017. using FormDataReader =
  1018. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1019. ContentReader(Reader reader, FormDataReader multipart_reader)
  1020. : reader_(std::move(reader)),
  1021. formdata_reader_(std::move(multipart_reader)) {}
  1022. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1023. return formdata_reader_(std::move(header), std::move(receiver));
  1024. }
  1025. bool operator()(ContentReceiver receiver) const {
  1026. return reader_(std::move(receiver));
  1027. }
  1028. Reader reader_;
  1029. FormDataReader formdata_reader_;
  1030. };
  1031. using Range = std::pair<ssize_t, ssize_t>;
  1032. using Ranges = std::vector<Range>;
  1033. #ifdef CPPHTTPLIB_SSL_ENABLED
  1034. // TLS abstraction layer - public type definitions and API
  1035. namespace tls {
  1036. // Opaque handles (defined as void* for abstraction)
  1037. using ctx_t = void *;
  1038. using session_t = void *;
  1039. using const_session_t = const void *; // For read-only session access
  1040. using cert_t = void *;
  1041. using ca_store_t = void *;
  1042. // TLS versions
  1043. enum class Version {
  1044. TLS1_2 = 0x0303,
  1045. TLS1_3 = 0x0304,
  1046. };
  1047. // Subject Alternative Names (SAN) entry types
  1048. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1049. // SAN entry structure
  1050. struct SanEntry {
  1051. SanType type;
  1052. std::string value;
  1053. };
  1054. // Verification context for certificate verification callback
  1055. struct VerifyContext {
  1056. session_t session; // TLS session handle
  1057. cert_t cert; // Current certificate being verified
  1058. int depth; // Certificate chain depth (0 = leaf)
  1059. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1060. long error_code; // Backend-specific error code (0 = no error)
  1061. const char *error_string; // Human-readable error description
  1062. // Certificate introspection methods
  1063. std::string subject_cn() const;
  1064. std::string issuer_name() const;
  1065. bool check_hostname(const char *hostname) const;
  1066. std::vector<SanEntry> sans() const;
  1067. bool validity(time_t &not_before, time_t &not_after) const;
  1068. std::string serial() const;
  1069. };
  1070. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1071. // TlsError codes for TLS operations (backend-independent)
  1072. enum class ErrorCode : int {
  1073. Success = 0,
  1074. WantRead, // Non-blocking: need to wait for read
  1075. WantWrite, // Non-blocking: need to wait for write
  1076. PeerClosed, // Peer closed the connection
  1077. Fatal, // Unrecoverable error
  1078. SyscallError, // System call error (check sys_errno)
  1079. CertVerifyFailed, // Certificate verification failed
  1080. HostnameMismatch, // Hostname verification failed
  1081. };
  1082. // TLS error information
  1083. struct TlsError {
  1084. ErrorCode code = ErrorCode::Fatal;
  1085. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1086. int sys_errno = 0; // errno when SyscallError
  1087. // Convert verification error code to human-readable string
  1088. static std::string verify_error_to_string(long error_code);
  1089. };
  1090. // RAII wrapper for peer certificate
  1091. class PeerCert {
  1092. public:
  1093. PeerCert();
  1094. PeerCert(PeerCert &&other) noexcept;
  1095. PeerCert &operator=(PeerCert &&other) noexcept;
  1096. ~PeerCert();
  1097. PeerCert(const PeerCert &) = delete;
  1098. PeerCert &operator=(const PeerCert &) = delete;
  1099. explicit operator bool() const;
  1100. std::string subject_cn() const;
  1101. std::string issuer_name() const;
  1102. bool check_hostname(const char *hostname) const;
  1103. std::vector<SanEntry> sans() const;
  1104. bool validity(time_t &not_before, time_t &not_after) const;
  1105. std::string serial() const;
  1106. private:
  1107. explicit PeerCert(cert_t cert);
  1108. cert_t cert_ = nullptr;
  1109. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1110. };
  1111. // Callback for TLS context setup (used by SSLServer constructor)
  1112. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1113. } // namespace tls
  1114. #endif
  1115. struct Request {
  1116. std::string method;
  1117. std::string path;
  1118. std::string matched_route;
  1119. Params params;
  1120. Headers headers;
  1121. Headers trailers;
  1122. std::string body;
  1123. std::string remote_addr;
  1124. int remote_port = -1;
  1125. std::string local_addr;
  1126. int local_port = -1;
  1127. // for server
  1128. std::string version;
  1129. std::string target;
  1130. MultipartFormData form;
  1131. Ranges ranges;
  1132. Match matches;
  1133. std::unordered_map<std::string, std::string> path_params;
  1134. std::function<bool()> is_connection_closed = []() { return true; };
  1135. // for client
  1136. std::vector<std::string> accept_content_types;
  1137. ResponseHandler response_handler;
  1138. ContentReceiverWithProgress content_receiver;
  1139. DownloadProgress download_progress;
  1140. UploadProgress upload_progress;
  1141. bool has_header(const std::string &key) const;
  1142. std::string get_header_value(const std::string &key, const char *def = "",
  1143. size_t id = 0) const;
  1144. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1145. size_t id = 0) const;
  1146. size_t get_header_value_count(const std::string &key) const;
  1147. void set_header(const std::string &key, const std::string &val);
  1148. bool has_trailer(const std::string &key) const;
  1149. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1150. size_t get_trailer_value_count(const std::string &key) const;
  1151. bool has_param(const std::string &key) const;
  1152. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1153. std::vector<std::string> get_param_values(const std::string &key) const;
  1154. size_t get_param_value_count(const std::string &key) const;
  1155. bool is_multipart_form_data() const;
  1156. // private members...
  1157. bool body_consumed_ = false;
  1158. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1159. size_t content_length_ = 0;
  1160. ContentProvider content_provider_;
  1161. bool is_chunked_content_provider_ = false;
  1162. size_t authorization_count_ = 0;
  1163. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1164. (std::chrono::steady_clock::time_point::min)();
  1165. #ifdef CPPHTTPLIB_SSL_ENABLED
  1166. tls::const_session_t ssl = nullptr;
  1167. tls::PeerCert peer_cert() const;
  1168. std::string sni() const;
  1169. #endif
  1170. };
  1171. struct Response {
  1172. std::string version;
  1173. int status = -1;
  1174. std::string reason;
  1175. Headers headers;
  1176. Headers trailers;
  1177. std::string body;
  1178. std::string location; // Redirect location
  1179. // User-defined context — set by pre-routing/pre-request handlers and read
  1180. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1181. UserData user_data;
  1182. bool has_header(const std::string &key) const;
  1183. std::string get_header_value(const std::string &key, const char *def = "",
  1184. size_t id = 0) const;
  1185. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1186. size_t id = 0) const;
  1187. size_t get_header_value_count(const std::string &key) const;
  1188. void set_header(const std::string &key, const std::string &val);
  1189. bool has_trailer(const std::string &key) const;
  1190. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1191. size_t get_trailer_value_count(const std::string &key) const;
  1192. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1193. void set_content(const char *s, size_t n, const std::string &content_type);
  1194. void set_content(const std::string &s, const std::string &content_type);
  1195. void set_content(std::string &&s, const std::string &content_type);
  1196. void set_content_provider(
  1197. size_t length, const std::string &content_type, ContentProvider provider,
  1198. ContentProviderResourceReleaser resource_releaser = nullptr);
  1199. void set_content_provider(
  1200. const std::string &content_type, ContentProviderWithoutLength provider,
  1201. ContentProviderResourceReleaser resource_releaser = nullptr);
  1202. void set_chunked_content_provider(
  1203. const std::string &content_type, ContentProviderWithoutLength provider,
  1204. ContentProviderResourceReleaser resource_releaser = nullptr);
  1205. void set_file_content(const std::string &path,
  1206. const std::string &content_type);
  1207. void set_file_content(const std::string &path);
  1208. Response() = default;
  1209. Response(const Response &) = default;
  1210. Response &operator=(const Response &) = default;
  1211. Response(Response &&) = default;
  1212. Response &operator=(Response &&) = default;
  1213. ~Response() {
  1214. if (content_provider_resource_releaser_) {
  1215. content_provider_resource_releaser_(content_provider_success_);
  1216. }
  1217. }
  1218. // private members...
  1219. size_t content_length_ = 0;
  1220. ContentProvider content_provider_;
  1221. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1222. bool is_chunked_content_provider_ = false;
  1223. bool content_provider_success_ = false;
  1224. std::string file_content_path_;
  1225. std::string file_content_content_type_;
  1226. };
  1227. enum class Error {
  1228. Success = 0,
  1229. Unknown,
  1230. Connection,
  1231. BindIPAddress,
  1232. Read,
  1233. Write,
  1234. ExceedRedirectCount,
  1235. Canceled,
  1236. SSLConnection,
  1237. SSLLoadingCerts,
  1238. SSLServerVerification,
  1239. SSLServerHostnameVerification,
  1240. UnsupportedMultipartBoundaryChars,
  1241. Compression,
  1242. ConnectionTimeout,
  1243. ProxyConnection,
  1244. ConnectionClosed,
  1245. Timeout,
  1246. ResourceExhaustion,
  1247. TooManyFormDataFiles,
  1248. ExceedMaxPayloadSize,
  1249. ExceedUriMaxLength,
  1250. ExceedMaxSocketDescriptorCount,
  1251. InvalidRequestLine,
  1252. InvalidHTTPMethod,
  1253. InvalidHTTPVersion,
  1254. InvalidHeaders,
  1255. MultipartParsing,
  1256. OpenFile,
  1257. Listen,
  1258. GetSockName,
  1259. UnsupportedAddressFamily,
  1260. HTTPParsing,
  1261. InvalidRangeHeader,
  1262. // For internal use only
  1263. SSLPeerCouldBeClosed_,
  1264. };
  1265. std::string to_string(Error error);
  1266. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1267. class Stream {
  1268. public:
  1269. virtual ~Stream() = default;
  1270. virtual bool is_readable() const = 0;
  1271. virtual bool wait_readable() const = 0;
  1272. virtual bool wait_writable() const = 0;
  1273. virtual bool is_peer_alive() const { return wait_writable(); }
  1274. virtual ssize_t read(char *ptr, size_t size) = 0;
  1275. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1276. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1277. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1278. virtual socket_t socket() const = 0;
  1279. virtual time_t duration() const = 0;
  1280. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1281. (void)sec;
  1282. (void)usec;
  1283. }
  1284. ssize_t write(const char *ptr);
  1285. ssize_t write(const std::string &s);
  1286. Error get_error() const { return error_; }
  1287. protected:
  1288. Error error_ = Error::Success;
  1289. };
  1290. class TaskQueue {
  1291. public:
  1292. TaskQueue() = default;
  1293. virtual ~TaskQueue() = default;
  1294. virtual bool enqueue(std::function<void()> fn) = 0;
  1295. virtual void shutdown() = 0;
  1296. virtual void on_idle() {}
  1297. };
  1298. class ThreadPool final : public TaskQueue {
  1299. public:
  1300. explicit ThreadPool(
  1301. size_t n, size_t max_n = 0, size_t mqr = 0,
  1302. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1303. ThreadPool(const ThreadPool &) = delete;
  1304. ~ThreadPool() override = default;
  1305. bool enqueue(std::function<void()> fn) override;
  1306. void shutdown() override;
  1307. private:
  1308. void worker(bool is_dynamic);
  1309. void move_to_finished(std::thread::id id);
  1310. void cleanup_finished_threads();
  1311. size_t base_thread_count_;
  1312. size_t max_thread_count_;
  1313. size_t max_queued_requests_;
  1314. time_t idle_timeout_sec_;
  1315. size_t idle_thread_count_;
  1316. bool shutdown_;
  1317. std::list<std::function<void()>> jobs_;
  1318. std::vector<std::thread> threads_; // base threads
  1319. std::list<std::thread> dynamic_threads_; // dynamic threads
  1320. std::vector<std::thread>
  1321. finished_threads_; // exited dynamic threads awaiting join
  1322. std::condition_variable cond_;
  1323. std::mutex mutex_;
  1324. };
  1325. using Logger = std::function<void(const Request &, const Response &)>;
  1326. // Forward declaration for Error type
  1327. enum class Error;
  1328. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1329. using SocketOptions = std::function<void(socket_t sock)>;
  1330. void default_socket_options(socket_t sock);
  1331. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1332. const char *status_message(int status);
  1333. std::string to_string(Error error);
  1334. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1335. std::string get_bearer_token_auth(const Request &req);
  1336. namespace detail {
  1337. class MatcherBase {
  1338. public:
  1339. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1340. virtual ~MatcherBase() = default;
  1341. const std::string &pattern() const { return pattern_; }
  1342. // Match request path and populate its matches and
  1343. virtual bool match(Request &request) const = 0;
  1344. private:
  1345. std::string pattern_;
  1346. };
  1347. /**
  1348. * Captures parameters in request path and stores them in Request::path_params
  1349. *
  1350. * Capture name is a substring of a pattern from : to /.
  1351. * The rest of the pattern is matched against the request path directly
  1352. * Parameters are captured starting from the next character after
  1353. * the end of the last matched static pattern fragment until the next /.
  1354. *
  1355. * Example pattern:
  1356. * "/path/fragments/:capture/more/fragments/:second_capture"
  1357. * Static fragments:
  1358. * "/path/fragments/", "more/fragments/"
  1359. *
  1360. * Given the following request path:
  1361. * "/path/fragments/:1/more/fragments/:2"
  1362. * the resulting capture will be
  1363. * {{"capture", "1"}, {"second_capture", "2"}}
  1364. */
  1365. class PathParamsMatcher final : public MatcherBase {
  1366. public:
  1367. PathParamsMatcher(const std::string &pattern);
  1368. bool match(Request &request) const override;
  1369. private:
  1370. // Treat segment separators as the end of path parameter capture
  1371. // Does not need to handle query parameters as they are parsed before path
  1372. // matching
  1373. static constexpr char separator = '/';
  1374. // Contains static path fragments to match against, excluding the '/' after
  1375. // path params
  1376. // Fragments are separated by path params
  1377. std::vector<std::string> static_fragments_;
  1378. // Stores the names of the path parameters to be used as keys in the
  1379. // Request::path_params map
  1380. std::vector<std::string> param_names_;
  1381. };
  1382. /**
  1383. * Performs std::regex_match on request path
  1384. * and stores the result in Request::matches
  1385. *
  1386. * Note that regex match is performed directly on the whole request.
  1387. * This means that wildcard patterns may match multiple path segments with /:
  1388. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1389. */
  1390. class RegexMatcher final : public MatcherBase {
  1391. public:
  1392. RegexMatcher(const std::string &pattern)
  1393. : MatcherBase(pattern), regex_(pattern) {}
  1394. bool match(Request &request) const override;
  1395. private:
  1396. std::regex regex_;
  1397. };
  1398. int close_socket(socket_t sock) noexcept;
  1399. ssize_t write_headers(Stream &strm, const Headers &headers);
  1400. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1401. time_t usec);
  1402. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1403. const std::string &boundary);
  1404. ContentProvider
  1405. make_multipart_content_provider(const UploadFormDataItems &items,
  1406. const std::string &boundary);
  1407. } // namespace detail
  1408. bool is_valid_multipart_boundary(const std::string &boundary);
  1409. // Serializer for multipart/form-data request bodies. The boundary is owned
  1410. // by the writer so that per-part framing and the final terminator always
  1411. // agree. Field names and filenames are escaped following the WHATWG HTML
  1412. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1413. // in content types.
  1414. class MultipartFormDataWriter {
  1415. public:
  1416. MultipartFormDataWriter();
  1417. // precondition: is_valid_multipart_boundary(boundary)
  1418. explicit MultipartFormDataWriter(std::string boundary);
  1419. const std::string &boundary() const;
  1420. std::string content_type() const;
  1421. // In-memory items -> whole body (known length)
  1422. std::string serialize(const UploadFormDataItems &items) const;
  1423. size_t content_length(const UploadFormDataItems &items) const;
  1424. // Per-part framing for streaming via a content provider
  1425. std::string item_begin(const UploadFormData &item) const;
  1426. static std::string item_end();
  1427. std::string finish() const;
  1428. private:
  1429. std::string boundary_;
  1430. };
  1431. class Server {
  1432. public:
  1433. using Handler = std::function<void(const Request &, Response &)>;
  1434. using ExceptionHandler =
  1435. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1436. enum class HandlerResponse {
  1437. Handled,
  1438. Unhandled,
  1439. };
  1440. using HandlerWithResponse =
  1441. std::function<HandlerResponse(const Request &, Response &)>;
  1442. using HandlerWithContentReader = std::function<void(
  1443. const Request &, Response &, const ContentReader &content_reader)>;
  1444. using Expect100ContinueHandler =
  1445. std::function<int(const Request &, Response &)>;
  1446. using StartHandler = std::function<void()>;
  1447. using WebSocketHandler =
  1448. std::function<void(const Request &, ws::WebSocket &)>;
  1449. using SubProtocolSelector =
  1450. std::function<std::string(const std::vector<std::string> &protocols)>;
  1451. Server();
  1452. virtual ~Server();
  1453. virtual bool is_valid() const;
  1454. Server &Get(const std::string &pattern, Handler handler);
  1455. Server &Post(const std::string &pattern, Handler handler);
  1456. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1457. Server &Put(const std::string &pattern, Handler handler);
  1458. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1459. Server &Patch(const std::string &pattern, Handler handler);
  1460. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1461. Server &Delete(const std::string &pattern, Handler handler);
  1462. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1463. Server &Options(const std::string &pattern, Handler handler);
  1464. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1465. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1466. SubProtocolSelector sub_protocol_selector);
  1467. bool set_base_dir(const std::string &dir,
  1468. const std::string &mount_point = std::string());
  1469. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1470. Headers headers = Headers());
  1471. bool remove_mount_point(const std::string &mount_point);
  1472. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1473. const std::string &mime);
  1474. Server &set_default_file_mimetype(const std::string &mime);
  1475. Server &set_file_request_handler(Handler handler);
  1476. template <class ErrorHandlerFunc>
  1477. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1478. return set_error_handler_core(
  1479. std::forward<ErrorHandlerFunc>(handler),
  1480. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1481. }
  1482. Server &set_exception_handler(ExceptionHandler handler);
  1483. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1484. Server &set_post_routing_handler(Handler handler);
  1485. Server &set_pre_request_handler(HandlerWithResponse handler);
  1486. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1487. Server &set_start_handler(StartHandler handler);
  1488. Server &set_logger(Logger logger);
  1489. Server &set_pre_compression_logger(Logger logger);
  1490. Server &set_error_logger(ErrorLogger error_logger);
  1491. Server &set_address_family(int family);
  1492. Server &set_tcp_nodelay(bool on);
  1493. Server &set_ipv6_v6only(bool on);
  1494. Server &set_socket_options(SocketOptions socket_options);
  1495. Server &set_default_headers(Headers headers);
  1496. Server &
  1497. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1498. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1499. Server &set_keep_alive_max_count(size_t count);
  1500. Server &set_keep_alive_timeout(time_t sec);
  1501. template <class Rep, class Period>
  1502. Server &
  1503. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1504. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1505. template <class Rep, class Period>
  1506. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1507. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1508. template <class Rep, class Period>
  1509. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1510. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1511. template <class Rep, class Period>
  1512. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1513. Server &set_payload_max_length(size_t length);
  1514. Server &set_websocket_ping_interval(time_t sec);
  1515. template <class Rep, class Period>
  1516. Server &set_websocket_ping_interval(
  1517. const std::chrono::duration<Rep, Period> &duration);
  1518. Server &set_websocket_max_missed_pongs(int count);
  1519. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1520. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1521. bool listen_after_bind();
  1522. bool listen(const std::string &host, int port, int socket_flags = 0);
  1523. bool is_running() const;
  1524. void wait_until_ready() const;
  1525. void stop() noexcept;
  1526. void decommission();
  1527. std::function<TaskQueue *(void)> new_task_queue;
  1528. protected:
  1529. bool process_request(Stream &strm, const std::string &remote_addr,
  1530. int remote_port, const std::string &local_addr,
  1531. int local_port, bool close_connection,
  1532. bool &connection_closed,
  1533. const std::function<void(Request &)> &setup_request,
  1534. bool *websocket_upgraded = nullptr);
  1535. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1536. std::vector<std::string> trusted_proxies_;
  1537. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1538. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1539. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1540. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1541. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1542. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1543. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1544. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1545. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1546. time_t websocket_ping_interval_sec_ =
  1547. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1548. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1549. private:
  1550. using Handlers =
  1551. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1552. using HandlersForContentReader =
  1553. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1554. HandlerWithContentReader>>;
  1555. static std::unique_ptr<detail::MatcherBase>
  1556. make_matcher(const std::string &pattern);
  1557. template <typename H>
  1558. Server &add_handler(
  1559. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1560. const std::string &pattern, H handler) {
  1561. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1562. return *this;
  1563. }
  1564. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1565. Server &set_error_handler_core(Handler handler, std::false_type);
  1566. socket_t create_server_socket(const std::string &host, int port,
  1567. int socket_flags,
  1568. SocketOptions socket_options) const;
  1569. int bind_internal(const std::string &host, int port, int socket_flags);
  1570. bool listen_internal();
  1571. bool routing(Request &req, Response &res, Stream &strm);
  1572. bool handle_file_request(Request &req, Response &res);
  1573. bool check_if_not_modified(const Request &req, Response &res,
  1574. const std::string &etag, time_t mtime) const;
  1575. bool check_if_range(Request &req, const std::string &etag,
  1576. time_t mtime) const;
  1577. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1578. Stream &strm);
  1579. bool dispatch_request_for_content_reader(
  1580. Request &req, Response &res, ContentReader content_reader,
  1581. const HandlersForContentReader &handlers) const;
  1582. bool parse_request_line(const char *s, Request &req) const;
  1583. void apply_ranges(const Request &req, Response &res,
  1584. std::string &content_type, std::string &boundary) const;
  1585. bool write_response(Stream &strm, bool close_connection, Request &req,
  1586. Response &res);
  1587. bool write_response_with_content(Stream &strm, bool close_connection,
  1588. const Request &req, Response &res);
  1589. bool write_response_core(Stream &strm, bool close_connection,
  1590. const Request &req, Response &res,
  1591. bool need_apply_ranges);
  1592. bool write_content_with_provider(Stream &strm, const Request &req,
  1593. Response &res, const std::string &boundary,
  1594. const std::string &content_type);
  1595. bool read_content(Stream &strm, Request &req, Response &res);
  1596. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1597. Response &res,
  1598. ContentReceiver receiver,
  1599. FormDataHeader multipart_header,
  1600. ContentReceiver multipart_receiver);
  1601. bool read_content_core(Stream &strm, Request &req, Response &res,
  1602. ContentReceiver receiver,
  1603. FormDataHeader multipart_header,
  1604. ContentReceiver multipart_receiver) const;
  1605. virtual bool process_and_close_socket(socket_t sock);
  1606. void output_log(const Request &req, const Response &res) const;
  1607. void output_pre_compression_log(const Request &req,
  1608. const Response &res) const;
  1609. void output_error_log(const Error &err, const Request *req) const;
  1610. std::atomic<bool> is_running_{false};
  1611. std::atomic<bool> is_decommissioned{false};
  1612. struct MountPointEntry {
  1613. std::string mount_point;
  1614. std::string base_dir;
  1615. std::string resolved_base_dir;
  1616. Headers headers;
  1617. };
  1618. std::vector<MountPointEntry> base_dirs_;
  1619. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1620. std::string default_file_mimetype_ = "application/octet-stream";
  1621. Handler file_request_handler_;
  1622. Handlers get_handlers_;
  1623. Handlers post_handlers_;
  1624. HandlersForContentReader post_handlers_for_content_reader_;
  1625. Handlers put_handlers_;
  1626. HandlersForContentReader put_handlers_for_content_reader_;
  1627. Handlers patch_handlers_;
  1628. HandlersForContentReader patch_handlers_for_content_reader_;
  1629. Handlers delete_handlers_;
  1630. HandlersForContentReader delete_handlers_for_content_reader_;
  1631. Handlers options_handlers_;
  1632. struct WebSocketHandlerEntry {
  1633. std::unique_ptr<detail::MatcherBase> matcher;
  1634. WebSocketHandler handler;
  1635. SubProtocolSelector sub_protocol_selector;
  1636. };
  1637. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1638. WebSocketHandlers websocket_handlers_;
  1639. HandlerWithResponse error_handler_;
  1640. ExceptionHandler exception_handler_;
  1641. HandlerWithResponse pre_routing_handler_;
  1642. Handler post_routing_handler_;
  1643. HandlerWithResponse pre_request_handler_;
  1644. Expect100ContinueHandler expect_100_continue_handler_;
  1645. StartHandler start_handler_;
  1646. mutable std::mutex logger_mutex_;
  1647. Logger logger_;
  1648. Logger pre_compression_logger_;
  1649. ErrorLogger error_logger_;
  1650. int address_family_ = AF_UNSPEC;
  1651. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1652. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1653. SocketOptions socket_options_ = default_socket_options;
  1654. Headers default_headers_;
  1655. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1656. detail::write_headers;
  1657. };
  1658. class Result {
  1659. public:
  1660. Result() = default;
  1661. Result(std::unique_ptr<Response> &&res, Error err,
  1662. Headers &&request_headers = Headers{})
  1663. : res_(std::move(res)), err_(err),
  1664. request_headers_(std::move(request_headers)) {}
  1665. // Response
  1666. operator bool() const { return res_ != nullptr; }
  1667. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1668. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1669. const Response &value() const { return *res_; }
  1670. Response &value() { return *res_; }
  1671. const Response &operator*() const { return *res_; }
  1672. Response &operator*() { return *res_; }
  1673. const Response *operator->() const { return res_.get(); }
  1674. Response *operator->() { return res_.get(); }
  1675. // Error
  1676. Error error() const { return err_; }
  1677. // Request Headers
  1678. bool has_request_header(const std::string &key) const;
  1679. std::string get_request_header_value(const std::string &key,
  1680. const char *def = "",
  1681. size_t id = 0) const;
  1682. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1683. size_t id = 0) const;
  1684. size_t get_request_header_value_count(const std::string &key) const;
  1685. private:
  1686. std::unique_ptr<Response> res_;
  1687. Error err_ = Error::Unknown;
  1688. Headers request_headers_;
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. public:
  1691. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1692. int ssl_error)
  1693. : res_(std::move(res)), err_(err),
  1694. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1695. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1696. int ssl_error, uint64_t ssl_backend_error)
  1697. : res_(std::move(res)), err_(err),
  1698. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1699. ssl_backend_error_(ssl_backend_error) {}
  1700. int ssl_error() const { return ssl_error_; }
  1701. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1702. private:
  1703. int ssl_error_ = 0;
  1704. uint64_t ssl_backend_error_ = 0;
  1705. #endif
  1706. };
  1707. struct ClientConnection {
  1708. socket_t sock = INVALID_SOCKET;
  1709. bool is_open() const { return sock != INVALID_SOCKET; }
  1710. ClientConnection() = default;
  1711. ~ClientConnection();
  1712. ClientConnection(const ClientConnection &) = delete;
  1713. ClientConnection &operator=(const ClientConnection &) = delete;
  1714. ClientConnection(ClientConnection &&other) noexcept
  1715. : sock(other.sock)
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. ,
  1718. session(other.session)
  1719. #endif
  1720. {
  1721. other.sock = INVALID_SOCKET;
  1722. #ifdef CPPHTTPLIB_SSL_ENABLED
  1723. other.session = nullptr;
  1724. #endif
  1725. }
  1726. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1727. if (this != &other) {
  1728. sock = other.sock;
  1729. other.sock = INVALID_SOCKET;
  1730. #ifdef CPPHTTPLIB_SSL_ENABLED
  1731. session = other.session;
  1732. other.session = nullptr;
  1733. #endif
  1734. }
  1735. return *this;
  1736. }
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. tls::session_t session = nullptr;
  1739. #endif
  1740. };
  1741. namespace detail {
  1742. struct ChunkedDecoder;
  1743. struct BodyReader {
  1744. Stream *stream = nullptr;
  1745. bool has_content_length = false;
  1746. size_t content_length = 0;
  1747. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1748. size_t bytes_read = 0;
  1749. bool chunked = false;
  1750. bool eof = false;
  1751. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1752. Error last_error = Error::Success;
  1753. ssize_t read(char *buf, size_t len);
  1754. bool has_error() const { return last_error != Error::Success; }
  1755. };
  1756. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1757. size_t len) {
  1758. (void)stream;
  1759. return br.read(buf, len);
  1760. }
  1761. class decompressor;
  1762. enum class NoProxyKind {
  1763. Wildcard, // "*"
  1764. HostnameSuffix, // "example.com" or ".example.com"
  1765. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1766. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1767. };
  1768. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1769. // Lets one CIDR matcher cover both families.
  1770. using IPBytes = std::array<uint8_t, 16>;
  1771. struct NoProxyEntry {
  1772. NoProxyKind kind = NoProxyKind::Wildcard;
  1773. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1774. IPBytes net{};
  1775. int prefix_bits = 0;
  1776. };
  1777. struct NormalizedTarget {
  1778. std::string hostname; // lowercase; brackets and trailing dot removed
  1779. bool is_ipv4 = false;
  1780. bool is_ipv6 = false;
  1781. IPBytes ip{};
  1782. };
  1783. } // namespace detail
  1784. class ClientImpl {
  1785. public:
  1786. explicit ClientImpl(const std::string &host);
  1787. explicit ClientImpl(const std::string &host, int port);
  1788. explicit ClientImpl(const std::string &host, int port,
  1789. const std::string &client_cert_path,
  1790. const std::string &client_key_path);
  1791. virtual ~ClientImpl();
  1792. virtual bool is_valid() const;
  1793. struct StreamHandle {
  1794. std::unique_ptr<Response> response;
  1795. Error error = Error::Success;
  1796. StreamHandle() = default;
  1797. StreamHandle(const StreamHandle &) = delete;
  1798. StreamHandle &operator=(const StreamHandle &) = delete;
  1799. StreamHandle(StreamHandle &&) = default;
  1800. StreamHandle &operator=(StreamHandle &&) = default;
  1801. ~StreamHandle() = default;
  1802. bool is_valid() const {
  1803. return response != nullptr && error == Error::Success;
  1804. }
  1805. ssize_t read(char *buf, size_t len);
  1806. void parse_trailers_if_needed();
  1807. Error get_read_error() const { return body_reader_.last_error; }
  1808. bool has_read_error() const { return body_reader_.has_error(); }
  1809. bool trailers_parsed_ = false;
  1810. private:
  1811. friend class ClientImpl;
  1812. ssize_t read_with_decompression(char *buf, size_t len);
  1813. std::unique_ptr<ClientConnection> connection_;
  1814. std::unique_ptr<Stream> socket_stream_;
  1815. Stream *stream_ = nullptr;
  1816. detail::BodyReader body_reader_;
  1817. std::unique_ptr<detail::decompressor> decompressor_;
  1818. std::string decompress_buffer_;
  1819. size_t decompress_offset_ = 0;
  1820. size_t decompressed_bytes_read_ = 0;
  1821. };
  1822. // clang-format off
  1823. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1824. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1825. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1826. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1827. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1828. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1829. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1830. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1831. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1832. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1833. Result Head(const std::string &path);
  1834. Result Head(const std::string &path, const Headers &headers);
  1835. Result Post(const std::string &path);
  1836. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1837. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1838. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1839. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1840. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1841. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1842. Result Post(const std::string &path, const Params &params);
  1843. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1844. Result Post(const std::string &path, const Headers &headers);
  1845. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1847. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1848. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1849. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1850. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1851. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1852. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1853. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1854. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1855. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1856. Result Put(const std::string &path);
  1857. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1859. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1861. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1862. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1863. Result Put(const std::string &path, const Params &params);
  1864. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1865. Result Put(const std::string &path, const Headers &headers);
  1866. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1868. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1869. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1870. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1871. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1872. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1873. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1874. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1875. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1876. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1877. Result Patch(const std::string &path);
  1878. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1880. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1882. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1883. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1884. Result Patch(const std::string &path, const Params &params);
  1885. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1886. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1887. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1888. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1889. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1890. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1891. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1892. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1893. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1894. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1895. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1896. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1897. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1898. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1899. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1900. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1901. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1902. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1903. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1904. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1905. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1906. Result Options(const std::string &path);
  1907. Result Options(const std::string &path, const Headers &headers);
  1908. // clang-format on
  1909. // Streaming API: Open a stream for reading response body incrementally
  1910. // Socket ownership is transferred to StreamHandle for true streaming
  1911. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1912. StreamHandle open_stream(const std::string &method, const std::string &path,
  1913. const Params &params = {},
  1914. const Headers &headers = {},
  1915. const std::string &body = {},
  1916. const std::string &content_type = {});
  1917. bool send(Request &req, Response &res, Error &error);
  1918. Result send(const Request &req);
  1919. void stop();
  1920. std::string host() const;
  1921. int port() const;
  1922. size_t is_socket_open() const;
  1923. socket_t socket() const;
  1924. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1925. void set_default_headers(Headers headers);
  1926. void
  1927. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1928. void set_address_family(int family);
  1929. void set_tcp_nodelay(bool on);
  1930. void set_ipv6_v6only(bool on);
  1931. void set_socket_options(SocketOptions socket_options);
  1932. void set_connection_timeout(time_t sec, time_t usec = 0);
  1933. template <class Rep, class Period>
  1934. void
  1935. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1936. void set_read_timeout(time_t sec, time_t usec = 0);
  1937. template <class Rep, class Period>
  1938. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1939. void set_write_timeout(time_t sec, time_t usec = 0);
  1940. template <class Rep, class Period>
  1941. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1942. void set_max_timeout(time_t msec);
  1943. template <class Rep, class Period>
  1944. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1945. void set_basic_auth(const std::string &username, const std::string &password);
  1946. void set_bearer_token_auth(const std::string &token);
  1947. void set_keep_alive(bool on);
  1948. void set_follow_location(bool on);
  1949. void set_path_encode(bool on);
  1950. void set_compress(bool on);
  1951. void set_decompress(bool on);
  1952. void set_payload_max_length(size_t length);
  1953. void set_interface(const std::string &intf);
  1954. void set_proxy(const std::string &host, int port);
  1955. void set_proxy_basic_auth(const std::string &username,
  1956. const std::string &password);
  1957. void set_proxy_bearer_token_auth(const std::string &token);
  1958. void set_no_proxy(const std::vector<std::string> &patterns);
  1959. void set_logger(Logger logger);
  1960. void set_error_logger(ErrorLogger error_logger);
  1961. protected:
  1962. struct Socket {
  1963. socket_t sock = INVALID_SOCKET;
  1964. // For Mbed TLS compatibility: start_time for request timeout tracking
  1965. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1966. bool is_open() const { return sock != INVALID_SOCKET; }
  1967. #ifdef CPPHTTPLIB_SSL_ENABLED
  1968. tls::session_t ssl = nullptr;
  1969. #endif
  1970. };
  1971. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1972. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1973. virtual bool setup_proxy_connection(
  1974. Socket &socket,
  1975. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1976. Response &res, bool &success, Error &error);
  1977. bool is_proxy_enabled_for_host(const std::string &host) const;
  1978. // All of:
  1979. // shutdown_ssl
  1980. // shutdown_socket
  1981. // close_socket
  1982. // disconnect
  1983. // should ONLY be called when socket_mutex_ is locked, and only when
  1984. // no other thread is using the socket.
  1985. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1986. void shutdown_socket(Socket &socket) const;
  1987. void close_socket(Socket &socket);
  1988. void disconnect(bool gracefully);
  1989. bool process_request(Stream &strm, Request &req, Response &res,
  1990. bool close_connection, Error &error);
  1991. bool write_content_with_provider(Stream &strm, const Request &req,
  1992. Error &error) const;
  1993. void copy_settings(const ClientImpl &rhs);
  1994. void output_log(const Request &req, const Response &res) const;
  1995. void output_error_log(const Error &err, const Request *req) const;
  1996. // Socket endpoint information
  1997. const std::string host_;
  1998. const int port_;
  1999. // Current open socket
  2000. Socket socket_;
  2001. mutable std::mutex socket_mutex_;
  2002. std::recursive_mutex request_mutex_;
  2003. // These are all protected under socket_mutex
  2004. size_t socket_requests_in_flight_ = 0;
  2005. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2006. bool socket_should_be_closed_when_request_is_done_ = false;
  2007. // Hostname-IP map
  2008. std::map<std::string, std::string> addr_map_;
  2009. // Default headers
  2010. Headers default_headers_;
  2011. // Header writer
  2012. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2013. detail::write_headers;
  2014. // Settings
  2015. std::string client_cert_path_;
  2016. std::string client_key_path_;
  2017. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2018. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2019. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2020. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2021. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2022. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2023. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2024. std::string basic_auth_username_;
  2025. std::string basic_auth_password_;
  2026. std::string bearer_token_auth_token_;
  2027. bool keep_alive_ = false;
  2028. bool follow_location_ = false;
  2029. bool path_encode_ = true;
  2030. int address_family_ = AF_UNSPEC;
  2031. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2032. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2033. SocketOptions socket_options_ = nullptr;
  2034. bool compress_ = false;
  2035. bool decompress_ = true;
  2036. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2037. bool has_payload_max_length_ = false;
  2038. std::string interface_;
  2039. std::string proxy_host_;
  2040. int proxy_port_ = -1;
  2041. std::string proxy_basic_auth_username_;
  2042. std::string proxy_basic_auth_password_;
  2043. std::string proxy_bearer_token_auth_token_;
  2044. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2045. mutable detail::NormalizedTarget host_normalized_;
  2046. mutable bool host_normalized_valid_ = false;
  2047. mutable std::mutex logger_mutex_;
  2048. Logger logger_;
  2049. ErrorLogger error_logger_;
  2050. private:
  2051. bool send_(Request &req, Response &res, Error &error);
  2052. Result send_(Request &&req);
  2053. socket_t create_client_socket(Error &error) const;
  2054. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2055. bool skip_100_continue = true) const;
  2056. bool write_request(Stream &strm, Request &req, bool close_connection,
  2057. Error &error, bool skip_body = false);
  2058. bool write_request_body(Stream &strm, Request &req, Error &error);
  2059. void prepare_default_headers(Request &r, bool for_stream,
  2060. const std::string &ct);
  2061. bool redirect(Request &req, Response &res, Error &error);
  2062. bool create_redirect_client(const std::string &scheme,
  2063. const std::string &host, int port, Request &req,
  2064. Response &res, const std::string &path,
  2065. const std::string &location, Error &error);
  2066. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2067. bool handle_request(Stream &strm, Request &req, Response &res,
  2068. bool close_connection, Error &error);
  2069. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2070. Request &req, const char *body, size_t content_length,
  2071. ContentProvider content_provider,
  2072. ContentProviderWithoutLength content_provider_without_length,
  2073. const std::string &content_type, ContentReceiver content_receiver,
  2074. Error &error);
  2075. Result send_with_content_provider_and_receiver(
  2076. const std::string &method, const std::string &path,
  2077. const Headers &headers, const char *body, size_t content_length,
  2078. ContentProvider content_provider,
  2079. ContentProviderWithoutLength content_provider_without_length,
  2080. const std::string &content_type, ContentReceiver content_receiver,
  2081. UploadProgress progress);
  2082. ContentProviderWithoutLength get_multipart_content_provider(
  2083. const std::string &boundary, const UploadFormDataItems &items,
  2084. const FormDataProviderItems &provider_items) const;
  2085. virtual bool
  2086. process_socket(const Socket &socket,
  2087. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2088. std::function<bool(Stream &strm)> callback);
  2089. virtual bool is_ssl() const;
  2090. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2091. #ifdef CPPHTTPLIB_SSL_ENABLED
  2092. public:
  2093. void set_digest_auth(const std::string &username,
  2094. const std::string &password);
  2095. void set_proxy_digest_auth(const std::string &username,
  2096. const std::string &password);
  2097. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2098. const std::string &ca_cert_dir_path = std::string());
  2099. void enable_server_certificate_verification(bool enabled);
  2100. void enable_server_hostname_verification(bool enabled);
  2101. void enable_system_ca(bool enabled);
  2102. protected:
  2103. std::string digest_auth_username_;
  2104. std::string digest_auth_password_;
  2105. std::string proxy_digest_auth_username_;
  2106. std::string proxy_digest_auth_password_;
  2107. std::string ca_cert_file_path_;
  2108. std::string ca_cert_dir_path_;
  2109. bool server_certificate_verification_ = true;
  2110. bool server_hostname_verification_ = true;
  2111. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2112. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2113. int last_ssl_error_ = 0;
  2114. uint64_t last_backend_error_ = 0;
  2115. #endif
  2116. };
  2117. class Client {
  2118. public:
  2119. // Universal interface
  2120. explicit Client(const std::string &scheme_host_port);
  2121. explicit Client(const std::string &scheme_host_port,
  2122. const std::string &client_cert_path,
  2123. const std::string &client_key_path);
  2124. // HTTP only interface
  2125. explicit Client(const std::string &host, int port);
  2126. explicit Client(const std::string &host, int port,
  2127. const std::string &client_cert_path,
  2128. const std::string &client_key_path);
  2129. Client(Client &&) = default;
  2130. Client &operator=(Client &&) = default;
  2131. ~Client();
  2132. bool is_valid() const;
  2133. // clang-format off
  2134. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2135. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2136. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2137. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2138. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2139. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2140. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2141. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2142. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2143. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2144. Result Head(const std::string &path);
  2145. Result Head(const std::string &path, const Headers &headers);
  2146. Result Post(const std::string &path);
  2147. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2149. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2150. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2151. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2152. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const Params &params);
  2154. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2155. Result Post(const std::string &path, const Headers &headers);
  2156. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2157. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2158. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2159. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2160. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2161. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2162. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2163. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2164. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2165. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2166. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2167. Result Put(const std::string &path);
  2168. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2171. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2172. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2173. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const Params &params);
  2175. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2176. Result Put(const std::string &path, const Headers &headers);
  2177. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2178. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2179. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2180. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2181. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2182. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2184. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2185. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2186. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2187. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2188. Result Patch(const std::string &path);
  2189. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2192. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2193. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2194. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const Params &params);
  2196. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2197. Result Patch(const std::string &path, const Headers &headers);
  2198. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2199. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2200. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2201. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2202. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2203. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2205. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2206. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2207. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2208. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2209. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2210. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2211. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2212. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2213. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2214. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2215. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2216. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2217. Result Options(const std::string &path);
  2218. Result Options(const std::string &path, const Headers &headers);
  2219. // clang-format on
  2220. // Streaming API: Open a stream for reading response body incrementally
  2221. // Socket ownership is transferred to StreamHandle for true streaming
  2222. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2223. ClientImpl::StreamHandle open_stream(const std::string &method,
  2224. const std::string &path,
  2225. const Params &params = {},
  2226. const Headers &headers = {},
  2227. const std::string &body = {},
  2228. const std::string &content_type = {});
  2229. bool send(Request &req, Response &res, Error &error);
  2230. Result send(const Request &req);
  2231. void stop();
  2232. std::string host() const;
  2233. int port() const;
  2234. size_t is_socket_open() const;
  2235. socket_t socket() const;
  2236. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2237. void set_default_headers(Headers headers);
  2238. void
  2239. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2240. void set_address_family(int family);
  2241. void set_tcp_nodelay(bool on);
  2242. void set_socket_options(SocketOptions socket_options);
  2243. void set_connection_timeout(time_t sec, time_t usec = 0);
  2244. template <class Rep, class Period>
  2245. void
  2246. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2247. void set_read_timeout(time_t sec, time_t usec = 0);
  2248. template <class Rep, class Period>
  2249. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2250. void set_write_timeout(time_t sec, time_t usec = 0);
  2251. template <class Rep, class Period>
  2252. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2253. void set_max_timeout(time_t msec);
  2254. template <class Rep, class Period>
  2255. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2256. void set_basic_auth(const std::string &username, const std::string &password);
  2257. void set_bearer_token_auth(const std::string &token);
  2258. void set_keep_alive(bool on);
  2259. void set_follow_location(bool on);
  2260. void set_path_encode(bool on);
  2261. void set_compress(bool on);
  2262. void set_decompress(bool on);
  2263. void set_payload_max_length(size_t length);
  2264. void set_interface(const std::string &intf);
  2265. void set_proxy(const std::string &host, int port);
  2266. void set_proxy_basic_auth(const std::string &username,
  2267. const std::string &password);
  2268. void set_proxy_bearer_token_auth(const std::string &token);
  2269. void set_no_proxy(const std::vector<std::string> &patterns);
  2270. void set_logger(Logger logger);
  2271. void set_error_logger(ErrorLogger error_logger);
  2272. private:
  2273. std::unique_ptr<ClientImpl> cli_;
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. public:
  2276. void set_digest_auth(const std::string &username,
  2277. const std::string &password);
  2278. void set_proxy_digest_auth(const std::string &username,
  2279. const std::string &password);
  2280. void enable_server_certificate_verification(bool enabled);
  2281. void enable_server_hostname_verification(bool enabled);
  2282. void enable_system_ca(bool enabled);
  2283. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2284. const std::string &ca_cert_dir_path = std::string());
  2285. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2286. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2287. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2288. void set_session_verifier(
  2289. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2290. tls::ctx_t tls_context() const;
  2291. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2292. void enable_windows_certificate_verification(bool enabled);
  2293. #endif
  2294. private:
  2295. bool is_ssl_ = false;
  2296. #endif
  2297. };
  2298. #ifdef CPPHTTPLIB_SSL_ENABLED
  2299. class SSLServer : public Server {
  2300. public:
  2301. SSLServer(const char *cert_path, const char *private_key_path,
  2302. const char *client_ca_cert_file_path = nullptr,
  2303. const char *client_ca_cert_dir_path = nullptr,
  2304. const char *private_key_password = nullptr);
  2305. struct PemMemory {
  2306. const char *cert_pem;
  2307. size_t cert_pem_len;
  2308. const char *key_pem;
  2309. size_t key_pem_len;
  2310. const char *client_ca_pem;
  2311. size_t client_ca_pem_len;
  2312. const char *private_key_password;
  2313. };
  2314. explicit SSLServer(const PemMemory &pem);
  2315. // The callback receives the ctx_t handle which can be cast to the
  2316. // appropriate backend type (SSL_CTX* for OpenSSL,
  2317. // tls::impl::MbedTlsContext* for Mbed TLS)
  2318. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2319. ~SSLServer() override;
  2320. bool is_valid() const override;
  2321. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2322. const char *client_ca_pem = nullptr,
  2323. const char *password = nullptr);
  2324. tls::ctx_t tls_context() const { return ctx_; }
  2325. int ssl_last_error() const { return last_ssl_error_; }
  2326. private:
  2327. bool process_and_close_socket(socket_t sock) override;
  2328. tls::ctx_t ctx_ = nullptr;
  2329. std::mutex ctx_mutex_;
  2330. int last_ssl_error_ = 0;
  2331. };
  2332. class SSLClient final : public ClientImpl {
  2333. public:
  2334. explicit SSLClient(const std::string &host);
  2335. explicit SSLClient(const std::string &host, int port);
  2336. explicit SSLClient(const std::string &host, int port,
  2337. const std::string &client_cert_path,
  2338. const std::string &client_key_path,
  2339. const std::string &private_key_password = std::string());
  2340. struct PemMemory {
  2341. const char *cert_pem;
  2342. size_t cert_pem_len;
  2343. const char *key_pem;
  2344. size_t key_pem_len;
  2345. const char *private_key_password;
  2346. };
  2347. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2348. ~SSLClient() override;
  2349. bool is_valid() const override;
  2350. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2351. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2352. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2353. // Post-handshake session verifier (backend-independent)
  2354. void set_session_verifier(
  2355. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2356. tls::ctx_t tls_context() const { return ctx_; }
  2357. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2358. void enable_windows_certificate_verification(bool enabled);
  2359. #endif
  2360. private:
  2361. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2362. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2363. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2364. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2365. bool
  2366. process_socket(const Socket &socket,
  2367. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2368. std::function<bool(Stream &strm)> callback) override;
  2369. bool is_ssl() const override;
  2370. bool setup_proxy_connection(
  2371. Socket &socket,
  2372. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2373. Response &res, bool &success, Error &error) override;
  2374. bool connect_with_proxy(
  2375. Socket &sock,
  2376. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2377. Response &res, bool &success, Error &error);
  2378. bool initialize_ssl(Socket &socket, Error &error);
  2379. void init_ctx();
  2380. void reset_ctx_on_error();
  2381. bool load_certs();
  2382. tls::ctx_t ctx_ = nullptr;
  2383. std::mutex ctx_mutex_;
  2384. std::once_flag initialize_cert_;
  2385. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2386. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2387. // Used to keep custom CA configuration exclusive with system CA loading.
  2388. bool ca_cert_store_set_ = false;
  2389. long verify_result_ = 0;
  2390. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2391. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2392. bool enable_windows_cert_verification_ = true;
  2393. #endif
  2394. friend class ClientImpl;
  2395. };
  2396. #endif // CPPHTTPLIB_SSL_ENABLED
  2397. namespace detail {
  2398. template <typename T, typename U>
  2399. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2400. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2401. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2402. duration - std::chrono::seconds(sec))
  2403. .count();
  2404. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2405. }
  2406. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2407. return N - 1;
  2408. }
  2409. inline bool is_numeric(const std::string &str) {
  2410. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2411. }
  2412. inline size_t get_header_value_u64(const Headers &headers,
  2413. const std::string &key, size_t def,
  2414. size_t id, bool &is_invalid_value) {
  2415. is_invalid_value = false;
  2416. auto rng = headers.equal_range(key);
  2417. auto it = rng.first;
  2418. std::advance(it, static_cast<ssize_t>(id));
  2419. if (it != rng.second) {
  2420. if (is_numeric(it->second)) {
  2421. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2422. } else {
  2423. is_invalid_value = true;
  2424. }
  2425. }
  2426. return def;
  2427. }
  2428. inline size_t get_header_value_u64(const Headers &headers,
  2429. const std::string &key, size_t def,
  2430. size_t id) {
  2431. auto dummy = false;
  2432. return get_header_value_u64(headers, key, def, id, dummy);
  2433. }
  2434. } // namespace detail
  2435. template <class Rep, class Period>
  2436. inline Server &
  2437. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2438. detail::duration_to_sec_and_usec(
  2439. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2440. return *this;
  2441. }
  2442. template <class Rep, class Period>
  2443. inline Server &
  2444. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2445. detail::duration_to_sec_and_usec(
  2446. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2447. return *this;
  2448. }
  2449. template <class Rep, class Period>
  2450. inline Server &
  2451. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2452. detail::duration_to_sec_and_usec(
  2453. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2454. return *this;
  2455. }
  2456. template <class Rep, class Period>
  2457. inline void ClientImpl::set_connection_timeout(
  2458. const std::chrono::duration<Rep, Period> &duration) {
  2459. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2460. set_connection_timeout(sec, usec);
  2461. });
  2462. }
  2463. template <class Rep, class Period>
  2464. inline void ClientImpl::set_read_timeout(
  2465. const std::chrono::duration<Rep, Period> &duration) {
  2466. detail::duration_to_sec_and_usec(
  2467. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2468. }
  2469. template <class Rep, class Period>
  2470. inline void ClientImpl::set_write_timeout(
  2471. const std::chrono::duration<Rep, Period> &duration) {
  2472. detail::duration_to_sec_and_usec(
  2473. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2474. }
  2475. template <class Rep, class Period>
  2476. inline void ClientImpl::set_max_timeout(
  2477. const std::chrono::duration<Rep, Period> &duration) {
  2478. auto msec =
  2479. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2480. set_max_timeout(msec);
  2481. }
  2482. template <class Rep, class Period>
  2483. inline void Client::set_connection_timeout(
  2484. const std::chrono::duration<Rep, Period> &duration) {
  2485. cli_->set_connection_timeout(duration);
  2486. }
  2487. template <class Rep, class Period>
  2488. inline void
  2489. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2490. cli_->set_read_timeout(duration);
  2491. }
  2492. template <class Rep, class Period>
  2493. inline void
  2494. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2495. cli_->set_write_timeout(duration);
  2496. }
  2497. inline void Client::set_max_timeout(time_t msec) {
  2498. cli_->set_max_timeout(msec);
  2499. }
  2500. template <class Rep, class Period>
  2501. inline void
  2502. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2503. cli_->set_max_timeout(duration);
  2504. }
  2505. /*
  2506. * Forward declarations and types that will be part of the .h file if split into
  2507. * .h + .cc.
  2508. */
  2509. std::string hosted_at(const std::string &hostname);
  2510. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2511. // JavaScript-style URL encoding/decoding functions
  2512. std::string encode_uri_component(const std::string &value);
  2513. std::string encode_uri(const std::string &value);
  2514. std::string decode_uri_component(const std::string &value);
  2515. std::string decode_uri(const std::string &value);
  2516. // RFC 3986 compliant URL component encoding/decoding functions
  2517. std::string encode_path_component(const std::string &component);
  2518. std::string decode_path_component(const std::string &component);
  2519. std::string encode_query_component(const std::string &component,
  2520. bool space_as_plus = true);
  2521. std::string decode_query_component(const std::string &component,
  2522. bool plus_as_space = true);
  2523. std::string sanitize_filename(const std::string &filename);
  2524. std::string append_query_params(const std::string &path, const Params &params);
  2525. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2526. std::pair<std::string, std::string>
  2527. make_basic_authentication_header(const std::string &username,
  2528. const std::string &password,
  2529. bool is_proxy = false);
  2530. namespace detail {
  2531. #if defined(_WIN32)
  2532. inline std::wstring u8string_to_wstring(const char *s) {
  2533. if (!s) { return std::wstring(); }
  2534. auto len = static_cast<int>(strlen(s));
  2535. if (!len) { return std::wstring(); }
  2536. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2537. if (!wlen) { return std::wstring(); }
  2538. std::wstring ws;
  2539. ws.resize(wlen);
  2540. wlen = ::MultiByteToWideChar(
  2541. CP_UTF8, 0, s, len,
  2542. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2543. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2544. return ws;
  2545. }
  2546. #endif
  2547. struct FileStat {
  2548. FileStat(const std::string &path);
  2549. bool is_file() const;
  2550. bool is_dir() const;
  2551. time_t mtime() const;
  2552. size_t size() const;
  2553. private:
  2554. #if defined(_WIN32)
  2555. struct _stat st_;
  2556. #else
  2557. struct stat st_;
  2558. #endif
  2559. int ret_ = -1;
  2560. };
  2561. std::string make_host_and_port_string(const std::string &host, int port,
  2562. bool is_ssl);
  2563. std::string trim_copy(const std::string &s);
  2564. void divide(
  2565. const char *data, std::size_t size, char d,
  2566. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2567. fn);
  2568. void divide(
  2569. const std::string &str, char d,
  2570. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2571. fn);
  2572. void split(const char *b, const char *e, char d,
  2573. std::function<void(const char *, const char *)> fn);
  2574. void split(const char *b, const char *e, char d, size_t m,
  2575. std::function<void(const char *, const char *)> fn);
  2576. bool process_client_socket(
  2577. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2578. time_t write_timeout_sec, time_t write_timeout_usec,
  2579. time_t max_timeout_msec,
  2580. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2581. std::function<bool(Stream &)> callback);
  2582. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2583. int port, int address_family, bool tcp_nodelay,
  2584. bool ipv6_v6only, SocketOptions socket_options,
  2585. time_t connection_timeout_sec,
  2586. time_t connection_timeout_usec,
  2587. time_t read_timeout_sec, time_t read_timeout_usec,
  2588. time_t write_timeout_sec,
  2589. time_t write_timeout_usec,
  2590. const std::string &intf, Error &error);
  2591. const char *get_header_value(const Headers &headers, const std::string &key,
  2592. const char *def, size_t id);
  2593. std::string params_to_query_str(const Params &params);
  2594. void parse_query_text(const char *data, std::size_t size, Params &params);
  2595. void parse_query_text(const std::string &s, Params &params);
  2596. bool parse_multipart_boundary(const std::string &content_type,
  2597. std::string &boundary);
  2598. bool parse_range_header(const std::string &s, Ranges &ranges);
  2599. bool parse_accept_header(const std::string &s,
  2600. std::vector<std::string> &content_types);
  2601. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2602. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2603. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2604. EncodingType encoding_type(const Request &req, const Response &res);
  2605. class BufferStream final : public Stream {
  2606. public:
  2607. BufferStream() = default;
  2608. ~BufferStream() override = default;
  2609. bool is_readable() const override;
  2610. bool wait_readable() const override;
  2611. bool wait_writable() const override;
  2612. ssize_t read(char *ptr, size_t size) override;
  2613. ssize_t write(const char *ptr, size_t size) override;
  2614. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2615. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2616. socket_t socket() const override;
  2617. time_t duration() const override;
  2618. const std::string &get_buffer() const;
  2619. private:
  2620. std::string buffer;
  2621. size_t position = 0;
  2622. };
  2623. class compressor {
  2624. public:
  2625. virtual ~compressor() = default;
  2626. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2627. virtual bool compress(const char *data, size_t data_length, bool last,
  2628. Callback callback) = 0;
  2629. };
  2630. class decompressor {
  2631. public:
  2632. virtual ~decompressor() = default;
  2633. virtual bool is_valid() const = 0;
  2634. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2635. virtual bool decompress(const char *data, size_t data_length,
  2636. Callback callback) = 0;
  2637. };
  2638. class nocompressor final : public compressor {
  2639. public:
  2640. ~nocompressor() override = default;
  2641. bool compress(const char *data, size_t data_length, bool /*last*/,
  2642. Callback callback) override;
  2643. };
  2644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2645. class gzip_compressor final : public compressor {
  2646. public:
  2647. gzip_compressor();
  2648. ~gzip_compressor() override;
  2649. bool compress(const char *data, size_t data_length, bool last,
  2650. Callback callback) override;
  2651. private:
  2652. bool is_valid_ = false;
  2653. z_stream strm_;
  2654. };
  2655. class gzip_decompressor final : public decompressor {
  2656. public:
  2657. gzip_decompressor();
  2658. ~gzip_decompressor() override;
  2659. bool is_valid() const override;
  2660. bool decompress(const char *data, size_t data_length,
  2661. Callback callback) override;
  2662. private:
  2663. bool is_valid_ = false;
  2664. z_stream strm_;
  2665. };
  2666. #endif
  2667. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2668. class brotli_compressor final : public compressor {
  2669. public:
  2670. brotli_compressor();
  2671. ~brotli_compressor();
  2672. bool compress(const char *data, size_t data_length, bool last,
  2673. Callback callback) override;
  2674. private:
  2675. BrotliEncoderState *state_ = nullptr;
  2676. };
  2677. class brotli_decompressor final : public decompressor {
  2678. public:
  2679. brotli_decompressor();
  2680. ~brotli_decompressor();
  2681. bool is_valid() const override;
  2682. bool decompress(const char *data, size_t data_length,
  2683. Callback callback) override;
  2684. private:
  2685. BrotliDecoderResult decoder_r;
  2686. BrotliDecoderState *decoder_s = nullptr;
  2687. };
  2688. #endif
  2689. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2690. class zstd_compressor : public compressor {
  2691. public:
  2692. zstd_compressor();
  2693. ~zstd_compressor();
  2694. bool compress(const char *data, size_t data_length, bool last,
  2695. Callback callback) override;
  2696. private:
  2697. ZSTD_CCtx *ctx_ = nullptr;
  2698. };
  2699. class zstd_decompressor : public decompressor {
  2700. public:
  2701. zstd_decompressor();
  2702. ~zstd_decompressor();
  2703. bool is_valid() const override;
  2704. bool decompress(const char *data, size_t data_length,
  2705. Callback callback) override;
  2706. private:
  2707. ZSTD_DCtx *ctx_ = nullptr;
  2708. };
  2709. #endif
  2710. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2711. // to store data. The call can set memory on stack for performance.
  2712. class stream_line_reader {
  2713. public:
  2714. stream_line_reader(Stream &strm, char *fixed_buffer,
  2715. size_t fixed_buffer_size);
  2716. const char *ptr() const;
  2717. size_t size() const;
  2718. bool end_with_crlf() const;
  2719. bool getline();
  2720. private:
  2721. void append(char c);
  2722. Stream &strm_;
  2723. char *fixed_buffer_;
  2724. const size_t fixed_buffer_size_;
  2725. size_t fixed_buffer_used_size_ = 0;
  2726. std::string growable_buffer_;
  2727. };
  2728. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2729. const Headers &src_headers);
  2730. struct ChunkedDecoder {
  2731. Stream &strm;
  2732. size_t chunk_remaining = 0;
  2733. bool finished = false;
  2734. char line_buf[64];
  2735. size_t last_chunk_total = 0;
  2736. size_t last_chunk_offset = 0;
  2737. explicit ChunkedDecoder(Stream &s);
  2738. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2739. size_t &out_chunk_total);
  2740. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2741. };
  2742. class mmap {
  2743. public:
  2744. mmap(const char *path);
  2745. ~mmap();
  2746. bool open(const char *path);
  2747. void close();
  2748. bool is_open() const;
  2749. size_t size() const;
  2750. const char *data() const;
  2751. private:
  2752. #if defined(_WIN32)
  2753. HANDLE hFile_ = NULL;
  2754. HANDLE hMapping_ = NULL;
  2755. #else
  2756. int fd_ = -1;
  2757. #endif
  2758. size_t size_ = 0;
  2759. void *addr_ = nullptr;
  2760. bool is_open_empty_file = false;
  2761. };
  2762. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2763. namespace fields {
  2764. bool is_token_char(char c);
  2765. bool is_token(const std::string &s);
  2766. bool is_field_name(const std::string &s);
  2767. bool is_vchar(char c);
  2768. bool is_obs_text(char c);
  2769. bool is_field_vchar(char c);
  2770. bool is_field_content(const std::string &s);
  2771. bool is_field_value(const std::string &s);
  2772. } // namespace fields
  2773. } // namespace detail
  2774. /*
  2775. * TLS Abstraction Layer Declarations
  2776. */
  2777. #ifdef CPPHTTPLIB_SSL_ENABLED
  2778. // TLS abstraction layer - backend-specific type declarations
  2779. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2780. namespace tls {
  2781. namespace impl {
  2782. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2783. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2784. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2785. struct MbedTlsContext {
  2786. mbedtls_ssl_config conf;
  2787. mbedtls_entropy_context entropy;
  2788. mbedtls_ctr_drbg_context ctr_drbg;
  2789. mbedtls_x509_crt ca_chain;
  2790. mbedtls_x509_crt own_cert;
  2791. mbedtls_pk_context own_key;
  2792. bool is_server = false;
  2793. bool verify_client = false;
  2794. bool has_verify_callback = false;
  2795. MbedTlsContext();
  2796. ~MbedTlsContext();
  2797. MbedTlsContext(const MbedTlsContext &) = delete;
  2798. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2799. };
  2800. } // namespace impl
  2801. } // namespace tls
  2802. #endif
  2803. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2804. namespace tls {
  2805. namespace impl {
  2806. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2807. // This struct is accessible via tls::impl for use in SSL context
  2808. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2809. struct WolfSSLContext {
  2810. WOLFSSL_CTX *ctx = nullptr;
  2811. bool is_server = false;
  2812. bool verify_client = false;
  2813. bool has_verify_callback = false;
  2814. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2815. WolfSSLContext();
  2816. ~WolfSSLContext();
  2817. WolfSSLContext(const WolfSSLContext &) = delete;
  2818. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2819. };
  2820. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2821. struct WolfSSLCAStore {
  2822. std::string pem_data;
  2823. };
  2824. } // namespace impl
  2825. } // namespace tls
  2826. #endif
  2827. #endif // CPPHTTPLIB_SSL_ENABLED
  2828. namespace stream {
  2829. class Result {
  2830. public:
  2831. Result();
  2832. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2833. Result(Result &&other) noexcept;
  2834. Result &operator=(Result &&other) noexcept;
  2835. Result(const Result &) = delete;
  2836. Result &operator=(const Result &) = delete;
  2837. // Response info
  2838. bool is_valid() const;
  2839. explicit operator bool() const;
  2840. int status() const;
  2841. const Headers &headers() const;
  2842. std::string get_header_value(const std::string &key,
  2843. const char *def = "") const;
  2844. bool has_header(const std::string &key) const;
  2845. Error error() const;
  2846. Error read_error() const;
  2847. bool has_read_error() const;
  2848. // Stream reading
  2849. bool next();
  2850. const char *data() const;
  2851. size_t size() const;
  2852. std::string read_all();
  2853. private:
  2854. ClientImpl::StreamHandle handle_;
  2855. std::string buffer_;
  2856. size_t current_size_ = 0;
  2857. size_t chunk_size_;
  2858. bool finished_ = false;
  2859. };
  2860. // GET
  2861. template <typename ClientType>
  2862. inline Result Get(ClientType &cli, const std::string &path,
  2863. size_t chunk_size = 8192) {
  2864. return Result{cli.open_stream("GET", path), chunk_size};
  2865. }
  2866. template <typename ClientType>
  2867. inline Result Get(ClientType &cli, const std::string &path,
  2868. const Headers &headers, size_t chunk_size = 8192) {
  2869. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2870. }
  2871. template <typename ClientType>
  2872. inline Result Get(ClientType &cli, const std::string &path,
  2873. const Params &params, size_t chunk_size = 8192) {
  2874. return Result{cli.open_stream("GET", path, params), chunk_size};
  2875. }
  2876. template <typename ClientType>
  2877. inline Result Get(ClientType &cli, const std::string &path,
  2878. const Params &params, const Headers &headers,
  2879. size_t chunk_size = 8192) {
  2880. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2881. }
  2882. // POST
  2883. template <typename ClientType>
  2884. inline Result Post(ClientType &cli, const std::string &path,
  2885. const std::string &body, const std::string &content_type,
  2886. size_t chunk_size = 8192) {
  2887. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2888. chunk_size};
  2889. }
  2890. template <typename ClientType>
  2891. inline Result Post(ClientType &cli, const std::string &path,
  2892. const Headers &headers, const std::string &body,
  2893. const std::string &content_type, size_t chunk_size = 8192) {
  2894. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2895. chunk_size};
  2896. }
  2897. template <typename ClientType>
  2898. inline Result Post(ClientType &cli, const std::string &path,
  2899. const Params &params, const std::string &body,
  2900. const std::string &content_type, size_t chunk_size = 8192) {
  2901. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2902. chunk_size};
  2903. }
  2904. template <typename ClientType>
  2905. inline Result Post(ClientType &cli, const std::string &path,
  2906. const Params &params, const Headers &headers,
  2907. const std::string &body, const std::string &content_type,
  2908. size_t chunk_size = 8192) {
  2909. return Result{
  2910. cli.open_stream("POST", path, params, headers, body, content_type),
  2911. chunk_size};
  2912. }
  2913. // PUT
  2914. template <typename ClientType>
  2915. inline Result Put(ClientType &cli, const std::string &path,
  2916. const std::string &body, const std::string &content_type,
  2917. size_t chunk_size = 8192) {
  2918. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2919. chunk_size};
  2920. }
  2921. template <typename ClientType>
  2922. inline Result Put(ClientType &cli, const std::string &path,
  2923. const Headers &headers, const std::string &body,
  2924. const std::string &content_type, size_t chunk_size = 8192) {
  2925. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2926. chunk_size};
  2927. }
  2928. template <typename ClientType>
  2929. inline Result Put(ClientType &cli, const std::string &path,
  2930. const Params &params, const std::string &body,
  2931. const std::string &content_type, size_t chunk_size = 8192) {
  2932. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2933. chunk_size};
  2934. }
  2935. template <typename ClientType>
  2936. inline Result Put(ClientType &cli, const std::string &path,
  2937. const Params &params, const Headers &headers,
  2938. const std::string &body, const std::string &content_type,
  2939. size_t chunk_size = 8192) {
  2940. return Result{
  2941. cli.open_stream("PUT", path, params, headers, body, content_type),
  2942. chunk_size};
  2943. }
  2944. // PATCH
  2945. template <typename ClientType>
  2946. inline Result Patch(ClientType &cli, const std::string &path,
  2947. const std::string &body, const std::string &content_type,
  2948. size_t chunk_size = 8192) {
  2949. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2950. chunk_size};
  2951. }
  2952. template <typename ClientType>
  2953. inline Result Patch(ClientType &cli, const std::string &path,
  2954. const Headers &headers, const std::string &body,
  2955. const std::string &content_type, size_t chunk_size = 8192) {
  2956. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2957. chunk_size};
  2958. }
  2959. template <typename ClientType>
  2960. inline Result Patch(ClientType &cli, const std::string &path,
  2961. const Params &params, const std::string &body,
  2962. const std::string &content_type, size_t chunk_size = 8192) {
  2963. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2964. chunk_size};
  2965. }
  2966. template <typename ClientType>
  2967. inline Result Patch(ClientType &cli, const std::string &path,
  2968. const Params &params, const Headers &headers,
  2969. const std::string &body, const std::string &content_type,
  2970. size_t chunk_size = 8192) {
  2971. return Result{
  2972. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2973. chunk_size};
  2974. }
  2975. // DELETE
  2976. template <typename ClientType>
  2977. inline Result Delete(ClientType &cli, const std::string &path,
  2978. size_t chunk_size = 8192) {
  2979. return Result{cli.open_stream("DELETE", path), chunk_size};
  2980. }
  2981. template <typename ClientType>
  2982. inline Result Delete(ClientType &cli, const std::string &path,
  2983. const Headers &headers, size_t chunk_size = 8192) {
  2984. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2985. }
  2986. template <typename ClientType>
  2987. inline Result Delete(ClientType &cli, const std::string &path,
  2988. const std::string &body, const std::string &content_type,
  2989. size_t chunk_size = 8192) {
  2990. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2991. chunk_size};
  2992. }
  2993. template <typename ClientType>
  2994. inline Result Delete(ClientType &cli, const std::string &path,
  2995. const Headers &headers, const std::string &body,
  2996. const std::string &content_type,
  2997. size_t chunk_size = 8192) {
  2998. return Result{
  2999. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3000. chunk_size};
  3001. }
  3002. template <typename ClientType>
  3003. inline Result Delete(ClientType &cli, const std::string &path,
  3004. const Params &params, size_t chunk_size = 8192) {
  3005. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3006. }
  3007. template <typename ClientType>
  3008. inline Result Delete(ClientType &cli, const std::string &path,
  3009. const Params &params, const Headers &headers,
  3010. size_t chunk_size = 8192) {
  3011. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3012. }
  3013. template <typename ClientType>
  3014. inline Result Delete(ClientType &cli, const std::string &path,
  3015. const Params &params, const std::string &body,
  3016. const std::string &content_type,
  3017. size_t chunk_size = 8192) {
  3018. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3019. chunk_size};
  3020. }
  3021. template <typename ClientType>
  3022. inline Result Delete(ClientType &cli, const std::string &path,
  3023. const Params &params, const Headers &headers,
  3024. const std::string &body, const std::string &content_type,
  3025. size_t chunk_size = 8192) {
  3026. return Result{
  3027. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3028. chunk_size};
  3029. }
  3030. // HEAD
  3031. template <typename ClientType>
  3032. inline Result Head(ClientType &cli, const std::string &path,
  3033. size_t chunk_size = 8192) {
  3034. return Result{cli.open_stream("HEAD", path), chunk_size};
  3035. }
  3036. template <typename ClientType>
  3037. inline Result Head(ClientType &cli, const std::string &path,
  3038. const Headers &headers, size_t chunk_size = 8192) {
  3039. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3040. }
  3041. template <typename ClientType>
  3042. inline Result Head(ClientType &cli, const std::string &path,
  3043. const Params &params, size_t chunk_size = 8192) {
  3044. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3045. }
  3046. template <typename ClientType>
  3047. inline Result Head(ClientType &cli, const std::string &path,
  3048. const Params &params, const Headers &headers,
  3049. size_t chunk_size = 8192) {
  3050. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3051. }
  3052. // OPTIONS
  3053. template <typename ClientType>
  3054. inline Result Options(ClientType &cli, const std::string &path,
  3055. size_t chunk_size = 8192) {
  3056. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3057. }
  3058. template <typename ClientType>
  3059. inline Result Options(ClientType &cli, const std::string &path,
  3060. const Headers &headers, size_t chunk_size = 8192) {
  3061. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3062. }
  3063. template <typename ClientType>
  3064. inline Result Options(ClientType &cli, const std::string &path,
  3065. const Params &params, size_t chunk_size = 8192) {
  3066. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3067. }
  3068. template <typename ClientType>
  3069. inline Result Options(ClientType &cli, const std::string &path,
  3070. const Params &params, const Headers &headers,
  3071. size_t chunk_size = 8192) {
  3072. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3073. }
  3074. } // namespace stream
  3075. namespace sse {
  3076. struct SSEMessage {
  3077. std::string event; // Event type (default: "message")
  3078. std::string data; // Event payload
  3079. std::string id; // Event ID for Last-Event-ID header
  3080. SSEMessage();
  3081. void clear();
  3082. };
  3083. class SSEClient {
  3084. public:
  3085. using MessageHandler = std::function<void(const SSEMessage &)>;
  3086. using ErrorHandler = std::function<void(Error)>;
  3087. using OpenHandler = std::function<void()>;
  3088. SSEClient(Client &client, const std::string &path);
  3089. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3090. ~SSEClient();
  3091. SSEClient(const SSEClient &) = delete;
  3092. SSEClient &operator=(const SSEClient &) = delete;
  3093. // Event handlers
  3094. SSEClient &on_message(MessageHandler handler);
  3095. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3096. SSEClient &on_open(OpenHandler handler);
  3097. SSEClient &on_error(ErrorHandler handler);
  3098. SSEClient &set_reconnect_interval(int ms);
  3099. SSEClient &set_max_reconnect_attempts(int n);
  3100. // Update headers (thread-safe)
  3101. SSEClient &set_headers(const Headers &headers);
  3102. // State accessors
  3103. bool is_connected() const;
  3104. const std::string &last_event_id() const;
  3105. // Blocking start - runs event loop with auto-reconnect
  3106. void start();
  3107. // Non-blocking start - runs in background thread
  3108. void start_async();
  3109. // Stop the client (thread-safe)
  3110. void stop();
  3111. private:
  3112. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3113. void run_event_loop();
  3114. void dispatch_event(const SSEMessage &msg);
  3115. bool should_reconnect(int count) const;
  3116. void wait_for_reconnect();
  3117. // Client and path
  3118. Client &client_;
  3119. std::string path_;
  3120. Headers headers_;
  3121. mutable std::mutex headers_mutex_;
  3122. // Callbacks
  3123. MessageHandler on_message_;
  3124. std::map<std::string, MessageHandler> event_handlers_;
  3125. OpenHandler on_open_;
  3126. ErrorHandler on_error_;
  3127. // Configuration
  3128. int reconnect_interval_ms_ = 3000;
  3129. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3130. // State
  3131. std::atomic<bool> running_{false};
  3132. std::atomic<bool> connected_{false};
  3133. std::string last_event_id_;
  3134. // Async support
  3135. std::thread async_thread_;
  3136. };
  3137. } // namespace sse
  3138. namespace ws {
  3139. enum class Opcode : uint8_t {
  3140. Continuation = 0x0,
  3141. Text = 0x1,
  3142. Binary = 0x2,
  3143. Close = 0x8,
  3144. Ping = 0x9,
  3145. Pong = 0xA,
  3146. };
  3147. enum class CloseStatus : uint16_t {
  3148. Normal = 1000,
  3149. GoingAway = 1001,
  3150. ProtocolError = 1002,
  3151. UnsupportedData = 1003,
  3152. NoStatus = 1005,
  3153. Abnormal = 1006,
  3154. InvalidPayload = 1007,
  3155. PolicyViolation = 1008,
  3156. MessageTooBig = 1009,
  3157. MandatoryExtension = 1010,
  3158. InternalError = 1011,
  3159. };
  3160. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3161. class WebSocket {
  3162. public:
  3163. WebSocket(const WebSocket &) = delete;
  3164. WebSocket &operator=(const WebSocket &) = delete;
  3165. ~WebSocket();
  3166. ReadResult read(std::string &msg);
  3167. bool send(const std::string &data);
  3168. bool send(const char *data, size_t len);
  3169. void close(CloseStatus status = CloseStatus::Normal,
  3170. const std::string &reason = "");
  3171. const Request &request() const;
  3172. bool is_open() const;
  3173. private:
  3174. friend class httplib::Server;
  3175. friend class WebSocketClient;
  3176. WebSocket(
  3177. Stream &strm, const Request &req, bool is_server,
  3178. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3179. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3180. : strm_(strm), req_(req), is_server_(is_server),
  3181. ping_interval_sec_(ping_interval_sec),
  3182. max_missed_pongs_(max_missed_pongs) {
  3183. start_heartbeat();
  3184. }
  3185. WebSocket(
  3186. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3187. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3188. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3189. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3190. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3191. max_missed_pongs_(max_missed_pongs) {
  3192. start_heartbeat();
  3193. }
  3194. void start_heartbeat();
  3195. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3196. Stream &strm_;
  3197. std::unique_ptr<Stream> owned_strm_;
  3198. Request req_;
  3199. bool is_server_;
  3200. time_t ping_interval_sec_;
  3201. int max_missed_pongs_;
  3202. int unacked_pings_ = 0;
  3203. std::atomic<bool> closed_{false};
  3204. std::mutex write_mutex_;
  3205. std::thread ping_thread_;
  3206. std::mutex ping_mutex_;
  3207. std::condition_variable ping_cv_;
  3208. };
  3209. class WebSocketClient {
  3210. public:
  3211. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3212. const Headers &headers = {});
  3213. ~WebSocketClient();
  3214. WebSocketClient(const WebSocketClient &) = delete;
  3215. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3216. bool is_valid() const;
  3217. bool connect();
  3218. ReadResult read(std::string &msg);
  3219. bool send(const std::string &data);
  3220. bool send(const char *data, size_t len);
  3221. void close(CloseStatus status = CloseStatus::Normal,
  3222. const std::string &reason = "");
  3223. bool is_open() const;
  3224. const std::string &subprotocol() const;
  3225. void set_read_timeout(time_t sec, time_t usec = 0);
  3226. void set_write_timeout(time_t sec, time_t usec = 0);
  3227. void set_websocket_ping_interval(time_t sec);
  3228. void set_websocket_max_missed_pongs(int count);
  3229. void set_tcp_nodelay(bool on);
  3230. void set_address_family(int family);
  3231. void set_ipv6_v6only(bool on);
  3232. void set_socket_options(SocketOptions socket_options);
  3233. void set_connection_timeout(time_t sec, time_t usec = 0);
  3234. void set_interface(const std::string &intf);
  3235. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3236. #ifdef CPPHTTPLIB_SSL_ENABLED
  3237. void set_ca_cert_path(const std::string &path);
  3238. void set_ca_cert_store(tls::ca_store_t store);
  3239. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3240. void enable_server_certificate_verification(bool enabled);
  3241. void enable_system_ca(bool enabled);
  3242. #endif
  3243. private:
  3244. void shutdown_and_close();
  3245. bool create_stream(std::unique_ptr<Stream> &strm);
  3246. std::string host_;
  3247. int port_;
  3248. std::string path_;
  3249. Headers headers_;
  3250. std::string subprotocol_;
  3251. bool is_valid_ = false;
  3252. socket_t sock_ = INVALID_SOCKET;
  3253. std::unique_ptr<WebSocket> ws_;
  3254. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3255. time_t read_timeout_usec_ = 0;
  3256. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3257. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3258. time_t websocket_ping_interval_sec_ =
  3259. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3260. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3261. int address_family_ = AF_UNSPEC;
  3262. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3263. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3264. SocketOptions socket_options_ = nullptr;
  3265. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3266. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3267. std::string interface_;
  3268. // Hostname-IP map
  3269. std::map<std::string, std::string> addr_map_;
  3270. #ifdef CPPHTTPLIB_SSL_ENABLED
  3271. bool is_ssl_ = false;
  3272. tls::ctx_t tls_ctx_ = nullptr;
  3273. tls::session_t tls_session_ = nullptr;
  3274. std::string ca_cert_file_path_;
  3275. bool custom_ca_loaded_ = false;
  3276. bool certs_loaded_ = false;
  3277. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3278. bool server_certificate_verification_ = true;
  3279. #endif
  3280. };
  3281. namespace impl {
  3282. bool is_valid_utf8(const std::string &s);
  3283. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3284. bool &fin, bool expect_masked, size_t max_len);
  3285. } // namespace impl
  3286. } // namespace ws
  3287. // ----------------------------------------------------------------------------
  3288. /*
  3289. * Implementation that will be part of the .cc file if split into .h + .cc.
  3290. */
  3291. namespace stream {
  3292. // stream::Result implementations
  3293. inline Result::Result() : chunk_size_(8192) {}
  3294. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3295. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3296. inline Result::Result(Result &&other) noexcept
  3297. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3298. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3299. finished_(other.finished_) {
  3300. other.current_size_ = 0;
  3301. other.finished_ = true;
  3302. }
  3303. inline Result &Result::operator=(Result &&other) noexcept {
  3304. if (this != &other) {
  3305. handle_ = std::move(other.handle_);
  3306. buffer_ = std::move(other.buffer_);
  3307. current_size_ = other.current_size_;
  3308. chunk_size_ = other.chunk_size_;
  3309. finished_ = other.finished_;
  3310. other.current_size_ = 0;
  3311. other.finished_ = true;
  3312. }
  3313. return *this;
  3314. }
  3315. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3316. inline Result::operator bool() const { return is_valid(); }
  3317. inline int Result::status() const {
  3318. return handle_.response ? handle_.response->status : -1;
  3319. }
  3320. inline const Headers &Result::headers() const {
  3321. static const Headers empty_headers;
  3322. return handle_.response ? handle_.response->headers : empty_headers;
  3323. }
  3324. inline std::string Result::get_header_value(const std::string &key,
  3325. const char *def) const {
  3326. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3327. }
  3328. inline bool Result::has_header(const std::string &key) const {
  3329. return handle_.response ? handle_.response->has_header(key) : false;
  3330. }
  3331. inline Error Result::error() const { return handle_.error; }
  3332. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3333. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3334. inline bool Result::next() {
  3335. if (!handle_.is_valid() || finished_) { return false; }
  3336. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3337. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3338. if (n > 0) {
  3339. current_size_ = static_cast<size_t>(n);
  3340. return true;
  3341. }
  3342. current_size_ = 0;
  3343. finished_ = true;
  3344. return false;
  3345. }
  3346. inline const char *Result::data() const { return buffer_.data(); }
  3347. inline size_t Result::size() const { return current_size_; }
  3348. inline std::string Result::read_all() {
  3349. std::string result;
  3350. while (next()) {
  3351. result.append(data(), size());
  3352. }
  3353. return result;
  3354. }
  3355. } // namespace stream
  3356. namespace sse {
  3357. // SSEMessage implementations
  3358. inline SSEMessage::SSEMessage() : event("message") {}
  3359. inline void SSEMessage::clear() {
  3360. event = "message";
  3361. data.clear();
  3362. id.clear();
  3363. }
  3364. // SSEClient implementations
  3365. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3366. : client_(client), path_(path) {}
  3367. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3368. const Headers &headers)
  3369. : client_(client), path_(path), headers_(headers) {}
  3370. inline SSEClient::~SSEClient() { stop(); }
  3371. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3372. on_message_ = std::move(handler);
  3373. return *this;
  3374. }
  3375. inline SSEClient &SSEClient::on_event(const std::string &type,
  3376. MessageHandler handler) {
  3377. event_handlers_[type] = std::move(handler);
  3378. return *this;
  3379. }
  3380. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3381. on_open_ = std::move(handler);
  3382. return *this;
  3383. }
  3384. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3385. on_error_ = std::move(handler);
  3386. return *this;
  3387. }
  3388. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3389. reconnect_interval_ms_ = ms;
  3390. return *this;
  3391. }
  3392. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3393. max_reconnect_attempts_ = n;
  3394. return *this;
  3395. }
  3396. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3397. std::lock_guard<std::mutex> lock(headers_mutex_);
  3398. headers_ = headers;
  3399. return *this;
  3400. }
  3401. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3402. inline const std::string &SSEClient::last_event_id() const {
  3403. return last_event_id_;
  3404. }
  3405. inline void SSEClient::start() {
  3406. running_.store(true);
  3407. run_event_loop();
  3408. }
  3409. inline void SSEClient::start_async() {
  3410. running_.store(true);
  3411. async_thread_ = std::thread([this]() { run_event_loop(); });
  3412. }
  3413. inline void SSEClient::stop() {
  3414. running_.store(false);
  3415. client_.stop(); // Cancel any pending operations
  3416. if (async_thread_.joinable()) { async_thread_.join(); }
  3417. }
  3418. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3419. int &retry_ms) {
  3420. // Blank line signals end of event
  3421. if (line.empty() || line == "\r") { return true; }
  3422. // Lines starting with ':' are comments (ignored)
  3423. if (!line.empty() && line[0] == ':') { return false; }
  3424. // Find the colon separator
  3425. auto colon_pos = line.find(':');
  3426. if (colon_pos == std::string::npos) {
  3427. // Line with no colon is treated as field name with empty value
  3428. return false;
  3429. }
  3430. auto field = line.substr(0, colon_pos);
  3431. std::string value;
  3432. // Value starts after colon, skip optional single space
  3433. if (colon_pos + 1 < line.size()) {
  3434. auto value_start = colon_pos + 1;
  3435. if (line[value_start] == ' ') { value_start++; }
  3436. value = line.substr(value_start);
  3437. // Remove trailing \r if present
  3438. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3439. }
  3440. // Handle known fields
  3441. if (field == "event") {
  3442. msg.event = value;
  3443. } else if (field == "data") {
  3444. // Multiple data lines are concatenated with newlines
  3445. if (!msg.data.empty()) { msg.data += "\n"; }
  3446. msg.data += value;
  3447. } else if (field == "id") {
  3448. // Empty id is valid (clears the last event ID)
  3449. msg.id = value;
  3450. } else if (field == "retry") {
  3451. // Parse retry interval in milliseconds
  3452. {
  3453. int v = 0;
  3454. auto res =
  3455. detail::from_chars(value.data(), value.data() + value.size(), v);
  3456. if (res.ec == std::errc{}) { retry_ms = v; }
  3457. }
  3458. }
  3459. // Unknown fields are ignored per SSE spec
  3460. return false;
  3461. }
  3462. inline void SSEClient::run_event_loop() {
  3463. auto reconnect_count = 0;
  3464. while (running_.load()) {
  3465. // Build headers, including Last-Event-ID if we have one
  3466. Headers request_headers;
  3467. {
  3468. std::lock_guard<std::mutex> lock(headers_mutex_);
  3469. request_headers = headers_;
  3470. }
  3471. if (!last_event_id_.empty()) {
  3472. request_headers.emplace("Last-Event-ID", last_event_id_);
  3473. }
  3474. // Open streaming connection
  3475. auto result = stream::Get(client_, path_, request_headers);
  3476. // Connection error handling
  3477. if (!result) {
  3478. connected_.store(false);
  3479. if (on_error_) { on_error_(result.error()); }
  3480. if (!should_reconnect(reconnect_count)) { break; }
  3481. wait_for_reconnect();
  3482. reconnect_count++;
  3483. continue;
  3484. }
  3485. if (result.status() != StatusCode::OK_200) {
  3486. connected_.store(false);
  3487. if (on_error_) { on_error_(Error::Connection); }
  3488. // For certain errors, don't reconnect.
  3489. // Note: 401 is intentionally absent so that handlers can refresh
  3490. // credentials via set_headers() and let the client reconnect.
  3491. if (result.status() == StatusCode::NoContent_204 ||
  3492. result.status() == StatusCode::NotFound_404 ||
  3493. result.status() == StatusCode::Forbidden_403) {
  3494. break;
  3495. }
  3496. if (!should_reconnect(reconnect_count)) { break; }
  3497. wait_for_reconnect();
  3498. reconnect_count++;
  3499. continue;
  3500. }
  3501. // Connection successful
  3502. connected_.store(true);
  3503. reconnect_count = 0;
  3504. if (on_open_) { on_open_(); }
  3505. // Event receiving loop
  3506. std::string buffer;
  3507. SSEMessage current_msg;
  3508. while (running_.load() && result.next()) {
  3509. buffer.append(result.data(), result.size());
  3510. // Process complete lines in the buffer
  3511. size_t line_start = 0;
  3512. size_t newline_pos;
  3513. while ((newline_pos = buffer.find('\n', line_start)) !=
  3514. std::string::npos) {
  3515. auto line = buffer.substr(line_start, newline_pos - line_start);
  3516. line_start = newline_pos + 1;
  3517. // Parse the line and check if event is complete
  3518. auto event_complete =
  3519. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3520. if (event_complete && !current_msg.data.empty()) {
  3521. // Update last_event_id for reconnection
  3522. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3523. // Dispatch event to appropriate handler
  3524. dispatch_event(current_msg);
  3525. current_msg.clear();
  3526. }
  3527. }
  3528. // Keep unprocessed data in buffer
  3529. buffer.erase(0, line_start);
  3530. }
  3531. // Connection ended
  3532. connected_.store(false);
  3533. if (!running_.load()) { break; }
  3534. // Check for read errors
  3535. if (result.has_read_error()) {
  3536. if (on_error_) { on_error_(result.read_error()); }
  3537. }
  3538. if (!should_reconnect(reconnect_count)) { break; }
  3539. wait_for_reconnect();
  3540. reconnect_count++;
  3541. }
  3542. connected_.store(false);
  3543. }
  3544. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3545. // Check for specific event type handler first
  3546. auto it = event_handlers_.find(msg.event);
  3547. if (it != event_handlers_.end()) {
  3548. it->second(msg);
  3549. return;
  3550. }
  3551. // Fall back to generic message handler
  3552. if (on_message_) { on_message_(msg); }
  3553. }
  3554. inline bool SSEClient::should_reconnect(int count) const {
  3555. if (!running_.load()) { return false; }
  3556. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3557. return count < max_reconnect_attempts_;
  3558. }
  3559. inline void SSEClient::wait_for_reconnect() {
  3560. // Use small increments to check running_ flag frequently
  3561. auto waited = 0;
  3562. while (running_.load() && waited < reconnect_interval_ms_) {
  3563. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3564. waited += 100;
  3565. }
  3566. }
  3567. } // namespace sse
  3568. #ifdef CPPHTTPLIB_SSL_ENABLED
  3569. /*
  3570. * TLS abstraction layer - internal function declarations
  3571. * These are implementation details and not part of the public API.
  3572. */
  3573. namespace tls {
  3574. // Client context
  3575. ctx_t create_client_context();
  3576. void free_context(ctx_t ctx);
  3577. bool set_min_version(ctx_t ctx, Version version);
  3578. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3579. bool load_ca_file(ctx_t ctx, const char *file_path);
  3580. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3581. bool load_system_certs(ctx_t ctx);
  3582. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3583. const char *password);
  3584. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3585. const char *key_path, const char *password);
  3586. // Server context
  3587. ctx_t create_server_context();
  3588. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3589. const char *password);
  3590. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3591. const char *key_path, const char *password);
  3592. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3593. void set_verify_client(ctx_t ctx, bool require);
  3594. // Session management
  3595. session_t create_session(ctx_t ctx, socket_t sock);
  3596. void free_session(session_t session);
  3597. bool set_sni(session_t session, const char *hostname);
  3598. bool set_hostname(session_t session, const char *hostname);
  3599. // Handshake (non-blocking capable)
  3600. TlsError connect(session_t session);
  3601. TlsError accept(session_t session);
  3602. // Handshake with timeout (blocking until timeout)
  3603. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3604. time_t timeout_usec, TlsError *err);
  3605. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3606. time_t timeout_usec, TlsError *err);
  3607. // I/O (non-blocking capable)
  3608. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3609. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3610. int pending(const_session_t session);
  3611. void shutdown(session_t session, bool graceful);
  3612. // Connection state
  3613. bool is_peer_closed(session_t session, socket_t sock);
  3614. // Certificate verification
  3615. cert_t get_peer_cert(const_session_t session);
  3616. void free_cert(cert_t cert);
  3617. bool verify_hostname(cert_t cert, const char *hostname);
  3618. uint64_t hostname_mismatch_code();
  3619. long get_verify_result(const_session_t session);
  3620. // Certificate introspection
  3621. std::string get_cert_subject_cn(cert_t cert);
  3622. std::string get_cert_issuer_name(cert_t cert);
  3623. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3624. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3625. std::string get_cert_serial(cert_t cert);
  3626. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3627. const char *get_sni(const_session_t session);
  3628. // CA store management
  3629. ca_store_t create_ca_store(const char *pem, size_t len);
  3630. void free_ca_store(ca_store_t store);
  3631. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3632. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3633. std::vector<std::string> get_ca_names(ctx_t ctx);
  3634. // Dynamic certificate update (for servers)
  3635. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3636. const char *password);
  3637. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3638. // Certificate verification callback
  3639. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3640. long get_verify_error(const_session_t session);
  3641. std::string verify_error_string(long error_code);
  3642. // TlsError information
  3643. uint64_t peek_error();
  3644. uint64_t get_error();
  3645. std::string error_string(uint64_t code);
  3646. } // namespace tls
  3647. #endif // CPPHTTPLIB_SSL_ENABLED
  3648. /*
  3649. * Group 1: detail namespace - Non-SSL utilities
  3650. */
  3651. namespace detail {
  3652. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3653. const void *optval, socklen_t optlen) {
  3654. return setsockopt(sock, level, optname,
  3655. #ifdef _WIN32
  3656. reinterpret_cast<const char *>(optval),
  3657. #else
  3658. optval,
  3659. #endif
  3660. optlen) == 0;
  3661. }
  3662. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3663. time_t sec, time_t usec) {
  3664. #ifdef _WIN32
  3665. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3666. #else
  3667. timeval timeout;
  3668. timeout.tv_sec = static_cast<long>(sec);
  3669. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3670. #endif
  3671. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3672. }
  3673. inline bool is_hex(char c, int &v) {
  3674. if (is_ascii_digit(c)) {
  3675. v = c - '0';
  3676. return true;
  3677. } else if ('A' <= c && c <= 'F') {
  3678. v = c - 'A' + 10;
  3679. return true;
  3680. } else if ('a' <= c && c <= 'f') {
  3681. v = c - 'a' + 10;
  3682. return true;
  3683. }
  3684. return false;
  3685. }
  3686. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3687. int &val) {
  3688. if (i >= s.size()) { return false; }
  3689. val = 0;
  3690. for (; cnt; i++, cnt--) {
  3691. if (!s[i]) { return false; }
  3692. auto v = 0;
  3693. if (is_hex(s[i], v)) {
  3694. val = val * 16 + v;
  3695. } else {
  3696. return false;
  3697. }
  3698. }
  3699. return true;
  3700. }
  3701. inline std::string from_i_to_hex(size_t n) {
  3702. static const auto charset = "0123456789abcdef";
  3703. std::string ret;
  3704. do {
  3705. ret = charset[n & 15] + ret;
  3706. n >>= 4;
  3707. } while (n > 0);
  3708. return ret;
  3709. }
  3710. inline std::string compute_etag(const FileStat &fs) {
  3711. if (!fs.is_file()) { return std::string(); }
  3712. // If mtime cannot be determined (negative value indicates an error
  3713. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3714. // value like 0 could collide with a real file that legitimately has
  3715. // mtime == 0 (epoch) and lead to misleading validators.
  3716. auto mtime_raw = fs.mtime();
  3717. if (mtime_raw < 0) { return std::string(); }
  3718. auto mtime = static_cast<size_t>(mtime_raw);
  3719. auto size = fs.size();
  3720. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3721. from_i_to_hex(size) + "\"";
  3722. }
  3723. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3724. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3725. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3726. inline std::string file_mtime_to_http_date(time_t mtime) {
  3727. if (mtime < 0) { return std::string(); }
  3728. struct tm tm_buf;
  3729. #ifdef _WIN32
  3730. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3731. #else
  3732. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3733. #endif
  3734. char buf[64];
  3735. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3736. return std::string();
  3737. }
  3738. return std::string(buf);
  3739. }
  3740. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3741. inline time_t parse_http_date(const std::string &date_str) {
  3742. struct tm tm_buf;
  3743. // Create a classic locale object once for all parsing attempts
  3744. const std::locale classic_locale = std::locale::classic();
  3745. // Try to parse using std::get_time (C++11, cross-platform)
  3746. auto try_parse = [&](const char *fmt) -> bool {
  3747. std::istringstream ss(date_str);
  3748. ss.imbue(classic_locale);
  3749. memset(&tm_buf, 0, sizeof(tm_buf));
  3750. ss >> std::get_time(&tm_buf, fmt);
  3751. return !ss.fail();
  3752. };
  3753. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3754. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3755. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3756. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3757. // asctime format: "Sun Nov 6 08:49:37 1994"
  3758. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3759. return static_cast<time_t>(-1);
  3760. }
  3761. }
  3762. }
  3763. #ifdef _WIN32
  3764. return _mkgmtime(&tm_buf);
  3765. #elif defined _AIX
  3766. return mktime(&tm_buf);
  3767. #else
  3768. return timegm(&tm_buf);
  3769. #endif
  3770. }
  3771. inline bool is_weak_etag(const std::string &s) {
  3772. // Check if the string is a weak ETag (starts with 'W/"')
  3773. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3774. }
  3775. inline bool is_strong_etag(const std::string &s) {
  3776. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3777. // chars)
  3778. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3779. }
  3780. inline size_t to_utf8(int code, char *buff) {
  3781. if (code < 0x0080) {
  3782. buff[0] = static_cast<char>(code & 0x7F);
  3783. return 1;
  3784. } else if (code < 0x0800) {
  3785. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3786. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3787. return 2;
  3788. } else if (code < 0xD800) {
  3789. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3790. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3791. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3792. return 3;
  3793. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3794. return 0;
  3795. } else if (code < 0x10000) {
  3796. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3797. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3798. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3799. return 3;
  3800. } else if (code < 0x110000) {
  3801. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3802. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3803. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3804. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3805. return 4;
  3806. }
  3807. // NOTREACHED
  3808. return 0;
  3809. }
  3810. } // namespace detail
  3811. namespace ws {
  3812. namespace impl {
  3813. inline bool is_valid_utf8(const std::string &s) {
  3814. size_t i = 0;
  3815. auto n = s.size();
  3816. while (i < n) {
  3817. auto c = static_cast<unsigned char>(s[i]);
  3818. size_t len;
  3819. uint32_t cp;
  3820. if (c < 0x80) {
  3821. i++;
  3822. continue;
  3823. } else if ((c & 0xE0) == 0xC0) {
  3824. len = 2;
  3825. cp = c & 0x1F;
  3826. } else if ((c & 0xF0) == 0xE0) {
  3827. len = 3;
  3828. cp = c & 0x0F;
  3829. } else if ((c & 0xF8) == 0xF0) {
  3830. len = 4;
  3831. cp = c & 0x07;
  3832. } else {
  3833. return false;
  3834. }
  3835. if (i + len > n) { return false; }
  3836. for (size_t j = 1; j < len; j++) {
  3837. auto b = static_cast<unsigned char>(s[i + j]);
  3838. if ((b & 0xC0) != 0x80) { return false; }
  3839. cp = (cp << 6) | (b & 0x3F);
  3840. }
  3841. // Overlong encoding check
  3842. if (len == 2 && cp < 0x80) { return false; }
  3843. if (len == 3 && cp < 0x800) { return false; }
  3844. if (len == 4 && cp < 0x10000) { return false; }
  3845. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3846. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3847. if (cp > 0x10FFFF) { return false; }
  3848. i += len;
  3849. }
  3850. return true;
  3851. }
  3852. } // namespace impl
  3853. } // namespace ws
  3854. namespace detail {
  3855. // NOTE: This code came up with the following stackoverflow post:
  3856. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3857. inline std::string base64_encode(const std::string &in) {
  3858. static const auto lookup =
  3859. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3860. std::string out;
  3861. out.reserve(in.size());
  3862. // Unsigned: the accumulator is never masked, so with a signed int the
  3863. // `val << 8` below overflows once enough bytes are folded in (undefined
  3864. // behaviour before C++20). Only the low bits are ever emitted, so the
  3865. // wrap-around of an unsigned accumulator does not affect the output.
  3866. uint32_t val = 0;
  3867. auto valb = -6;
  3868. for (auto c : in) {
  3869. val = (val << 8) + static_cast<uint8_t>(c);
  3870. valb += 8;
  3871. while (valb >= 0) {
  3872. out.push_back(lookup[(val >> valb) & 0x3F]);
  3873. valb -= 6;
  3874. }
  3875. }
  3876. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3877. while (out.size() % 4) {
  3878. out.push_back('=');
  3879. }
  3880. return out;
  3881. }
  3882. inline std::string sha1(const std::string &input) {
  3883. // RFC 3174 SHA-1 implementation
  3884. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3885. return (x << n) | (x >> (32 - n));
  3886. };
  3887. uint32_t h0 = 0x67452301;
  3888. uint32_t h1 = 0xEFCDAB89;
  3889. uint32_t h2 = 0x98BADCFE;
  3890. uint32_t h3 = 0x10325476;
  3891. uint32_t h4 = 0xC3D2E1F0;
  3892. // Pre-processing: adding padding bits
  3893. std::string msg = input;
  3894. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3895. msg.push_back(static_cast<char>(0x80u));
  3896. while (msg.size() % 64 != 56) {
  3897. msg.push_back(0);
  3898. }
  3899. // Append original length in bits as 64-bit big-endian
  3900. for (int i = 56; i >= 0; i -= 8) {
  3901. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3902. }
  3903. // Process each 512-bit chunk
  3904. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3905. uint32_t w[80];
  3906. for (size_t i = 0; i < 16; i++) {
  3907. w[i] =
  3908. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3909. << 24) |
  3910. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3911. << 16) |
  3912. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3913. << 8) |
  3914. (static_cast<uint32_t>(
  3915. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3916. }
  3917. for (int i = 16; i < 80; i++) {
  3918. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3919. }
  3920. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3921. for (int i = 0; i < 80; i++) {
  3922. uint32_t f, k;
  3923. if (i < 20) {
  3924. f = (b & c) | ((~b) & d);
  3925. k = 0x5A827999;
  3926. } else if (i < 40) {
  3927. f = b ^ c ^ d;
  3928. k = 0x6ED9EBA1;
  3929. } else if (i < 60) {
  3930. f = (b & c) | (b & d) | (c & d);
  3931. k = 0x8F1BBCDC;
  3932. } else {
  3933. f = b ^ c ^ d;
  3934. k = 0xCA62C1D6;
  3935. }
  3936. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3937. e = d;
  3938. d = c;
  3939. c = left_rotate(b, 30);
  3940. b = a;
  3941. a = temp;
  3942. }
  3943. h0 += a;
  3944. h1 += b;
  3945. h2 += c;
  3946. h3 += d;
  3947. h4 += e;
  3948. }
  3949. // Produce the final hash as a 20-byte binary string
  3950. std::string hash(20, '\0');
  3951. for (size_t i = 0; i < 4; i++) {
  3952. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3953. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3954. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3955. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3956. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3957. }
  3958. return hash;
  3959. }
  3960. inline std::string websocket_accept_key(const std::string &client_key) {
  3961. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3962. return base64_encode(sha1(client_key + magic));
  3963. }
  3964. inline bool is_websocket_upgrade(const Request &req) {
  3965. if (req.method != "GET") { return false; }
  3966. // Check Upgrade: websocket (case-insensitive)
  3967. auto upgrade_it = req.headers.find("Upgrade");
  3968. if (upgrade_it == req.headers.end()) { return false; }
  3969. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3970. if (upgrade_val != "websocket") { return false; }
  3971. // Check Connection header contains "Upgrade"
  3972. auto connection_it = req.headers.find("Connection");
  3973. if (connection_it == req.headers.end()) { return false; }
  3974. auto connection_val = case_ignore::to_lower(connection_it->second);
  3975. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3976. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3977. // RFC 6455 Section 4.2.1
  3978. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3979. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3980. return false;
  3981. }
  3982. static const std::string b64chars =
  3983. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3984. for (size_t i = 0; i < 22; i++) {
  3985. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3986. }
  3987. // Check Sec-WebSocket-Version: 13
  3988. auto version = req.get_header_value("Sec-WebSocket-Version");
  3989. if (version != "13") { return false; }
  3990. return true;
  3991. }
  3992. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3993. const char *data, size_t len, bool fin,
  3994. bool mask) {
  3995. // First byte: FIN + opcode
  3996. uint8_t header[2];
  3997. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3998. (static_cast<uint8_t>(opcode) & 0x0F));
  3999. // Second byte: MASK + payload length
  4000. if (len < 126) {
  4001. header[1] = static_cast<uint8_t>(len);
  4002. if (mask) { header[1] |= 0x80; }
  4003. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4004. } else if (len <= 0xFFFF) {
  4005. header[1] = 126;
  4006. if (mask) { header[1] |= 0x80; }
  4007. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4008. uint8_t ext[2];
  4009. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4010. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4011. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4012. } else {
  4013. header[1] = 127;
  4014. if (mask) { header[1] |= 0x80; }
  4015. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4016. uint8_t ext[8];
  4017. for (int i = 7; i >= 0; i--) {
  4018. ext[7 - i] =
  4019. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4020. }
  4021. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4022. }
  4023. if (mask) {
  4024. // Generate random mask key
  4025. thread_local std::mt19937 rng(std::random_device{}());
  4026. uint8_t mask_key[4];
  4027. auto r = rng();
  4028. std::memcpy(mask_key, &r, 4);
  4029. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4030. // Write masked payload in chunks
  4031. const size_t chunk_size = 4096;
  4032. std::vector<char> buf((std::min)(len, chunk_size));
  4033. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4034. size_t n = (std::min)(chunk_size, len - offset);
  4035. for (size_t i = 0; i < n; i++) {
  4036. buf[i] =
  4037. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4038. }
  4039. if (strm.write(buf.data(), n) < 0) { return false; }
  4040. }
  4041. } else {
  4042. if (len > 0) {
  4043. if (strm.write(data, len) < 0) { return false; }
  4044. }
  4045. }
  4046. return true;
  4047. }
  4048. } // namespace detail
  4049. namespace ws {
  4050. namespace impl {
  4051. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4052. std::string &payload, bool &fin,
  4053. bool expect_masked, size_t max_len) {
  4054. // Read first 2 bytes
  4055. uint8_t header[2];
  4056. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4057. fin = (header[0] & 0x80) != 0;
  4058. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4059. if (header[0] & 0x70) { return false; }
  4060. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4061. bool masked = (header[1] & 0x80) != 0;
  4062. uint64_t payload_len = header[1] & 0x7F;
  4063. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4064. // MUST have a payload length of 125 bytes or less
  4065. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4066. if (is_control) {
  4067. if (!fin) { return false; }
  4068. if (payload_len > 125) { return false; }
  4069. }
  4070. if (masked != expect_masked) { return false; }
  4071. // Extended payload length
  4072. if (payload_len == 126) {
  4073. uint8_t ext[2];
  4074. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4075. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4076. } else if (payload_len == 127) {
  4077. uint8_t ext[8];
  4078. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4079. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4080. if (ext[0] & 0x80) { return false; }
  4081. payload_len = 0;
  4082. for (int i = 0; i < 8; i++) {
  4083. payload_len = (payload_len << 8) | ext[i];
  4084. }
  4085. }
  4086. if (payload_len > max_len) { return false; }
  4087. // Read mask key if present
  4088. uint8_t mask_key[4] = {0};
  4089. if (masked) {
  4090. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4091. }
  4092. // Read payload
  4093. payload.resize(static_cast<size_t>(payload_len));
  4094. if (payload_len > 0) {
  4095. size_t total_read = 0;
  4096. while (total_read < payload_len) {
  4097. auto n = strm.read(&payload[total_read],
  4098. static_cast<size_t>(payload_len - total_read));
  4099. if (n <= 0) { return false; }
  4100. total_read += static_cast<size_t>(n);
  4101. }
  4102. }
  4103. // Unmask if needed
  4104. if (masked) {
  4105. for (size_t i = 0; i < payload.size(); i++) {
  4106. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4107. }
  4108. }
  4109. return true;
  4110. }
  4111. } // namespace impl
  4112. } // namespace ws
  4113. namespace detail {
  4114. inline bool is_valid_path(const std::string &path) {
  4115. size_t level = 0;
  4116. size_t i = 0;
  4117. // Skip slash
  4118. while (i < path.size() && path[i] == '/') {
  4119. i++;
  4120. }
  4121. while (i < path.size()) {
  4122. // Read component
  4123. auto beg = i;
  4124. while (i < path.size() && path[i] != '/') {
  4125. if (path[i] == '\0') {
  4126. return false;
  4127. } else if (path[i] == '\\') {
  4128. return false;
  4129. }
  4130. i++;
  4131. }
  4132. auto len = i - beg;
  4133. assert(len > 0);
  4134. if (!path.compare(beg, len, ".")) {
  4135. ;
  4136. } else if (!path.compare(beg, len, "..")) {
  4137. if (level == 0) { return false; }
  4138. level--;
  4139. } else {
  4140. level++;
  4141. }
  4142. // Skip slash
  4143. while (i < path.size() && path[i] == '/') {
  4144. i++;
  4145. }
  4146. }
  4147. return true;
  4148. }
  4149. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4150. #if defined(_WIN32)
  4151. char buf[_MAX_PATH];
  4152. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4153. resolved = buf;
  4154. #elif defined(PATH_MAX)
  4155. char buf[PATH_MAX];
  4156. if (realpath(path, buf) == nullptr) { return false; }
  4157. resolved = buf;
  4158. #else
  4159. auto buf = realpath(path, nullptr);
  4160. auto guard = scope_exit([&]() { std::free(buf); });
  4161. if (buf == nullptr) { return false; }
  4162. resolved = buf;
  4163. #endif
  4164. return true;
  4165. }
  4166. inline bool is_path_within_base(const std::string &resolved_path,
  4167. const std::string &resolved_base) {
  4168. #if defined(_WIN32)
  4169. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4170. resolved_base.size()) == 0;
  4171. #else
  4172. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4173. resolved_base.size()) == 0;
  4174. #endif
  4175. }
  4176. inline FileStat::FileStat(const std::string &path) {
  4177. #if defined(_WIN32)
  4178. auto wpath = u8string_to_wstring(path.c_str());
  4179. ret_ = _wstat(wpath.c_str(), &st_);
  4180. #else
  4181. ret_ = stat(path.c_str(), &st_);
  4182. #endif
  4183. }
  4184. inline bool FileStat::is_file() const {
  4185. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4186. }
  4187. inline bool FileStat::is_dir() const {
  4188. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4189. }
  4190. inline time_t FileStat::mtime() const {
  4191. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4192. : static_cast<time_t>(-1);
  4193. }
  4194. inline size_t FileStat::size() const {
  4195. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4196. }
  4197. inline std::string encode_path(const std::string &s) {
  4198. std::string result;
  4199. result.reserve(s.size());
  4200. for (size_t i = 0; s[i]; i++) {
  4201. switch (s[i]) {
  4202. case ' ': result += "%20"; break;
  4203. case '+': result += "%2B"; break;
  4204. case '\r': result += "%0D"; break;
  4205. case '\n': result += "%0A"; break;
  4206. case '\'': result += "%27"; break;
  4207. case ',': result += "%2C"; break;
  4208. // case ':': result += "%3A"; break; // ok? probably...
  4209. case ';': result += "%3B"; break;
  4210. default:
  4211. auto c = static_cast<uint8_t>(s[i]);
  4212. if (c >= 0x80) {
  4213. result += '%';
  4214. char hex[4];
  4215. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4216. assert(len == 2);
  4217. result.append(hex, static_cast<size_t>(len));
  4218. } else {
  4219. result += s[i];
  4220. }
  4221. break;
  4222. }
  4223. }
  4224. return result;
  4225. }
  4226. inline std::string file_extension(const std::string &path) {
  4227. std::smatch m;
  4228. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4229. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4230. return std::string();
  4231. }
  4232. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4233. template <typename T>
  4234. inline bool parse_header(const char *beg, const char *end, T fn);
  4235. template <typename T>
  4236. inline bool parse_header(const char *beg, const char *end, T fn) {
  4237. // Skip trailing spaces and tabs.
  4238. while (beg < end && is_space_or_tab(end[-1])) {
  4239. end--;
  4240. }
  4241. auto p = beg;
  4242. while (p < end && *p != ':') {
  4243. p++;
  4244. }
  4245. auto name = std::string(beg, p);
  4246. if (!detail::fields::is_field_name(name)) { return false; }
  4247. if (p == end) { return false; }
  4248. auto key_end = p;
  4249. if (*p++ != ':') { return false; }
  4250. while (p < end && is_space_or_tab(*p)) {
  4251. p++;
  4252. }
  4253. if (p <= end) {
  4254. auto key_len = key_end - beg;
  4255. if (!key_len) { return false; }
  4256. auto key = std::string(beg, key_end);
  4257. auto val = std::string(p, end);
  4258. if (!detail::fields::is_field_value(val)) { return false; }
  4259. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4260. // percent-decoded by the recipient. Applications that need to interpret a
  4261. // value as a URI component should call httplib::decode_uri_component()
  4262. // (or decode_path_component()) explicitly.
  4263. fn(key, val);
  4264. return true;
  4265. }
  4266. return false;
  4267. }
  4268. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4269. const Headers &src_headers) {
  4270. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4271. // transfer coding is complete when a chunk with a chunk-size of zero is
  4272. // received, possibly followed by a trailer section, and finally terminated by
  4273. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4274. //
  4275. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4276. // doesn't care for the existence of the final CRLF. In other words, it seems
  4277. // to be ok whether the final CRLF exists or not in the chunked data.
  4278. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4279. //
  4280. // According to the reference code in RFC 9112, cpp-httplib now allows
  4281. // chunked transfer coding data without the final CRLF.
  4282. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4283. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4284. "transfer-encoding",
  4285. "content-length",
  4286. "host",
  4287. "authorization",
  4288. "www-authenticate",
  4289. "proxy-authenticate",
  4290. "proxy-authorization",
  4291. "cookie",
  4292. "set-cookie",
  4293. "cache-control",
  4294. "expect",
  4295. "max-forwards",
  4296. "pragma",
  4297. "range",
  4298. "te",
  4299. "age",
  4300. "expires",
  4301. "date",
  4302. "location",
  4303. "retry-after",
  4304. "vary",
  4305. "warning",
  4306. "content-encoding",
  4307. "content-type",
  4308. "content-range",
  4309. "trailer"};
  4310. case_ignore::unordered_set<std::string> declared_trailers;
  4311. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4312. if (trailer_header && std::strlen(trailer_header)) {
  4313. auto len = std::strlen(trailer_header);
  4314. split(trailer_header, trailer_header + len, ',',
  4315. [&](const char *b, const char *e) {
  4316. const char *kbeg = b;
  4317. const char *kend = e;
  4318. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4319. ++kbeg;
  4320. }
  4321. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4322. --kend;
  4323. }
  4324. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4325. if (!key.empty() &&
  4326. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4327. declared_trailers.insert(key);
  4328. }
  4329. });
  4330. }
  4331. size_t trailer_header_count = 0;
  4332. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4333. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4334. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4335. constexpr auto line_terminator_len = 2;
  4336. auto line_beg = line_reader.ptr();
  4337. auto line_end =
  4338. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4339. if (!parse_header(line_beg, line_end,
  4340. [&](const std::string &key, const std::string &val) {
  4341. if (declared_trailers.find(key) !=
  4342. declared_trailers.end()) {
  4343. dest.emplace(key, val);
  4344. trailer_header_count++;
  4345. }
  4346. })) {
  4347. return false;
  4348. }
  4349. if (!line_reader.getline()) { return false; }
  4350. }
  4351. return true;
  4352. }
  4353. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4354. size_t right) {
  4355. while (b + left < e && is_space_or_tab(b[left])) {
  4356. left++;
  4357. }
  4358. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4359. right--;
  4360. }
  4361. return std::make_pair(left, right);
  4362. }
  4363. inline std::string trim_copy(const std::string &s) {
  4364. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4365. return s.substr(r.first, r.second - r.first);
  4366. }
  4367. inline std::string trim_double_quotes_copy(const std::string &s) {
  4368. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4369. return s.substr(1, s.size() - 2);
  4370. }
  4371. return s;
  4372. }
  4373. inline void
  4374. divide(const char *data, std::size_t size, char d,
  4375. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4376. fn) {
  4377. const auto it = std::find(data, data + size, d);
  4378. const auto found = static_cast<std::size_t>(it != data + size);
  4379. const auto lhs_data = data;
  4380. const auto lhs_size = static_cast<std::size_t>(it - data);
  4381. const auto rhs_data = it + found;
  4382. const auto rhs_size = size - lhs_size - found;
  4383. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4384. }
  4385. inline void
  4386. divide(const std::string &str, char d,
  4387. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4388. fn) {
  4389. divide(str.data(), str.size(), d, std::move(fn));
  4390. }
  4391. inline void split(const char *b, const char *e, char d,
  4392. std::function<void(const char *, const char *)> fn) {
  4393. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4394. }
  4395. inline void split(const char *b, const char *e, char d, size_t m,
  4396. std::function<void(const char *, const char *)> fn) {
  4397. size_t i = 0;
  4398. size_t beg = 0;
  4399. size_t count = 1;
  4400. while (e ? (b + i < e) : (b[i] != '\0')) {
  4401. if (b[i] == d && count < m) {
  4402. auto r = trim(b, e, beg, i);
  4403. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4404. beg = i + 1;
  4405. count++;
  4406. }
  4407. i++;
  4408. }
  4409. if (i) {
  4410. auto r = trim(b, e, beg, i);
  4411. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4412. }
  4413. }
  4414. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4415. std::function<bool(const char *, const char *)> fn) {
  4416. size_t i = 0;
  4417. size_t beg = 0;
  4418. size_t count = 1;
  4419. while (e ? (b + i < e) : (b[i] != '\0')) {
  4420. if (b[i] == d && count < m) {
  4421. auto r = trim(b, e, beg, i);
  4422. if (r.first < r.second) {
  4423. auto found = fn(&b[r.first], &b[r.second]);
  4424. if (found) { return true; }
  4425. }
  4426. beg = i + 1;
  4427. count++;
  4428. }
  4429. i++;
  4430. }
  4431. if (i) {
  4432. auto r = trim(b, e, beg, i);
  4433. if (r.first < r.second) {
  4434. auto found = fn(&b[r.first], &b[r.second]);
  4435. if (found) { return true; }
  4436. }
  4437. }
  4438. return false;
  4439. }
  4440. inline bool split_find(const char *b, const char *e, char d,
  4441. std::function<bool(const char *, const char *)> fn) {
  4442. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4443. std::move(fn));
  4444. }
  4445. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4446. size_t fixed_buffer_size)
  4447. : strm_(strm), fixed_buffer_(fixed_buffer),
  4448. fixed_buffer_size_(fixed_buffer_size) {}
  4449. inline const char *stream_line_reader::ptr() const {
  4450. if (growable_buffer_.empty()) {
  4451. return fixed_buffer_;
  4452. } else {
  4453. return growable_buffer_.data();
  4454. }
  4455. }
  4456. inline size_t stream_line_reader::size() const {
  4457. if (growable_buffer_.empty()) {
  4458. return fixed_buffer_used_size_;
  4459. } else {
  4460. return growable_buffer_.size();
  4461. }
  4462. }
  4463. inline bool stream_line_reader::end_with_crlf() const {
  4464. auto end = ptr() + size();
  4465. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4466. }
  4467. inline bool stream_line_reader::getline() {
  4468. fixed_buffer_used_size_ = 0;
  4469. growable_buffer_.clear();
  4470. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4471. char prev_byte = 0;
  4472. #endif
  4473. for (size_t i = 0;; i++) {
  4474. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4475. // Treat exceptionally long lines as an error to
  4476. // prevent infinite loops/memory exhaustion
  4477. return false;
  4478. }
  4479. char byte;
  4480. auto n = strm_.read(&byte, 1);
  4481. if (n < 0) {
  4482. return false;
  4483. } else if (n == 0) {
  4484. if (i == 0) {
  4485. return false;
  4486. } else {
  4487. break;
  4488. }
  4489. }
  4490. append(byte);
  4491. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4492. if (byte == '\n') { break; }
  4493. #else
  4494. if (prev_byte == '\r' && byte == '\n') { break; }
  4495. prev_byte = byte;
  4496. #endif
  4497. }
  4498. return true;
  4499. }
  4500. inline void stream_line_reader::append(char c) {
  4501. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4502. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4503. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4504. } else {
  4505. if (growable_buffer_.empty()) {
  4506. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4507. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4508. }
  4509. growable_buffer_ += c;
  4510. }
  4511. }
  4512. inline mmap::mmap(const char *path) { open(path); }
  4513. inline mmap::~mmap() { close(); }
  4514. inline bool mmap::open(const char *path) {
  4515. close();
  4516. #if defined(_WIN32)
  4517. auto wpath = u8string_to_wstring(path);
  4518. if (wpath.empty()) { return false; }
  4519. hFile_ =
  4520. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4521. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4522. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4523. LARGE_INTEGER size{};
  4524. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4525. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4526. // See:
  4527. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4528. if (static_cast<ULONGLONG>(size.QuadPart) >
  4529. (std::numeric_limits<decltype(size_)>::max)()) {
  4530. // `size_t` might be 32-bits, on 32-bits Windows.
  4531. return false;
  4532. }
  4533. size_ = static_cast<size_t>(size.QuadPart);
  4534. hMapping_ =
  4535. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4536. // Special treatment for an empty file...
  4537. if (hMapping_ == NULL && size_ == 0) {
  4538. close();
  4539. is_open_empty_file = true;
  4540. return true;
  4541. }
  4542. if (hMapping_ == NULL) {
  4543. close();
  4544. return false;
  4545. }
  4546. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4547. if (addr_ == nullptr) {
  4548. close();
  4549. return false;
  4550. }
  4551. #else
  4552. fd_ = ::open(path, O_RDONLY);
  4553. if (fd_ == -1) { return false; }
  4554. struct stat sb;
  4555. if (fstat(fd_, &sb) == -1) {
  4556. close();
  4557. return false;
  4558. }
  4559. size_ = static_cast<size_t>(sb.st_size);
  4560. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4561. // Special treatment for an empty file...
  4562. if (addr_ == MAP_FAILED && size_ == 0) {
  4563. close();
  4564. is_open_empty_file = true;
  4565. return false;
  4566. }
  4567. #endif
  4568. return true;
  4569. }
  4570. inline bool mmap::is_open() const {
  4571. return is_open_empty_file ? true : addr_ != nullptr;
  4572. }
  4573. inline size_t mmap::size() const { return size_; }
  4574. inline const char *mmap::data() const {
  4575. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4576. }
  4577. inline void mmap::close() {
  4578. #if defined(_WIN32)
  4579. if (addr_) {
  4580. ::UnmapViewOfFile(addr_);
  4581. addr_ = nullptr;
  4582. }
  4583. if (hMapping_) {
  4584. ::CloseHandle(hMapping_);
  4585. hMapping_ = NULL;
  4586. }
  4587. if (hFile_ != INVALID_HANDLE_VALUE) {
  4588. ::CloseHandle(hFile_);
  4589. hFile_ = INVALID_HANDLE_VALUE;
  4590. }
  4591. is_open_empty_file = false;
  4592. #else
  4593. if (addr_ != nullptr) {
  4594. munmap(addr_, size_);
  4595. addr_ = nullptr;
  4596. }
  4597. if (fd_ != -1) {
  4598. ::close(fd_);
  4599. fd_ = -1;
  4600. }
  4601. #endif
  4602. size_ = 0;
  4603. }
  4604. inline int close_socket(socket_t sock) noexcept {
  4605. #ifdef _WIN32
  4606. return closesocket(sock);
  4607. #else
  4608. return close(sock);
  4609. #endif
  4610. }
  4611. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4612. ssize_t res = 0;
  4613. while (true) {
  4614. res = fn();
  4615. if (res < 0 && errno == EINTR) {
  4616. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4617. continue;
  4618. }
  4619. break;
  4620. }
  4621. return res;
  4622. }
  4623. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4624. return handle_EINTR([&]() {
  4625. return recv(sock,
  4626. #ifdef _WIN32
  4627. static_cast<char *>(ptr), static_cast<int>(size),
  4628. #else
  4629. ptr, size,
  4630. #endif
  4631. flags);
  4632. });
  4633. }
  4634. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4635. int flags) {
  4636. return handle_EINTR([&]() {
  4637. return send(sock,
  4638. #ifdef _WIN32
  4639. static_cast<const char *>(ptr), static_cast<int>(size),
  4640. #else
  4641. ptr, size,
  4642. #endif
  4643. flags);
  4644. });
  4645. }
  4646. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4647. #ifdef _WIN32
  4648. return ::WSAPoll(fds, nfds, timeout);
  4649. #else
  4650. return ::poll(fds, nfds, timeout);
  4651. #endif
  4652. }
  4653. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4654. time_t usec) {
  4655. struct pollfd pfd;
  4656. pfd.fd = sock;
  4657. pfd.events = events;
  4658. pfd.revents = 0;
  4659. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4660. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4661. }
  4662. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4663. return select_impl(sock, POLLIN, sec, usec);
  4664. }
  4665. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4666. return select_impl(sock, POLLOUT, sec, usec);
  4667. }
  4668. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4669. time_t usec) {
  4670. struct pollfd pfd_read;
  4671. pfd_read.fd = sock;
  4672. pfd_read.events = POLLIN | POLLOUT;
  4673. pfd_read.revents = 0;
  4674. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4675. auto poll_res =
  4676. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4677. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4678. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4679. auto error = 0;
  4680. socklen_t len = sizeof(error);
  4681. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4682. reinterpret_cast<char *>(&error), &len);
  4683. auto successful = res >= 0 && !error;
  4684. return successful ? Error::Success : Error::Connection;
  4685. }
  4686. return Error::Connection;
  4687. }
  4688. inline bool is_socket_alive(socket_t sock) {
  4689. const auto val = detail::select_read(sock, 0, 0);
  4690. if (val == 0) {
  4691. return true;
  4692. } else if (val < 0 && errno == EBADF) {
  4693. return false;
  4694. }
  4695. char buf[1];
  4696. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4697. }
  4698. class SocketStream final : public Stream {
  4699. public:
  4700. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4701. time_t write_timeout_sec, time_t write_timeout_usec,
  4702. time_t max_timeout_msec = 0,
  4703. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4704. (std::chrono::steady_clock::time_point::min)());
  4705. ~SocketStream() override;
  4706. bool is_readable() const override;
  4707. bool wait_readable() const override;
  4708. bool wait_writable() const override;
  4709. bool is_peer_alive() const override;
  4710. ssize_t read(char *ptr, size_t size) override;
  4711. ssize_t write(const char *ptr, size_t size) override;
  4712. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4713. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4714. socket_t socket() const override;
  4715. time_t duration() const override;
  4716. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4717. private:
  4718. socket_t sock_;
  4719. time_t read_timeout_sec_;
  4720. time_t read_timeout_usec_;
  4721. time_t write_timeout_sec_;
  4722. time_t write_timeout_usec_;
  4723. time_t max_timeout_msec_;
  4724. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4725. std::vector<char> read_buff_;
  4726. size_t read_buff_off_ = 0;
  4727. size_t read_buff_content_size_ = 0;
  4728. static const size_t read_buff_size_ = 1024l * 4;
  4729. };
  4730. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4731. time_t keep_alive_timeout_sec) {
  4732. using namespace std::chrono;
  4733. const auto interval_usec =
  4734. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4735. // Avoid expensive `steady_clock::now()` call for the first time
  4736. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4737. const auto start = steady_clock::now() - microseconds{interval_usec};
  4738. const auto timeout = seconds{keep_alive_timeout_sec};
  4739. while (true) {
  4740. if (svr_sock == INVALID_SOCKET) {
  4741. break; // Server socket is closed
  4742. }
  4743. auto val = select_read(sock, 0, interval_usec);
  4744. if (val < 0) {
  4745. break; // Ssocket error
  4746. } else if (val == 0) {
  4747. if (steady_clock::now() - start > timeout) {
  4748. break; // Timeout
  4749. }
  4750. } else {
  4751. return true; // Ready for read
  4752. }
  4753. }
  4754. return false;
  4755. }
  4756. template <typename T>
  4757. inline bool
  4758. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4759. size_t keep_alive_max_count,
  4760. time_t keep_alive_timeout_sec, T callback) {
  4761. assert(keep_alive_max_count > 0);
  4762. auto ret = false;
  4763. auto count = keep_alive_max_count;
  4764. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4765. auto close_connection = count == 1;
  4766. auto connection_closed = false;
  4767. ret = callback(close_connection, connection_closed);
  4768. if (!ret || connection_closed) { break; }
  4769. count--;
  4770. }
  4771. return ret;
  4772. }
  4773. template <typename T>
  4774. inline bool
  4775. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4776. size_t keep_alive_max_count,
  4777. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4778. time_t read_timeout_usec, time_t write_timeout_sec,
  4779. time_t write_timeout_usec, T callback) {
  4780. return process_server_socket_core(
  4781. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4782. [&](bool close_connection, bool &connection_closed) {
  4783. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4784. write_timeout_sec, write_timeout_usec);
  4785. return callback(strm, close_connection, connection_closed);
  4786. });
  4787. }
  4788. inline bool process_client_socket(
  4789. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4790. time_t write_timeout_sec, time_t write_timeout_usec,
  4791. time_t max_timeout_msec,
  4792. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4793. std::function<bool(Stream &)> callback) {
  4794. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4795. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4796. start_time);
  4797. return callback(strm);
  4798. }
  4799. inline int shutdown_socket(socket_t sock) noexcept {
  4800. #ifdef _WIN32
  4801. return shutdown(sock, SD_BOTH);
  4802. #else
  4803. return shutdown(sock, SHUT_RDWR);
  4804. #endif
  4805. }
  4806. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4807. if (s.size() > 1 && s[0] == '\0') {
  4808. auto ret = s;
  4809. ret[0] = '@';
  4810. return ret;
  4811. }
  4812. return s;
  4813. }
  4814. inline std::string
  4815. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4816. if (s.size() > 1 && s[0] == '@') {
  4817. auto ret = s;
  4818. ret[0] = '\0';
  4819. return ret;
  4820. }
  4821. return s;
  4822. }
  4823. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4824. const struct addrinfo *hints,
  4825. struct addrinfo **res, time_t timeout_sec) {
  4826. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4827. if (timeout_sec <= 0) {
  4828. // No timeout specified, use standard getaddrinfo
  4829. return getaddrinfo(node, service, hints, res);
  4830. }
  4831. #ifdef _WIN32
  4832. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4833. OVERLAPPED overlapped = {};
  4834. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4835. if (!event) { return EAI_FAIL; }
  4836. overlapped.hEvent = event;
  4837. PADDRINFOEXW result_addrinfo = nullptr;
  4838. HANDLE cancel_handle = nullptr;
  4839. ADDRINFOEXW hints_ex = {};
  4840. if (hints) {
  4841. hints_ex.ai_flags = hints->ai_flags;
  4842. hints_ex.ai_family = hints->ai_family;
  4843. hints_ex.ai_socktype = hints->ai_socktype;
  4844. hints_ex.ai_protocol = hints->ai_protocol;
  4845. }
  4846. auto wnode = u8string_to_wstring(node);
  4847. auto wservice = u8string_to_wstring(service);
  4848. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4849. hints ? &hints_ex : nullptr, &result_addrinfo,
  4850. nullptr, &overlapped, nullptr, &cancel_handle);
  4851. if (ret == WSA_IO_PENDING) {
  4852. auto wait_result =
  4853. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4854. if (wait_result == WAIT_TIMEOUT) {
  4855. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4856. ::CloseHandle(event);
  4857. return EAI_AGAIN;
  4858. }
  4859. DWORD bytes_returned;
  4860. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4861. &bytes_returned, FALSE)) {
  4862. ::CloseHandle(event);
  4863. return ::WSAGetLastError();
  4864. }
  4865. }
  4866. ::CloseHandle(event);
  4867. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4868. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4869. return 0;
  4870. }
  4871. return ret;
  4872. #elif TARGET_OS_MAC && defined(__clang__)
  4873. if (!node) { return EAI_NONAME; }
  4874. // macOS implementation using CFHost API for asynchronous DNS resolution
  4875. CFStringRef hostname_ref = CFStringCreateWithCString(
  4876. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4877. if (!hostname_ref) { return EAI_MEMORY; }
  4878. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4879. CFRelease(hostname_ref);
  4880. if (!host_ref) { return EAI_MEMORY; }
  4881. // Set up context for callback
  4882. struct CFHostContext {
  4883. bool completed = false;
  4884. bool success = false;
  4885. CFArrayRef addresses = nullptr;
  4886. std::mutex mutex;
  4887. std::condition_variable cv;
  4888. } context;
  4889. CFHostClientContext client_context;
  4890. memset(&client_context, 0, sizeof(client_context));
  4891. client_context.info = &context;
  4892. // Set callback
  4893. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4894. const CFStreamError *error, void *info) {
  4895. auto ctx = static_cast<CFHostContext *>(info);
  4896. std::lock_guard<std::mutex> lock(ctx->mutex);
  4897. if (error && error->error != 0) {
  4898. ctx->success = false;
  4899. } else {
  4900. Boolean hasBeenResolved;
  4901. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4902. if (ctx->addresses && hasBeenResolved) {
  4903. CFRetain(ctx->addresses);
  4904. ctx->success = true;
  4905. } else {
  4906. ctx->success = false;
  4907. }
  4908. }
  4909. ctx->completed = true;
  4910. ctx->cv.notify_one();
  4911. };
  4912. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4913. CFRelease(host_ref);
  4914. return EAI_SYSTEM;
  4915. }
  4916. // Schedule on run loop
  4917. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4918. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4919. // Start resolution
  4920. CFStreamError stream_error;
  4921. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4922. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4923. CFRelease(host_ref);
  4924. return EAI_FAIL;
  4925. }
  4926. // Wait for completion with timeout
  4927. auto timeout_time =
  4928. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4929. bool timed_out = false;
  4930. {
  4931. std::unique_lock<std::mutex> lock(context.mutex);
  4932. while (!context.completed) {
  4933. auto now = std::chrono::steady_clock::now();
  4934. if (now >= timeout_time) {
  4935. timed_out = true;
  4936. break;
  4937. }
  4938. // Run the runloop for a short time
  4939. lock.unlock();
  4940. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4941. lock.lock();
  4942. }
  4943. }
  4944. // Clean up
  4945. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4946. CFHostSetClient(host_ref, nullptr, nullptr);
  4947. if (timed_out || !context.completed) {
  4948. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4949. CFRelease(host_ref);
  4950. return EAI_AGAIN;
  4951. }
  4952. if (!context.success || !context.addresses) {
  4953. CFRelease(host_ref);
  4954. return EAI_NODATA;
  4955. }
  4956. // Convert CFArray to addrinfo
  4957. CFIndex count = CFArrayGetCount(context.addresses);
  4958. if (count == 0) {
  4959. CFRelease(context.addresses);
  4960. CFRelease(host_ref);
  4961. return EAI_NODATA;
  4962. }
  4963. struct addrinfo *result_addrinfo = nullptr;
  4964. struct addrinfo **current = &result_addrinfo;
  4965. for (CFIndex i = 0; i < count; i++) {
  4966. CFDataRef addr_data =
  4967. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4968. if (!addr_data) continue;
  4969. const struct sockaddr *sockaddr_ptr =
  4970. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4971. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4972. // Allocate addrinfo structure
  4973. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4974. if (!*current) {
  4975. freeaddrinfo(result_addrinfo);
  4976. CFRelease(context.addresses);
  4977. CFRelease(host_ref);
  4978. return EAI_MEMORY;
  4979. }
  4980. memset(*current, 0, sizeof(struct addrinfo));
  4981. // Set up addrinfo fields
  4982. (*current)->ai_family = sockaddr_ptr->sa_family;
  4983. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4984. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4985. (*current)->ai_addrlen = sockaddr_len;
  4986. // Copy sockaddr
  4987. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4988. if (!(*current)->ai_addr) {
  4989. freeaddrinfo(result_addrinfo);
  4990. CFRelease(context.addresses);
  4991. CFRelease(host_ref);
  4992. return EAI_MEMORY;
  4993. }
  4994. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4995. // Set port if service is specified
  4996. if (service && *service) {
  4997. int port = 0;
  4998. if (parse_port(service, strlen(service), port)) {
  4999. if (sockaddr_ptr->sa_family == AF_INET) {
  5000. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5001. ->sin_port = htons(static_cast<uint16_t>(port));
  5002. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5003. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5004. ->sin6_port = htons(static_cast<uint16_t>(port));
  5005. }
  5006. }
  5007. }
  5008. current = &((*current)->ai_next);
  5009. }
  5010. CFRelease(context.addresses);
  5011. CFRelease(host_ref);
  5012. *res = result_addrinfo;
  5013. return 0;
  5014. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5015. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5016. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5017. // the resolver worker still references the stack-local gaicb. The cancel
  5018. // path therefore waits (gai_suspend with no timeout) for the worker to
  5019. // actually finish before letting the stack frame go. The trade-off is that
  5020. // a wedged DNS server can hold this thread for the system resolver timeout
  5021. // (~30s by default) past the caller's connection timeout.
  5022. struct gaicb request {};
  5023. struct gaicb *requests[1] = {&request};
  5024. struct sigevent sevp {};
  5025. struct timespec timeout {
  5026. timeout_sec, 0
  5027. };
  5028. request.ar_name = node;
  5029. request.ar_service = service;
  5030. request.ar_request = hints;
  5031. sevp.sigev_notify = SIGEV_NONE;
  5032. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5033. if (rc != 0) { return rc; }
  5034. auto cleanup = scope_exit([&] {
  5035. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5036. });
  5037. int wait_result = gai_suspend(requests, 1, &timeout);
  5038. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5039. int gai_result = gai_error(&request);
  5040. if (gai_result == 0) {
  5041. *res = request.ar_result;
  5042. request.ar_result = nullptr;
  5043. return 0;
  5044. }
  5045. return gai_result;
  5046. }
  5047. gai_cancel(&request);
  5048. while (gai_error(&request) == EAI_INPROGRESS) {
  5049. gai_suspend(requests, 1, nullptr);
  5050. }
  5051. return wait_result;
  5052. #else
  5053. // Fallback implementation using thread-based timeout for other Unix systems.
  5054. struct GetAddrInfoState {
  5055. ~GetAddrInfoState() {
  5056. if (info) { freeaddrinfo(info); }
  5057. }
  5058. std::mutex mutex;
  5059. std::condition_variable result_cv;
  5060. bool completed = false;
  5061. int result = EAI_SYSTEM;
  5062. std::string node;
  5063. std::string service;
  5064. struct addrinfo hints;
  5065. struct addrinfo *info = nullptr;
  5066. };
  5067. // Allocate on the heap, so the resolver thread can keep using the data.
  5068. auto state = std::make_shared<GetAddrInfoState>();
  5069. if (node) { state->node = node; }
  5070. state->service = service;
  5071. state->hints = *hints;
  5072. std::thread resolve_thread([state]() {
  5073. auto thread_result =
  5074. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5075. &state->info);
  5076. std::lock_guard<std::mutex> lock(state->mutex);
  5077. state->result = thread_result;
  5078. state->completed = true;
  5079. state->result_cv.notify_one();
  5080. });
  5081. // Wait for completion or timeout
  5082. std::unique_lock<std::mutex> lock(state->mutex);
  5083. auto finished =
  5084. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5085. [&] { return state->completed; });
  5086. if (finished) {
  5087. // Operation completed within timeout
  5088. resolve_thread.join();
  5089. *res = state->info;
  5090. state->info = nullptr; // Pass ownership to caller
  5091. return state->result;
  5092. } else {
  5093. // Timeout occurred
  5094. resolve_thread.detach(); // Let the thread finish in background
  5095. return EAI_AGAIN; // Return timeout error
  5096. }
  5097. #endif
  5098. #else
  5099. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5100. return getaddrinfo(node, service, hints, res);
  5101. #endif
  5102. }
  5103. template <typename BindOrConnect>
  5104. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5105. int address_family, int socket_flags, bool tcp_nodelay,
  5106. bool ipv6_v6only, SocketOptions socket_options,
  5107. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5108. // Get address info
  5109. const char *node = nullptr;
  5110. struct addrinfo hints;
  5111. struct addrinfo *result;
  5112. memset(&hints, 0, sizeof(struct addrinfo));
  5113. hints.ai_socktype = SOCK_STREAM;
  5114. hints.ai_protocol = IPPROTO_IP;
  5115. if (!ip.empty()) {
  5116. node = ip.c_str();
  5117. // Ask getaddrinfo to convert IP in c-string to address
  5118. hints.ai_family = AF_UNSPEC;
  5119. hints.ai_flags = AI_NUMERICHOST;
  5120. } else {
  5121. if (!host.empty()) { node = host.c_str(); }
  5122. hints.ai_family = address_family;
  5123. hints.ai_flags = socket_flags;
  5124. }
  5125. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5126. if (hints.ai_family == AF_UNIX) {
  5127. const auto addrlen = host.length();
  5128. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5129. #ifdef SOCK_CLOEXEC
  5130. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5131. hints.ai_protocol);
  5132. #else
  5133. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5134. #endif
  5135. if (sock != INVALID_SOCKET) {
  5136. sockaddr_un addr{};
  5137. addr.sun_family = AF_UNIX;
  5138. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5139. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5140. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5141. hints.ai_addrlen = static_cast<socklen_t>(
  5142. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5143. #ifndef SOCK_CLOEXEC
  5144. #ifndef _WIN32
  5145. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5146. #endif
  5147. #endif
  5148. if (socket_options) { socket_options(sock); }
  5149. #ifdef _WIN32
  5150. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5151. // remove the option.
  5152. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5153. #endif
  5154. bool dummy;
  5155. if (!bind_or_connect(sock, hints, dummy)) {
  5156. close_socket(sock);
  5157. sock = INVALID_SOCKET;
  5158. }
  5159. }
  5160. return sock;
  5161. }
  5162. #endif
  5163. auto service = std::to_string(port);
  5164. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5165. timeout_sec)) {
  5166. #if defined __linux__ && !defined __ANDROID__
  5167. res_init();
  5168. #endif
  5169. return INVALID_SOCKET;
  5170. }
  5171. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5172. for (auto rp = result; rp; rp = rp->ai_next) {
  5173. // Create a socket
  5174. #ifdef _WIN32
  5175. auto sock =
  5176. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5177. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5178. /**
  5179. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5180. * and above the socket creation fails on older Windows Systems.
  5181. *
  5182. * Let's try to create a socket the old way in this case.
  5183. *
  5184. * Reference:
  5185. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5186. *
  5187. * WSA_FLAG_NO_HANDLE_INHERIT:
  5188. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5189. * SP1, and later
  5190. *
  5191. */
  5192. if (sock == INVALID_SOCKET) {
  5193. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5194. }
  5195. #else
  5196. #ifdef SOCK_CLOEXEC
  5197. auto sock =
  5198. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5199. #else
  5200. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5201. #endif
  5202. #endif
  5203. if (sock == INVALID_SOCKET) { continue; }
  5204. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5205. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5206. close_socket(sock);
  5207. continue;
  5208. }
  5209. #endif
  5210. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5211. if (rp->ai_family == AF_INET6) {
  5212. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5213. }
  5214. if (socket_options) { socket_options(sock); }
  5215. // bind or connect
  5216. auto quit = false;
  5217. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5218. close_socket(sock);
  5219. if (quit) { break; }
  5220. }
  5221. return INVALID_SOCKET;
  5222. }
  5223. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5224. #ifdef _WIN32
  5225. auto flags = nonblocking ? 1UL : 0UL;
  5226. ioctlsocket(sock, FIONBIO, &flags);
  5227. #else
  5228. auto flags = fcntl(sock, F_GETFL, 0);
  5229. fcntl(sock, F_SETFL,
  5230. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5231. #endif
  5232. }
  5233. inline bool is_connection_error() {
  5234. #ifdef _WIN32
  5235. return WSAGetLastError() != WSAEWOULDBLOCK;
  5236. #else
  5237. return errno != EINPROGRESS;
  5238. #endif
  5239. }
  5240. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5241. struct addrinfo hints;
  5242. struct addrinfo *result;
  5243. memset(&hints, 0, sizeof(struct addrinfo));
  5244. hints.ai_family = AF_UNSPEC;
  5245. hints.ai_socktype = SOCK_STREAM;
  5246. hints.ai_protocol = 0;
  5247. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5248. return false;
  5249. }
  5250. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5251. auto ret = false;
  5252. for (auto rp = result; rp; rp = rp->ai_next) {
  5253. const auto &ai = *rp;
  5254. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5255. ret = true;
  5256. break;
  5257. }
  5258. }
  5259. return ret;
  5260. }
  5261. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5262. #define USE_IF2IP
  5263. #endif
  5264. #ifdef USE_IF2IP
  5265. inline std::string if2ip(int address_family, const std::string &ifn) {
  5266. struct ifaddrs *ifap;
  5267. getifaddrs(&ifap);
  5268. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5269. std::string addr_candidate;
  5270. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5271. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5272. (AF_UNSPEC == address_family ||
  5273. ifa->ifa_addr->sa_family == address_family)) {
  5274. if (ifa->ifa_addr->sa_family == AF_INET) {
  5275. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5276. char buf[INET_ADDRSTRLEN];
  5277. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5278. return std::string(buf, INET_ADDRSTRLEN);
  5279. }
  5280. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5281. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5282. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5283. char buf[INET6_ADDRSTRLEN] = {};
  5284. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5285. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5286. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5287. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5288. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5289. } else {
  5290. return std::string(buf, INET6_ADDRSTRLEN);
  5291. }
  5292. }
  5293. }
  5294. }
  5295. }
  5296. }
  5297. return addr_candidate;
  5298. }
  5299. #endif
  5300. inline socket_t create_client_socket(
  5301. const std::string &host, const std::string &ip, int port,
  5302. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5303. SocketOptions socket_options, time_t connection_timeout_sec,
  5304. time_t connection_timeout_usec, time_t read_timeout_sec,
  5305. time_t read_timeout_usec, time_t write_timeout_sec,
  5306. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5307. auto sock = create_socket(
  5308. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5309. std::move(socket_options),
  5310. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5311. if (!intf.empty()) {
  5312. #ifdef USE_IF2IP
  5313. auto ip_from_if = if2ip(address_family, intf);
  5314. if (ip_from_if.empty()) { ip_from_if = intf; }
  5315. if (!bind_ip_address(sock2, ip_from_if)) {
  5316. error = Error::BindIPAddress;
  5317. return false;
  5318. }
  5319. #endif
  5320. }
  5321. set_nonblocking(sock2, true);
  5322. auto ret =
  5323. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5324. if (ret < 0) {
  5325. if (is_connection_error()) {
  5326. error = Error::Connection;
  5327. return false;
  5328. }
  5329. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5330. connection_timeout_usec);
  5331. if (error != Error::Success) {
  5332. if (error == Error::ConnectionTimeout) { quit = true; }
  5333. return false;
  5334. }
  5335. }
  5336. set_nonblocking(sock2, false);
  5337. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5338. read_timeout_usec);
  5339. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5340. write_timeout_usec);
  5341. error = Error::Success;
  5342. return true;
  5343. },
  5344. connection_timeout_sec); // Pass DNS timeout
  5345. if (sock != INVALID_SOCKET) {
  5346. error = Error::Success;
  5347. } else {
  5348. if (error == Error::Success) { error = Error::Connection; }
  5349. }
  5350. return sock;
  5351. }
  5352. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5353. socklen_t addr_len, std::string &ip, int &port) {
  5354. if (addr.ss_family == AF_INET) {
  5355. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5356. } else if (addr.ss_family == AF_INET6) {
  5357. port =
  5358. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5359. } else {
  5360. return false;
  5361. }
  5362. std::array<char, NI_MAXHOST> ipstr{};
  5363. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5364. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5365. 0, NI_NUMERICHOST)) {
  5366. return false;
  5367. }
  5368. ip = ipstr.data();
  5369. return true;
  5370. }
  5371. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5372. struct sockaddr_storage addr;
  5373. socklen_t addr_len = sizeof(addr);
  5374. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5375. &addr_len)) {
  5376. get_ip_and_port(addr, addr_len, ip, port);
  5377. }
  5378. }
  5379. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5380. struct sockaddr_storage addr;
  5381. socklen_t addr_len = sizeof(addr);
  5382. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5383. &addr_len)) {
  5384. #ifndef _WIN32
  5385. if (addr.ss_family == AF_UNIX) {
  5386. #if defined(__linux__)
  5387. struct ucred ucred;
  5388. socklen_t len = sizeof(ucred);
  5389. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5390. port = ucred.pid;
  5391. }
  5392. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5393. pid_t pid;
  5394. socklen_t len = sizeof(pid);
  5395. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5396. port = pid;
  5397. }
  5398. #endif
  5399. return;
  5400. }
  5401. #endif
  5402. get_ip_and_port(addr, addr_len, ip, port);
  5403. }
  5404. }
  5405. // Recursive form retained so operator""_t below can compute hashes for
  5406. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5407. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5408. // instead, which is iterative and stack-safe.
  5409. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5410. unsigned int h) {
  5411. return (l == 0)
  5412. ? h
  5413. : str2tag_core(
  5414. s + 1, l - 1,
  5415. // Unsets the 6 high bits of h, therefore no overflow happens
  5416. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5417. h * 33) ^
  5418. static_cast<unsigned char>(*s));
  5419. }
  5420. inline unsigned int str2tag(const std::string &s) {
  5421. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5422. // for compile-time UDL evaluation of short string literals, but at runtime
  5423. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5424. // would blow the stack with one frame per character.
  5425. unsigned int h = 0;
  5426. for (auto c : s) {
  5427. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5428. static_cast<unsigned char>(c);
  5429. }
  5430. return h;
  5431. }
  5432. namespace udl {
  5433. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5434. return str2tag_core(s, l, 0);
  5435. }
  5436. } // namespace udl
  5437. inline std::string
  5438. find_content_type(const std::string &path,
  5439. const std::map<std::string, std::string> &user_data,
  5440. const std::string &default_content_type) {
  5441. auto ext = file_extension(path);
  5442. auto it = user_data.find(ext);
  5443. if (it != user_data.end()) { return it->second; }
  5444. using udl::operator""_t;
  5445. switch (str2tag(ext)) {
  5446. default: return default_content_type;
  5447. case "css"_t: return "text/css";
  5448. case "csv"_t: return "text/csv";
  5449. case "htm"_t:
  5450. case "html"_t: return "text/html";
  5451. case "js"_t:
  5452. case "mjs"_t: return "text/javascript";
  5453. case "txt"_t: return "text/plain";
  5454. case "vtt"_t: return "text/vtt";
  5455. case "apng"_t: return "image/apng";
  5456. case "avif"_t: return "image/avif";
  5457. case "bmp"_t: return "image/bmp";
  5458. case "gif"_t: return "image/gif";
  5459. case "png"_t: return "image/png";
  5460. case "svg"_t: return "image/svg+xml";
  5461. case "webp"_t: return "image/webp";
  5462. case "ico"_t: return "image/x-icon";
  5463. case "tif"_t: return "image/tiff";
  5464. case "tiff"_t: return "image/tiff";
  5465. case "jpg"_t:
  5466. case "jpeg"_t: return "image/jpeg";
  5467. case "mp4"_t: return "video/mp4";
  5468. case "mpeg"_t: return "video/mpeg";
  5469. case "webm"_t: return "video/webm";
  5470. case "mp3"_t: return "audio/mp3";
  5471. case "mpga"_t: return "audio/mpeg";
  5472. case "weba"_t: return "audio/webm";
  5473. case "wav"_t: return "audio/wave";
  5474. case "otf"_t: return "font/otf";
  5475. case "ttf"_t: return "font/ttf";
  5476. case "woff"_t: return "font/woff";
  5477. case "woff2"_t: return "font/woff2";
  5478. case "7z"_t: return "application/x-7z-compressed";
  5479. case "atom"_t: return "application/atom+xml";
  5480. case "pdf"_t: return "application/pdf";
  5481. case "json"_t: return "application/json";
  5482. case "rss"_t: return "application/rss+xml";
  5483. case "tar"_t: return "application/x-tar";
  5484. case "xht"_t:
  5485. case "xhtml"_t: return "application/xhtml+xml";
  5486. case "xslt"_t: return "application/xslt+xml";
  5487. case "xml"_t: return "application/xml";
  5488. case "gz"_t: return "application/gzip";
  5489. case "zip"_t: return "application/zip";
  5490. case "wasm"_t: return "application/wasm";
  5491. }
  5492. }
  5493. inline std::string
  5494. extract_media_type(const std::string &content_type,
  5495. std::map<std::string, std::string> *params = nullptr) {
  5496. // Extract type/subtype from Content-Type value (RFC 2045)
  5497. // e.g. "application/json; charset=utf-8" -> "application/json"
  5498. auto media_type = content_type;
  5499. auto semicolon_pos = media_type.find(';');
  5500. if (semicolon_pos != std::string::npos) {
  5501. auto param_str = media_type.substr(semicolon_pos + 1);
  5502. media_type = media_type.substr(0, semicolon_pos);
  5503. if (params) {
  5504. // Parse parameters: key=value pairs separated by ';'
  5505. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5506. [&](const char *b, const char *e) {
  5507. std::string key;
  5508. std::string val;
  5509. split(b, e, '=', [&](const char *b2, const char *e2) {
  5510. if (key.empty()) {
  5511. key.assign(b2, e2);
  5512. } else {
  5513. val.assign(b2, e2);
  5514. }
  5515. });
  5516. if (!key.empty()) {
  5517. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5518. }
  5519. });
  5520. }
  5521. }
  5522. // Trim whitespace from media type
  5523. return trim_copy(media_type);
  5524. }
  5525. inline bool can_compress_content_type(const std::string &content_type) {
  5526. using udl::operator""_t;
  5527. auto mime_type = extract_media_type(content_type);
  5528. auto tag = str2tag(mime_type);
  5529. switch (tag) {
  5530. case "image/svg+xml"_t:
  5531. case "application/javascript"_t:
  5532. case "application/x-javascript"_t:
  5533. case "application/json"_t:
  5534. case "application/ld+json"_t:
  5535. case "application/xml"_t:
  5536. case "application/xhtml+xml"_t:
  5537. case "application/rss+xml"_t:
  5538. case "application/atom+xml"_t:
  5539. case "application/xslt+xml"_t:
  5540. case "application/protobuf"_t: return true;
  5541. case "text/event-stream"_t: return false;
  5542. default: return !mime_type.rfind("text/", 0);
  5543. }
  5544. }
  5545. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5546. double &quality) {
  5547. quality = 1.0;
  5548. token.clear();
  5549. // Split on first ';': left = token name, right = parameters
  5550. const char *params_b = nullptr;
  5551. std::size_t params_len = 0;
  5552. divide(
  5553. b, static_cast<std::size_t>(e - b), ';',
  5554. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5555. auto r = trim(lb, lb + llen, 0, llen);
  5556. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5557. params_b = rb;
  5558. params_len = rlen;
  5559. });
  5560. if (token.empty()) { return false; }
  5561. if (params_len == 0) { return true; }
  5562. // Scan parameters for q= (stops on first match)
  5563. bool invalid = false;
  5564. split_find(params_b, params_b + params_len, ';',
  5565. (std::numeric_limits<size_t>::max)(),
  5566. [&](const char *pb, const char *pe) -> bool {
  5567. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5568. auto len = static_cast<size_t>(pe - pb);
  5569. if (len < 2) { return false; }
  5570. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5571. return false;
  5572. }
  5573. // Trim the value portion
  5574. auto r = trim(pb, pe, 2, len);
  5575. if (r.first >= r.second) {
  5576. invalid = true;
  5577. return true;
  5578. }
  5579. double v = 0.0;
  5580. auto res = from_chars(pb + r.first, pb + r.second, v);
  5581. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5582. invalid = true;
  5583. return true;
  5584. }
  5585. quality = v;
  5586. return true;
  5587. });
  5588. return !invalid;
  5589. }
  5590. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5591. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5592. return EncodingType::None;
  5593. }
  5594. const auto &s = req.get_header_value("Accept-Encoding");
  5595. if (s.empty()) { return EncodingType::None; }
  5596. // Single-pass: iterate tokens and track the best supported encoding.
  5597. // Server preference breaks ties (br > gzip > zstd).
  5598. EncodingType best = EncodingType::None;
  5599. double best_q = 0.0; // q=0 means "not acceptable"
  5600. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5601. auto priority = [](EncodingType t) -> int {
  5602. switch (t) {
  5603. case EncodingType::Brotli: return 0;
  5604. case EncodingType::Gzip: return 1;
  5605. case EncodingType::Zstd: return 2;
  5606. default: return 3;
  5607. }
  5608. };
  5609. std::string name;
  5610. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5611. double quality = 1.0;
  5612. if (!parse_quality(b, e, name, quality)) { return; }
  5613. if (quality <= 0.0) { return; }
  5614. EncodingType type = EncodingType::None;
  5615. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5616. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5617. #endif
  5618. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5619. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5620. type = EncodingType::Gzip;
  5621. }
  5622. #endif
  5623. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5624. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5625. type = EncodingType::Zstd;
  5626. }
  5627. #endif
  5628. if (type == EncodingType::None) { return; }
  5629. // Higher q-value wins; for equal q, server preference breaks ties
  5630. if (quality > best_q ||
  5631. (quality == best_q && priority(type) < priority(best))) {
  5632. best_q = quality;
  5633. best = type;
  5634. }
  5635. });
  5636. return best;
  5637. }
  5638. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5639. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5640. if (type == EncodingType::Gzip) {
  5641. return detail::make_unique<gzip_compressor>();
  5642. }
  5643. #endif
  5644. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5645. if (type == EncodingType::Brotli) {
  5646. return detail::make_unique<brotli_compressor>();
  5647. }
  5648. #endif
  5649. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5650. if (type == EncodingType::Zstd) {
  5651. return detail::make_unique<zstd_compressor>();
  5652. }
  5653. #endif
  5654. (void)type;
  5655. return nullptr;
  5656. }
  5657. inline const char *encoding_name(EncodingType type) {
  5658. switch (type) {
  5659. case EncodingType::Gzip: return "gzip";
  5660. case EncodingType::Brotli: return "br";
  5661. case EncodingType::Zstd: return "zstd";
  5662. default: return "";
  5663. }
  5664. }
  5665. inline bool nocompressor::compress(const char *data, size_t data_length,
  5666. bool /*last*/, Callback callback) {
  5667. if (!data_length) { return true; }
  5668. return callback(data, data_length);
  5669. }
  5670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5671. inline gzip_compressor::gzip_compressor() {
  5672. std::memset(&strm_, 0, sizeof(strm_));
  5673. strm_.zalloc = Z_NULL;
  5674. strm_.zfree = Z_NULL;
  5675. strm_.opaque = Z_NULL;
  5676. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5677. Z_DEFAULT_STRATEGY) == Z_OK;
  5678. }
  5679. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5680. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5681. bool last, Callback callback) {
  5682. assert(is_valid_);
  5683. do {
  5684. constexpr size_t max_avail_in =
  5685. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5686. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5687. (std::min)(data_length, max_avail_in));
  5688. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5689. data_length -= strm_.avail_in;
  5690. data += strm_.avail_in;
  5691. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5692. auto ret = Z_OK;
  5693. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5694. do {
  5695. strm_.avail_out = static_cast<uInt>(buff.size());
  5696. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5697. ret = deflate(&strm_, flush);
  5698. if (ret == Z_STREAM_ERROR) { return false; }
  5699. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5700. return false;
  5701. }
  5702. } while (strm_.avail_out == 0);
  5703. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5704. (flush == Z_NO_FLUSH && ret == Z_OK));
  5705. assert(strm_.avail_in == 0);
  5706. } while (data_length > 0);
  5707. return true;
  5708. }
  5709. inline gzip_decompressor::gzip_decompressor() {
  5710. std::memset(&strm_, 0, sizeof(strm_));
  5711. strm_.zalloc = Z_NULL;
  5712. strm_.zfree = Z_NULL;
  5713. strm_.opaque = Z_NULL;
  5714. // 15 is the value of wbits, which should be at the maximum possible value
  5715. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5716. // that the stream type should be automatically detected either gzip or
  5717. // deflate.
  5718. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5719. }
  5720. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5721. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5722. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5723. Callback callback) {
  5724. assert(is_valid_);
  5725. auto ret = Z_OK;
  5726. do {
  5727. constexpr size_t max_avail_in =
  5728. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5729. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5730. (std::min)(data_length, max_avail_in));
  5731. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5732. data_length -= strm_.avail_in;
  5733. data += strm_.avail_in;
  5734. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5735. while (strm_.avail_in > 0 && ret == Z_OK) {
  5736. strm_.avail_out = static_cast<uInt>(buff.size());
  5737. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5738. ret = inflate(&strm_, Z_NO_FLUSH);
  5739. assert(ret != Z_STREAM_ERROR);
  5740. switch (ret) {
  5741. case Z_NEED_DICT:
  5742. case Z_DATA_ERROR:
  5743. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5744. }
  5745. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5746. return false;
  5747. }
  5748. }
  5749. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5750. } while (data_length > 0);
  5751. return true;
  5752. }
  5753. #endif
  5754. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5755. inline brotli_compressor::brotli_compressor() {
  5756. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5757. }
  5758. inline brotli_compressor::~brotli_compressor() {
  5759. BrotliEncoderDestroyInstance(state_);
  5760. }
  5761. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5762. bool last, Callback callback) {
  5763. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5764. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5765. auto available_in = data_length;
  5766. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5767. for (;;) {
  5768. if (last) {
  5769. if (BrotliEncoderIsFinished(state_)) { break; }
  5770. } else {
  5771. if (!available_in) { break; }
  5772. }
  5773. auto available_out = buff.size();
  5774. auto next_out = buff.data();
  5775. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5776. &available_out, &next_out, nullptr)) {
  5777. return false;
  5778. }
  5779. auto output_bytes = buff.size() - available_out;
  5780. if (output_bytes) {
  5781. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5782. }
  5783. }
  5784. return true;
  5785. }
  5786. inline brotli_decompressor::brotli_decompressor() {
  5787. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5788. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5789. : BROTLI_DECODER_RESULT_ERROR;
  5790. }
  5791. inline brotli_decompressor::~brotli_decompressor() {
  5792. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5793. }
  5794. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5795. inline bool brotli_decompressor::decompress(const char *data,
  5796. size_t data_length,
  5797. Callback callback) {
  5798. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5799. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5800. return 0;
  5801. }
  5802. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5803. size_t avail_in = data_length;
  5804. size_t total_out;
  5805. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5806. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5807. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5808. char *next_out = buff.data();
  5809. size_t avail_out = buff.size();
  5810. decoder_r = BrotliDecoderDecompressStream(
  5811. decoder_s, &avail_in, &next_in, &avail_out,
  5812. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5813. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5814. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5815. }
  5816. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5817. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5818. }
  5819. #endif
  5820. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5821. inline zstd_compressor::zstd_compressor() {
  5822. ctx_ = ZSTD_createCCtx();
  5823. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5824. }
  5825. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5826. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5827. bool last, Callback callback) {
  5828. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5829. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5830. ZSTD_inBuffer input = {data, data_length, 0};
  5831. bool finished;
  5832. do {
  5833. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5834. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5835. if (ZSTD_isError(remaining)) { return false; }
  5836. if (!callback(buff.data(), output.pos)) { return false; }
  5837. finished = last ? (remaining == 0) : (input.pos == input.size);
  5838. } while (!finished);
  5839. return true;
  5840. }
  5841. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5842. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5843. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5844. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5845. Callback callback) {
  5846. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5847. ZSTD_inBuffer input = {data, data_length, 0};
  5848. while (input.pos < input.size) {
  5849. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5850. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5851. if (ZSTD_isError(remaining)) { return false; }
  5852. if (!callback(buff.data(), output.pos)) { return false; }
  5853. }
  5854. return true;
  5855. }
  5856. #endif
  5857. inline std::unique_ptr<decompressor>
  5858. create_decompressor(const std::string &encoding) {
  5859. std::unique_ptr<decompressor> decompressor;
  5860. if (encoding == "gzip" || encoding == "deflate") {
  5861. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5862. decompressor = detail::make_unique<gzip_decompressor>();
  5863. #endif
  5864. } else if (encoding.find("br") != std::string::npos) {
  5865. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5866. decompressor = detail::make_unique<brotli_decompressor>();
  5867. #endif
  5868. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5869. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5870. decompressor = detail::make_unique<zstd_decompressor>();
  5871. #endif
  5872. }
  5873. return decompressor;
  5874. }
  5875. // Returns the best available compressor and its Content-Encoding name.
  5876. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5877. inline std::pair<std::unique_ptr<compressor>, const char *>
  5878. create_compressor() {
  5879. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5880. return {detail::make_unique<brotli_compressor>(), "br"};
  5881. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5882. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5883. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5884. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5885. #else
  5886. return {nullptr, nullptr};
  5887. #endif
  5888. }
  5889. inline bool is_prohibited_header_name(const std::string &name) {
  5890. using udl::operator""_t;
  5891. switch (str2tag(name)) {
  5892. case "REMOTE_ADDR"_t:
  5893. case "REMOTE_PORT"_t:
  5894. case "LOCAL_ADDR"_t:
  5895. case "LOCAL_PORT"_t: return true;
  5896. default: return false;
  5897. }
  5898. }
  5899. inline bool has_header(const Headers &headers, const std::string &key) {
  5900. if (is_prohibited_header_name(key)) { return false; }
  5901. return headers.find(key) != headers.end();
  5902. }
  5903. inline const char *get_header_value(const Headers &headers,
  5904. const std::string &key, const char *def,
  5905. size_t id) {
  5906. if (is_prohibited_header_name(key)) {
  5907. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5908. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5909. throw std::invalid_argument(msg);
  5910. #else
  5911. return "";
  5912. #endif
  5913. }
  5914. auto rng = headers.equal_range(key);
  5915. auto it = rng.first;
  5916. std::advance(it, static_cast<ssize_t>(id));
  5917. if (it != rng.second) { return it->second.c_str(); }
  5918. return def;
  5919. }
  5920. inline size_t get_header_value_count(const Headers &headers,
  5921. const std::string &key) {
  5922. auto r = headers.equal_range(key);
  5923. return static_cast<size_t>(std::distance(r.first, r.second));
  5924. }
  5925. template <typename Map>
  5926. inline typename Map::mapped_type
  5927. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5928. auto rng = m.equal_range(key);
  5929. auto it = rng.first;
  5930. std::advance(it, static_cast<ssize_t>(id));
  5931. if (it != rng.second) { return it->second; }
  5932. return typename Map::mapped_type();
  5933. }
  5934. inline void set_header(Headers &headers, const std::string &key,
  5935. const std::string &val) {
  5936. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5937. headers.emplace(key, val);
  5938. }
  5939. }
  5940. inline bool read_headers(Stream &strm, Headers &headers) {
  5941. const auto bufsiz = 2048;
  5942. char buf[bufsiz];
  5943. stream_line_reader line_reader(strm, buf, bufsiz);
  5944. size_t header_count = 0;
  5945. for (;;) {
  5946. if (!line_reader.getline()) { return false; }
  5947. // Check if the line ends with CRLF.
  5948. auto line_terminator_len = 2;
  5949. if (line_reader.end_with_crlf()) {
  5950. // Blank line indicates end of headers.
  5951. if (line_reader.size() == 2) { break; }
  5952. } else {
  5953. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5954. // Blank line indicates end of headers.
  5955. if (line_reader.size() == 1) { break; }
  5956. line_terminator_len = 1;
  5957. #else
  5958. continue; // Skip invalid line.
  5959. #endif
  5960. }
  5961. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5962. // Check header count limit
  5963. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5964. // Exclude line terminator
  5965. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5966. if (!parse_header(line_reader.ptr(), end,
  5967. [&](const std::string &key, const std::string &val) {
  5968. headers.emplace(key, val);
  5969. })) {
  5970. return false;
  5971. }
  5972. header_count++;
  5973. }
  5974. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5975. // headers that have different values to prevent request smuggling.
  5976. auto cl_range = headers.equal_range("Content-Length");
  5977. if (cl_range.first != cl_range.second) {
  5978. const auto &first_val = cl_range.first->second;
  5979. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5980. if (it->second != first_val) { return false; }
  5981. }
  5982. }
  5983. return true;
  5984. }
  5985. inline bool read_websocket_upgrade_response(Stream &strm,
  5986. const std::string &expected_accept,
  5987. std::string &selected_subprotocol) {
  5988. // Read status line
  5989. const auto bufsiz = 2048;
  5990. char buf[bufsiz];
  5991. stream_line_reader line_reader(strm, buf, bufsiz);
  5992. if (!line_reader.getline()) { return false; }
  5993. // Check for "HTTP/1.1 101"
  5994. auto line = std::string(line_reader.ptr(), line_reader.size());
  5995. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5996. // Parse headers using existing read_headers
  5997. Headers headers;
  5998. if (!read_headers(strm, headers)) { return false; }
  5999. // Verify Upgrade: websocket (case-insensitive)
  6000. auto upgrade_it = headers.find("Upgrade");
  6001. if (upgrade_it == headers.end()) { return false; }
  6002. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  6003. if (upgrade_val != "websocket") { return false; }
  6004. // Verify Connection header contains "Upgrade" (case-insensitive)
  6005. auto connection_it = headers.find("Connection");
  6006. if (connection_it == headers.end()) { return false; }
  6007. auto connection_val = case_ignore::to_lower(connection_it->second);
  6008. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  6009. // Verify Sec-WebSocket-Accept header value
  6010. auto it = headers.find("Sec-WebSocket-Accept");
  6011. if (it == headers.end() || it->second != expected_accept) { return false; }
  6012. // Extract negotiated subprotocol
  6013. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6014. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6015. return true;
  6016. }
  6017. enum class ReadContentResult {
  6018. Success, // Successfully read the content
  6019. PayloadTooLarge, // The content exceeds the specified payload limit
  6020. Error // An error occurred while reading the content
  6021. };
  6022. inline ReadContentResult read_content_with_length(
  6023. Stream &strm, size_t len, DownloadProgress progress,
  6024. ContentReceiverWithProgress out,
  6025. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6026. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6027. detail::BodyReader br;
  6028. br.stream = &strm;
  6029. br.has_content_length = true;
  6030. br.content_length = len;
  6031. br.payload_max_length = payload_max_length;
  6032. br.chunked = false;
  6033. br.bytes_read = 0;
  6034. br.last_error = Error::Success;
  6035. size_t r = 0;
  6036. while (r < len) {
  6037. auto read_len = static_cast<size_t>(len - r);
  6038. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6039. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6040. if (n <= 0) {
  6041. // Check if it was a payload size error
  6042. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6043. return ReadContentResult::PayloadTooLarge;
  6044. }
  6045. return ReadContentResult::Error;
  6046. }
  6047. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6048. return ReadContentResult::Error;
  6049. }
  6050. r += static_cast<size_t>(n);
  6051. if (progress) {
  6052. if (!progress(r, len)) { return ReadContentResult::Error; }
  6053. }
  6054. }
  6055. return ReadContentResult::Success;
  6056. }
  6057. inline ReadContentResult
  6058. read_content_without_length(Stream &strm, size_t payload_max_length,
  6059. ContentReceiverWithProgress out) {
  6060. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6061. size_t r = 0;
  6062. for (;;) {
  6063. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6064. if (n == 0) { return ReadContentResult::Success; }
  6065. if (n < 0) { return ReadContentResult::Error; }
  6066. // Check if adding this data would exceed the payload limit
  6067. if (r > payload_max_length ||
  6068. payload_max_length - r < static_cast<size_t>(n)) {
  6069. return ReadContentResult::PayloadTooLarge;
  6070. }
  6071. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6072. return ReadContentResult::Error;
  6073. }
  6074. r += static_cast<size_t>(n);
  6075. }
  6076. return ReadContentResult::Success;
  6077. }
  6078. template <typename T>
  6079. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6080. size_t payload_max_length,
  6081. ContentReceiverWithProgress out) {
  6082. detail::ChunkedDecoder dec(strm);
  6083. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6084. size_t total_len = 0;
  6085. for (;;) {
  6086. size_t chunk_offset = 0;
  6087. size_t chunk_total = 0;
  6088. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6089. if (n < 0) { return ReadContentResult::Error; }
  6090. if (n == 0) {
  6091. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6092. return ReadContentResult::Error;
  6093. }
  6094. return ReadContentResult::Success;
  6095. }
  6096. if (total_len > payload_max_length ||
  6097. payload_max_length - total_len < static_cast<size_t>(n)) {
  6098. return ReadContentResult::PayloadTooLarge;
  6099. }
  6100. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6101. return ReadContentResult::Error;
  6102. }
  6103. total_len += static_cast<size_t>(n);
  6104. }
  6105. }
  6106. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6107. return case_ignore::equal(
  6108. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  6109. }
  6110. template <typename T, typename U>
  6111. bool prepare_content_receiver(T &x, int &status,
  6112. ContentReceiverWithProgress receiver,
  6113. bool decompress, size_t payload_max_length,
  6114. bool &exceed_payload_max_length, U callback) {
  6115. if (decompress) {
  6116. std::string encoding = x.get_header_value("Content-Encoding");
  6117. std::unique_ptr<decompressor> decompressor;
  6118. if (!encoding.empty()) {
  6119. decompressor = detail::create_decompressor(encoding);
  6120. if (!decompressor) {
  6121. // Unsupported encoding or no support compiled in
  6122. status = StatusCode::UnsupportedMediaType_415;
  6123. return false;
  6124. }
  6125. }
  6126. if (decompressor) {
  6127. if (decompressor->is_valid()) {
  6128. size_t decompressed_size = 0;
  6129. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6130. size_t off, size_t len) {
  6131. return decompressor->decompress(
  6132. buf, n, [&](const char *buf2, size_t n2) {
  6133. // Guard against zip-bomb: check
  6134. // decompressed size against limit.
  6135. if (payload_max_length > 0 &&
  6136. (decompressed_size >= payload_max_length ||
  6137. n2 > payload_max_length - decompressed_size)) {
  6138. exceed_payload_max_length = true;
  6139. return false;
  6140. }
  6141. decompressed_size += n2;
  6142. return receiver(buf2, n2, off, len);
  6143. });
  6144. };
  6145. return callback(std::move(out));
  6146. } else {
  6147. status = StatusCode::InternalServerError_500;
  6148. return false;
  6149. }
  6150. }
  6151. }
  6152. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6153. size_t len) {
  6154. return receiver(buf, n, off, len);
  6155. };
  6156. return callback(std::move(out));
  6157. }
  6158. template <typename T>
  6159. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6160. DownloadProgress progress,
  6161. ContentReceiverWithProgress receiver, bool decompress) {
  6162. bool exceed_payload_max_length = false;
  6163. return prepare_content_receiver(
  6164. x, status, std::move(receiver), decompress, payload_max_length,
  6165. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6166. auto ret = true;
  6167. // Note: exceed_payload_max_length may also be set by the decompressor
  6168. // wrapper in prepare_content_receiver when the decompressed payload
  6169. // size exceeds the limit.
  6170. if (is_chunked_transfer_encoding(x.headers)) {
  6171. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6172. if (result == ReadContentResult::Success) {
  6173. ret = true;
  6174. } else if (result == ReadContentResult::PayloadTooLarge) {
  6175. exceed_payload_max_length = true;
  6176. ret = false;
  6177. } else {
  6178. ret = false;
  6179. }
  6180. } else if (!has_header(x.headers, "Content-Length")) {
  6181. auto result =
  6182. read_content_without_length(strm, payload_max_length, out);
  6183. if (result == ReadContentResult::Success) {
  6184. ret = true;
  6185. } else if (result == ReadContentResult::PayloadTooLarge) {
  6186. exceed_payload_max_length = true;
  6187. ret = false;
  6188. } else {
  6189. ret = false;
  6190. }
  6191. } else {
  6192. auto is_invalid_value = false;
  6193. auto len = get_header_value_u64(x.headers, "Content-Length",
  6194. (std::numeric_limits<size_t>::max)(),
  6195. 0, is_invalid_value);
  6196. if (is_invalid_value) {
  6197. ret = false;
  6198. } else if (len > 0) {
  6199. auto result = read_content_with_length(
  6200. strm, len, std::move(progress), out, payload_max_length);
  6201. ret = (result == ReadContentResult::Success);
  6202. if (result == ReadContentResult::PayloadTooLarge) {
  6203. exceed_payload_max_length = true;
  6204. }
  6205. }
  6206. }
  6207. if (!ret) {
  6208. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6209. : StatusCode::BadRequest_400;
  6210. }
  6211. return ret;
  6212. });
  6213. }
  6214. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6215. const std::string &path) {
  6216. std::string s = method;
  6217. s += ' ';
  6218. s += path;
  6219. s += " HTTP/1.1\r\n";
  6220. return strm.write(s.data(), s.size());
  6221. }
  6222. inline ssize_t write_response_line(Stream &strm, int status) {
  6223. std::string s = "HTTP/1.1 ";
  6224. s += std::to_string(status);
  6225. s += ' ';
  6226. s += httplib::status_message(status);
  6227. s += "\r\n";
  6228. return strm.write(s.data(), s.size());
  6229. }
  6230. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6231. ssize_t write_len = 0;
  6232. for (const auto &x : headers) {
  6233. std::string s;
  6234. s = x.first;
  6235. s += ": ";
  6236. s += x.second;
  6237. s += "\r\n";
  6238. auto len = strm.write(s.data(), s.size());
  6239. if (len < 0) { return len; }
  6240. write_len += len;
  6241. }
  6242. auto len = strm.write("\r\n");
  6243. if (len < 0) { return len; }
  6244. write_len += len;
  6245. return write_len;
  6246. }
  6247. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6248. size_t offset = 0;
  6249. while (offset < l) {
  6250. auto length = strm.write(d + offset, l - offset);
  6251. if (length < 0) { return false; }
  6252. offset += static_cast<size_t>(length);
  6253. }
  6254. return true;
  6255. }
  6256. template <typename T>
  6257. inline bool write_content_with_progress(Stream &strm,
  6258. const ContentProvider &content_provider,
  6259. size_t offset, size_t length,
  6260. T is_shutting_down,
  6261. const UploadProgress &upload_progress,
  6262. Error &error) {
  6263. size_t end_offset = offset + length;
  6264. size_t start_offset = offset;
  6265. auto ok = true;
  6266. DataSink data_sink;
  6267. data_sink.write = [&](const char *d, size_t l) -> bool {
  6268. if (ok) {
  6269. if (write_data(strm, d, l)) {
  6270. offset += l;
  6271. if (upload_progress && length > 0) {
  6272. size_t current_written = offset - start_offset;
  6273. if (!upload_progress(current_written, length)) {
  6274. ok = false;
  6275. return false;
  6276. }
  6277. }
  6278. } else {
  6279. ok = false;
  6280. }
  6281. }
  6282. return ok;
  6283. };
  6284. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6285. while (offset < end_offset && !is_shutting_down()) {
  6286. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6287. error = Error::Write;
  6288. return false;
  6289. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6290. error = Error::Canceled;
  6291. return false;
  6292. } else if (!ok) {
  6293. error = Error::Write;
  6294. return false;
  6295. }
  6296. }
  6297. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6298. error = Error::Write;
  6299. return false;
  6300. }
  6301. error = Error::Success;
  6302. return true;
  6303. }
  6304. template <typename T>
  6305. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6306. size_t offset, size_t length, T is_shutting_down,
  6307. Error &error) {
  6308. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6309. is_shutting_down, nullptr, error);
  6310. }
  6311. template <typename T>
  6312. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6313. size_t offset, size_t length,
  6314. const T &is_shutting_down) {
  6315. auto error = Error::Success;
  6316. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6317. error);
  6318. }
  6319. template <typename T>
  6320. inline bool
  6321. write_content_without_length(Stream &strm,
  6322. const ContentProvider &content_provider,
  6323. const T &is_shutting_down) {
  6324. size_t offset = 0;
  6325. auto data_available = true;
  6326. auto ok = true;
  6327. DataSink data_sink;
  6328. data_sink.write = [&](const char *d, size_t l) -> bool {
  6329. if (ok) {
  6330. offset += l;
  6331. if (!write_data(strm, d, l)) { ok = false; }
  6332. }
  6333. return ok;
  6334. };
  6335. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6336. data_sink.done = [&](void) { data_available = false; };
  6337. while (data_available && !is_shutting_down()) {
  6338. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6339. return false;
  6340. } else if (!content_provider(offset, 0, data_sink)) {
  6341. return false;
  6342. } else if (!ok) {
  6343. return false;
  6344. }
  6345. }
  6346. return !data_available; // true only if done() was called, false if shutting
  6347. // down
  6348. }
  6349. template <typename T, typename U>
  6350. inline bool
  6351. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6352. const T &is_shutting_down, U &compressor, Error &error) {
  6353. size_t offset = 0;
  6354. auto data_available = true;
  6355. auto ok = true;
  6356. DataSink data_sink;
  6357. data_sink.write = [&](const char *d, size_t l) -> bool {
  6358. if (ok) {
  6359. data_available = l > 0;
  6360. offset += l;
  6361. std::string payload;
  6362. if (compressor.compress(d, l, false,
  6363. [&](const char *data, size_t data_len) {
  6364. payload.append(data, data_len);
  6365. return true;
  6366. })) {
  6367. if (!payload.empty()) {
  6368. // Emit chunked response header and footer for each chunk
  6369. auto chunk =
  6370. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6371. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6372. }
  6373. } else {
  6374. ok = false;
  6375. }
  6376. }
  6377. return ok;
  6378. };
  6379. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6380. auto done_with_trailer = [&](const Headers *trailer) {
  6381. if (!ok) { return; }
  6382. data_available = false;
  6383. std::string payload;
  6384. if (!compressor.compress(nullptr, 0, true,
  6385. [&](const char *data, size_t data_len) {
  6386. payload.append(data, data_len);
  6387. return true;
  6388. })) {
  6389. ok = false;
  6390. return;
  6391. }
  6392. if (!payload.empty()) {
  6393. // Emit chunked response header and footer for each chunk
  6394. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6395. if (!write_data(strm, chunk.data(), chunk.size())) {
  6396. ok = false;
  6397. return;
  6398. }
  6399. }
  6400. constexpr const char done_marker[] = "0\r\n";
  6401. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6402. // Trailer
  6403. if (trailer) {
  6404. for (const auto &kv : *trailer) {
  6405. // Skip fields with invalid names or values to prevent response
  6406. // splitting via CR/LF injection, matching set_header().
  6407. if (!fields::is_field_name(kv.first) ||
  6408. !fields::is_field_value(kv.second)) {
  6409. continue;
  6410. }
  6411. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6412. if (!write_data(strm, field_line.data(), field_line.size())) {
  6413. ok = false;
  6414. }
  6415. }
  6416. }
  6417. constexpr const char crlf[] = "\r\n";
  6418. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6419. };
  6420. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6421. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6422. done_with_trailer(&trailer);
  6423. };
  6424. while (data_available && !is_shutting_down()) {
  6425. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6426. error = Error::Write;
  6427. return false;
  6428. } else if (!content_provider(offset, 0, data_sink)) {
  6429. error = Error::Canceled;
  6430. return false;
  6431. } else if (!ok) {
  6432. error = Error::Write;
  6433. return false;
  6434. }
  6435. }
  6436. if (data_available) { // exited due to is_shutting_down(), not done()
  6437. error = Error::Write;
  6438. return false;
  6439. }
  6440. error = Error::Success;
  6441. return true;
  6442. }
  6443. template <typename T, typename U>
  6444. inline bool write_content_chunked(Stream &strm,
  6445. const ContentProvider &content_provider,
  6446. const T &is_shutting_down, U &compressor) {
  6447. auto error = Error::Success;
  6448. return write_content_chunked(strm, content_provider, is_shutting_down,
  6449. compressor, error);
  6450. }
  6451. template <typename T>
  6452. inline bool redirect(T &cli, Request &req, Response &res,
  6453. const std::string &path, const std::string &location,
  6454. Error &error) {
  6455. Request new_req = req;
  6456. new_req.path = path;
  6457. new_req.redirect_count_ -= 1;
  6458. if (res.status == StatusCode::SeeOther_303 &&
  6459. (req.method != "GET" && req.method != "HEAD")) {
  6460. new_req.method = "GET";
  6461. new_req.body.clear();
  6462. new_req.headers.clear();
  6463. }
  6464. Response new_res;
  6465. auto ret = cli.send(new_req, new_res, error);
  6466. if (ret) {
  6467. req = std::move(new_req);
  6468. res = std::move(new_res);
  6469. if (res.location.empty()) { res.location = location; }
  6470. }
  6471. return ret;
  6472. }
  6473. inline std::string params_to_query_str(const Params &params) {
  6474. std::string query;
  6475. for (auto it = params.begin(); it != params.end(); ++it) {
  6476. if (it != params.begin()) { query += '&'; }
  6477. query += encode_query_component(it->first);
  6478. query += '=';
  6479. query += encode_query_component(it->second);
  6480. }
  6481. return query;
  6482. }
  6483. inline void parse_query_text(const char *data, std::size_t size,
  6484. Params &params) {
  6485. std::set<std::string> cache;
  6486. split(data, data + size, '&', [&](const char *b, const char *e) {
  6487. std::string kv(b, e);
  6488. if (cache.find(kv) != cache.end()) { return; }
  6489. cache.insert(std::move(kv));
  6490. std::string key;
  6491. std::string val;
  6492. divide(b, static_cast<std::size_t>(e - b), '=',
  6493. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6494. std::size_t rhs_size) {
  6495. key.assign(lhs_data, lhs_size);
  6496. val.assign(rhs_data, rhs_size);
  6497. });
  6498. if (!key.empty()) {
  6499. params.emplace(decode_query_component(key), decode_query_component(val));
  6500. }
  6501. });
  6502. }
  6503. inline void parse_query_text(const std::string &s, Params &params) {
  6504. parse_query_text(s.data(), s.size(), params);
  6505. }
  6506. // Normalize a query string by decoding and re-encoding each key/value pair
  6507. // while preserving the original parameter order. This avoids double-encoding
  6508. // and ensures consistent encoding without reordering (unlike Params which
  6509. // uses std::multimap and sorts keys).
  6510. inline std::string normalize_query_string(const std::string &query) {
  6511. std::string result;
  6512. split(query.data(), query.data() + query.size(), '&',
  6513. [&](const char *b, const char *e) {
  6514. std::string key;
  6515. std::string val;
  6516. divide(b, static_cast<std::size_t>(e - b), '=',
  6517. [&](const char *lhs_data, std::size_t lhs_size,
  6518. const char *rhs_data, std::size_t rhs_size) {
  6519. key.assign(lhs_data, lhs_size);
  6520. val.assign(rhs_data, rhs_size);
  6521. });
  6522. if (!key.empty()) {
  6523. auto dec_key = decode_query_component(key);
  6524. auto dec_val = decode_query_component(val);
  6525. if (!result.empty()) { result += '&'; }
  6526. result += encode_query_component(dec_key);
  6527. if (!val.empty() || std::find(b, e, '=') != e) {
  6528. result += '=';
  6529. result += encode_query_component(dec_val);
  6530. }
  6531. }
  6532. });
  6533. return result;
  6534. }
  6535. inline bool parse_multipart_boundary(const std::string &content_type,
  6536. std::string &boundary) {
  6537. std::map<std::string, std::string> params;
  6538. extract_media_type(content_type, &params);
  6539. auto it = params.find("boundary");
  6540. if (it == params.end()) { return false; }
  6541. boundary = it->second;
  6542. return !boundary.empty();
  6543. }
  6544. inline void parse_disposition_params(const std::string &s, Params &params) {
  6545. std::set<std::string> cache;
  6546. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6547. std::string kv(b, e);
  6548. if (cache.find(kv) != cache.end()) { return; }
  6549. cache.insert(kv);
  6550. std::string key;
  6551. std::string val;
  6552. split(b, e, '=', [&](const char *b2, const char *e2) {
  6553. if (key.empty()) {
  6554. key.assign(b2, e2);
  6555. } else {
  6556. val.assign(b2, e2);
  6557. }
  6558. });
  6559. if (!key.empty()) {
  6560. params.emplace(trim_double_quotes_copy((key)),
  6561. trim_double_quotes_copy((val)));
  6562. }
  6563. });
  6564. }
  6565. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6566. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6567. #else
  6568. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6569. #endif
  6570. auto is_valid = [](const std::string &str) {
  6571. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6572. };
  6573. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6574. const auto pos = static_cast<size_t>(6);
  6575. const auto len = static_cast<size_t>(s.size() - 6);
  6576. auto all_valid_ranges = true;
  6577. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6578. if (!all_valid_ranges) { return; }
  6579. const auto it = std::find(b, e, '-');
  6580. if (it == e) {
  6581. all_valid_ranges = false;
  6582. return;
  6583. }
  6584. const auto lhs = std::string(b, it);
  6585. const auto rhs = std::string(it + 1, e);
  6586. if (!is_valid(lhs) || !is_valid(rhs)) {
  6587. all_valid_ranges = false;
  6588. return;
  6589. }
  6590. ssize_t first = -1;
  6591. if (!lhs.empty()) {
  6592. ssize_t v;
  6593. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6594. if (res.ec == std::errc{}) { first = v; }
  6595. }
  6596. ssize_t last = -1;
  6597. if (!rhs.empty()) {
  6598. ssize_t v;
  6599. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6600. if (res.ec == std::errc{}) { last = v; }
  6601. }
  6602. if ((first == -1 && last == -1) ||
  6603. (first != -1 && last != -1 && first > last)) {
  6604. all_valid_ranges = false;
  6605. return;
  6606. }
  6607. ranges.emplace_back(first, last);
  6608. });
  6609. return all_valid_ranges && !ranges.empty();
  6610. }
  6611. return false;
  6612. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6613. }
  6614. #else
  6615. } catch (...) { return false; }
  6616. #endif
  6617. inline bool parse_accept_header(const std::string &s,
  6618. std::vector<std::string> &content_types) {
  6619. content_types.clear();
  6620. // Empty string is considered valid (no preference)
  6621. if (s.empty()) { return true; }
  6622. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6623. if (s.front() == ',' || s.back() == ',' ||
  6624. s.find(",,") != std::string::npos) {
  6625. return false;
  6626. }
  6627. struct AcceptEntry {
  6628. std::string media_type;
  6629. double quality;
  6630. int order;
  6631. };
  6632. std::vector<AcceptEntry> entries;
  6633. int order = 0;
  6634. bool has_invalid_entry = false;
  6635. // Split by comma and parse each entry
  6636. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6637. std::string entry(b, e);
  6638. entry = trim_copy(entry);
  6639. if (entry.empty()) {
  6640. has_invalid_entry = true;
  6641. return;
  6642. }
  6643. AcceptEntry accept_entry;
  6644. accept_entry.order = order++;
  6645. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6646. accept_entry.media_type, accept_entry.quality)) {
  6647. has_invalid_entry = true;
  6648. return;
  6649. }
  6650. // Remove additional parameters from media type
  6651. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6652. // Basic validation of media type format
  6653. if (accept_entry.media_type.empty()) {
  6654. has_invalid_entry = true;
  6655. return;
  6656. }
  6657. // Check for basic media type format (should contain '/' or be '*')
  6658. if (accept_entry.media_type != "*" &&
  6659. accept_entry.media_type.find('/') == std::string::npos) {
  6660. has_invalid_entry = true;
  6661. return;
  6662. }
  6663. entries.push_back(std::move(accept_entry));
  6664. });
  6665. // Return false if any invalid entry was found
  6666. if (has_invalid_entry) { return false; }
  6667. // Sort by quality (descending), then by original order (ascending)
  6668. std::sort(entries.begin(), entries.end(),
  6669. [](const AcceptEntry &a, const AcceptEntry &b) {
  6670. if (a.quality != b.quality) {
  6671. return a.quality > b.quality; // Higher quality first
  6672. }
  6673. return a.order < b.order; // Earlier order first for same quality
  6674. });
  6675. // Extract sorted media types
  6676. content_types.reserve(entries.size());
  6677. for (auto &entry : entries) {
  6678. content_types.push_back(std::move(entry.media_type));
  6679. }
  6680. return true;
  6681. }
  6682. class FormDataParser {
  6683. public:
  6684. FormDataParser() = default;
  6685. void set_boundary(std::string &&boundary) {
  6686. boundary_ = std::move(boundary);
  6687. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6688. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6689. }
  6690. bool is_valid() const { return is_valid_; }
  6691. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6692. const ContentReceiver &content_callback) {
  6693. buf_append(buf, n);
  6694. while (buf_size() > 0) {
  6695. switch (state_) {
  6696. case 0: { // Initial boundary
  6697. auto pos = buf_find(dash_boundary_crlf_);
  6698. if (pos == buf_size()) { return true; }
  6699. buf_erase(pos + dash_boundary_crlf_.size());
  6700. state_ = 1;
  6701. break;
  6702. }
  6703. case 1: { // New entry
  6704. clear_file_info();
  6705. state_ = 2;
  6706. break;
  6707. }
  6708. case 2: { // Headers
  6709. auto pos = buf_find(crlf_);
  6710. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6711. while (pos < buf_size()) {
  6712. // Empty line
  6713. if (pos == 0) {
  6714. if (!header_callback(file_)) {
  6715. is_valid_ = false;
  6716. return false;
  6717. }
  6718. buf_erase(crlf_.size());
  6719. state_ = 3;
  6720. break;
  6721. }
  6722. const auto header = buf_head(pos);
  6723. if (!parse_header(header.data(), header.data() + header.size(),
  6724. [&](const std::string &, const std::string &) {})) {
  6725. is_valid_ = false;
  6726. return false;
  6727. }
  6728. // Parse and emplace space trimmed headers into a map
  6729. if (!parse_header(
  6730. header.data(), header.data() + header.size(),
  6731. [&](const std::string &key, const std::string &val) {
  6732. file_.headers.emplace(key, val);
  6733. })) {
  6734. is_valid_ = false;
  6735. return false;
  6736. }
  6737. constexpr const char header_content_type[] = "Content-Type:";
  6738. if (start_with_case_ignore(header, header_content_type)) {
  6739. file_.content_type =
  6740. trim_copy(header.substr(str_len(header_content_type)));
  6741. } else {
  6742. std::string disposition_params;
  6743. if (parse_content_disposition(header, disposition_params)) {
  6744. Params params;
  6745. parse_disposition_params(disposition_params, params);
  6746. auto it = params.find("name");
  6747. if (it != params.end()) {
  6748. file_.name = it->second;
  6749. } else {
  6750. is_valid_ = false;
  6751. return false;
  6752. }
  6753. it = params.find("filename");
  6754. if (it != params.end()) { file_.filename = it->second; }
  6755. it = params.find("filename*");
  6756. if (it != params.end()) {
  6757. // RFC 5987: only UTF-8 encoding is allowed
  6758. const auto &val = it->second;
  6759. constexpr const char utf8_prefix[] = "UTF-8''";
  6760. constexpr size_t prefix_len = str_len(utf8_prefix);
  6761. if (val.size() > prefix_len &&
  6762. start_with_case_ignore(val, utf8_prefix)) {
  6763. file_.filename = decode_path_component(
  6764. val.substr(prefix_len)); // override...
  6765. } else {
  6766. is_valid_ = false;
  6767. return false;
  6768. }
  6769. }
  6770. }
  6771. }
  6772. buf_erase(pos + crlf_.size());
  6773. pos = buf_find(crlf_);
  6774. }
  6775. if (state_ != 3) { return true; }
  6776. break;
  6777. }
  6778. case 3: { // Body
  6779. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6780. auto pos = buf_find(crlf_dash_boundary_);
  6781. if (pos < buf_size()) {
  6782. if (!content_callback(buf_data(), pos)) {
  6783. is_valid_ = false;
  6784. return false;
  6785. }
  6786. buf_erase(pos + crlf_dash_boundary_.size());
  6787. state_ = 4;
  6788. } else {
  6789. auto len = buf_size() - crlf_dash_boundary_.size();
  6790. if (len > 0) {
  6791. if (!content_callback(buf_data(), len)) {
  6792. is_valid_ = false;
  6793. return false;
  6794. }
  6795. buf_erase(len);
  6796. }
  6797. return true;
  6798. }
  6799. break;
  6800. }
  6801. case 4: { // Boundary
  6802. if (crlf_.size() > buf_size()) { return true; }
  6803. if (buf_start_with(crlf_)) {
  6804. buf_erase(crlf_.size());
  6805. state_ = 1;
  6806. } else {
  6807. if (dash_.size() > buf_size()) { return true; }
  6808. if (buf_start_with(dash_)) {
  6809. buf_erase(dash_.size());
  6810. is_valid_ = true;
  6811. buf_erase(buf_size()); // Remove epilogue
  6812. } else {
  6813. return true;
  6814. }
  6815. }
  6816. break;
  6817. }
  6818. }
  6819. }
  6820. return true;
  6821. }
  6822. private:
  6823. void clear_file_info() {
  6824. file_.name.clear();
  6825. file_.filename.clear();
  6826. file_.content_type.clear();
  6827. file_.headers.clear();
  6828. }
  6829. bool start_with_case_ignore(const std::string &a, const char *b,
  6830. size_t offset = 0) const {
  6831. const auto b_len = strlen(b);
  6832. if (a.size() < offset + b_len) { return false; }
  6833. for (size_t i = 0; i < b_len; i++) {
  6834. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6835. return false;
  6836. }
  6837. }
  6838. return true;
  6839. }
  6840. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6841. // Returns true if header matches, with the params portion in `params_out`.
  6842. bool parse_content_disposition(const std::string &header,
  6843. std::string &params_out) const {
  6844. constexpr const char prefix[] = "Content-Disposition:";
  6845. constexpr size_t prefix_len = str_len(prefix);
  6846. if (!start_with_case_ignore(header, prefix)) { return false; }
  6847. // Skip whitespace after "Content-Disposition:"
  6848. auto pos = prefix_len;
  6849. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6850. pos++;
  6851. }
  6852. // Match "form-data;" (case-insensitive)
  6853. constexpr const char form_data[] = "form-data;";
  6854. constexpr size_t form_data_len = str_len(form_data);
  6855. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6856. pos += form_data_len;
  6857. // Skip whitespace after "form-data;"
  6858. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6859. pos++;
  6860. }
  6861. params_out = header.substr(pos);
  6862. return true;
  6863. }
  6864. const std::string dash_ = "--";
  6865. const std::string crlf_ = "\r\n";
  6866. std::string boundary_;
  6867. std::string dash_boundary_crlf_;
  6868. std::string crlf_dash_boundary_;
  6869. size_t state_ = 0;
  6870. bool is_valid_ = false;
  6871. FormData file_;
  6872. // Buffer
  6873. bool start_with(const std::string &a, size_t spos, size_t epos,
  6874. const std::string &b) const {
  6875. if (epos - spos < b.size()) { return false; }
  6876. for (size_t i = 0; i < b.size(); i++) {
  6877. if (a[i + spos] != b[i]) { return false; }
  6878. }
  6879. return true;
  6880. }
  6881. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6882. const char *buf_data() const { return &buf_[buf_spos_]; }
  6883. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6884. bool buf_start_with(const std::string &s) const {
  6885. return start_with(buf_, buf_spos_, buf_epos_, s);
  6886. }
  6887. size_t buf_find(const std::string &s) const {
  6888. auto c = s.front();
  6889. size_t off = buf_spos_;
  6890. while (off < buf_epos_) {
  6891. auto pos = off;
  6892. while (true) {
  6893. if (pos == buf_epos_) { return buf_size(); }
  6894. if (buf_[pos] == c) { break; }
  6895. pos++;
  6896. }
  6897. auto remaining_size = buf_epos_ - pos;
  6898. if (s.size() > remaining_size) { return buf_size(); }
  6899. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6900. off = pos + 1;
  6901. }
  6902. return buf_size();
  6903. }
  6904. void buf_append(const char *data, size_t n) {
  6905. auto remaining_size = buf_size();
  6906. if (remaining_size > 0 && buf_spos_ > 0) {
  6907. for (size_t i = 0; i < remaining_size; i++) {
  6908. buf_[i] = buf_[buf_spos_ + i];
  6909. }
  6910. }
  6911. buf_spos_ = 0;
  6912. buf_epos_ = remaining_size;
  6913. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6914. for (size_t i = 0; i < n; i++) {
  6915. buf_[buf_epos_ + i] = data[i];
  6916. }
  6917. buf_epos_ += n;
  6918. }
  6919. void buf_erase(size_t size) { buf_spos_ += size; }
  6920. std::string buf_;
  6921. size_t buf_spos_ = 0;
  6922. size_t buf_epos_ = 0;
  6923. };
  6924. inline std::string random_string(size_t length) {
  6925. constexpr const char data[] =
  6926. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6927. thread_local auto engine([]() {
  6928. // std::random_device might actually be deterministic on some
  6929. // platforms, but due to lack of support in the c++ standard library,
  6930. // doing better requires either some ugly hacks or breaking portability.
  6931. std::random_device seed_gen;
  6932. // Request 128 bits of entropy for initialization
  6933. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6934. return std::mt19937(seed_sequence);
  6935. }());
  6936. std::string result;
  6937. for (size_t i = 0; i < length; i++) {
  6938. result += data[engine() % (sizeof(data) - 1)];
  6939. }
  6940. return result;
  6941. }
  6942. inline std::string make_multipart_data_boundary() {
  6943. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6944. }
  6945. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6946. auto valid = true;
  6947. for (size_t i = 0; i < boundary.size(); i++) {
  6948. auto c = boundary[i];
  6949. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  6950. valid = false;
  6951. break;
  6952. }
  6953. }
  6954. return valid;
  6955. }
  6956. // Escape a multipart field name/filename following the WHATWG HTML standard
  6957. // ("escape a multipart form-data name"), which is what browsers send:
  6958. // '"' -> %22, CR -> %0D, LF -> %0A
  6959. // With escape_quote = false, only CR and LF are escaped; this is for header
  6960. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  6961. inline std::string escape_multipart_field(const std::string &s,
  6962. bool escape_quote = true) {
  6963. std::string result;
  6964. result.reserve(s.size());
  6965. for (auto c : s) {
  6966. switch (c) {
  6967. case '"':
  6968. if (escape_quote) {
  6969. result += "%22";
  6970. } else {
  6971. result += c;
  6972. }
  6973. break;
  6974. case '\r': result += "%0D"; break;
  6975. case '\n': result += "%0A"; break;
  6976. default: result += c; break;
  6977. }
  6978. }
  6979. return result;
  6980. }
  6981. template <typename T>
  6982. inline std::string
  6983. serialize_multipart_formdata_item_begin(const T &item,
  6984. const std::string &boundary) {
  6985. std::string body = "--" + boundary + "\r\n";
  6986. body += "Content-Disposition: form-data; name=\"" +
  6987. escape_multipart_field(item.name) + "\"";
  6988. if (!item.filename.empty()) {
  6989. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  6990. }
  6991. body += "\r\n";
  6992. if (!item.content_type.empty()) {
  6993. body +=
  6994. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  6995. "\r\n";
  6996. }
  6997. body += "\r\n";
  6998. return body;
  6999. }
  7000. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  7001. inline std::string
  7002. serialize_multipart_formdata_finish(const std::string &boundary) {
  7003. return "--" + boundary + "--\r\n";
  7004. }
  7005. inline std::string
  7006. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7007. return "multipart/form-data; boundary=" + boundary;
  7008. }
  7009. inline std::string
  7010. serialize_multipart_formdata(const UploadFormDataItems &items,
  7011. const std::string &boundary, bool finish = true) {
  7012. std::string body;
  7013. for (const auto &item : items) {
  7014. body += serialize_multipart_formdata_item_begin(item, boundary);
  7015. body += item.content + serialize_multipart_formdata_item_end();
  7016. }
  7017. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7018. return body;
  7019. }
  7020. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7021. const std::string &boundary) {
  7022. size_t total = 0;
  7023. for (const auto &item : items) {
  7024. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7025. total += item.content.size();
  7026. total += serialize_multipart_formdata_item_end().size();
  7027. }
  7028. total += serialize_multipart_formdata_finish(boundary).size();
  7029. return total;
  7030. }
  7031. struct MultipartSegment {
  7032. const char *data;
  7033. size_t size;
  7034. };
  7035. // NOTE: items must outlive the returned ContentProvider
  7036. // (safe for synchronous use inside Post/Put/Patch)
  7037. inline ContentProvider
  7038. make_multipart_content_provider(const UploadFormDataItems &items,
  7039. const std::string &boundary) {
  7040. // Own the per-item header strings and the finish string
  7041. std::vector<std::string> owned;
  7042. owned.reserve(items.size() + 1);
  7043. for (const auto &item : items)
  7044. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7045. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7046. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7047. std::vector<MultipartSegment> segs;
  7048. segs.reserve(items.size() * 3 + 1);
  7049. static const char crlf[] = "\r\n";
  7050. for (size_t i = 0; i < items.size(); i++) {
  7051. segs.push_back({owned[i].data(), owned[i].size()});
  7052. segs.push_back({items[i].content.data(), items[i].content.size()});
  7053. segs.push_back({crlf, 2});
  7054. }
  7055. segs.push_back({owned.back().data(), owned.back().size()});
  7056. struct MultipartState {
  7057. std::vector<std::string> owned;
  7058. std::vector<MultipartSegment> segs;
  7059. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7060. };
  7061. auto state = std::make_shared<MultipartState>();
  7062. state->owned = std::move(owned);
  7063. // `segs` holds raw pointers into owned strings; std::string move preserves
  7064. // the data pointer, so these pointers remain valid after the move above.
  7065. state->segs = std::move(segs);
  7066. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7067. // Buffer multiple small segments into fewer, larger writes to avoid
  7068. // excessive TCP packets when there are many form data items (#2410)
  7069. auto &buf = state->buf;
  7070. auto buf_size = buf.size();
  7071. size_t buf_len = 0;
  7072. size_t remaining = length;
  7073. // Find the first segment containing 'offset'
  7074. size_t pos = 0;
  7075. size_t seg_idx = 0;
  7076. for (; seg_idx < state->segs.size(); seg_idx++) {
  7077. const auto &seg = state->segs[seg_idx];
  7078. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7079. pos += seg.size;
  7080. }
  7081. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7082. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7083. const auto &seg = state->segs[seg_idx];
  7084. size_t available = seg.size - seg_offset;
  7085. size_t to_copy = (std::min)(available, remaining);
  7086. const char *src = seg.data + seg_offset;
  7087. seg_offset = 0; // only the first segment has a non-zero offset
  7088. while (to_copy > 0) {
  7089. size_t space = buf_size - buf_len;
  7090. size_t chunk = (std::min)(to_copy, space);
  7091. std::memcpy(buf.data() + buf_len, src, chunk);
  7092. buf_len += chunk;
  7093. src += chunk;
  7094. to_copy -= chunk;
  7095. remaining -= chunk;
  7096. if (buf_len == buf_size) {
  7097. if (!sink.write(buf.data(), buf_len)) { return false; }
  7098. buf_len = 0;
  7099. }
  7100. }
  7101. }
  7102. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7103. return true;
  7104. };
  7105. }
  7106. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7107. if (ranges.size() <= 1) return;
  7108. // Sort ranges by start position
  7109. std::sort(ranges.begin(), ranges.end(),
  7110. [](const Range &a, const Range &b) { return a.first < b.first; });
  7111. Ranges coalesced;
  7112. coalesced.reserve(ranges.size());
  7113. for (auto &r : ranges) {
  7114. auto first_pos = r.first;
  7115. auto last_pos = r.second;
  7116. // Handle special cases like in range_error
  7117. if (first_pos == -1 && last_pos == -1) {
  7118. first_pos = 0;
  7119. last_pos = static_cast<ssize_t>(content_length);
  7120. }
  7121. if (first_pos == -1) {
  7122. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7123. last_pos = static_cast<ssize_t>(content_length) - 1;
  7124. }
  7125. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7126. last_pos = static_cast<ssize_t>(content_length) - 1;
  7127. }
  7128. // Skip invalid ranges
  7129. if (!(0 <= first_pos && first_pos <= last_pos &&
  7130. last_pos < static_cast<ssize_t>(content_length))) {
  7131. continue;
  7132. }
  7133. // Coalesce with previous range if overlapping or adjacent (but not
  7134. // identical)
  7135. if (!coalesced.empty()) {
  7136. auto &prev = coalesced.back();
  7137. // Check if current range overlaps or is adjacent to previous range
  7138. // but don't coalesce identical ranges (allow duplicates)
  7139. if (first_pos <= prev.second + 1 &&
  7140. !(first_pos == prev.first && last_pos == prev.second)) {
  7141. // Extend the previous range
  7142. prev.second = (std::max)(prev.second, last_pos);
  7143. continue;
  7144. }
  7145. }
  7146. // Add new range
  7147. coalesced.emplace_back(first_pos, last_pos);
  7148. }
  7149. ranges = std::move(coalesced);
  7150. }
  7151. inline bool range_error(Request &req, Response &res) {
  7152. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7153. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7154. req.ranges.clear();
  7155. if (res.status == StatusCode::PartialContent_206) {
  7156. res.status = StatusCode::OK_200;
  7157. }
  7158. return false;
  7159. }
  7160. ssize_t content_len = static_cast<ssize_t>(
  7161. res.content_length_ ? res.content_length_ : res.body.size());
  7162. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7163. size_t overwrapping_count = 0;
  7164. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7165. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7166. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7167. // Too many ranges
  7168. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7169. for (auto &r : req.ranges) {
  7170. auto &first_pos = r.first;
  7171. auto &last_pos = r.second;
  7172. if (first_pos == -1 && last_pos == -1) {
  7173. first_pos = 0;
  7174. last_pos = content_len;
  7175. }
  7176. if (first_pos == -1) {
  7177. first_pos = content_len - last_pos;
  7178. last_pos = content_len - 1;
  7179. }
  7180. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7181. // A client can limit the number of bytes requested without knowing the
  7182. // size of the selected representation. If the last-pos value is absent,
  7183. // or if the value is greater than or equal to the current length of the
  7184. // representation data, the byte range is interpreted as the remainder of
  7185. // the representation (i.e., the server replaces the value of last-pos
  7186. // with a value that is one less than the current length of the selected
  7187. // representation).
  7188. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7189. if (last_pos == -1 || last_pos >= content_len) {
  7190. last_pos = content_len - 1;
  7191. }
  7192. // Range must be within content length
  7193. if (!(0 <= first_pos && first_pos <= last_pos &&
  7194. last_pos <= content_len - 1)) {
  7195. return true;
  7196. }
  7197. // Request must not have more than two overlapping ranges
  7198. for (const auto &processed_range : processed_ranges) {
  7199. if (!(last_pos < processed_range.first ||
  7200. first_pos > processed_range.second)) {
  7201. overwrapping_count++;
  7202. if (overwrapping_count > 2) { return true; }
  7203. break; // Only count once per range
  7204. }
  7205. }
  7206. processed_ranges.emplace_back(first_pos, last_pos);
  7207. }
  7208. // After validation, coalesce overlapping ranges as per RFC 9110
  7209. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7210. }
  7211. return false;
  7212. }
  7213. inline std::pair<size_t, size_t>
  7214. get_range_offset_and_length(Range r, size_t content_length) {
  7215. assert(r.first != -1 && r.second != -1);
  7216. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7217. assert(r.first <= r.second &&
  7218. r.second < static_cast<ssize_t>(content_length));
  7219. (void)(content_length);
  7220. return std::make_pair(static_cast<size_t>(r.first),
  7221. static_cast<size_t>(r.second - r.first) + 1);
  7222. }
  7223. inline std::string make_content_range_header_field(
  7224. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7225. auto st = offset_and_length.first;
  7226. auto ed = st + offset_and_length.second - 1;
  7227. std::string field = "bytes ";
  7228. field += std::to_string(st);
  7229. field += '-';
  7230. field += std::to_string(ed);
  7231. field += '/';
  7232. field += std::to_string(content_length);
  7233. return field;
  7234. }
  7235. template <typename SToken, typename CToken, typename Content>
  7236. bool process_multipart_ranges_data(const Request &req,
  7237. const std::string &boundary,
  7238. const std::string &content_type,
  7239. size_t content_length, SToken stoken,
  7240. CToken ctoken, Content content) {
  7241. for (size_t i = 0; i < req.ranges.size(); i++) {
  7242. ctoken("--");
  7243. stoken(boundary);
  7244. ctoken("\r\n");
  7245. if (!content_type.empty()) {
  7246. ctoken("Content-Type: ");
  7247. stoken(content_type);
  7248. ctoken("\r\n");
  7249. }
  7250. auto offset_and_length =
  7251. get_range_offset_and_length(req.ranges[i], content_length);
  7252. ctoken("Content-Range: ");
  7253. stoken(make_content_range_header_field(offset_and_length, content_length));
  7254. ctoken("\r\n");
  7255. ctoken("\r\n");
  7256. if (!content(offset_and_length.first, offset_and_length.second)) {
  7257. return false;
  7258. }
  7259. ctoken("\r\n");
  7260. }
  7261. ctoken("--");
  7262. stoken(boundary);
  7263. ctoken("--");
  7264. return true;
  7265. }
  7266. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7267. const std::string &boundary,
  7268. const std::string &content_type,
  7269. size_t content_length,
  7270. std::string &data) {
  7271. process_multipart_ranges_data(
  7272. req, boundary, content_type, content_length,
  7273. [&](const std::string &token) { data += token; },
  7274. [&](const std::string &token) { data += token; },
  7275. [&](size_t offset, size_t length) {
  7276. assert(offset + length <= content_length);
  7277. data += res.body.substr(offset, length);
  7278. return true;
  7279. });
  7280. }
  7281. inline size_t get_multipart_ranges_data_length(const Request &req,
  7282. const std::string &boundary,
  7283. const std::string &content_type,
  7284. size_t content_length) {
  7285. size_t data_length = 0;
  7286. process_multipart_ranges_data(
  7287. req, boundary, content_type, content_length,
  7288. [&](const std::string &token) { data_length += token.size(); },
  7289. [&](const std::string &token) { data_length += token.size(); },
  7290. [&](size_t /*offset*/, size_t length) {
  7291. data_length += length;
  7292. return true;
  7293. });
  7294. return data_length;
  7295. }
  7296. template <typename T>
  7297. inline bool
  7298. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7299. const std::string &boundary,
  7300. const std::string &content_type,
  7301. size_t content_length, const T &is_shutting_down) {
  7302. return process_multipart_ranges_data(
  7303. req, boundary, content_type, content_length,
  7304. [&](const std::string &token) { strm.write(token); },
  7305. [&](const std::string &token) { strm.write(token); },
  7306. [&](size_t offset, size_t length) {
  7307. return write_content(strm, res.content_provider_, offset, length,
  7308. is_shutting_down);
  7309. });
  7310. }
  7311. inline bool has_framed_body(const Request &req) {
  7312. return is_chunked_transfer_encoding(req.headers) ||
  7313. req.get_header_value_u64("Content-Length") > 0;
  7314. }
  7315. inline bool is_connection_persistent(const Request &req) {
  7316. auto conn = req.get_header_value("Connection");
  7317. if (conn == "close") { return false; }
  7318. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7319. return true;
  7320. }
  7321. inline bool expect_content(const Request &req) {
  7322. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7323. req.method == "DELETE") {
  7324. return true;
  7325. }
  7326. return has_framed_body(req);
  7327. }
  7328. #ifdef _WIN32
  7329. class WSInit {
  7330. public:
  7331. WSInit() {
  7332. WSADATA wsaData;
  7333. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7334. }
  7335. ~WSInit() {
  7336. if (is_valid_) WSACleanup();
  7337. }
  7338. bool is_valid_ = false;
  7339. };
  7340. static WSInit wsinit_;
  7341. #endif
  7342. inline bool parse_www_authenticate(const Response &res,
  7343. std::map<std::string, std::string> &auth,
  7344. bool is_proxy) {
  7345. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7346. if (res.has_header(auth_key)) {
  7347. thread_local auto re =
  7348. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7349. auto s = res.get_header_value(auth_key);
  7350. auto pos = s.find(' ');
  7351. if (pos != std::string::npos) {
  7352. auto type = s.substr(0, pos);
  7353. if (type == "Basic") {
  7354. return false;
  7355. } else if (type == "Digest") {
  7356. s = s.substr(pos + 1);
  7357. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7358. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7359. const auto &m = *i;
  7360. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7361. static_cast<size_t>(m.length(1)));
  7362. auto val = m.length(2) > 0
  7363. ? s.substr(static_cast<size_t>(m.position(2)),
  7364. static_cast<size_t>(m.length(2)))
  7365. : s.substr(static_cast<size_t>(m.position(3)),
  7366. static_cast<size_t>(m.length(3)));
  7367. auth[std::move(key)] = std::move(val);
  7368. }
  7369. return true;
  7370. }
  7371. }
  7372. }
  7373. return false;
  7374. }
  7375. class ContentProviderAdapter {
  7376. public:
  7377. explicit ContentProviderAdapter(
  7378. ContentProviderWithoutLength &&content_provider)
  7379. : content_provider_(std::move(content_provider)) {}
  7380. bool operator()(size_t offset, size_t, DataSink &sink) {
  7381. return content_provider_(offset, sink);
  7382. }
  7383. private:
  7384. ContentProviderWithoutLength content_provider_;
  7385. };
  7386. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7387. namespace fields {
  7388. inline bool is_token_char(char c) {
  7389. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7390. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7391. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7392. }
  7393. inline bool is_token(const std::string &s) {
  7394. if (s.empty()) { return false; }
  7395. for (auto c : s) {
  7396. if (!is_token_char(c)) { return false; }
  7397. }
  7398. return true;
  7399. }
  7400. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7401. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7402. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7403. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7404. inline bool is_field_content(const std::string &s) {
  7405. if (s.empty()) { return true; }
  7406. if (s.size() == 1) {
  7407. return is_field_vchar(s[0]);
  7408. } else if (s.size() == 2) {
  7409. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7410. } else {
  7411. size_t i = 0;
  7412. if (!is_field_vchar(s[i])) { return false; }
  7413. i++;
  7414. while (i < s.size() - 1) {
  7415. auto c = s[i++];
  7416. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7417. } else {
  7418. return false;
  7419. }
  7420. }
  7421. return is_field_vchar(s[i]);
  7422. }
  7423. }
  7424. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7425. } // namespace fields
  7426. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7427. int port, bool is_ssl,
  7428. const std::string &path,
  7429. const Headers &headers,
  7430. std::string &selected_subprotocol) {
  7431. // Validate path and host
  7432. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7433. return false;
  7434. }
  7435. // Validate user-provided headers
  7436. for (const auto &h : headers) {
  7437. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7438. return false;
  7439. }
  7440. }
  7441. // Generate random Sec-WebSocket-Key
  7442. thread_local std::mt19937 rng(std::random_device{}());
  7443. std::string key_bytes(16, '\0');
  7444. for (size_t i = 0; i < 16; i += 4) {
  7445. auto r = rng();
  7446. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7447. }
  7448. auto client_key = base64_encode(key_bytes);
  7449. // Build upgrade request
  7450. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7451. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7452. req_str += "Upgrade: websocket\r\n";
  7453. req_str += "Connection: Upgrade\r\n";
  7454. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7455. req_str += "Sec-WebSocket-Version: 13\r\n";
  7456. for (const auto &h : headers) {
  7457. req_str += h.first + ": " + h.second + "\r\n";
  7458. }
  7459. req_str += "\r\n";
  7460. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7461. // Verify 101 response and Sec-WebSocket-Accept header
  7462. auto expected_accept = websocket_accept_key(client_key);
  7463. return read_websocket_upgrade_response(strm, expected_accept,
  7464. selected_subprotocol);
  7465. }
  7466. } // namespace detail
  7467. /*
  7468. * Group 2: detail namespace - SSL common utilities
  7469. */
  7470. #ifdef CPPHTTPLIB_SSL_ENABLED
  7471. namespace detail {
  7472. class SSLSocketStream final : public Stream {
  7473. public:
  7474. SSLSocketStream(
  7475. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7476. time_t read_timeout_usec, time_t write_timeout_sec,
  7477. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7478. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7479. (std::chrono::steady_clock::time_point::min)());
  7480. ~SSLSocketStream() override;
  7481. bool is_readable() const override;
  7482. bool wait_readable() const override;
  7483. bool wait_writable() const override;
  7484. bool is_peer_alive() const override;
  7485. ssize_t read(char *ptr, size_t size) override;
  7486. ssize_t write(const char *ptr, size_t size) override;
  7487. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7488. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7489. socket_t socket() const override;
  7490. time_t duration() const override;
  7491. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7492. private:
  7493. socket_t sock_;
  7494. tls::session_t session_;
  7495. time_t read_timeout_sec_;
  7496. time_t read_timeout_usec_;
  7497. time_t write_timeout_sec_;
  7498. time_t write_timeout_usec_;
  7499. time_t max_timeout_msec_;
  7500. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7501. };
  7502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7503. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7504. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7505. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7506. unsigned int hash_length = 0;
  7507. unsigned char hash[EVP_MAX_MD_SIZE];
  7508. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7509. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7510. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7511. std::stringstream ss;
  7512. for (auto i = 0u; i < hash_length; ++i) {
  7513. ss << std::hex << std::setw(2) << std::setfill('0')
  7514. << static_cast<unsigned int>(hash[i]);
  7515. }
  7516. return ss.str();
  7517. }
  7518. inline std::string MD5(const std::string &s) {
  7519. return message_digest(s, EVP_md5());
  7520. }
  7521. inline std::string SHA_256(const std::string &s) {
  7522. return message_digest(s, EVP_sha256());
  7523. }
  7524. inline std::string SHA_512(const std::string &s) {
  7525. return message_digest(s, EVP_sha512());
  7526. }
  7527. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7528. namespace {
  7529. template <size_t N>
  7530. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7531. std::stringstream ss;
  7532. for (size_t i = 0; i < N; ++i) {
  7533. ss << std::hex << std::setw(2) << std::setfill('0')
  7534. << static_cast<unsigned int>(hash[i]);
  7535. }
  7536. return ss.str();
  7537. }
  7538. } // namespace
  7539. inline std::string MD5(const std::string &s) {
  7540. unsigned char hash[16];
  7541. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7542. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7543. hash);
  7544. #else
  7545. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7546. hash);
  7547. #endif
  7548. return hash_to_hex(hash);
  7549. }
  7550. inline std::string SHA_256(const std::string &s) {
  7551. unsigned char hash[32];
  7552. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7553. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7554. hash, 0);
  7555. #else
  7556. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7557. s.size(), hash, 0);
  7558. #endif
  7559. return hash_to_hex(hash);
  7560. }
  7561. inline std::string SHA_512(const std::string &s) {
  7562. unsigned char hash[64];
  7563. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7564. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7565. hash, 0);
  7566. #else
  7567. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7568. s.size(), hash, 0);
  7569. #endif
  7570. return hash_to_hex(hash);
  7571. }
  7572. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7573. namespace {
  7574. template <size_t N>
  7575. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7576. std::stringstream ss;
  7577. for (size_t i = 0; i < N; ++i) {
  7578. ss << std::hex << std::setw(2) << std::setfill('0')
  7579. << static_cast<unsigned int>(hash[i]);
  7580. }
  7581. return ss.str();
  7582. }
  7583. } // namespace
  7584. inline std::string MD5(const std::string &s) {
  7585. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7586. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7587. static_cast<word32>(s.size()), hash);
  7588. return hash_to_hex(hash);
  7589. }
  7590. inline std::string SHA_256(const std::string &s) {
  7591. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7592. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7593. static_cast<word32>(s.size()), hash);
  7594. return hash_to_hex(hash);
  7595. }
  7596. inline std::string SHA_512(const std::string &s) {
  7597. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7598. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7599. static_cast<word32>(s.size()), hash);
  7600. return hash_to_hex(hash);
  7601. }
  7602. #endif
  7603. inline bool is_ip_address(const std::string &host) {
  7604. struct in_addr addr4;
  7605. struct in6_addr addr6;
  7606. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7607. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7608. }
  7609. template <typename T>
  7610. inline bool process_server_socket_ssl(
  7611. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7612. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7613. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7614. time_t write_timeout_usec, T callback) {
  7615. return process_server_socket_core(
  7616. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7617. [&](bool close_connection, bool &connection_closed) {
  7618. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7619. write_timeout_sec, write_timeout_usec);
  7620. return callback(strm, close_connection, connection_closed);
  7621. });
  7622. }
  7623. template <typename T>
  7624. inline bool process_client_socket_ssl(
  7625. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7626. time_t read_timeout_usec, time_t write_timeout_sec,
  7627. time_t write_timeout_usec, time_t max_timeout_msec,
  7628. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7629. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7630. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7631. start_time);
  7632. return callback(strm);
  7633. }
  7634. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7635. const Request &req, const std::map<std::string, std::string> &auth,
  7636. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7637. const std::string &password, bool is_proxy = false) {
  7638. std::string nc;
  7639. {
  7640. std::stringstream ss;
  7641. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7642. nc = ss.str();
  7643. }
  7644. std::string qop;
  7645. if (auth.find("qop") != auth.end()) {
  7646. qop = auth.at("qop");
  7647. if (qop.find("auth-int") != std::string::npos) {
  7648. qop = "auth-int";
  7649. } else if (qop.find("auth") != std::string::npos) {
  7650. qop = "auth";
  7651. } else {
  7652. qop.clear();
  7653. }
  7654. }
  7655. std::string algo = "MD5";
  7656. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7657. std::string response;
  7658. {
  7659. auto H = algo == "SHA-256" ? detail::SHA_256
  7660. : algo == "SHA-512" ? detail::SHA_512
  7661. : detail::MD5;
  7662. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7663. auto A2 = req.method + ":" + req.path;
  7664. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7665. if (qop.empty()) {
  7666. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7667. } else {
  7668. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7669. ":" + qop + ":" + H(A2));
  7670. }
  7671. }
  7672. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7673. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7674. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7675. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7676. (qop.empty() ? ", response=\""
  7677. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7678. cnonce + "\", response=\"") +
  7679. response + "\"" +
  7680. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7681. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7682. return std::make_pair(key, field);
  7683. }
  7684. inline bool match_hostname(const std::string &pattern,
  7685. const std::string &hostname) {
  7686. // Exact match (case-insensitive)
  7687. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7688. // Split both pattern and hostname into components by '.'
  7689. std::vector<std::string> pattern_components;
  7690. if (!pattern.empty()) {
  7691. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7692. [&](const char *b, const char *e) {
  7693. pattern_components.emplace_back(b, e);
  7694. });
  7695. }
  7696. std::vector<std::string> host_components;
  7697. if (!hostname.empty()) {
  7698. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7699. [&](const char *b, const char *e) {
  7700. host_components.emplace_back(b, e);
  7701. });
  7702. }
  7703. // Component count must match
  7704. if (host_components.size() != pattern_components.size()) { return false; }
  7705. // Compare each component with wildcard support
  7706. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7707. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7708. auto itr = pattern_components.begin();
  7709. for (const auto &h : host_components) {
  7710. auto &p = *itr;
  7711. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7712. bool partial_match = false;
  7713. if (!p.empty() && p[p.size() - 1] == '*') {
  7714. const auto prefix_length = p.size() - 1;
  7715. if (prefix_length == 0) {
  7716. partial_match = true;
  7717. } else if (h.size() >= prefix_length) {
  7718. partial_match =
  7719. std::equal(p.begin(),
  7720. p.begin() + static_cast<std::string::difference_type>(
  7721. prefix_length),
  7722. h.begin(), [](const char ca, const char cb) {
  7723. return detail::case_ignore::to_lower(ca) ==
  7724. detail::case_ignore::to_lower(cb);
  7725. });
  7726. }
  7727. }
  7728. if (!partial_match) { return false; }
  7729. }
  7730. ++itr;
  7731. }
  7732. return true;
  7733. }
  7734. #ifdef _WIN32
  7735. // Verify certificate using Windows CertGetCertificateChain API.
  7736. // This provides real-time certificate validation with Windows Update
  7737. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7738. inline bool
  7739. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7740. const std::string &hostname,
  7741. bool verify_hostname, uint64_t &out_error) {
  7742. if (der_cert.empty()) { return false; }
  7743. out_error = 0;
  7744. // Create Windows certificate context from DER data
  7745. auto cert_context = CertCreateCertificateContext(
  7746. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7747. static_cast<DWORD>(der_cert.size()));
  7748. if (!cert_context) {
  7749. out_error = GetLastError();
  7750. return false;
  7751. }
  7752. auto cert_guard =
  7753. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7754. // Setup chain parameters
  7755. CERT_CHAIN_PARA chain_para = {};
  7756. chain_para.cbSize = sizeof(chain_para);
  7757. // Build certificate chain with revocation checking
  7758. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7759. auto chain_result = CertGetCertificateChain(
  7760. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7761. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7762. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7763. nullptr, &chain_context);
  7764. if (!chain_result || !chain_context) {
  7765. out_error = GetLastError();
  7766. return false;
  7767. }
  7768. auto chain_guard =
  7769. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7770. // Check if chain has errors
  7771. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7772. out_error = chain_context->TrustStatus.dwErrorStatus;
  7773. return false;
  7774. }
  7775. // Verify SSL policy
  7776. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7777. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7778. #ifdef AUTHTYPE_SERVER
  7779. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7780. #endif
  7781. std::wstring whost;
  7782. if (verify_hostname) {
  7783. whost = u8string_to_wstring(hostname.c_str());
  7784. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7785. }
  7786. CERT_CHAIN_POLICY_PARA policy_para = {};
  7787. policy_para.cbSize = sizeof(policy_para);
  7788. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7789. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7790. #else
  7791. policy_para.dwFlags = 0;
  7792. #endif
  7793. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7794. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7795. policy_status.cbSize = sizeof(policy_status);
  7796. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7797. &policy_para, &policy_status)) {
  7798. out_error = GetLastError();
  7799. return false;
  7800. }
  7801. if (policy_status.dwError != 0) {
  7802. out_error = policy_status.dwError;
  7803. return false;
  7804. }
  7805. return true;
  7806. }
  7807. #endif // _WIN32
  7808. // Loads CA file/dir configuration and applies the system CA policy to a
  7809. // client TLS context. PEM data and native stores are applied to the context
  7810. // directly at set time; has_custom_store reflects them for the Auto policy
  7811. // decision.
  7812. inline bool load_client_ca_config(tls::ctx_t ctx,
  7813. const std::string &ca_cert_file_path,
  7814. const std::string &ca_cert_dir_path,
  7815. bool has_custom_store, SystemCAMode mode,
  7816. uint64_t &backend_error) {
  7817. auto ret = true;
  7818. if (!ca_cert_file_path.empty()) {
  7819. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7820. backend_error = tls::get_error();
  7821. ret = false;
  7822. }
  7823. } else if (!ca_cert_dir_path.empty()) {
  7824. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7825. backend_error = tls::get_error();
  7826. ret = false;
  7827. }
  7828. }
  7829. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7830. !ca_cert_dir_path.empty() || has_custom_store;
  7831. if (mode == SystemCAMode::Enabled ||
  7832. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7833. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7834. }
  7835. return ret;
  7836. }
  7837. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7838. tls::session_t &session, socket_t sock,
  7839. bool server_certificate_verification,
  7840. time_t timeout_sec, time_t timeout_usec) {
  7841. using namespace tls;
  7842. if (!ctx) { return false; }
  7843. bool is_ip = is_ip_address(host);
  7844. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7845. // Chain verification happens during the handshake even for IP hosts; the
  7846. // certificate identity is verified post-handshake via verify_hostname()
  7847. set_verify_client(ctx, server_certificate_verification);
  7848. #endif
  7849. session = create_session(ctx, sock);
  7850. if (!session) { return false; }
  7851. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7852. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7853. // their identity is checked post-handshake below instead.
  7854. if (!is_ip) {
  7855. if (server_certificate_verification) {
  7856. set_hostname(session, host.c_str());
  7857. } else {
  7858. set_sni(session, host.c_str());
  7859. }
  7860. }
  7861. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7862. return false;
  7863. }
  7864. if (server_certificate_verification) {
  7865. if (get_verify_result(session) != 0) { return false; }
  7866. // Identity check against the peer certificate, post-handshake for all
  7867. // backends (same as SSLClient). For IP hosts this is the only identity
  7868. // verification since no hostname is bound during the handshake.
  7869. auto server_cert = get_peer_cert(session);
  7870. if (!server_cert) { return false; }
  7871. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7872. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7873. }
  7874. return true;
  7875. }
  7876. } // namespace detail
  7877. #endif // CPPHTTPLIB_SSL_ENABLED
  7878. /*
  7879. * Group 3: httplib namespace - Non-SSL public API implementations
  7880. */
  7881. inline void default_socket_options(socket_t sock) {
  7882. set_socket_opt(sock, SOL_SOCKET,
  7883. #ifdef SO_REUSEPORT
  7884. SO_REUSEPORT,
  7885. #else
  7886. SO_REUSEADDR,
  7887. #endif
  7888. 1);
  7889. }
  7890. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7891. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7892. sizeof(optval));
  7893. }
  7894. inline std::string get_bearer_token_auth(const Request &req) {
  7895. if (req.has_header("Authorization")) {
  7896. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7897. return req.get_header_value("Authorization")
  7898. .substr(bearer_header_prefix_len);
  7899. }
  7900. return "";
  7901. }
  7902. inline const char *status_message(int status) {
  7903. switch (status) {
  7904. case StatusCode::Continue_100: return "Continue";
  7905. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7906. case StatusCode::Processing_102: return "Processing";
  7907. case StatusCode::EarlyHints_103: return "Early Hints";
  7908. case StatusCode::OK_200: return "OK";
  7909. case StatusCode::Created_201: return "Created";
  7910. case StatusCode::Accepted_202: return "Accepted";
  7911. case StatusCode::NonAuthoritativeInformation_203:
  7912. return "Non-Authoritative Information";
  7913. case StatusCode::NoContent_204: return "No Content";
  7914. case StatusCode::ResetContent_205: return "Reset Content";
  7915. case StatusCode::PartialContent_206: return "Partial Content";
  7916. case StatusCode::MultiStatus_207: return "Multi-Status";
  7917. case StatusCode::AlreadyReported_208: return "Already Reported";
  7918. case StatusCode::IMUsed_226: return "IM Used";
  7919. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7920. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7921. case StatusCode::Found_302: return "Found";
  7922. case StatusCode::SeeOther_303: return "See Other";
  7923. case StatusCode::NotModified_304: return "Not Modified";
  7924. case StatusCode::UseProxy_305: return "Use Proxy";
  7925. case StatusCode::unused_306: return "unused";
  7926. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7927. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7928. case StatusCode::BadRequest_400: return "Bad Request";
  7929. case StatusCode::Unauthorized_401: return "Unauthorized";
  7930. case StatusCode::PaymentRequired_402: return "Payment Required";
  7931. case StatusCode::Forbidden_403: return "Forbidden";
  7932. case StatusCode::NotFound_404: return "Not Found";
  7933. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7934. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7935. case StatusCode::ProxyAuthenticationRequired_407:
  7936. return "Proxy Authentication Required";
  7937. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7938. case StatusCode::Conflict_409: return "Conflict";
  7939. case StatusCode::Gone_410: return "Gone";
  7940. case StatusCode::LengthRequired_411: return "Length Required";
  7941. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7942. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7943. case StatusCode::UriTooLong_414: return "URI Too Long";
  7944. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7945. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7946. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7947. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7948. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7949. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7950. case StatusCode::Locked_423: return "Locked";
  7951. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7952. case StatusCode::TooEarly_425: return "Too Early";
  7953. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7954. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7955. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7956. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7957. return "Request Header Fields Too Large";
  7958. case StatusCode::UnavailableForLegalReasons_451:
  7959. return "Unavailable For Legal Reasons";
  7960. case StatusCode::NotImplemented_501: return "Not Implemented";
  7961. case StatusCode::BadGateway_502: return "Bad Gateway";
  7962. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7963. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7964. case StatusCode::HttpVersionNotSupported_505:
  7965. return "HTTP Version Not Supported";
  7966. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7967. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7968. case StatusCode::LoopDetected_508: return "Loop Detected";
  7969. case StatusCode::NotExtended_510: return "Not Extended";
  7970. case StatusCode::NetworkAuthenticationRequired_511:
  7971. return "Network Authentication Required";
  7972. default:
  7973. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7974. }
  7975. }
  7976. inline std::string to_string(const Error error) {
  7977. switch (error) {
  7978. case Error::Success: return "Success (no error)";
  7979. case Error::Unknown: return "Unknown";
  7980. case Error::Connection: return "Could not establish connection";
  7981. case Error::BindIPAddress: return "Failed to bind IP address";
  7982. case Error::Read: return "Failed to read connection";
  7983. case Error::Write: return "Failed to write connection";
  7984. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7985. case Error::Canceled: return "Connection handling canceled";
  7986. case Error::SSLConnection: return "SSL connection failed";
  7987. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7988. case Error::SSLServerVerification: return "SSL server verification failed";
  7989. case Error::SSLServerHostnameVerification:
  7990. return "SSL server hostname verification failed";
  7991. case Error::UnsupportedMultipartBoundaryChars:
  7992. return "Unsupported HTTP multipart boundary characters";
  7993. case Error::Compression: return "Compression failed";
  7994. case Error::ConnectionTimeout: return "Connection timed out";
  7995. case Error::ProxyConnection: return "Proxy connection failed";
  7996. case Error::ConnectionClosed: return "Connection closed by server";
  7997. case Error::Timeout: return "Read timeout";
  7998. case Error::ResourceExhaustion: return "Resource exhaustion";
  7999. case Error::TooManyFormDataFiles: return "Too many form data files";
  8000. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  8001. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  8002. case Error::ExceedMaxSocketDescriptorCount:
  8003. return "Exceeded maximum socket descriptor count";
  8004. case Error::InvalidRequestLine: return "Invalid request line";
  8005. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8006. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8007. case Error::InvalidHeaders: return "Invalid headers";
  8008. case Error::MultipartParsing: return "Multipart parsing failed";
  8009. case Error::OpenFile: return "Failed to open file";
  8010. case Error::Listen: return "Failed to listen on socket";
  8011. case Error::GetSockName: return "Failed to get socket name";
  8012. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8013. case Error::HTTPParsing: return "HTTP parsing failed";
  8014. case Error::InvalidRangeHeader: return "Invalid Range header";
  8015. default: break;
  8016. }
  8017. return "Invalid";
  8018. }
  8019. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8020. os << to_string(obj);
  8021. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8022. return os;
  8023. }
  8024. inline std::string hosted_at(const std::string &hostname) {
  8025. std::vector<std::string> addrs;
  8026. hosted_at(hostname, addrs);
  8027. if (addrs.empty()) { return std::string(); }
  8028. return addrs[0];
  8029. }
  8030. inline void hosted_at(const std::string &hostname,
  8031. std::vector<std::string> &addrs) {
  8032. struct addrinfo hints;
  8033. struct addrinfo *result;
  8034. memset(&hints, 0, sizeof(struct addrinfo));
  8035. hints.ai_family = AF_UNSPEC;
  8036. hints.ai_socktype = SOCK_STREAM;
  8037. hints.ai_protocol = 0;
  8038. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8039. &result, 0)) {
  8040. #if defined __linux__ && !defined __ANDROID__
  8041. res_init();
  8042. #endif
  8043. return;
  8044. }
  8045. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8046. for (auto rp = result; rp; rp = rp->ai_next) {
  8047. const auto &addr =
  8048. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8049. std::string ip;
  8050. auto dummy = -1;
  8051. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8052. dummy)) {
  8053. addrs.emplace_back(std::move(ip));
  8054. }
  8055. }
  8056. }
  8057. inline std::string encode_uri_component(const std::string &value) {
  8058. std::ostringstream escaped;
  8059. escaped.fill('0');
  8060. escaped << std::hex;
  8061. for (auto c : value) {
  8062. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8063. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8064. escaped << c;
  8065. } else {
  8066. escaped << std::uppercase;
  8067. escaped << '%' << std::setw(2)
  8068. << static_cast<int>(static_cast<unsigned char>(c));
  8069. escaped << std::nouppercase;
  8070. }
  8071. }
  8072. return escaped.str();
  8073. }
  8074. inline std::string encode_uri(const std::string &value) {
  8075. std::ostringstream escaped;
  8076. escaped.fill('0');
  8077. escaped << std::hex;
  8078. for (auto c : value) {
  8079. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8080. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8081. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8082. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8083. escaped << c;
  8084. } else {
  8085. escaped << std::uppercase;
  8086. escaped << '%' << std::setw(2)
  8087. << static_cast<int>(static_cast<unsigned char>(c));
  8088. escaped << std::nouppercase;
  8089. }
  8090. }
  8091. return escaped.str();
  8092. }
  8093. inline std::string decode_uri_component(const std::string &value) {
  8094. std::string result;
  8095. for (size_t i = 0; i < value.size(); i++) {
  8096. if (value[i] == '%' && i + 2 < value.size()) {
  8097. auto val = 0;
  8098. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8099. result += static_cast<char>(val);
  8100. i += 2;
  8101. } else {
  8102. result += value[i];
  8103. }
  8104. } else {
  8105. result += value[i];
  8106. }
  8107. }
  8108. return result;
  8109. }
  8110. inline std::string decode_uri(const std::string &value) {
  8111. std::string result;
  8112. for (size_t i = 0; i < value.size(); i++) {
  8113. if (value[i] == '%' && i + 2 < value.size()) {
  8114. auto val = 0;
  8115. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8116. result += static_cast<char>(val);
  8117. i += 2;
  8118. } else {
  8119. result += value[i];
  8120. }
  8121. } else {
  8122. result += value[i];
  8123. }
  8124. }
  8125. return result;
  8126. }
  8127. inline std::string encode_path_component(const std::string &component) {
  8128. std::string result;
  8129. result.reserve(component.size() * 3);
  8130. for (size_t i = 0; i < component.size(); i++) {
  8131. auto c = static_cast<unsigned char>(component[i]);
  8132. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8133. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8134. c == '_' || c == '~') {
  8135. result += static_cast<char>(c);
  8136. }
  8137. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8138. // "," / ";" / "="
  8139. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8140. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8141. c == '=') {
  8142. result += static_cast<char>(c);
  8143. }
  8144. // Colon is allowed in path segments except first segment
  8145. else if (c == ':') {
  8146. result += static_cast<char>(c);
  8147. }
  8148. // @ is allowed in path
  8149. else if (c == '@') {
  8150. result += static_cast<char>(c);
  8151. } else {
  8152. result += '%';
  8153. char hex[3];
  8154. snprintf(hex, sizeof(hex), "%02X", c);
  8155. result.append(hex, 2);
  8156. }
  8157. }
  8158. return result;
  8159. }
  8160. inline std::string decode_path_component(const std::string &component) {
  8161. std::string result;
  8162. result.reserve(component.size());
  8163. for (size_t i = 0; i < component.size(); i++) {
  8164. if (component[i] == '%' && i + 1 < component.size()) {
  8165. if (component[i + 1] == 'u') {
  8166. // Unicode %uXXXX encoding
  8167. auto val = 0;
  8168. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8169. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8170. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8171. char buff[4];
  8172. size_t len = detail::to_utf8(val, buff);
  8173. if (len > 0) { result.append(buff, len); }
  8174. i += 5; // 'u0000'
  8175. } else {
  8176. result += component[i];
  8177. }
  8178. } else {
  8179. // Standard %XX encoding
  8180. auto val = 0;
  8181. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8182. // 2 digits hex codes
  8183. result += static_cast<char>(val);
  8184. i += 2; // 'XX'
  8185. } else {
  8186. result += component[i];
  8187. }
  8188. }
  8189. } else {
  8190. result += component[i];
  8191. }
  8192. }
  8193. return result;
  8194. }
  8195. inline std::string encode_query_component(const std::string &component,
  8196. bool space_as_plus) {
  8197. std::string result;
  8198. result.reserve(component.size() * 3);
  8199. for (size_t i = 0; i < component.size(); i++) {
  8200. auto c = static_cast<unsigned char>(component[i]);
  8201. // Unreserved characters per RFC 3986
  8202. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8203. c == '_' || c == '~') {
  8204. result += static_cast<char>(c);
  8205. }
  8206. // Space handling
  8207. else if (c == ' ') {
  8208. if (space_as_plus) {
  8209. result += '+';
  8210. } else {
  8211. result += "%20";
  8212. }
  8213. }
  8214. // Plus sign handling
  8215. else if (c == '+') {
  8216. if (space_as_plus) {
  8217. result += "%2B";
  8218. } else {
  8219. result += static_cast<char>(c);
  8220. }
  8221. }
  8222. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8223. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8224. c == '*' || c == ',' || c == ';') {
  8225. result += static_cast<char>(c);
  8226. }
  8227. // Colon and @ are allowed in query
  8228. else if (c == ':' || c == '@') {
  8229. result += static_cast<char>(c);
  8230. }
  8231. // Forward slash is allowed in query values
  8232. else if (c == '/') {
  8233. result += static_cast<char>(c);
  8234. }
  8235. // Question mark is allowed in query values (after first ?)
  8236. else if (c == '?') {
  8237. result += static_cast<char>(c);
  8238. } else {
  8239. result += '%';
  8240. char hex[3];
  8241. snprintf(hex, sizeof(hex), "%02X", c);
  8242. result.append(hex, 2);
  8243. }
  8244. }
  8245. return result;
  8246. }
  8247. inline std::string decode_query_component(const std::string &component,
  8248. bool plus_as_space) {
  8249. std::string result;
  8250. result.reserve(component.size());
  8251. for (size_t i = 0; i < component.size(); i++) {
  8252. if (component[i] == '%' && i + 2 < component.size()) {
  8253. auto val = 0;
  8254. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8255. result += static_cast<char>(val);
  8256. i += 2;
  8257. } else {
  8258. result += component[i];
  8259. }
  8260. } else if (component[i] == '+' && plus_as_space) {
  8261. result += ' '; // + becomes space in form-urlencoded
  8262. } else {
  8263. result += component[i];
  8264. }
  8265. }
  8266. return result;
  8267. }
  8268. inline std::string sanitize_filename(const std::string &filename) {
  8269. // Extract basename: find the last path separator (/ or \)
  8270. auto pos = filename.find_last_of("/\\");
  8271. auto result =
  8272. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8273. // Strip null bytes
  8274. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8275. // Trim whitespace
  8276. {
  8277. auto start = result.find_first_not_of(" \t");
  8278. auto end = result.find_last_not_of(" \t");
  8279. result = (start == std::string::npos)
  8280. ? ""
  8281. : result.substr(start, end - start + 1);
  8282. }
  8283. // Reject . and ..
  8284. if (result == "." || result == "..") { return ""; }
  8285. return result;
  8286. }
  8287. inline std::string append_query_params(const std::string &path,
  8288. const Params &params) {
  8289. std::string path_with_query = path;
  8290. thread_local const std::regex re("[^?]+\\?.*");
  8291. auto delm = std::regex_match(path, re) ? '&' : '?';
  8292. path_with_query += delm + detail::params_to_query_str(params);
  8293. return path_with_query;
  8294. }
  8295. // Header utilities
  8296. inline std::pair<std::string, std::string>
  8297. make_range_header(const Ranges &ranges) {
  8298. std::string field = "bytes=";
  8299. auto i = 0;
  8300. for (const auto &r : ranges) {
  8301. if (i != 0) { field += ", "; }
  8302. if (r.first != -1) { field += std::to_string(r.first); }
  8303. field += '-';
  8304. if (r.second != -1) { field += std::to_string(r.second); }
  8305. i++;
  8306. }
  8307. return std::make_pair("Range", std::move(field));
  8308. }
  8309. inline std::pair<std::string, std::string>
  8310. make_basic_authentication_header(const std::string &username,
  8311. const std::string &password, bool is_proxy) {
  8312. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8313. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8314. return std::make_pair(key, std::move(field));
  8315. }
  8316. inline std::pair<std::string, std::string>
  8317. make_bearer_token_authentication_header(const std::string &token,
  8318. bool is_proxy = false) {
  8319. auto field = "Bearer " + token;
  8320. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8321. return std::make_pair(key, std::move(field));
  8322. }
  8323. // Request implementation
  8324. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8325. size_t id) const {
  8326. return detail::get_header_value_u64(headers, key, def, id);
  8327. }
  8328. inline bool Request::has_header(const std::string &key) const {
  8329. return detail::has_header(headers, key);
  8330. }
  8331. inline std::string Request::get_header_value(const std::string &key,
  8332. const char *def, size_t id) const {
  8333. return detail::get_header_value(headers, key, def, id);
  8334. }
  8335. inline size_t Request::get_header_value_count(const std::string &key) const {
  8336. return detail::get_header_value_count(headers, key);
  8337. }
  8338. inline void Request::set_header(const std::string &key,
  8339. const std::string &val) {
  8340. detail::set_header(headers, key, val);
  8341. }
  8342. inline bool Request::has_trailer(const std::string &key) const {
  8343. return trailers.find(key) != trailers.end();
  8344. }
  8345. inline std::string Request::get_trailer_value(const std::string &key,
  8346. size_t id) const {
  8347. return detail::get_multimap_value(trailers, key, id);
  8348. }
  8349. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8350. auto r = trailers.equal_range(key);
  8351. return static_cast<size_t>(std::distance(r.first, r.second));
  8352. }
  8353. inline bool Request::has_param(const std::string &key) const {
  8354. return params.find(key) != params.end();
  8355. }
  8356. inline std::string Request::get_param_value(const std::string &key,
  8357. size_t id) const {
  8358. return detail::get_multimap_value(params, key, id);
  8359. }
  8360. inline std::vector<std::string>
  8361. Request::get_param_values(const std::string &key) const {
  8362. auto rng = params.equal_range(key);
  8363. std::vector<std::string> values;
  8364. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8365. for (auto it = rng.first; it != rng.second; ++it) {
  8366. values.push_back(it->second);
  8367. }
  8368. return values;
  8369. }
  8370. inline size_t Request::get_param_value_count(const std::string &key) const {
  8371. auto r = params.equal_range(key);
  8372. return static_cast<size_t>(std::distance(r.first, r.second));
  8373. }
  8374. inline bool Request::is_multipart_form_data() const {
  8375. const auto &content_type = get_header_value("Content-Type");
  8376. return detail::extract_media_type(content_type) == "multipart/form-data";
  8377. }
  8378. // Multipart FormData implementation
  8379. inline std::string MultipartFormData::get_field(const std::string &key,
  8380. size_t id) const {
  8381. auto rng = fields.equal_range(key);
  8382. auto it = rng.first;
  8383. std::advance(it, static_cast<ssize_t>(id));
  8384. if (it != rng.second) { return it->second.content; }
  8385. return std::string();
  8386. }
  8387. inline std::vector<std::string>
  8388. MultipartFormData::get_fields(const std::string &key) const {
  8389. std::vector<std::string> values;
  8390. auto rng = fields.equal_range(key);
  8391. for (auto it = rng.first; it != rng.second; it++) {
  8392. values.push_back(it->second.content);
  8393. }
  8394. return values;
  8395. }
  8396. inline bool MultipartFormData::has_field(const std::string &key) const {
  8397. return fields.find(key) != fields.end();
  8398. }
  8399. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8400. auto r = fields.equal_range(key);
  8401. return static_cast<size_t>(std::distance(r.first, r.second));
  8402. }
  8403. inline FormData MultipartFormData::get_file(const std::string &key,
  8404. size_t id) const {
  8405. return detail::get_multimap_value(files, key, id);
  8406. }
  8407. inline std::vector<FormData>
  8408. MultipartFormData::get_files(const std::string &key) const {
  8409. std::vector<FormData> values;
  8410. auto rng = files.equal_range(key);
  8411. for (auto it = rng.first; it != rng.second; it++) {
  8412. values.push_back(it->second);
  8413. }
  8414. return values;
  8415. }
  8416. inline bool MultipartFormData::has_file(const std::string &key) const {
  8417. return files.find(key) != files.end();
  8418. }
  8419. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8420. auto r = files.equal_range(key);
  8421. return static_cast<size_t>(std::distance(r.first, r.second));
  8422. }
  8423. // Multipart FormData writer implementation
  8424. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8425. return detail::is_multipart_boundary_chars_valid(boundary);
  8426. }
  8427. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8428. : boundary_(detail::make_multipart_data_boundary()) {}
  8429. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8430. : boundary_(std::move(boundary)) {}
  8431. inline const std::string &MultipartFormDataWriter::boundary() const {
  8432. return boundary_;
  8433. }
  8434. inline std::string MultipartFormDataWriter::content_type() const {
  8435. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8436. }
  8437. inline std::string
  8438. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8439. return detail::serialize_multipart_formdata(items, boundary_);
  8440. }
  8441. inline size_t MultipartFormDataWriter::content_length(
  8442. const UploadFormDataItems &items) const {
  8443. return detail::get_multipart_content_length(items, boundary_);
  8444. }
  8445. inline std::string
  8446. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8447. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8448. }
  8449. inline std::string MultipartFormDataWriter::item_end() {
  8450. return detail::serialize_multipart_formdata_item_end();
  8451. }
  8452. inline std::string MultipartFormDataWriter::finish() const {
  8453. return detail::serialize_multipart_formdata_finish(boundary_);
  8454. }
  8455. // Response implementation
  8456. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8457. size_t id) const {
  8458. return detail::get_header_value_u64(headers, key, def, id);
  8459. }
  8460. inline bool Response::has_header(const std::string &key) const {
  8461. return headers.find(key) != headers.end();
  8462. }
  8463. inline std::string Response::get_header_value(const std::string &key,
  8464. const char *def,
  8465. size_t id) const {
  8466. return detail::get_header_value(headers, key, def, id);
  8467. }
  8468. inline size_t Response::get_header_value_count(const std::string &key) const {
  8469. return detail::get_header_value_count(headers, key);
  8470. }
  8471. inline void Response::set_header(const std::string &key,
  8472. const std::string &val) {
  8473. detail::set_header(headers, key, val);
  8474. }
  8475. inline bool Response::has_trailer(const std::string &key) const {
  8476. return trailers.find(key) != trailers.end();
  8477. }
  8478. inline std::string Response::get_trailer_value(const std::string &key,
  8479. size_t id) const {
  8480. return detail::get_multimap_value(trailers, key, id);
  8481. }
  8482. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8483. auto r = trailers.equal_range(key);
  8484. return static_cast<size_t>(std::distance(r.first, r.second));
  8485. }
  8486. inline void Response::set_redirect(const std::string &url, int stat) {
  8487. if (detail::fields::is_field_value(url)) {
  8488. set_header("Location", url);
  8489. if (300 <= stat && stat < 400) {
  8490. this->status = stat;
  8491. } else {
  8492. this->status = StatusCode::Found_302;
  8493. }
  8494. }
  8495. }
  8496. inline void Response::set_content(const char *s, size_t n,
  8497. const std::string &content_type) {
  8498. body.assign(s, n);
  8499. auto rng = headers.equal_range("Content-Type");
  8500. headers.erase(rng.first, rng.second);
  8501. set_header("Content-Type", content_type);
  8502. }
  8503. inline void Response::set_content(const std::string &s,
  8504. const std::string &content_type) {
  8505. set_content(s.data(), s.size(), content_type);
  8506. }
  8507. inline void Response::set_content(std::string &&s,
  8508. const std::string &content_type) {
  8509. body = std::move(s);
  8510. auto rng = headers.equal_range("Content-Type");
  8511. headers.erase(rng.first, rng.second);
  8512. set_header("Content-Type", content_type);
  8513. }
  8514. inline void Response::set_content_provider(
  8515. size_t in_length, const std::string &content_type, ContentProvider provider,
  8516. ContentProviderResourceReleaser resource_releaser) {
  8517. set_header("Content-Type", content_type);
  8518. content_length_ = in_length;
  8519. if (in_length > 0) { content_provider_ = std::move(provider); }
  8520. content_provider_resource_releaser_ = std::move(resource_releaser);
  8521. is_chunked_content_provider_ = false;
  8522. }
  8523. inline void Response::set_content_provider(
  8524. const std::string &content_type, ContentProviderWithoutLength provider,
  8525. ContentProviderResourceReleaser resource_releaser) {
  8526. set_header("Content-Type", content_type);
  8527. content_length_ = 0;
  8528. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8529. content_provider_resource_releaser_ = std::move(resource_releaser);
  8530. is_chunked_content_provider_ = false;
  8531. }
  8532. inline void Response::set_chunked_content_provider(
  8533. const std::string &content_type, ContentProviderWithoutLength provider,
  8534. ContentProviderResourceReleaser resource_releaser) {
  8535. set_header("Content-Type", content_type);
  8536. content_length_ = 0;
  8537. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8538. content_provider_resource_releaser_ = std::move(resource_releaser);
  8539. is_chunked_content_provider_ = true;
  8540. }
  8541. inline void Response::set_file_content(const std::string &path,
  8542. const std::string &content_type) {
  8543. file_content_path_ = path;
  8544. file_content_content_type_ = content_type;
  8545. }
  8546. inline void Response::set_file_content(const std::string &path) {
  8547. file_content_path_ = path;
  8548. }
  8549. // Result implementation
  8550. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8551. size_t def,
  8552. size_t id) const {
  8553. return detail::get_header_value_u64(request_headers_, key, def, id);
  8554. }
  8555. inline bool Result::has_request_header(const std::string &key) const {
  8556. return request_headers_.find(key) != request_headers_.end();
  8557. }
  8558. inline std::string Result::get_request_header_value(const std::string &key,
  8559. const char *def,
  8560. size_t id) const {
  8561. return detail::get_header_value(request_headers_, key, def, id);
  8562. }
  8563. inline size_t
  8564. Result::get_request_header_value_count(const std::string &key) const {
  8565. auto r = request_headers_.equal_range(key);
  8566. return static_cast<size_t>(std::distance(r.first, r.second));
  8567. }
  8568. // Stream implementation
  8569. inline ssize_t Stream::write(const char *ptr) {
  8570. return write(ptr, strlen(ptr));
  8571. }
  8572. inline ssize_t Stream::write(const std::string &s) {
  8573. return write(s.data(), s.size());
  8574. }
  8575. // BodyReader implementation
  8576. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8577. if (!stream) {
  8578. last_error = Error::Connection;
  8579. return -1;
  8580. }
  8581. if (eof) { return 0; }
  8582. if (!chunked) {
  8583. // Content-Length based reading
  8584. if (has_content_length && bytes_read >= content_length) {
  8585. eof = true;
  8586. return 0;
  8587. }
  8588. auto to_read = len;
  8589. if (has_content_length) {
  8590. auto remaining = content_length - bytes_read;
  8591. to_read = (std::min)(len, remaining);
  8592. }
  8593. auto n = stream->read(buf, to_read);
  8594. if (n < 0) {
  8595. last_error = stream->get_error();
  8596. if (last_error == Error::Success) { last_error = Error::Read; }
  8597. eof = true;
  8598. return n;
  8599. }
  8600. if (n == 0) {
  8601. // Unexpected EOF before content_length
  8602. last_error = stream->get_error();
  8603. if (last_error == Error::Success) { last_error = Error::Read; }
  8604. eof = true;
  8605. return 0;
  8606. }
  8607. bytes_read += static_cast<size_t>(n);
  8608. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8609. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8610. last_error = Error::ExceedMaxPayloadSize;
  8611. eof = true;
  8612. return -1;
  8613. }
  8614. return n;
  8615. }
  8616. // Chunked transfer encoding: delegate to shared decoder instance.
  8617. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8618. size_t chunk_offset = 0;
  8619. size_t chunk_total = 0;
  8620. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8621. if (n < 0) {
  8622. last_error = stream->get_error();
  8623. if (last_error == Error::Success) { last_error = Error::Read; }
  8624. eof = true;
  8625. return n;
  8626. }
  8627. if (n == 0) {
  8628. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8629. eof = true;
  8630. return 0;
  8631. }
  8632. bytes_read += static_cast<size_t>(n);
  8633. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8634. last_error = Error::ExceedMaxPayloadSize;
  8635. eof = true;
  8636. return -1;
  8637. }
  8638. return n;
  8639. }
  8640. // ThreadPool implementation
  8641. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8642. time_t idle_timeout_sec)
  8643. : base_thread_count_(n), max_queued_requests_(mqr),
  8644. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8645. shutdown_(false) {
  8646. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8647. if (max_n != 0 && max_n < n) {
  8648. std::string msg = "max_threads must be >= base_threads";
  8649. throw std::invalid_argument(msg);
  8650. }
  8651. #endif
  8652. max_thread_count_ = max_n == 0 ? n : max_n;
  8653. threads_.reserve(base_thread_count_);
  8654. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8655. try {
  8656. #endif
  8657. for (size_t i = 0; i < base_thread_count_; i++) {
  8658. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8659. }
  8660. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8661. } catch (...) {
  8662. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8663. // signal the workers we already spawned to exit and join them so the
  8664. // vector destructor does not see joinable threads (which would call
  8665. // std::terminate). Then rethrow so the caller learns of the failure.
  8666. {
  8667. std::unique_lock<std::mutex> lock(mutex_);
  8668. shutdown_ = true;
  8669. }
  8670. cond_.notify_all();
  8671. for (auto &t : threads_) {
  8672. if (t.joinable()) { t.join(); }
  8673. }
  8674. throw;
  8675. }
  8676. #endif
  8677. }
  8678. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8679. {
  8680. std::unique_lock<std::mutex> lock(mutex_);
  8681. if (shutdown_) { return false; }
  8682. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8683. return false;
  8684. }
  8685. jobs_.push_back(std::move(fn));
  8686. // Spawn a dynamic thread if no idle threads and under max
  8687. if (idle_thread_count_ == 0 &&
  8688. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8689. cleanup_finished_threads();
  8690. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8691. }
  8692. }
  8693. cond_.notify_one();
  8694. return true;
  8695. }
  8696. inline void ThreadPool::shutdown() {
  8697. {
  8698. std::unique_lock<std::mutex> lock(mutex_);
  8699. shutdown_ = true;
  8700. }
  8701. cond_.notify_all();
  8702. for (auto &t : threads_) {
  8703. if (t.joinable()) { t.join(); }
  8704. }
  8705. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8706. // with worker threads that call move_to_finished() concurrently.
  8707. std::list<std::thread> remaining_dynamic;
  8708. {
  8709. std::unique_lock<std::mutex> lock(mutex_);
  8710. remaining_dynamic = std::move(dynamic_threads_);
  8711. }
  8712. for (auto &t : remaining_dynamic) {
  8713. if (t.joinable()) { t.join(); }
  8714. }
  8715. std::unique_lock<std::mutex> lock(mutex_);
  8716. cleanup_finished_threads();
  8717. }
  8718. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8719. // Must be called with mutex_ held
  8720. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8721. if (it->get_id() == id) {
  8722. finished_threads_.push_back(std::move(*it));
  8723. dynamic_threads_.erase(it);
  8724. return;
  8725. }
  8726. }
  8727. }
  8728. inline void ThreadPool::cleanup_finished_threads() {
  8729. // Must be called with mutex_ held
  8730. for (auto &t : finished_threads_) {
  8731. if (t.joinable()) { t.join(); }
  8732. }
  8733. finished_threads_.clear();
  8734. }
  8735. inline void ThreadPool::worker(bool is_dynamic) {
  8736. for (;;) {
  8737. std::function<void()> fn;
  8738. {
  8739. std::unique_lock<std::mutex> lock(mutex_);
  8740. idle_thread_count_++;
  8741. if (is_dynamic) {
  8742. auto has_work =
  8743. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8744. [&] { return !jobs_.empty() || shutdown_; });
  8745. if (!has_work) {
  8746. // Timed out with no work - exit this dynamic thread
  8747. idle_thread_count_--;
  8748. move_to_finished(std::this_thread::get_id());
  8749. break;
  8750. }
  8751. } else {
  8752. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8753. }
  8754. idle_thread_count_--;
  8755. if (shutdown_ && jobs_.empty()) { break; }
  8756. fn = std::move(jobs_.front());
  8757. jobs_.pop_front();
  8758. }
  8759. assert(true == static_cast<bool>(fn));
  8760. fn();
  8761. }
  8762. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8763. !defined(LIBRESSL_VERSION_NUMBER)
  8764. OPENSSL_thread_stop();
  8765. #endif
  8766. }
  8767. /*
  8768. * Group 1 (continued): detail namespace - Stream implementations
  8769. */
  8770. namespace detail {
  8771. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8772. time_t timeout_sec, time_t timeout_usec,
  8773. time_t &actual_timeout_sec,
  8774. time_t &actual_timeout_usec) {
  8775. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8776. auto actual_timeout_msec =
  8777. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8778. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8779. actual_timeout_sec = actual_timeout_msec / 1000;
  8780. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8781. }
  8782. // Socket stream implementation
  8783. inline SocketStream::SocketStream(
  8784. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8785. time_t write_timeout_sec, time_t write_timeout_usec,
  8786. time_t max_timeout_msec,
  8787. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8788. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8789. read_timeout_usec_(read_timeout_usec),
  8790. write_timeout_sec_(write_timeout_sec),
  8791. write_timeout_usec_(write_timeout_usec),
  8792. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8793. read_buff_(read_buff_size_, 0) {}
  8794. inline SocketStream::~SocketStream() = default;
  8795. inline bool SocketStream::is_readable() const {
  8796. return read_buff_off_ < read_buff_content_size_;
  8797. }
  8798. inline bool SocketStream::wait_readable() const {
  8799. if (max_timeout_msec_ <= 0) {
  8800. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8801. }
  8802. time_t read_timeout_sec;
  8803. time_t read_timeout_usec;
  8804. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8805. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8806. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8807. }
  8808. inline bool SocketStream::wait_writable() const {
  8809. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8810. }
  8811. inline bool SocketStream::is_peer_alive() const {
  8812. return detail::is_socket_alive(sock_);
  8813. }
  8814. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8815. #ifdef _WIN32
  8816. size =
  8817. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8818. #else
  8819. size = (std::min)(size,
  8820. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8821. #endif
  8822. if (read_buff_off_ < read_buff_content_size_) {
  8823. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8824. if (size <= remaining_size) {
  8825. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8826. read_buff_off_ += size;
  8827. return static_cast<ssize_t>(size);
  8828. } else {
  8829. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8830. read_buff_off_ += remaining_size;
  8831. return static_cast<ssize_t>(remaining_size);
  8832. }
  8833. }
  8834. if (!wait_readable()) {
  8835. error_ = Error::Timeout;
  8836. return -1;
  8837. }
  8838. read_buff_off_ = 0;
  8839. read_buff_content_size_ = 0;
  8840. if (size < read_buff_size_) {
  8841. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8842. CPPHTTPLIB_RECV_FLAGS);
  8843. if (n <= 0) {
  8844. if (n == 0) {
  8845. error_ = Error::ConnectionClosed;
  8846. } else {
  8847. error_ = Error::Read;
  8848. }
  8849. return n;
  8850. } else if (n <= static_cast<ssize_t>(size)) {
  8851. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8852. return n;
  8853. } else {
  8854. memcpy(ptr, read_buff_.data(), size);
  8855. read_buff_off_ = size;
  8856. read_buff_content_size_ = static_cast<size_t>(n);
  8857. return static_cast<ssize_t>(size);
  8858. }
  8859. } else {
  8860. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8861. if (n <= 0) {
  8862. if (n == 0) {
  8863. error_ = Error::ConnectionClosed;
  8864. } else {
  8865. error_ = Error::Read;
  8866. }
  8867. }
  8868. return n;
  8869. }
  8870. }
  8871. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8872. if (!wait_writable()) { return -1; }
  8873. #if defined(_WIN32) && !defined(_WIN64)
  8874. size =
  8875. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8876. #endif
  8877. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8878. }
  8879. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8880. int &port) const {
  8881. return detail::get_remote_ip_and_port(sock_, ip, port);
  8882. }
  8883. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8884. int &port) const {
  8885. return detail::get_local_ip_and_port(sock_, ip, port);
  8886. }
  8887. inline socket_t SocketStream::socket() const { return sock_; }
  8888. inline time_t SocketStream::duration() const {
  8889. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8890. std::chrono::steady_clock::now() - start_time_)
  8891. .count();
  8892. }
  8893. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8894. read_timeout_sec_ = sec;
  8895. read_timeout_usec_ = usec;
  8896. }
  8897. // Buffer stream implementation
  8898. inline bool BufferStream::is_readable() const { return true; }
  8899. inline bool BufferStream::wait_readable() const { return true; }
  8900. inline bool BufferStream::wait_writable() const { return true; }
  8901. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8902. #if defined(_MSC_VER) && _MSC_VER < 1910
  8903. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8904. #else
  8905. auto len_read = buffer.copy(ptr, size, position);
  8906. #endif
  8907. position += static_cast<size_t>(len_read);
  8908. return static_cast<ssize_t>(len_read);
  8909. }
  8910. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8911. buffer.append(ptr, size);
  8912. return static_cast<ssize_t>(size);
  8913. }
  8914. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8915. int & /*port*/) const {}
  8916. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8917. int & /*port*/) const {}
  8918. inline socket_t BufferStream::socket() const { return 0; }
  8919. inline time_t BufferStream::duration() const { return 0; }
  8920. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8921. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8922. : MatcherBase(pattern) {
  8923. constexpr const char marker[] = "/:";
  8924. // One past the last ending position of a path param substring
  8925. std::size_t last_param_end = 0;
  8926. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8927. // Needed to ensure that parameter names are unique during matcher
  8928. // construction
  8929. // If exceptions are disabled, only last duplicate path
  8930. // parameter will be set
  8931. std::unordered_set<std::string> param_name_set;
  8932. #endif
  8933. while (true) {
  8934. const auto marker_pos = pattern.find(
  8935. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8936. if (marker_pos == std::string::npos) { break; }
  8937. static_fragments_.push_back(
  8938. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8939. const auto param_name_start = marker_pos + str_len(marker);
  8940. auto sep_pos = pattern.find(separator, param_name_start);
  8941. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8942. auto param_name =
  8943. pattern.substr(param_name_start, sep_pos - param_name_start);
  8944. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8945. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8946. std::string msg = "Encountered path parameter '" + param_name +
  8947. "' multiple times in route pattern '" + pattern + "'.";
  8948. throw std::invalid_argument(msg);
  8949. }
  8950. #endif
  8951. param_names_.push_back(std::move(param_name));
  8952. last_param_end = sep_pos + 1;
  8953. }
  8954. if (last_param_end < pattern.length()) {
  8955. static_fragments_.push_back(pattern.substr(last_param_end));
  8956. }
  8957. }
  8958. inline bool PathParamsMatcher::match(Request &request) const {
  8959. request.matches = std::smatch();
  8960. request.path_params.clear();
  8961. request.path_params.reserve(param_names_.size());
  8962. // One past the position at which the path matched the pattern last time
  8963. std::size_t starting_pos = 0;
  8964. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8965. const auto &fragment = static_fragments_[i];
  8966. if (starting_pos + fragment.length() > request.path.length()) {
  8967. return false;
  8968. }
  8969. // Avoid unnecessary allocation by using strncmp instead of substr +
  8970. // comparison
  8971. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8972. fragment.length()) != 0) {
  8973. return false;
  8974. }
  8975. starting_pos += fragment.length();
  8976. // Should only happen when we have a static fragment after a param
  8977. // Example: '/users/:id/subscriptions'
  8978. // The 'subscriptions' fragment here does not have a corresponding param
  8979. if (i >= param_names_.size()) { continue; }
  8980. auto sep_pos = request.path.find(separator, starting_pos);
  8981. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8982. const auto &param_name = param_names_[i];
  8983. request.path_params.emplace(
  8984. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8985. // Mark everything up to '/' as matched
  8986. starting_pos = sep_pos + 1;
  8987. }
  8988. // Returns false if the path is longer than the pattern
  8989. return starting_pos >= request.path.length();
  8990. }
  8991. inline bool RegexMatcher::match(Request &request) const {
  8992. request.path_params.clear();
  8993. return std::regex_match(request.path, request.matches, regex_);
  8994. }
  8995. // Enclose IPv6 address in brackets if needed
  8996. inline std::string prepare_host_string(const std::string &host) {
  8997. // Enclose IPv6 address in brackets (but not if already enclosed)
  8998. if (host.find(':') == std::string::npos ||
  8999. (!host.empty() && host[0] == '[')) {
  9000. // IPv4, hostname, or already bracketed IPv6
  9001. return host;
  9002. } else {
  9003. // IPv6 address without brackets
  9004. return "[" + host + "]";
  9005. }
  9006. }
  9007. inline std::string make_host_and_port_string(const std::string &host, int port,
  9008. bool is_ssl) {
  9009. auto result = prepare_host_string(host);
  9010. // Append port if not default
  9011. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9012. ; // do nothing
  9013. } else {
  9014. result += ":" + std::to_string(port);
  9015. }
  9016. return result;
  9017. }
  9018. // Create "host:port" string always including port number (for CONNECT method)
  9019. inline std::string
  9020. make_host_and_port_string_always_port(const std::string &host, int port) {
  9021. return prepare_host_string(host) + ":" + std::to_string(port);
  9022. }
  9023. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9024. NormalizedTarget normalize_target(const std::string &host);
  9025. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9026. bool host_matches_no_proxy(const NormalizedTarget &target,
  9027. const std::vector<NoProxyEntry> &entries);
  9028. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9029. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9030. if (prefix_bits == 0) { return true; }
  9031. int full_bytes = prefix_bits / 8;
  9032. int rem_bits = prefix_bits % 8;
  9033. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9034. static_cast<size_t>(full_bytes)) != 0) {
  9035. return false;
  9036. }
  9037. if (rem_bits == 0) { return true; }
  9038. auto i = static_cast<size_t>(full_bytes);
  9039. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9040. return (ip[i] & mask) == (net[i] & mask);
  9041. }
  9042. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9043. if (token.empty()) { return false; }
  9044. if (token == "*") {
  9045. out.kind = NoProxyKind::Wildcard;
  9046. return true;
  9047. }
  9048. auto slash = token.find('/');
  9049. std::string addr_part =
  9050. (slash == std::string::npos) ? token : token.substr(0, slash);
  9051. std::string prefix_part =
  9052. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9053. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9054. // don't silently treat it as a /32 (or /128).
  9055. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9056. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9057. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9058. // when brackets are present.
  9059. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9060. addr_part.back() == ']';
  9061. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9062. if (!bracketed) {
  9063. struct in_addr v4;
  9064. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9065. int prefix = 32;
  9066. if (!prefix_part.empty()) {
  9067. auto r = from_chars(prefix_part.data(),
  9068. prefix_part.data() + prefix_part.size(), prefix);
  9069. if (r.ec != std::errc{} ||
  9070. r.ptr != prefix_part.data() + prefix_part.size()) {
  9071. return false;
  9072. }
  9073. if (prefix < 0 || prefix > 32) { return false; }
  9074. }
  9075. out.kind = NoProxyKind::IPv4Cidr;
  9076. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9077. out.prefix_bits = prefix;
  9078. return true;
  9079. }
  9080. }
  9081. struct in6_addr v6;
  9082. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9083. int prefix = 128;
  9084. if (!prefix_part.empty()) {
  9085. auto r = from_chars(prefix_part.data(),
  9086. prefix_part.data() + prefix_part.size(), prefix);
  9087. if (r.ec != std::errc{} ||
  9088. r.ptr != prefix_part.data() + prefix_part.size()) {
  9089. return false;
  9090. }
  9091. if (prefix < 0 || prefix > 128) { return false; }
  9092. }
  9093. out.kind = NoProxyKind::IPv6Cidr;
  9094. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9095. out.prefix_bits = prefix;
  9096. return true;
  9097. }
  9098. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9099. // the entry is malformed — don't fall through to the hostname branch.
  9100. if (bracketed) { return false; }
  9101. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9102. if (slash != std::string::npos) { return false; }
  9103. // Port-specific entries (host:port) are not supported.
  9104. if (token.find(':') != std::string::npos) { return false; }
  9105. std::string hostname = case_ignore::to_lower(token);
  9106. while (!hostname.empty() && hostname.front() == '.') {
  9107. hostname.erase(hostname.begin());
  9108. }
  9109. while (!hostname.empty() && hostname.back() == '.') {
  9110. hostname.pop_back();
  9111. }
  9112. if (hostname.empty()) { return false; }
  9113. out.kind = NoProxyKind::HostnameSuffix;
  9114. out.hostname_pattern = std::move(hostname);
  9115. return true;
  9116. }
  9117. inline NormalizedTarget normalize_target(const std::string &host) {
  9118. NormalizedTarget t;
  9119. std::string h = host;
  9120. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9121. h = h.substr(1, h.size() - 2);
  9122. }
  9123. // Strip a single trailing dot so "example.com." canonicalizes to
  9124. // "example.com".
  9125. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9126. t.hostname = case_ignore::to_lower(h);
  9127. if (!t.hostname.empty()) {
  9128. struct in_addr v4;
  9129. struct in6_addr v6;
  9130. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9131. t.is_ipv4 = true;
  9132. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9133. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9134. t.is_ipv6 = true;
  9135. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9136. }
  9137. }
  9138. return t;
  9139. }
  9140. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9141. const std::vector<NoProxyEntry> &entries) {
  9142. if (target.hostname.empty()) { return false; }
  9143. for (const auto &e : entries) {
  9144. switch (e.kind) {
  9145. case NoProxyKind::Wildcard: return true;
  9146. case NoProxyKind::IPv4Cidr:
  9147. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9148. return true;
  9149. }
  9150. break;
  9151. case NoProxyKind::IPv6Cidr:
  9152. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9153. return true;
  9154. }
  9155. break;
  9156. case NoProxyKind::HostnameSuffix:
  9157. if (target.is_ipv4 || target.is_ipv6) { break; }
  9158. if (target.hostname == e.hostname_pattern) { return true; }
  9159. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9160. // an entry of "example.com".
  9161. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9162. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9163. if (target.hostname[offset - 1] == '.' &&
  9164. target.hostname.compare(offset, e.hostname_pattern.size(),
  9165. e.hostname_pattern) == 0) {
  9166. return true;
  9167. }
  9168. }
  9169. break;
  9170. }
  9171. }
  9172. return false;
  9173. }
  9174. template <typename T>
  9175. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9176. T header_writer, Error &error) {
  9177. for (const auto &h : headers) {
  9178. if (!detail::fields::is_field_name(h.first) ||
  9179. !detail::fields::is_field_value(h.second)) {
  9180. error = Error::InvalidHeaders;
  9181. return false;
  9182. }
  9183. }
  9184. if (header_writer(strm, headers) <= 0) {
  9185. error = Error::Write;
  9186. return false;
  9187. }
  9188. return true;
  9189. }
  9190. } // namespace detail
  9191. /*
  9192. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9193. */
  9194. #ifdef CPPHTTPLIB_SSL_ENABLED
  9195. namespace detail {
  9196. // SSL socket stream implementation
  9197. inline SSLSocketStream::SSLSocketStream(
  9198. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9199. time_t read_timeout_usec, time_t write_timeout_sec,
  9200. time_t write_timeout_usec, time_t max_timeout_msec,
  9201. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9202. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9203. read_timeout_usec_(read_timeout_usec),
  9204. write_timeout_sec_(write_timeout_sec),
  9205. write_timeout_usec_(write_timeout_usec),
  9206. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9207. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9208. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9209. // Note: create_session() also clears this, but SSLClient currently
  9210. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9211. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9212. // SSL session was created.
  9213. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9214. #endif
  9215. }
  9216. inline SSLSocketStream::~SSLSocketStream() = default;
  9217. inline bool SSLSocketStream::is_readable() const {
  9218. return tls::pending(session_) > 0;
  9219. }
  9220. inline bool SSLSocketStream::wait_readable() const {
  9221. if (max_timeout_msec_ <= 0) {
  9222. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9223. }
  9224. time_t read_timeout_sec;
  9225. time_t read_timeout_usec;
  9226. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9227. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9228. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9229. }
  9230. inline bool SSLSocketStream::wait_writable() const {
  9231. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9232. !tls::is_peer_closed(session_, sock_);
  9233. }
  9234. inline bool SSLSocketStream::is_peer_alive() const {
  9235. return !tls::is_peer_closed(session_, sock_);
  9236. }
  9237. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9238. if (tls::pending(session_) > 0) {
  9239. tls::TlsError err;
  9240. auto ret = tls::read(session_, ptr, size, err);
  9241. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9242. error_ = Error::ConnectionClosed;
  9243. }
  9244. return ret;
  9245. } else if (wait_readable()) {
  9246. tls::TlsError err;
  9247. auto ret = tls::read(session_, ptr, size, err);
  9248. if (ret < 0) {
  9249. auto n = 1000;
  9250. #ifdef _WIN32
  9251. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9252. (err.code == tls::ErrorCode::SyscallError &&
  9253. WSAGetLastError() == WSAETIMEDOUT))) {
  9254. #else
  9255. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9256. #endif
  9257. if (tls::pending(session_) > 0) {
  9258. return tls::read(session_, ptr, size, err);
  9259. } else if (wait_readable()) {
  9260. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9261. ret = tls::read(session_, ptr, size, err);
  9262. if (ret >= 0) { return ret; }
  9263. } else {
  9264. break;
  9265. }
  9266. }
  9267. assert(ret < 0);
  9268. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9269. error_ = Error::ConnectionClosed;
  9270. }
  9271. return ret;
  9272. } else {
  9273. error_ = Error::Timeout;
  9274. return -1;
  9275. }
  9276. }
  9277. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9278. if (wait_writable()) {
  9279. auto handle_size =
  9280. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9281. tls::TlsError err;
  9282. auto ret = tls::write(session_, ptr, handle_size, err);
  9283. if (ret < 0) {
  9284. auto n = 1000;
  9285. #ifdef _WIN32
  9286. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9287. (err.code == tls::ErrorCode::SyscallError &&
  9288. WSAGetLastError() == WSAETIMEDOUT))) {
  9289. #else
  9290. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9291. #endif
  9292. if (wait_writable()) {
  9293. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9294. ret = tls::write(session_, ptr, handle_size, err);
  9295. if (ret >= 0) { return ret; }
  9296. } else {
  9297. break;
  9298. }
  9299. }
  9300. assert(ret < 0);
  9301. }
  9302. return ret;
  9303. }
  9304. return -1;
  9305. }
  9306. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9307. int &port) const {
  9308. detail::get_remote_ip_and_port(sock_, ip, port);
  9309. }
  9310. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9311. int &port) const {
  9312. detail::get_local_ip_and_port(sock_, ip, port);
  9313. }
  9314. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9315. inline time_t SSLSocketStream::duration() const {
  9316. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9317. std::chrono::steady_clock::now() - start_time_)
  9318. .count();
  9319. }
  9320. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9321. read_timeout_sec_ = sec;
  9322. read_timeout_usec_ = usec;
  9323. }
  9324. } // namespace detail
  9325. #endif // CPPHTTPLIB_SSL_ENABLED
  9326. /*
  9327. * Group 4: Server implementation
  9328. */
  9329. // HTTP server implementation
  9330. inline Server::Server()
  9331. : new_task_queue([] {
  9332. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9333. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9334. }) {
  9335. #ifndef _WIN32
  9336. signal(SIGPIPE, SIG_IGN);
  9337. #endif
  9338. }
  9339. inline Server::~Server() = default;
  9340. inline std::unique_ptr<detail::MatcherBase>
  9341. Server::make_matcher(const std::string &pattern) {
  9342. if (pattern.find("/:") != std::string::npos) {
  9343. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9344. } else {
  9345. return detail::make_unique<detail::RegexMatcher>(pattern);
  9346. }
  9347. }
  9348. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9349. return add_handler(get_handlers_, pattern, std::move(handler));
  9350. }
  9351. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9352. return add_handler(post_handlers_, pattern, std::move(handler));
  9353. }
  9354. inline Server &Server::Post(const std::string &pattern,
  9355. HandlerWithContentReader handler) {
  9356. return add_handler(post_handlers_for_content_reader_, pattern,
  9357. std::move(handler));
  9358. }
  9359. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9360. return add_handler(put_handlers_, pattern, std::move(handler));
  9361. }
  9362. inline Server &Server::Put(const std::string &pattern,
  9363. HandlerWithContentReader handler) {
  9364. return add_handler(put_handlers_for_content_reader_, pattern,
  9365. std::move(handler));
  9366. }
  9367. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9368. return add_handler(patch_handlers_, pattern, std::move(handler));
  9369. }
  9370. inline Server &Server::Patch(const std::string &pattern,
  9371. HandlerWithContentReader handler) {
  9372. return add_handler(patch_handlers_for_content_reader_, pattern,
  9373. std::move(handler));
  9374. }
  9375. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9376. return add_handler(delete_handlers_, pattern, std::move(handler));
  9377. }
  9378. inline Server &Server::Delete(const std::string &pattern,
  9379. HandlerWithContentReader handler) {
  9380. return add_handler(delete_handlers_for_content_reader_, pattern,
  9381. std::move(handler));
  9382. }
  9383. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9384. return add_handler(options_handlers_, pattern, std::move(handler));
  9385. }
  9386. inline Server &Server::WebSocket(const std::string &pattern,
  9387. WebSocketHandler handler) {
  9388. websocket_handlers_.push_back(
  9389. {make_matcher(pattern), std::move(handler), nullptr});
  9390. return *this;
  9391. }
  9392. inline Server &Server::WebSocket(const std::string &pattern,
  9393. WebSocketHandler handler,
  9394. SubProtocolSelector sub_protocol_selector) {
  9395. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9396. std::move(sub_protocol_selector)});
  9397. return *this;
  9398. }
  9399. inline bool Server::set_base_dir(const std::string &dir,
  9400. const std::string &mount_point) {
  9401. return set_mount_point(mount_point, dir);
  9402. }
  9403. inline bool Server::set_mount_point(const std::string &mount_point,
  9404. const std::string &dir, Headers headers) {
  9405. detail::FileStat stat(dir);
  9406. if (stat.is_dir()) {
  9407. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9408. if (!mnt.empty() && mnt[0] == '/') {
  9409. std::string resolved_base;
  9410. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9411. #if defined(_WIN32)
  9412. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9413. resolved_base += '\\';
  9414. }
  9415. #else
  9416. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9417. #endif
  9418. }
  9419. base_dirs_.push_back(
  9420. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9421. return true;
  9422. }
  9423. }
  9424. return false;
  9425. }
  9426. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9427. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9428. if (it->mount_point == mount_point) {
  9429. base_dirs_.erase(it);
  9430. return true;
  9431. }
  9432. }
  9433. return false;
  9434. }
  9435. inline Server &
  9436. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9437. const std::string &mime) {
  9438. file_extension_and_mimetype_map_[ext] = mime;
  9439. return *this;
  9440. }
  9441. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9442. default_file_mimetype_ = mime;
  9443. return *this;
  9444. }
  9445. inline Server &Server::set_file_request_handler(Handler handler) {
  9446. file_request_handler_ = std::move(handler);
  9447. return *this;
  9448. }
  9449. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9450. std::true_type) {
  9451. error_handler_ = std::move(handler);
  9452. return *this;
  9453. }
  9454. inline Server &Server::set_error_handler_core(Handler handler,
  9455. std::false_type) {
  9456. error_handler_ = [handler](const Request &req, Response &res) {
  9457. handler(req, res);
  9458. return HandlerResponse::Handled;
  9459. };
  9460. return *this;
  9461. }
  9462. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9463. exception_handler_ = std::move(handler);
  9464. return *this;
  9465. }
  9466. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9467. pre_routing_handler_ = std::move(handler);
  9468. return *this;
  9469. }
  9470. inline Server &Server::set_post_routing_handler(Handler handler) {
  9471. post_routing_handler_ = std::move(handler);
  9472. return *this;
  9473. }
  9474. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9475. pre_request_handler_ = std::move(handler);
  9476. return *this;
  9477. }
  9478. inline Server &Server::set_logger(Logger logger) {
  9479. logger_ = std::move(logger);
  9480. return *this;
  9481. }
  9482. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9483. error_logger_ = std::move(error_logger);
  9484. return *this;
  9485. }
  9486. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9487. pre_compression_logger_ = std::move(logger);
  9488. return *this;
  9489. }
  9490. inline Server &
  9491. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9492. expect_100_continue_handler_ = std::move(handler);
  9493. return *this;
  9494. }
  9495. inline Server &Server::set_start_handler(StartHandler handler) {
  9496. start_handler_ = std::move(handler);
  9497. return *this;
  9498. }
  9499. inline Server &Server::set_address_family(int family) {
  9500. address_family_ = family;
  9501. return *this;
  9502. }
  9503. inline Server &Server::set_tcp_nodelay(bool on) {
  9504. tcp_nodelay_ = on;
  9505. return *this;
  9506. }
  9507. inline Server &Server::set_ipv6_v6only(bool on) {
  9508. ipv6_v6only_ = on;
  9509. return *this;
  9510. }
  9511. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9512. socket_options_ = std::move(socket_options);
  9513. return *this;
  9514. }
  9515. inline Server &Server::set_default_headers(Headers headers) {
  9516. default_headers_ = std::move(headers);
  9517. return *this;
  9518. }
  9519. inline Server &Server::set_header_writer(
  9520. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9521. header_writer_ = writer;
  9522. return *this;
  9523. }
  9524. inline Server &
  9525. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9526. trusted_proxies_ = proxies;
  9527. return *this;
  9528. }
  9529. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9530. keep_alive_max_count_ = count;
  9531. return *this;
  9532. }
  9533. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9534. keep_alive_timeout_sec_ = sec;
  9535. return *this;
  9536. }
  9537. template <class Rep, class Period>
  9538. inline Server &Server::set_keep_alive_timeout(
  9539. const std::chrono::duration<Rep, Period> &duration) {
  9540. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9541. set_keep_alive_timeout(sec);
  9542. });
  9543. return *this;
  9544. }
  9545. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9546. read_timeout_sec_ = sec;
  9547. read_timeout_usec_ = usec;
  9548. return *this;
  9549. }
  9550. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9551. write_timeout_sec_ = sec;
  9552. write_timeout_usec_ = usec;
  9553. return *this;
  9554. }
  9555. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9556. idle_interval_sec_ = sec;
  9557. idle_interval_usec_ = usec;
  9558. return *this;
  9559. }
  9560. inline Server &Server::set_payload_max_length(size_t length) {
  9561. payload_max_length_ = length;
  9562. return *this;
  9563. }
  9564. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9565. websocket_max_missed_pongs_ = count;
  9566. return *this;
  9567. }
  9568. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9569. websocket_ping_interval_sec_ = sec;
  9570. return *this;
  9571. }
  9572. template <class Rep, class Period>
  9573. inline Server &Server::set_websocket_ping_interval(
  9574. const std::chrono::duration<Rep, Period> &duration) {
  9575. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9576. set_websocket_ping_interval(sec);
  9577. });
  9578. return *this;
  9579. }
  9580. inline bool Server::bind_to_port(const std::string &host, int port,
  9581. int socket_flags) {
  9582. auto ret = bind_internal(host, port, socket_flags);
  9583. if (ret == -1) { is_decommissioned = true; }
  9584. return ret >= 0;
  9585. }
  9586. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9587. auto ret = bind_internal(host, 0, socket_flags);
  9588. if (ret == -1) { is_decommissioned = true; }
  9589. return ret;
  9590. }
  9591. inline bool Server::listen_after_bind() { return listen_internal(); }
  9592. inline bool Server::listen(const std::string &host, int port,
  9593. int socket_flags) {
  9594. return bind_to_port(host, port, socket_flags) && listen_internal();
  9595. }
  9596. inline bool Server::is_running() const { return is_running_; }
  9597. inline void Server::wait_until_ready() const {
  9598. while (!is_running_ && !is_decommissioned) {
  9599. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9600. }
  9601. }
  9602. inline void Server::stop() noexcept {
  9603. if (is_running_) {
  9604. assert(svr_sock_ != INVALID_SOCKET);
  9605. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9606. detail::shutdown_socket(sock);
  9607. detail::close_socket(sock);
  9608. }
  9609. is_decommissioned = false;
  9610. }
  9611. inline void Server::decommission() { is_decommissioned = true; }
  9612. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9613. auto len = strlen(s);
  9614. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9615. len -= 2;
  9616. {
  9617. size_t count = 0;
  9618. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9619. switch (count) {
  9620. case 0: req.method = std::string(b, e); break;
  9621. case 1: req.target = std::string(b, e); break;
  9622. case 2: req.version = std::string(b, e); break;
  9623. default: break;
  9624. }
  9625. count++;
  9626. });
  9627. if (count != 3) { return false; }
  9628. }
  9629. thread_local const std::set<std::string> methods{
  9630. "GET", "HEAD", "POST", "PUT", "DELETE",
  9631. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9632. if (methods.find(req.method) == methods.end()) {
  9633. output_error_log(Error::InvalidHTTPMethod, &req);
  9634. return false;
  9635. }
  9636. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9637. output_error_log(Error::InvalidHTTPVersion, &req);
  9638. return false;
  9639. }
  9640. {
  9641. // Skip URL fragment
  9642. for (size_t i = 0; i < req.target.size(); i++) {
  9643. if (req.target[i] == '#') {
  9644. req.target.erase(i);
  9645. break;
  9646. }
  9647. }
  9648. detail::divide(req.target, '?',
  9649. [&](const char *lhs_data, std::size_t lhs_size,
  9650. const char *rhs_data, std::size_t rhs_size) {
  9651. req.path =
  9652. decode_path_component(std::string(lhs_data, lhs_size));
  9653. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9654. });
  9655. }
  9656. return true;
  9657. }
  9658. inline bool Server::write_response(Stream &strm, bool close_connection,
  9659. Request &req, Response &res) {
  9660. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9661. // incorrectly to the error content.
  9662. req.ranges.clear();
  9663. return write_response_core(strm, close_connection, req, res, false);
  9664. }
  9665. inline bool Server::write_response_with_content(Stream &strm,
  9666. bool close_connection,
  9667. const Request &req,
  9668. Response &res) {
  9669. return write_response_core(strm, close_connection, req, res, true);
  9670. }
  9671. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9672. const Request &req, Response &res,
  9673. bool need_apply_ranges) {
  9674. assert(res.status != -1);
  9675. if (400 <= res.status && error_handler_ &&
  9676. error_handler_(req, res) == HandlerResponse::Handled) {
  9677. need_apply_ranges = true;
  9678. }
  9679. std::string content_type;
  9680. std::string boundary;
  9681. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9682. // Prepare additional headers
  9683. if (close_connection || req.get_header_value("Connection") == "close" ||
  9684. 400 <= res.status) { // Don't leave connections open after errors
  9685. res.set_header("Connection", "close");
  9686. } else {
  9687. std::string s = "timeout=";
  9688. s += std::to_string(keep_alive_timeout_sec_);
  9689. s += ", max=";
  9690. s += std::to_string(keep_alive_max_count_);
  9691. res.set_header("Keep-Alive", s);
  9692. }
  9693. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9694. !res.has_header("Content-Type")) {
  9695. res.set_header("Content-Type", "text/plain");
  9696. }
  9697. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9698. !res.has_header("Content-Length")) {
  9699. res.set_header("Content-Length", "0");
  9700. }
  9701. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9702. res.set_header("Accept-Ranges", "bytes");
  9703. }
  9704. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9705. // Response line and headers
  9706. detail::BufferStream bstrm;
  9707. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9708. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9709. // Combine small body with headers to reduce write syscalls
  9710. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9711. bstrm.write(res.body.data(), res.body.size());
  9712. }
  9713. // Log before writing to avoid race condition with client-side code that
  9714. // accesses logger-captured data immediately after receiving the response.
  9715. output_log(req, res);
  9716. // Flush buffer
  9717. auto &data = bstrm.get_buffer();
  9718. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9719. // Streaming body
  9720. auto ret = true;
  9721. if (req.method != "HEAD" && res.content_provider_) {
  9722. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9723. res.content_provider_success_ = true;
  9724. } else {
  9725. ret = false;
  9726. }
  9727. }
  9728. return ret;
  9729. }
  9730. inline bool
  9731. Server::write_content_with_provider(Stream &strm, const Request &req,
  9732. Response &res, const std::string &boundary,
  9733. const std::string &content_type) {
  9734. auto is_shutting_down = [this]() {
  9735. return this->svr_sock_ == INVALID_SOCKET;
  9736. };
  9737. if (res.content_length_ > 0) {
  9738. if (req.ranges.empty()) {
  9739. return detail::write_content(strm, res.content_provider_, 0,
  9740. res.content_length_, is_shutting_down);
  9741. } else if (req.ranges.size() == 1) {
  9742. auto offset_and_length = detail::get_range_offset_and_length(
  9743. req.ranges[0], res.content_length_);
  9744. return detail::write_content(strm, res.content_provider_,
  9745. offset_and_length.first,
  9746. offset_and_length.second, is_shutting_down);
  9747. } else {
  9748. return detail::write_multipart_ranges_data(
  9749. strm, req, res, boundary, content_type, res.content_length_,
  9750. is_shutting_down);
  9751. }
  9752. } else {
  9753. if (res.is_chunked_content_provider_) {
  9754. auto type = detail::encoding_type(req, res);
  9755. auto compressor = detail::make_compressor(type);
  9756. if (!compressor) {
  9757. compressor = detail::make_unique<detail::nocompressor>();
  9758. }
  9759. return detail::write_content_chunked(strm, res.content_provider_,
  9760. is_shutting_down, *compressor);
  9761. } else {
  9762. return detail::write_content_without_length(strm, res.content_provider_,
  9763. is_shutting_down);
  9764. }
  9765. }
  9766. }
  9767. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9768. FormFields::iterator cur_field;
  9769. FormFiles::iterator cur_file;
  9770. auto is_text_field = false;
  9771. size_t count = 0;
  9772. if (read_content_core(
  9773. strm, req, res,
  9774. // Regular
  9775. [&](const char *buf, size_t n) {
  9776. // Prevent arithmetic overflow when checking sizes.
  9777. // Avoid computing (req.body.size() + n) directly because
  9778. // adding two unsigned `size_t` values can wrap around and
  9779. // produce a small result instead of indicating overflow.
  9780. // Instead, check using subtraction: ensure `n` does not
  9781. // exceed the remaining capacity `max_size() - size()`.
  9782. if (req.body.size() >= req.body.max_size() ||
  9783. n > req.body.max_size() - req.body.size()) {
  9784. return false;
  9785. }
  9786. // Limit decompressed body size to payload_max_length_ to protect
  9787. // against "zip bomb" attacks where a small compressed payload
  9788. // decompresses to a massive size.
  9789. if (payload_max_length_ > 0 &&
  9790. (req.body.size() >= payload_max_length_ ||
  9791. n > payload_max_length_ - req.body.size())) {
  9792. return false;
  9793. }
  9794. req.body.append(buf, n);
  9795. return true;
  9796. },
  9797. // Multipart FormData
  9798. [&](const FormData &file) {
  9799. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9800. output_error_log(Error::TooManyFormDataFiles, &req);
  9801. return false;
  9802. }
  9803. if (file.filename.empty()) {
  9804. cur_field = req.form.fields.emplace(
  9805. file.name, FormField{file.name, file.content, file.headers});
  9806. is_text_field = true;
  9807. } else {
  9808. cur_file = req.form.files.emplace(file.name, file);
  9809. is_text_field = false;
  9810. }
  9811. return true;
  9812. },
  9813. [&](const char *buf, size_t n) {
  9814. if (is_text_field) {
  9815. auto &content = cur_field->second.content;
  9816. if (content.size() + n > content.max_size()) { return false; }
  9817. content.append(buf, n);
  9818. } else {
  9819. auto &content = cur_file->second.content;
  9820. if (content.size() + n > content.max_size()) { return false; }
  9821. content.append(buf, n);
  9822. }
  9823. return true;
  9824. })) {
  9825. const auto &content_type = req.get_header_value("Content-Type");
  9826. if (detail::extract_media_type(content_type) ==
  9827. "application/x-www-form-urlencoded") {
  9828. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9829. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9830. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9831. return false;
  9832. }
  9833. detail::parse_query_text(req.body, req.params);
  9834. }
  9835. return true;
  9836. }
  9837. return false;
  9838. }
  9839. inline bool Server::read_content_with_content_receiver(
  9840. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9841. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9842. return read_content_core(strm, req, res, std::move(receiver),
  9843. std::move(multipart_header),
  9844. std::move(multipart_receiver));
  9845. }
  9846. inline bool Server::read_content_core(
  9847. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9848. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9849. detail::FormDataParser multipart_form_data_parser;
  9850. ContentReceiverWithProgress out;
  9851. if (req.is_multipart_form_data()) {
  9852. const auto &content_type = req.get_header_value("Content-Type");
  9853. std::string boundary;
  9854. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9855. res.status = StatusCode::BadRequest_400;
  9856. output_error_log(Error::MultipartParsing, &req);
  9857. return false;
  9858. }
  9859. multipart_form_data_parser.set_boundary(std::move(boundary));
  9860. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9861. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9862. multipart_receiver);
  9863. };
  9864. } else {
  9865. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9866. size_t /*len*/) { return receiver(buf, n); };
  9867. }
  9868. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9869. // For non-SSL builds we still scan non-persistent connections for stray
  9870. // body bytes so the payload limit is enforced (413). On keep-alive,
  9871. // pending bytes may be the next request (issue #2450), so skip.
  9872. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9873. if (!req.has_header("Content-Length") &&
  9874. !detail::is_chunked_transfer_encoding(req.headers)) {
  9875. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9876. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9877. auto has_data = strm.is_readable();
  9878. if (!has_data) {
  9879. auto s = strm.socket();
  9880. if (s != INVALID_SOCKET) {
  9881. has_data = detail::select_read(s, 0, 0) > 0;
  9882. }
  9883. }
  9884. if (has_data) {
  9885. auto result =
  9886. detail::read_content_without_length(strm, payload_max_length_, out);
  9887. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9888. res.status = StatusCode::PayloadTooLarge_413;
  9889. return false;
  9890. } else if (result != detail::ReadContentResult::Success) {
  9891. return false;
  9892. }
  9893. return true;
  9894. }
  9895. }
  9896. return true;
  9897. }
  9898. #else
  9899. if (!req.has_header("Content-Length") &&
  9900. !detail::is_chunked_transfer_encoding(req.headers)) {
  9901. return true;
  9902. }
  9903. #endif
  9904. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9905. out, true)) {
  9906. return false;
  9907. }
  9908. req.body_consumed_ = true;
  9909. if (req.is_multipart_form_data()) {
  9910. if (!multipart_form_data_parser.is_valid()) {
  9911. res.status = StatusCode::BadRequest_400;
  9912. output_error_log(Error::MultipartParsing, &req);
  9913. return false;
  9914. }
  9915. }
  9916. return true;
  9917. }
  9918. inline bool Server::handle_file_request(Request &req, Response &res) {
  9919. for (const auto &entry : base_dirs_) {
  9920. // Prefix match
  9921. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9922. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9923. if (detail::is_valid_path(sub_path)) {
  9924. auto path = entry.base_dir + sub_path;
  9925. if (path.back() == '/') { path += "index.html"; }
  9926. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9927. // but symlinks/junctions can still escape the base directory.
  9928. if (!entry.resolved_base_dir.empty()) {
  9929. std::string resolved_path;
  9930. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9931. !detail::is_path_within_base(resolved_path,
  9932. entry.resolved_base_dir)) {
  9933. res.status = StatusCode::Forbidden_403;
  9934. return true;
  9935. }
  9936. }
  9937. detail::FileStat stat(path);
  9938. if (stat.is_dir()) {
  9939. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9940. return true;
  9941. }
  9942. if (stat.is_file()) {
  9943. for (const auto &kv : entry.headers) {
  9944. res.set_header(kv.first, kv.second);
  9945. }
  9946. auto etag = detail::compute_etag(stat);
  9947. if (!etag.empty()) { res.set_header("ETag", etag); }
  9948. auto mtime = stat.mtime();
  9949. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9950. if (!last_modified.empty()) {
  9951. res.set_header("Last-Modified", last_modified);
  9952. }
  9953. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9954. check_if_range(req, etag, mtime);
  9955. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9956. if (!mm->is_open()) {
  9957. output_error_log(Error::OpenFile, &req);
  9958. return false;
  9959. }
  9960. res.set_content_provider(
  9961. mm->size(),
  9962. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9963. default_file_mimetype_),
  9964. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9965. sink.write(mm->data() + offset, length);
  9966. return true;
  9967. });
  9968. if (req.method != "HEAD" && file_request_handler_) {
  9969. file_request_handler_(req, res);
  9970. }
  9971. return true;
  9972. } else {
  9973. output_error_log(Error::OpenFile, &req);
  9974. }
  9975. }
  9976. }
  9977. }
  9978. return false;
  9979. }
  9980. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9981. const std::string &etag,
  9982. time_t mtime) const {
  9983. // Handle conditional GET:
  9984. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9985. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9986. if (req.has_header("If-None-Match")) {
  9987. if (!etag.empty()) {
  9988. auto val = req.get_header_value("If-None-Match");
  9989. // NOTE: We use exact string matching here. This works correctly
  9990. // because our server always generates weak ETags (W/"..."), and
  9991. // clients typically send back the same ETag they received.
  9992. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9993. // If-None-Match, where W/"x" and "x" would match, but this
  9994. // simplified implementation requires exact matches.
  9995. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9996. [&](const char *b, const char *e) {
  9997. auto seg_len = static_cast<size_t>(e - b);
  9998. return (seg_len == 1 && *b == '*') ||
  9999. (seg_len == etag.size() &&
  10000. std::equal(b, e, etag.begin()));
  10001. });
  10002. if (ret) {
  10003. res.status = StatusCode::NotModified_304;
  10004. return true;
  10005. }
  10006. }
  10007. } else if (req.has_header("If-Modified-Since")) {
  10008. auto val = req.get_header_value("If-Modified-Since");
  10009. auto t = detail::parse_http_date(val);
  10010. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10011. res.status = StatusCode::NotModified_304;
  10012. return true;
  10013. }
  10014. }
  10015. return false;
  10016. }
  10017. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10018. time_t mtime) const {
  10019. // Handle If-Range for partial content requests (RFC 9110
  10020. // Section 13.1.5). If-Range is only evaluated when Range header is
  10021. // present. If the validator matches, serve partial content; otherwise
  10022. // serve full content.
  10023. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10024. auto val = req.get_header_value("If-Range");
  10025. auto is_valid_range = [&]() {
  10026. if (detail::is_strong_etag(val)) {
  10027. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10028. // comparison.
  10029. return (!etag.empty() && val == etag);
  10030. } else if (detail::is_weak_etag(val)) {
  10031. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10032. return false;
  10033. } else {
  10034. // HTTP-date comparison
  10035. auto t = detail::parse_http_date(val);
  10036. return (t != static_cast<time_t>(-1) && mtime <= t);
  10037. }
  10038. };
  10039. if (!is_valid_range()) {
  10040. // Validator doesn't match: ignore Range and serve full content
  10041. req.ranges.clear();
  10042. return false;
  10043. }
  10044. }
  10045. return true;
  10046. }
  10047. inline socket_t
  10048. Server::create_server_socket(const std::string &host, int port,
  10049. int socket_flags,
  10050. SocketOptions socket_options) const {
  10051. return detail::create_socket(
  10052. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10053. ipv6_v6only_, std::move(socket_options),
  10054. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10055. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10056. output_error_log(Error::BindIPAddress, nullptr);
  10057. return false;
  10058. }
  10059. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10060. output_error_log(Error::Listen, nullptr);
  10061. return false;
  10062. }
  10063. return true;
  10064. });
  10065. }
  10066. inline int Server::bind_internal(const std::string &host, int port,
  10067. int socket_flags) {
  10068. if (is_decommissioned) { return -1; }
  10069. if (!is_valid()) { return -1; }
  10070. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10071. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10072. if (port == 0) {
  10073. struct sockaddr_storage addr;
  10074. socklen_t addr_len = sizeof(addr);
  10075. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10076. &addr_len) == -1) {
  10077. output_error_log(Error::GetSockName, nullptr);
  10078. return -1;
  10079. }
  10080. if (addr.ss_family == AF_INET) {
  10081. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10082. } else if (addr.ss_family == AF_INET6) {
  10083. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10084. } else {
  10085. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10086. return -1;
  10087. }
  10088. } else {
  10089. return port;
  10090. }
  10091. }
  10092. inline bool Server::listen_internal() {
  10093. if (is_decommissioned) { return false; }
  10094. auto ret = true;
  10095. is_running_ = true;
  10096. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10097. if (start_handler_) { start_handler_(); }
  10098. {
  10099. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10100. while (svr_sock_ != INVALID_SOCKET) {
  10101. #ifndef _WIN32
  10102. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10103. #endif
  10104. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10105. idle_interval_usec_);
  10106. if (val == 0) { // Timeout
  10107. task_queue->on_idle();
  10108. continue;
  10109. }
  10110. #ifndef _WIN32
  10111. }
  10112. #endif
  10113. #if defined _WIN32
  10114. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10115. // OVERLAPPED
  10116. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10117. #elif defined SOCK_CLOEXEC
  10118. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10119. #else
  10120. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10121. #endif
  10122. if (sock == INVALID_SOCKET) {
  10123. if (errno == EMFILE) {
  10124. // The per-process limit of open file descriptors has been reached.
  10125. // Try to accept new connections after a short sleep.
  10126. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10127. continue;
  10128. } else if (errno == EINTR || errno == EAGAIN) {
  10129. continue;
  10130. }
  10131. if (svr_sock_ != INVALID_SOCKET) {
  10132. detail::close_socket(svr_sock_);
  10133. ret = false;
  10134. output_error_log(Error::Connection, nullptr);
  10135. } else {
  10136. ; // The server socket was closed by user.
  10137. }
  10138. break;
  10139. }
  10140. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10141. read_timeout_sec_, read_timeout_usec_);
  10142. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10143. write_timeout_sec_, write_timeout_usec_);
  10144. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10145. if (!task_queue->enqueue(
  10146. [this, sock]() { process_and_close_socket(sock); })) {
  10147. output_error_log(Error::ResourceExhaustion, nullptr);
  10148. detail::shutdown_socket(sock);
  10149. detail::close_socket(sock);
  10150. }
  10151. }
  10152. task_queue->shutdown();
  10153. }
  10154. is_decommissioned = !ret;
  10155. return ret;
  10156. }
  10157. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10158. if (pre_routing_handler_ &&
  10159. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10160. return true;
  10161. }
  10162. // File handler
  10163. if ((req.method == "GET" || req.method == "HEAD") &&
  10164. handle_file_request(req, res)) {
  10165. return true;
  10166. }
  10167. if (detail::expect_content(req)) {
  10168. // Content reader handler
  10169. {
  10170. // Track whether the ContentReader was aborted due to the decompressed
  10171. // payload exceeding `payload_max_length_`.
  10172. // The user handler runs after the lambda returns, so we must restore the
  10173. // 413 status if the handler overwrites it.
  10174. bool content_reader_payload_too_large = false;
  10175. ContentReader reader(
  10176. [&](ContentReceiver receiver) {
  10177. auto result = read_content_with_content_receiver(
  10178. strm, req, res, std::move(receiver), nullptr, nullptr);
  10179. if (!result) {
  10180. output_error_log(Error::Read, &req);
  10181. if (res.status == StatusCode::PayloadTooLarge_413) {
  10182. content_reader_payload_too_large = true;
  10183. }
  10184. }
  10185. return result;
  10186. },
  10187. [&](FormDataHeader header, ContentReceiver receiver) {
  10188. auto result = read_content_with_content_receiver(
  10189. strm, req, res, nullptr, std::move(header),
  10190. std::move(receiver));
  10191. if (!result) {
  10192. output_error_log(Error::Read, &req);
  10193. if (res.status == StatusCode::PayloadTooLarge_413) {
  10194. content_reader_payload_too_large = true;
  10195. }
  10196. }
  10197. return result;
  10198. });
  10199. bool dispatched = false;
  10200. if (req.method == "POST") {
  10201. dispatched = dispatch_request_for_content_reader(
  10202. req, res, std::move(reader), post_handlers_for_content_reader_);
  10203. } else if (req.method == "PUT") {
  10204. dispatched = dispatch_request_for_content_reader(
  10205. req, res, std::move(reader), put_handlers_for_content_reader_);
  10206. } else if (req.method == "PATCH") {
  10207. dispatched = dispatch_request_for_content_reader(
  10208. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10209. } else if (req.method == "DELETE") {
  10210. dispatched = dispatch_request_for_content_reader(
  10211. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10212. }
  10213. if (dispatched) {
  10214. if (content_reader_payload_too_large) {
  10215. // Enforce the limit: override any status the handler may have set
  10216. // and return false so the error path sends a plain 413 response.
  10217. res.status = StatusCode::PayloadTooLarge_413;
  10218. res.body.clear();
  10219. res.content_length_ = 0;
  10220. res.content_provider_ = nullptr;
  10221. return false;
  10222. }
  10223. return true;
  10224. }
  10225. }
  10226. // NOTE: `req.body` is not read here. For a regular handler the body is
  10227. // read inside dispatch_request(), after the route has matched and the
  10228. // pre-request handler has approved the request, so that a rejected
  10229. // request (e.g. failed authentication) never forces us to buffer a
  10230. // potentially large body.
  10231. }
  10232. // Regular handler
  10233. if (req.method == "GET" || req.method == "HEAD") {
  10234. return dispatch_request(req, res, get_handlers_, strm);
  10235. } else if (req.method == "POST") {
  10236. return dispatch_request(req, res, post_handlers_, strm);
  10237. } else if (req.method == "PUT") {
  10238. return dispatch_request(req, res, put_handlers_, strm);
  10239. } else if (req.method == "DELETE") {
  10240. return dispatch_request(req, res, delete_handlers_, strm);
  10241. } else if (req.method == "OPTIONS") {
  10242. return dispatch_request(req, res, options_handlers_, strm);
  10243. } else if (req.method == "PATCH") {
  10244. return dispatch_request(req, res, patch_handlers_, strm);
  10245. }
  10246. res.status = StatusCode::BadRequest_400;
  10247. return false;
  10248. }
  10249. inline bool Server::dispatch_request(Request &req, Response &res,
  10250. const Handlers &handlers, Stream &strm) {
  10251. for (const auto &x : handlers) {
  10252. const auto &matcher = x.first;
  10253. const auto &handler = x.second;
  10254. if (matcher->match(req)) {
  10255. req.matched_route = matcher->pattern();
  10256. // Run the pre-request handler before reading the body so a rejected
  10257. // request (e.g. failed authentication) never forces us to buffer a
  10258. // potentially large body. `req.matched_route` is available here.
  10259. if (pre_request_handler_ &&
  10260. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10261. return true;
  10262. }
  10263. // The route matched and the request was approved; read the body now.
  10264. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10265. output_error_log(Error::Read, &req);
  10266. return false;
  10267. }
  10268. handler(req, res);
  10269. return true;
  10270. }
  10271. }
  10272. return false;
  10273. }
  10274. inline void Server::apply_ranges(const Request &req, Response &res,
  10275. std::string &content_type,
  10276. std::string &boundary) const {
  10277. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10278. auto it = res.headers.find("Content-Type");
  10279. if (it != res.headers.end()) {
  10280. content_type = it->second;
  10281. res.headers.erase(it);
  10282. }
  10283. boundary = detail::make_multipart_data_boundary();
  10284. res.set_header("Content-Type",
  10285. "multipart/byteranges; boundary=" + boundary);
  10286. }
  10287. auto type = detail::encoding_type(req, res);
  10288. if (res.body.empty()) {
  10289. if (res.content_length_ > 0) {
  10290. size_t length = 0;
  10291. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10292. length = res.content_length_;
  10293. } else if (req.ranges.size() == 1) {
  10294. auto offset_and_length = detail::get_range_offset_and_length(
  10295. req.ranges[0], res.content_length_);
  10296. length = offset_and_length.second;
  10297. auto content_range = detail::make_content_range_header_field(
  10298. offset_and_length, res.content_length_);
  10299. res.set_header("Content-Range", content_range);
  10300. } else {
  10301. length = detail::get_multipart_ranges_data_length(
  10302. req, boundary, content_type, res.content_length_);
  10303. }
  10304. res.set_header("Content-Length", std::to_string(length));
  10305. } else {
  10306. if (res.content_provider_) {
  10307. if (res.is_chunked_content_provider_) {
  10308. res.set_header("Transfer-Encoding", "chunked");
  10309. if (type != detail::EncodingType::None) {
  10310. res.set_header("Content-Encoding", detail::encoding_name(type));
  10311. res.set_header("Vary", "Accept-Encoding");
  10312. }
  10313. }
  10314. }
  10315. }
  10316. } else {
  10317. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10318. ;
  10319. } else if (req.ranges.size() == 1) {
  10320. auto offset_and_length =
  10321. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10322. auto offset = offset_and_length.first;
  10323. auto length = offset_and_length.second;
  10324. auto content_range = detail::make_content_range_header_field(
  10325. offset_and_length, res.body.size());
  10326. res.set_header("Content-Range", content_range);
  10327. assert(offset + length <= res.body.size());
  10328. res.body = res.body.substr(offset, length);
  10329. } else {
  10330. std::string data;
  10331. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10332. res.body.size(), data);
  10333. res.body.swap(data);
  10334. }
  10335. if (type != detail::EncodingType::None) {
  10336. output_pre_compression_log(req, res);
  10337. if (auto compressor = detail::make_compressor(type)) {
  10338. std::string compressed;
  10339. if (compressor->compress(res.body.data(), res.body.size(), true,
  10340. [&](const char *data, size_t data_len) {
  10341. compressed.append(data, data_len);
  10342. return true;
  10343. })) {
  10344. res.body.swap(compressed);
  10345. res.set_header("Content-Encoding", detail::encoding_name(type));
  10346. res.set_header("Vary", "Accept-Encoding");
  10347. }
  10348. }
  10349. }
  10350. auto length = std::to_string(res.body.size());
  10351. res.set_header("Content-Length", length);
  10352. }
  10353. }
  10354. inline bool Server::dispatch_request_for_content_reader(
  10355. Request &req, Response &res, ContentReader content_reader,
  10356. const HandlersForContentReader &handlers) const {
  10357. for (const auto &x : handlers) {
  10358. const auto &matcher = x.first;
  10359. const auto &handler = x.second;
  10360. if (matcher->match(req)) {
  10361. req.matched_route = matcher->pattern();
  10362. if (!pre_request_handler_ ||
  10363. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10364. handler(req, res, content_reader);
  10365. }
  10366. return true;
  10367. }
  10368. }
  10369. return false;
  10370. }
  10371. inline std::string
  10372. get_client_ip(const std::string &x_forwarded_for,
  10373. const std::vector<std::string> &trusted_proxies) {
  10374. // X-Forwarded-For is a comma-separated list per RFC 7239
  10375. std::vector<std::string> ip_list;
  10376. detail::split(x_forwarded_for.data(),
  10377. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10378. [&](const char *b, const char *e) {
  10379. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10380. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10381. });
  10382. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10383. // no segments. Signal "no client IP derived" with an empty string so the
  10384. // caller can fall back to the connection-level remote address.
  10385. if (ip_list.empty()) { return std::string(); }
  10386. for (size_t i = 0; i < ip_list.size(); ++i) {
  10387. auto ip = ip_list[i];
  10388. auto is_trusted_proxy =
  10389. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10390. [&](const std::string &proxy) { return ip == proxy; });
  10391. if (is_trusted_proxy) {
  10392. if (i == 0) {
  10393. // If the trusted proxy is the first IP, there's no preceding client IP
  10394. return ip;
  10395. } else {
  10396. // Return the IP immediately before the trusted proxy
  10397. return ip_list[i - 1];
  10398. }
  10399. }
  10400. }
  10401. // If no trusted proxy is found, return the first IP in the list
  10402. return ip_list.front();
  10403. }
  10404. inline bool
  10405. Server::process_request(Stream &strm, const std::string &remote_addr,
  10406. int remote_port, const std::string &local_addr,
  10407. int local_port, bool close_connection,
  10408. bool &connection_closed,
  10409. const std::function<void(Request &)> &setup_request,
  10410. bool *websocket_upgraded) {
  10411. std::array<char, 2048> buf{};
  10412. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10413. // Connection has been closed on client
  10414. if (!line_reader.getline()) { return false; }
  10415. Request req;
  10416. req.start_time_ = std::chrono::steady_clock::now();
  10417. req.remote_addr = remote_addr;
  10418. req.remote_port = remote_port;
  10419. req.local_addr = local_addr;
  10420. req.local_port = local_port;
  10421. Response res;
  10422. res.version = "HTTP/1.1";
  10423. res.headers = default_headers_;
  10424. // Request line and headers
  10425. if (!parse_request_line(line_reader.ptr(), req)) {
  10426. res.status = StatusCode::BadRequest_400;
  10427. output_error_log(Error::InvalidRequestLine, &req);
  10428. return write_response(strm, close_connection, req, res);
  10429. }
  10430. // Request headers
  10431. if (!detail::read_headers(strm, req.headers)) {
  10432. res.status = StatusCode::BadRequest_400;
  10433. output_error_log(Error::InvalidHeaders, &req);
  10434. return write_response(strm, close_connection, req, res);
  10435. }
  10436. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10437. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10438. // tolerated for compatibility with existing clients.
  10439. if (req.get_header_value_u64("Content-Length") > 0 &&
  10440. req.has_header("Transfer-Encoding")) {
  10441. connection_closed = true;
  10442. res.status = StatusCode::BadRequest_400;
  10443. return write_response(strm, close_connection, req, res);
  10444. }
  10445. // Check if the request URI doesn't exceed the limit
  10446. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10447. connection_closed = true;
  10448. res.status = StatusCode::UriTooLong_414;
  10449. output_error_log(Error::ExceedUriMaxLength, &req);
  10450. return write_response(strm, close_connection, req, res);
  10451. }
  10452. if (req.get_header_value("Connection") == "close") {
  10453. connection_closed = true;
  10454. }
  10455. if (req.version == "HTTP/1.0" &&
  10456. req.get_header_value("Connection") != "Keep-Alive") {
  10457. connection_closed = true;
  10458. }
  10459. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10460. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10461. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10462. req.remote_addr = derived.empty() ? remote_addr : derived;
  10463. } else {
  10464. req.remote_addr = remote_addr;
  10465. }
  10466. req.remote_port = remote_port;
  10467. req.local_addr = local_addr;
  10468. req.local_port = local_port;
  10469. if (req.has_header("Accept")) {
  10470. const auto &accept_header = req.get_header_value("Accept");
  10471. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10472. connection_closed = true;
  10473. res.status = StatusCode::BadRequest_400;
  10474. output_error_log(Error::HTTPParsing, &req);
  10475. return write_response(strm, close_connection, req, res);
  10476. }
  10477. }
  10478. if (req.has_header("Range")) {
  10479. const auto &range_header_value = req.get_header_value("Range");
  10480. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10481. connection_closed = true;
  10482. res.status = StatusCode::RangeNotSatisfiable_416;
  10483. output_error_log(Error::InvalidRangeHeader, &req);
  10484. return write_response(strm, close_connection, req, res);
  10485. }
  10486. }
  10487. if (setup_request) { setup_request(req); }
  10488. if (req.get_header_value("Expect") == "100-continue") {
  10489. int status = StatusCode::Continue_100;
  10490. if (expect_100_continue_handler_) {
  10491. status = expect_100_continue_handler_(req, res);
  10492. }
  10493. switch (status) {
  10494. case StatusCode::Continue_100:
  10495. case StatusCode::ExpectationFailed_417:
  10496. detail::write_response_line(strm, status);
  10497. strm.write("\r\n");
  10498. break;
  10499. default:
  10500. connection_closed = true;
  10501. return write_response(strm, true, req, res);
  10502. }
  10503. }
  10504. // Setup `is_connection_closed` method
  10505. auto sock = strm.socket();
  10506. req.is_connection_closed = [sock]() {
  10507. return !detail::is_socket_alive(sock);
  10508. };
  10509. // WebSocket upgrade
  10510. // Check pre_routing_handler_ before upgrading so that authentication
  10511. // and other middleware can reject the request with an HTTP response
  10512. // (e.g., 401) before the protocol switches.
  10513. if (detail::is_websocket_upgrade(req)) {
  10514. if (pre_routing_handler_ &&
  10515. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10516. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10517. return write_response(strm, close_connection, req, res);
  10518. }
  10519. // Find matching WebSocket handler
  10520. for (const auto &entry : websocket_handlers_) {
  10521. if (entry.matcher->match(req)) {
  10522. // Compute accept key
  10523. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10524. auto accept_key = detail::websocket_accept_key(client_key);
  10525. // Negotiate subprotocol
  10526. std::string selected_subprotocol;
  10527. if (entry.sub_protocol_selector) {
  10528. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10529. if (!protocol_header.empty()) {
  10530. std::vector<std::string> protocols;
  10531. std::istringstream iss(protocol_header);
  10532. std::string token;
  10533. while (std::getline(iss, token, ',')) {
  10534. // Trim whitespace
  10535. auto start = token.find_first_not_of(' ');
  10536. auto end = token.find_last_not_of(' ');
  10537. if (start != std::string::npos) {
  10538. protocols.push_back(token.substr(start, end - start + 1));
  10539. }
  10540. }
  10541. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10542. }
  10543. }
  10544. // Send 101 Switching Protocols
  10545. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10546. "Upgrade: websocket\r\n"
  10547. "Connection: Upgrade\r\n"
  10548. "Sec-WebSocket-Accept: " +
  10549. accept_key + "\r\n";
  10550. if (!selected_subprotocol.empty()) {
  10551. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10552. return false;
  10553. }
  10554. handshake_response +=
  10555. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10556. }
  10557. handshake_response += "\r\n";
  10558. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10559. 0) {
  10560. return false;
  10561. }
  10562. connection_closed = true;
  10563. if (websocket_upgraded) { *websocket_upgraded = true; }
  10564. {
  10565. // Use WebSocket-specific read timeout instead of HTTP timeout
  10566. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10567. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10568. websocket_max_missed_pongs_);
  10569. entry.handler(req, ws);
  10570. }
  10571. return true;
  10572. }
  10573. }
  10574. // No matching handler - fall through to 404
  10575. }
  10576. // Routing
  10577. auto routed = false;
  10578. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10579. routed = routing(req, res, strm);
  10580. #else
  10581. try {
  10582. routed = routing(req, res, strm);
  10583. } catch (std::exception &) {
  10584. if (exception_handler_) {
  10585. auto ep = std::current_exception();
  10586. exception_handler_(req, res, ep);
  10587. routed = true;
  10588. } else {
  10589. res.status = StatusCode::InternalServerError_500;
  10590. }
  10591. } catch (...) {
  10592. if (exception_handler_) {
  10593. auto ep = std::current_exception();
  10594. exception_handler_(req, res, ep);
  10595. routed = true;
  10596. } else {
  10597. res.status = StatusCode::InternalServerError_500;
  10598. }
  10599. }
  10600. #endif
  10601. auto ret = false;
  10602. if (routed) {
  10603. if (res.status == -1) {
  10604. res.status = req.ranges.empty() ? StatusCode::OK_200
  10605. : StatusCode::PartialContent_206;
  10606. }
  10607. // Serve file content by using a content provider
  10608. auto file_open_error = false;
  10609. if (!res.file_content_path_.empty()) {
  10610. const auto &path = res.file_content_path_;
  10611. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10612. if (!mm->is_open()) {
  10613. res.body.clear();
  10614. res.content_length_ = 0;
  10615. res.content_provider_ = nullptr;
  10616. res.status = StatusCode::NotFound_404;
  10617. output_error_log(Error::OpenFile, &req);
  10618. file_open_error = true;
  10619. } else {
  10620. auto content_type = res.file_content_content_type_;
  10621. if (content_type.empty()) {
  10622. content_type = detail::find_content_type(
  10623. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10624. }
  10625. res.set_content_provider(
  10626. mm->size(), content_type,
  10627. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10628. sink.write(mm->data() + offset, length);
  10629. return true;
  10630. });
  10631. }
  10632. }
  10633. if (file_open_error) {
  10634. ret = write_response(strm, close_connection, req, res);
  10635. } else if (detail::range_error(req, res)) {
  10636. res.body.clear();
  10637. res.content_length_ = 0;
  10638. res.content_provider_ = nullptr;
  10639. res.status = StatusCode::RangeNotSatisfiable_416;
  10640. ret = write_response(strm, close_connection, req, res);
  10641. } else {
  10642. ret = write_response_with_content(strm, close_connection, req, res);
  10643. }
  10644. } else {
  10645. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10646. ret = write_response(strm, close_connection, req, res);
  10647. }
  10648. // Drain any unconsumed framed body to prevent request smuggling on
  10649. // keep-alive. Without framing there is no body to drain — reading would
  10650. // consume the next request (issue #2450).
  10651. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10652. int dummy_status;
  10653. if (!detail::read_content(
  10654. strm, req, payload_max_length_, dummy_status, nullptr,
  10655. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10656. connection_closed = true;
  10657. }
  10658. }
  10659. return ret;
  10660. }
  10661. inline bool Server::is_valid() const { return true; }
  10662. inline bool Server::process_and_close_socket(socket_t sock) {
  10663. std::string remote_addr;
  10664. int remote_port = 0;
  10665. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10666. std::string local_addr;
  10667. int local_port = 0;
  10668. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10669. bool websocket_upgraded = false;
  10670. auto ret = detail::process_server_socket(
  10671. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10672. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10673. write_timeout_usec_,
  10674. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10675. return process_request(strm, remote_addr, remote_port, local_addr,
  10676. local_port, close_connection, connection_closed,
  10677. nullptr, &websocket_upgraded);
  10678. });
  10679. detail::shutdown_socket(sock);
  10680. detail::close_socket(sock);
  10681. return ret;
  10682. }
  10683. inline void Server::output_log(const Request &req, const Response &res) const {
  10684. if (logger_) {
  10685. std::lock_guard<std::mutex> guard(logger_mutex_);
  10686. logger_(req, res);
  10687. }
  10688. }
  10689. inline void Server::output_pre_compression_log(const Request &req,
  10690. const Response &res) const {
  10691. if (pre_compression_logger_) {
  10692. std::lock_guard<std::mutex> guard(logger_mutex_);
  10693. pre_compression_logger_(req, res);
  10694. }
  10695. }
  10696. inline void Server::output_error_log(const Error &err,
  10697. const Request *req) const {
  10698. if (error_logger_) {
  10699. std::lock_guard<std::mutex> guard(logger_mutex_);
  10700. error_logger_(err, req);
  10701. }
  10702. }
  10703. /*
  10704. * Group 5: ClientImpl and Client (Universal) implementation
  10705. */
  10706. // HTTP client implementation
  10707. inline ClientImpl::ClientImpl(const std::string &host)
  10708. : ClientImpl(host, 80, std::string(), std::string()) {}
  10709. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10710. : ClientImpl(host, port, std::string(), std::string()) {}
  10711. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10712. const std::string &client_cert_path,
  10713. const std::string &client_key_path)
  10714. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10715. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10716. inline ClientImpl::~ClientImpl() {
  10717. // Wait until all the requests in flight are handled.
  10718. size_t retry_count = 10;
  10719. while (retry_count-- > 0) {
  10720. {
  10721. std::lock_guard<std::mutex> guard(socket_mutex_);
  10722. if (socket_requests_in_flight_ == 0) { break; }
  10723. }
  10724. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10725. }
  10726. std::lock_guard<std::mutex> guard(socket_mutex_);
  10727. shutdown_socket(socket_);
  10728. close_socket(socket_);
  10729. }
  10730. inline bool ClientImpl::is_valid() const { return true; }
  10731. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10732. client_cert_path_ = rhs.client_cert_path_;
  10733. client_key_path_ = rhs.client_key_path_;
  10734. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10735. read_timeout_sec_ = rhs.read_timeout_sec_;
  10736. read_timeout_usec_ = rhs.read_timeout_usec_;
  10737. write_timeout_sec_ = rhs.write_timeout_sec_;
  10738. write_timeout_usec_ = rhs.write_timeout_usec_;
  10739. max_timeout_msec_ = rhs.max_timeout_msec_;
  10740. basic_auth_username_ = rhs.basic_auth_username_;
  10741. basic_auth_password_ = rhs.basic_auth_password_;
  10742. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10743. keep_alive_ = rhs.keep_alive_;
  10744. follow_location_ = rhs.follow_location_;
  10745. path_encode_ = rhs.path_encode_;
  10746. address_family_ = rhs.address_family_;
  10747. tcp_nodelay_ = rhs.tcp_nodelay_;
  10748. ipv6_v6only_ = rhs.ipv6_v6only_;
  10749. socket_options_ = rhs.socket_options_;
  10750. compress_ = rhs.compress_;
  10751. decompress_ = rhs.decompress_;
  10752. payload_max_length_ = rhs.payload_max_length_;
  10753. has_payload_max_length_ = rhs.has_payload_max_length_;
  10754. interface_ = rhs.interface_;
  10755. proxy_host_ = rhs.proxy_host_;
  10756. proxy_port_ = rhs.proxy_port_;
  10757. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10758. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10759. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10760. no_proxy_entries_ = rhs.no_proxy_entries_;
  10761. logger_ = rhs.logger_;
  10762. error_logger_ = rhs.error_logger_;
  10763. #ifdef CPPHTTPLIB_SSL_ENABLED
  10764. digest_auth_username_ = rhs.digest_auth_username_;
  10765. digest_auth_password_ = rhs.digest_auth_password_;
  10766. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10767. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10768. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10769. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10770. server_certificate_verification_ = rhs.server_certificate_verification_;
  10771. server_hostname_verification_ = rhs.server_hostname_verification_;
  10772. system_ca_mode_ = rhs.system_ca_mode_;
  10773. #endif
  10774. }
  10775. inline bool
  10776. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10777. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10778. if (no_proxy_entries_.empty()) { return true; }
  10779. // host_ is const so its normalized form is invariant; cache it. The
  10780. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10781. if (host == host_) {
  10782. if (!host_normalized_valid_) {
  10783. host_normalized_ = detail::normalize_target(host_);
  10784. host_normalized_valid_ = true;
  10785. }
  10786. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10787. }
  10788. auto target = detail::normalize_target(host);
  10789. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10790. }
  10791. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10792. if (is_proxy_enabled_for_host(host_)) {
  10793. return detail::create_client_socket(
  10794. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10795. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10796. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10797. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10798. }
  10799. // Check is custom IP specified for host_
  10800. std::string ip;
  10801. auto it = addr_map_.find(host_);
  10802. if (it != addr_map_.end()) { ip = it->second; }
  10803. return detail::create_client_socket(
  10804. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10805. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10806. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10807. write_timeout_usec_, interface_, error);
  10808. }
  10809. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10810. Error &error) {
  10811. auto sock = create_client_socket(error);
  10812. if (sock == INVALID_SOCKET) { return false; }
  10813. socket.sock = sock;
  10814. return true;
  10815. }
  10816. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10817. return create_and_connect_socket(socket, error);
  10818. }
  10819. inline bool ClientImpl::setup_proxy_connection(
  10820. Socket & /*socket*/,
  10821. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10822. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10823. return true;
  10824. }
  10825. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10826. bool /*shutdown_gracefully*/) {
  10827. // If there are any requests in flight from threads other than us, then it's
  10828. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10829. assert(socket_requests_in_flight_ == 0 ||
  10830. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10831. }
  10832. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10833. if (socket.sock == INVALID_SOCKET) { return; }
  10834. detail::shutdown_socket(socket.sock);
  10835. }
  10836. inline void ClientImpl::close_socket(Socket &socket) {
  10837. // If there are requests in flight in another thread, usually closing
  10838. // the socket will be fine and they will simply receive an error when
  10839. // using the closed socket, but it is still a bug since rarely the OS
  10840. // may reassign the socket id to be used for a new socket, and then
  10841. // suddenly they will be operating on a live socket that is different
  10842. // than the one they intended!
  10843. assert(socket_requests_in_flight_ == 0 ||
  10844. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10845. // It is also a bug if this happens while SSL is still active
  10846. #ifdef CPPHTTPLIB_SSL_ENABLED
  10847. assert(socket.ssl == nullptr);
  10848. #endif
  10849. if (socket.sock == INVALID_SOCKET) { return; }
  10850. detail::close_socket(socket.sock);
  10851. socket.sock = INVALID_SOCKET;
  10852. }
  10853. inline void ClientImpl::disconnect(bool gracefully) {
  10854. shutdown_ssl(socket_, gracefully);
  10855. shutdown_socket(socket_);
  10856. close_socket(socket_);
  10857. }
  10858. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10859. Response &res,
  10860. bool skip_100_continue) const {
  10861. std::array<char, 2048> buf{};
  10862. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10863. if (!line_reader.getline()) { return false; }
  10864. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10865. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10866. #else
  10867. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10868. #endif
  10869. std::cmatch m;
  10870. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10871. return req.method == "CONNECT";
  10872. }
  10873. res.version = std::string(m[1]);
  10874. res.status = std::stoi(std::string(m[2]));
  10875. res.reason = std::string(m[3]);
  10876. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10877. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10878. if (!line_reader.getline()) { return false; } // CRLF
  10879. if (!line_reader.getline()) { return false; } // next response line
  10880. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10881. res.version = std::string(m[1]);
  10882. res.status = std::stoi(std::string(m[2]));
  10883. res.reason = std::string(m[3]);
  10884. }
  10885. return true;
  10886. }
  10887. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10888. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10889. auto ret = send_(req, res, error);
  10890. if (error == Error::SSLPeerCouldBeClosed_) {
  10891. assert(!ret);
  10892. ret = send_(req, res, error);
  10893. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10894. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10895. }
  10896. return ret;
  10897. }
  10898. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10899. {
  10900. std::lock_guard<std::mutex> guard(socket_mutex_);
  10901. // Set this to false immediately - if it ever gets set to true by the end
  10902. // of the request, we know another thread instructed us to close the
  10903. // socket.
  10904. socket_should_be_closed_when_request_is_done_ = false;
  10905. auto is_alive = false;
  10906. if (socket_.is_open()) {
  10907. is_alive = detail::is_socket_alive(socket_.sock);
  10908. #ifdef CPPHTTPLIB_SSL_ENABLED
  10909. if (is_alive && is_ssl()) {
  10910. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10911. is_alive = false;
  10912. }
  10913. }
  10914. #endif
  10915. if (!is_alive) {
  10916. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10917. disconnect(/*gracefully=*/false);
  10918. }
  10919. }
  10920. if (!is_alive) {
  10921. if (!ensure_socket_connection(socket_, error)) {
  10922. output_error_log(error, &req);
  10923. return false;
  10924. }
  10925. {
  10926. auto success = true;
  10927. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10928. error)) {
  10929. if (!success) { output_error_log(error, &req); }
  10930. return success;
  10931. }
  10932. }
  10933. }
  10934. // Mark the current socket as being in use so that it cannot be closed by
  10935. // anyone else while this request is ongoing, even though we will be
  10936. // releasing the mutex.
  10937. if (socket_requests_in_flight_ > 1) {
  10938. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10939. }
  10940. socket_requests_in_flight_ += 1;
  10941. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10942. }
  10943. for (const auto &header : default_headers_) {
  10944. if (req.headers.find(header.first) == req.headers.end()) {
  10945. req.headers.insert(header);
  10946. }
  10947. }
  10948. auto ret = false;
  10949. auto close_connection = !keep_alive_;
  10950. auto se = detail::scope_exit([&]() {
  10951. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10952. std::lock_guard<std::mutex> guard(socket_mutex_);
  10953. socket_requests_in_flight_ -= 1;
  10954. if (socket_requests_in_flight_ <= 0) {
  10955. assert(socket_requests_in_flight_ == 0);
  10956. socket_requests_are_from_thread_ = std::thread::id();
  10957. }
  10958. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10959. !ret) {
  10960. disconnect(/*gracefully=*/true);
  10961. }
  10962. });
  10963. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10964. return handle_request(strm, req, res, close_connection, error);
  10965. });
  10966. if (!ret) {
  10967. if (error == Error::Success) {
  10968. error = Error::Unknown;
  10969. output_error_log(error, &req);
  10970. }
  10971. }
  10972. return ret;
  10973. }
  10974. inline Result ClientImpl::send(const Request &req) {
  10975. auto req2 = req;
  10976. return send_(std::move(req2));
  10977. }
  10978. inline Result ClientImpl::send_(Request &&req) {
  10979. auto res = detail::make_unique<Response>();
  10980. auto error = Error::Success;
  10981. auto ret = send(req, *res, error);
  10982. #ifdef CPPHTTPLIB_SSL_ENABLED
  10983. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10984. last_ssl_error_, last_backend_error_};
  10985. #else
  10986. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10987. #endif
  10988. }
  10989. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10990. const std::string &ct) {
  10991. (void)for_stream;
  10992. for (const auto &header : default_headers_) {
  10993. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10994. }
  10995. if (!r.has_header("Host")) {
  10996. if (address_family_ == AF_UNIX) {
  10997. r.headers.emplace("Host", "localhost");
  10998. } else {
  10999. r.headers.emplace(
  11000. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  11001. }
  11002. }
  11003. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  11004. if (!r.content_receiver) {
  11005. if (!r.has_header("Accept-Encoding")) {
  11006. std::string accept_encoding;
  11007. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11008. accept_encoding = "br";
  11009. #endif
  11010. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11011. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11012. accept_encoding += "gzip, deflate";
  11013. #endif
  11014. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11015. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11016. accept_encoding += "zstd";
  11017. #endif
  11018. r.set_header("Accept-Encoding", accept_encoding);
  11019. }
  11020. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11021. if (!r.has_header("User-Agent")) {
  11022. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11023. r.set_header("User-Agent", agent);
  11024. }
  11025. #endif
  11026. }
  11027. if (!r.body.empty()) {
  11028. if (!ct.empty() && !r.has_header("Content-Type")) {
  11029. r.headers.emplace("Content-Type", ct);
  11030. }
  11031. if (!r.has_header("Content-Length")) {
  11032. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11033. }
  11034. }
  11035. }
  11036. inline ClientImpl::StreamHandle
  11037. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11038. const Params &params, const Headers &headers,
  11039. const std::string &body,
  11040. const std::string &content_type) {
  11041. StreamHandle handle;
  11042. handle.response = detail::make_unique<Response>();
  11043. handle.error = Error::Success;
  11044. auto query_path = params.empty() ? path : append_query_params(path, params);
  11045. handle.connection_ = detail::make_unique<ClientConnection>();
  11046. {
  11047. std::lock_guard<std::mutex> guard(socket_mutex_);
  11048. auto is_alive = false;
  11049. if (socket_.is_open()) {
  11050. is_alive = detail::is_socket_alive(socket_.sock);
  11051. #ifdef CPPHTTPLIB_SSL_ENABLED
  11052. if (is_alive && is_ssl()) {
  11053. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11054. is_alive = false;
  11055. }
  11056. }
  11057. #endif
  11058. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11059. }
  11060. if (!is_alive) {
  11061. if (!ensure_socket_connection(socket_, handle.error)) {
  11062. handle.response.reset();
  11063. return handle;
  11064. }
  11065. {
  11066. auto success = true;
  11067. auto start_time = std::chrono::steady_clock::now();
  11068. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11069. success, handle.error)) {
  11070. if (!success) { handle.response.reset(); }
  11071. return handle;
  11072. }
  11073. }
  11074. }
  11075. transfer_socket_ownership_to_handle(handle);
  11076. }
  11077. #ifdef CPPHTTPLIB_SSL_ENABLED
  11078. if (is_ssl() && handle.connection_->session) {
  11079. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11080. handle.connection_->sock, handle.connection_->session,
  11081. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11082. write_timeout_usec_);
  11083. } else {
  11084. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11085. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11086. write_timeout_sec_, write_timeout_usec_);
  11087. }
  11088. #else
  11089. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11090. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11091. write_timeout_sec_, write_timeout_usec_);
  11092. #endif
  11093. handle.stream_ = handle.socket_stream_.get();
  11094. Request req;
  11095. req.method = method;
  11096. req.path = query_path;
  11097. req.headers = headers;
  11098. req.body = body;
  11099. prepare_default_headers(req, true, content_type);
  11100. auto &strm = *handle.stream_;
  11101. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11102. handle.error = Error::Write;
  11103. handle.response.reset();
  11104. return handle;
  11105. }
  11106. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11107. handle.error)) {
  11108. handle.response.reset();
  11109. return handle;
  11110. }
  11111. if (!body.empty()) {
  11112. if (strm.write(body.data(), body.size()) < 0) {
  11113. handle.error = Error::Write;
  11114. handle.response.reset();
  11115. return handle;
  11116. }
  11117. }
  11118. if (!read_response_line(strm, req, *handle.response) ||
  11119. !detail::read_headers(strm, handle.response->headers)) {
  11120. handle.error = Error::Read;
  11121. handle.response.reset();
  11122. return handle;
  11123. }
  11124. handle.body_reader_.stream = handle.stream_;
  11125. handle.body_reader_.payload_max_length = payload_max_length_;
  11126. if (handle.response->has_header("Content-Length")) {
  11127. bool is_invalid = false;
  11128. auto content_length = detail::get_header_value_u64(
  11129. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11130. if (is_invalid) {
  11131. handle.error = Error::Read;
  11132. handle.response.reset();
  11133. return handle;
  11134. }
  11135. handle.body_reader_.has_content_length = true;
  11136. handle.body_reader_.content_length = content_length;
  11137. }
  11138. auto transfer_encoding =
  11139. handle.response->get_header_value("Transfer-Encoding");
  11140. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  11141. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11142. if (!content_encoding.empty()) {
  11143. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11144. }
  11145. return handle;
  11146. }
  11147. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11148. if (!is_valid() || !response) { return -1; }
  11149. if (decompressor_) { return read_with_decompression(buf, len); }
  11150. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11151. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11152. trailers_parsed_ = true;
  11153. if (body_reader_.chunked_decoder) {
  11154. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11155. response->trailers, response->headers)) {
  11156. return n;
  11157. }
  11158. } else {
  11159. detail::ChunkedDecoder dec(*stream_);
  11160. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11161. return n;
  11162. }
  11163. }
  11164. }
  11165. return n;
  11166. }
  11167. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11168. size_t len) {
  11169. if (decompress_offset_ < decompress_buffer_.size()) {
  11170. auto available = decompress_buffer_.size() - decompress_offset_;
  11171. auto to_copy = (std::min)(len, available);
  11172. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11173. decompress_offset_ += to_copy;
  11174. decompressed_bytes_read_ += to_copy;
  11175. return static_cast<ssize_t>(to_copy);
  11176. }
  11177. decompress_buffer_.clear();
  11178. decompress_offset_ = 0;
  11179. constexpr size_t kDecompressionBufferSize = 8192;
  11180. char compressed_buf[kDecompressionBufferSize];
  11181. while (true) {
  11182. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11183. sizeof(compressed_buf));
  11184. if (n <= 0) { return n; }
  11185. bool decompress_ok = decompressor_->decompress(
  11186. compressed_buf, static_cast<size_t>(n),
  11187. [this](const char *data, size_t data_len) {
  11188. decompress_buffer_.append(data, data_len);
  11189. auto limit = body_reader_.payload_max_length;
  11190. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11191. return false;
  11192. }
  11193. return true;
  11194. });
  11195. if (!decompress_ok) {
  11196. body_reader_.last_error = Error::Read;
  11197. return -1;
  11198. }
  11199. if (!decompress_buffer_.empty()) { break; }
  11200. }
  11201. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11202. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11203. decompress_offset_ = to_copy;
  11204. decompressed_bytes_read_ += to_copy;
  11205. return static_cast<ssize_t>(to_copy);
  11206. }
  11207. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11208. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11209. return;
  11210. }
  11211. trailers_parsed_ = true;
  11212. const auto bufsiz = 128;
  11213. char line_buf[bufsiz];
  11214. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11215. if (!line_reader.getline()) { return; }
  11216. if (!detail::parse_trailers(line_reader, response->trailers,
  11217. response->headers)) {
  11218. return;
  11219. }
  11220. }
  11221. namespace detail {
  11222. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11223. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11224. size_t &out_chunk_offset,
  11225. size_t &out_chunk_total) {
  11226. if (finished) { return 0; }
  11227. if (chunk_remaining == 0) {
  11228. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11229. if (!lr.getline()) { return -1; }
  11230. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11231. const char *p = lr.ptr();
  11232. int v = 0;
  11233. if (!is_hex(*p, v)) { return -1; }
  11234. size_t chunk_len = 0;
  11235. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11236. for (; is_hex(*p, v); ++p) {
  11237. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11238. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11239. }
  11240. while (is_space_or_tab(*p)) {
  11241. ++p;
  11242. }
  11243. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11244. if (chunk_len == 0) {
  11245. chunk_remaining = 0;
  11246. finished = true;
  11247. out_chunk_offset = 0;
  11248. out_chunk_total = 0;
  11249. return 0;
  11250. }
  11251. chunk_remaining = chunk_len;
  11252. last_chunk_total = chunk_remaining;
  11253. last_chunk_offset = 0;
  11254. }
  11255. auto to_read = (std::min)(chunk_remaining, len);
  11256. auto n = strm.read(buf, to_read);
  11257. if (n <= 0) { return -1; }
  11258. auto offset_before = last_chunk_offset;
  11259. last_chunk_offset += static_cast<size_t>(n);
  11260. chunk_remaining -= static_cast<size_t>(n);
  11261. out_chunk_offset = offset_before;
  11262. out_chunk_total = last_chunk_total;
  11263. if (chunk_remaining == 0) {
  11264. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11265. if (!lr.getline()) { return -1; }
  11266. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11267. }
  11268. return n;
  11269. }
  11270. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11271. const Headers &src_headers) {
  11272. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11273. if (!lr.getline()) { return false; }
  11274. return parse_trailers(lr, dest, src_headers);
  11275. }
  11276. } // namespace detail
  11277. inline void
  11278. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11279. handle.connection_->sock = socket_.sock;
  11280. #ifdef CPPHTTPLIB_SSL_ENABLED
  11281. handle.connection_->session = socket_.ssl;
  11282. socket_.ssl = nullptr;
  11283. #endif
  11284. socket_.sock = INVALID_SOCKET;
  11285. }
  11286. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11287. Response &res, bool close_connection,
  11288. Error &error) {
  11289. if (req.path.empty()) {
  11290. error = Error::Connection;
  11291. output_error_log(error, &req);
  11292. return false;
  11293. }
  11294. auto req_save = req;
  11295. bool ret;
  11296. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11297. auto req2 = req;
  11298. req2.path = "http://" +
  11299. detail::make_host_and_port_string(host_, port_, false) +
  11300. req.path;
  11301. ret = process_request(strm, req2, res, close_connection, error);
  11302. req = std::move(req2);
  11303. req.path = req_save.path;
  11304. } else {
  11305. ret = process_request(strm, req, res, close_connection, error);
  11306. }
  11307. if (!ret) { return false; }
  11308. if (res.get_header_value("Connection") == "close" ||
  11309. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11310. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11311. // for this to be safe.
  11312. // This is safe to call because handle_request is only called by send_
  11313. // which locks the request mutex during the process. It would be a bug
  11314. // to call it from a different thread since it's a thread-safety issue
  11315. // to do these things to the socket if another thread is using the socket.
  11316. std::lock_guard<std::mutex> guard(socket_mutex_);
  11317. disconnect(/*gracefully=*/true);
  11318. }
  11319. if (300 < res.status && res.status < 400 && follow_location_) {
  11320. req = std::move(req_save);
  11321. ret = redirect(req, res, error);
  11322. }
  11323. #ifdef CPPHTTPLIB_SSL_ENABLED
  11324. if ((res.status == StatusCode::Unauthorized_401 ||
  11325. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11326. req.authorization_count_ < 5) {
  11327. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11328. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11329. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11330. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11331. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11332. return ret;
  11333. }
  11334. const auto &username =
  11335. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11336. const auto &password =
  11337. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11338. if (!username.empty() && !password.empty()) {
  11339. std::map<std::string, std::string> auth;
  11340. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11341. Request new_req = req;
  11342. new_req.authorization_count_ += 1;
  11343. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11344. : "Authorization");
  11345. new_req.headers.insert(detail::make_digest_authentication_header(
  11346. req, auth, new_req.authorization_count_, detail::random_string(10),
  11347. username, password, is_proxy));
  11348. Response new_res;
  11349. ret = send(new_req, new_res, error);
  11350. if (ret) { res = std::move(new_res); }
  11351. }
  11352. }
  11353. }
  11354. #endif
  11355. return ret;
  11356. }
  11357. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11358. if (req.redirect_count_ == 0) {
  11359. error = Error::ExceedRedirectCount;
  11360. output_error_log(error, &req);
  11361. return false;
  11362. }
  11363. auto location = res.get_header_value("location");
  11364. if (location.empty()) { return false; }
  11365. detail::UrlComponents uc;
  11366. if (!detail::parse_url(location, uc)) { return false; }
  11367. // Only follow http/https redirects
  11368. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11369. return false;
  11370. }
  11371. auto scheme = is_ssl() ? "https" : "http";
  11372. auto next_scheme = std::move(uc.scheme);
  11373. auto next_host = std::move(uc.host);
  11374. auto port_str = std::move(uc.port);
  11375. auto next_path = std::move(uc.path);
  11376. auto next_query = std::move(uc.query);
  11377. auto next_port = port_;
  11378. if (!port_str.empty()) {
  11379. if (!detail::parse_port(port_str, next_port)) { return false; }
  11380. } else if (!next_scheme.empty()) {
  11381. next_port = next_scheme == "https" ? 443 : 80;
  11382. }
  11383. if (next_scheme.empty()) { next_scheme = scheme; }
  11384. if (next_host.empty()) { next_host = host_; }
  11385. if (next_path.empty()) { next_path = "/"; }
  11386. auto path = decode_path_component(next_path) + next_query;
  11387. // Same host redirect - use current client
  11388. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11389. return detail::redirect(*this, req, res, path, location, error);
  11390. }
  11391. // Cross-host/scheme redirect - create new client with robust setup
  11392. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11393. path, location, error);
  11394. }
  11395. // New method for robust redirect client creation
  11396. inline bool ClientImpl::create_redirect_client(
  11397. const std::string &scheme, const std::string &host, int port, Request &req,
  11398. Response &res, const std::string &path, const std::string &location,
  11399. Error &error) {
  11400. // Determine if we need SSL
  11401. auto need_ssl = (scheme == "https");
  11402. // Clean up request headers that are host/client specific
  11403. // Remove headers that should not be carried over to new host
  11404. auto headers_to_remove =
  11405. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  11406. for (const auto &header_name : headers_to_remove) {
  11407. auto it = req.headers.find(header_name);
  11408. while (it != req.headers.end()) {
  11409. it = req.headers.erase(it);
  11410. it = req.headers.find(header_name);
  11411. }
  11412. }
  11413. // Create appropriate client type and handle redirect
  11414. if (need_ssl) {
  11415. #ifdef CPPHTTPLIB_SSL_ENABLED
  11416. // Create SSL client for HTTPS redirect
  11417. SSLClient redirect_client(host, port);
  11418. // Setup basic client configuration first
  11419. setup_redirect_client(redirect_client);
  11420. redirect_client.enable_server_certificate_verification(
  11421. server_certificate_verification_);
  11422. redirect_client.enable_server_hostname_verification(
  11423. server_hostname_verification_);
  11424. redirect_client.system_ca_mode_ = system_ca_mode_;
  11425. // Transfer CA certificate to redirect client
  11426. if (!ca_cert_pem_.empty()) {
  11427. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11428. ca_cert_pem_.size());
  11429. }
  11430. if (!ca_cert_file_path_.empty()) {
  11431. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11432. }
  11433. // Client certificates are set through constructor for SSLClient
  11434. // NOTE: SSLClient constructor already takes client_cert_path and
  11435. // client_key_path so we need to create it properly if client certs are
  11436. // needed
  11437. // Execute the redirect
  11438. return detail::redirect(redirect_client, req, res, path, location, error);
  11439. #else
  11440. // SSL not supported - set appropriate error
  11441. error = Error::SSLConnection;
  11442. output_error_log(error, &req);
  11443. return false;
  11444. #endif
  11445. } else {
  11446. // HTTP redirect
  11447. ClientImpl redirect_client(host, port);
  11448. // Setup client with robust configuration
  11449. setup_redirect_client(redirect_client);
  11450. // Execute the redirect
  11451. return detail::redirect(redirect_client, req, res, path, location, error);
  11452. }
  11453. }
  11454. // New method for robust client setup (based on basic_manual_redirect.cpp
  11455. // logic)
  11456. template <typename ClientType>
  11457. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11458. // Copy basic settings first
  11459. client.set_connection_timeout(connection_timeout_sec_);
  11460. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11461. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11462. client.set_keep_alive(keep_alive_);
  11463. client.set_follow_location(
  11464. true); // Enable redirects to handle multi-step redirects
  11465. client.set_path_encode(path_encode_);
  11466. client.set_compress(compress_);
  11467. client.set_decompress(decompress_);
  11468. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11469. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11470. // 15.4, credentials must not be forwarded when redirecting to a different
  11471. // host. This function is only called for cross-host redirects; same-host
  11472. // redirects are handled directly in ClientImpl::redirect().
  11473. // Copy the proxy configuration unconditionally; the per-target bypass is
  11474. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11475. // still use the proxy.
  11476. client.no_proxy_entries_ = no_proxy_entries_;
  11477. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11478. client.set_proxy(proxy_host_, proxy_port_);
  11479. if (!proxy_basic_auth_username_.empty()) {
  11480. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11481. proxy_basic_auth_password_);
  11482. }
  11483. if (!proxy_bearer_token_auth_token_.empty()) {
  11484. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11485. }
  11486. #ifdef CPPHTTPLIB_SSL_ENABLED
  11487. if (!proxy_digest_auth_username_.empty()) {
  11488. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11489. proxy_digest_auth_password_);
  11490. }
  11491. #endif
  11492. }
  11493. // Copy network and socket settings
  11494. client.set_address_family(address_family_);
  11495. client.set_tcp_nodelay(tcp_nodelay_);
  11496. client.set_ipv6_v6only(ipv6_v6only_);
  11497. if (socket_options_) { client.set_socket_options(socket_options_); }
  11498. if (!interface_.empty()) { client.set_interface(interface_); }
  11499. // Copy logging and headers
  11500. if (logger_) { client.set_logger(logger_); }
  11501. if (error_logger_) { client.set_error_logger(error_logger_); }
  11502. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11503. // Each new client should generate its own headers based on its target host
  11504. }
  11505. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11506. const Request &req,
  11507. Error &error) const {
  11508. auto is_shutting_down = []() { return false; };
  11509. if (req.is_chunked_content_provider_) {
  11510. auto compressor = compress_ ? detail::create_compressor().first
  11511. : std::unique_ptr<detail::compressor>();
  11512. if (!compressor) {
  11513. compressor = detail::make_unique<detail::nocompressor>();
  11514. }
  11515. return detail::write_content_chunked(strm, req.content_provider_,
  11516. is_shutting_down, *compressor, error);
  11517. } else {
  11518. return detail::write_content_with_progress(
  11519. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11520. req.upload_progress, error);
  11521. }
  11522. }
  11523. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11524. bool close_connection, Error &error,
  11525. bool skip_body) {
  11526. // Prepare additional headers
  11527. if (close_connection) {
  11528. if (!req.has_header("Connection")) {
  11529. req.set_header("Connection", "close");
  11530. }
  11531. }
  11532. std::string ct_for_defaults;
  11533. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11534. ct_for_defaults = "text/plain";
  11535. }
  11536. prepare_default_headers(req, false, ct_for_defaults);
  11537. if (req.body.empty()) {
  11538. if (req.content_provider_) {
  11539. if (!req.is_chunked_content_provider_) {
  11540. if (!req.has_header("Content-Length")) {
  11541. auto length = std::to_string(req.content_length_);
  11542. req.set_header("Content-Length", length);
  11543. }
  11544. }
  11545. } else {
  11546. if (req.method == "POST" || req.method == "PUT" ||
  11547. req.method == "PATCH") {
  11548. req.set_header("Content-Length", "0");
  11549. }
  11550. }
  11551. }
  11552. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11553. if (!req.has_header("Authorization")) {
  11554. req.headers.insert(make_basic_authentication_header(
  11555. basic_auth_username_, basic_auth_password_, false));
  11556. }
  11557. }
  11558. if (!bearer_token_auth_token_.empty()) {
  11559. if (!req.has_header("Authorization")) {
  11560. req.headers.insert(make_bearer_token_authentication_header(
  11561. bearer_token_auth_token_, false));
  11562. }
  11563. }
  11564. // Proxy-Authorization is only sent when the proxy is actually used for
  11565. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11566. // credentials directly to the destination server.
  11567. if (is_proxy_enabled_for_host(host_)) {
  11568. if (!proxy_basic_auth_username_.empty() &&
  11569. !proxy_basic_auth_password_.empty() &&
  11570. !req.has_header("Proxy-Authorization")) {
  11571. req.headers.insert(make_basic_authentication_header(
  11572. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11573. }
  11574. if (!proxy_bearer_token_auth_token_.empty() &&
  11575. !req.has_header("Proxy-Authorization")) {
  11576. req.headers.insert(make_bearer_token_authentication_header(
  11577. proxy_bearer_token_auth_token_, true));
  11578. }
  11579. }
  11580. // Request line and headers
  11581. {
  11582. detail::BufferStream bstrm;
  11583. // Extract path and query from req.path
  11584. std::string path_part, query_part;
  11585. auto query_pos = req.path.find('?');
  11586. if (query_pos != std::string::npos) {
  11587. path_part = req.path.substr(0, query_pos);
  11588. query_part = req.path.substr(query_pos + 1);
  11589. } else {
  11590. path_part = req.path;
  11591. query_part = "";
  11592. }
  11593. // Encode path part. If the original `req.path` already contained a
  11594. // query component, preserve its raw query string (including parameter
  11595. // order) instead of reparsing and reassembling it which may reorder
  11596. // parameters due to container ordering (e.g. `Params` uses
  11597. // `std::multimap`). When there is no query in `req.path`, fall back to
  11598. // building a query from `req.params` so existing callers that pass
  11599. // `Params` continue to work.
  11600. auto path_with_query =
  11601. path_encode_ ? detail::encode_path(path_part) : path_part;
  11602. if (!query_part.empty()) {
  11603. // Normalize the query string (decode then re-encode) while preserving
  11604. // the original parameter order. When path encoding is disabled the
  11605. // caller has supplied an already-encoded target and expects the exact
  11606. // bytes to be sent on the wire, so skip normalization for the query
  11607. // too. Normalizing here would decode-then-re-encode the query and
  11608. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11609. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11610. if (path_encode_) {
  11611. auto normalized = detail::normalize_query_string(query_part);
  11612. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11613. } else {
  11614. path_with_query += '?' + query_part;
  11615. }
  11616. // Still populate req.params for handlers/users who read them.
  11617. detail::parse_query_text(query_part, req.params);
  11618. } else {
  11619. // No query in path; parse any query_part (empty) and append params
  11620. // from `req.params` when present (preserves prior behavior for
  11621. // callers who provide Params separately).
  11622. detail::parse_query_text(query_part, req.params);
  11623. if (!req.params.empty()) {
  11624. path_with_query = append_query_params(path_with_query, req.params);
  11625. }
  11626. }
  11627. // Write request line and headers
  11628. detail::write_request_line(bstrm, req.method, path_with_query);
  11629. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11630. error)) {
  11631. output_error_log(error, &req);
  11632. return false;
  11633. }
  11634. // Flush buffer
  11635. auto &data = bstrm.get_buffer();
  11636. if (!detail::write_data(strm, data.data(), data.size())) {
  11637. error = Error::Write;
  11638. output_error_log(error, &req);
  11639. return false;
  11640. }
  11641. }
  11642. // After sending request line and headers, wait briefly for an early server
  11643. // response (e.g. 4xx) and avoid sending a potentially large request body
  11644. // unnecessarily. This workaround is only enabled on Windows because Unix
  11645. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11646. // buffering can accept large writes even when the peer already responded.
  11647. // Check the stream first (which covers SSL via `is_readable()`), then
  11648. // fall back to select on the socket. Only perform the wait for very large
  11649. // request bodies to avoid interfering with normal small requests and
  11650. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11651. // response. Skip this check when using Expect: 100-continue, as the protocol
  11652. // handles early responses properly.
  11653. #if defined(_WIN32)
  11654. if (!skip_body &&
  11655. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11656. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11657. auto start = std::chrono::high_resolution_clock::now();
  11658. for (;;) {
  11659. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11660. // from SSL internals. If the underlying socket is readable, assume an
  11661. // early response may be present.
  11662. auto sock = strm.socket();
  11663. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11664. return false;
  11665. }
  11666. // Fallback to stream-level check for non-socket streams or when the
  11667. // socket isn't reporting readable. Avoid using `is_readable()` for
  11668. // SSL, since `SSL_pending()` may report buffered records that do not
  11669. // indicate a complete application-level response yet.
  11670. if (!is_ssl() && strm.is_readable()) { return false; }
  11671. auto now = std::chrono::high_resolution_clock::now();
  11672. auto elapsed =
  11673. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11674. .count();
  11675. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11676. break;
  11677. }
  11678. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11679. }
  11680. }
  11681. #endif
  11682. // Body
  11683. if (skip_body) { return true; }
  11684. return write_request_body(strm, req, error);
  11685. }
  11686. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11687. Error &error) {
  11688. if (req.body.empty()) {
  11689. return write_content_with_provider(strm, req, error);
  11690. }
  11691. if (req.upload_progress) {
  11692. auto body_size = req.body.size();
  11693. size_t written = 0;
  11694. auto data = req.body.data();
  11695. while (written < body_size) {
  11696. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11697. if (!detail::write_data(strm, data + written, to_write)) {
  11698. error = Error::Write;
  11699. output_error_log(error, &req);
  11700. return false;
  11701. }
  11702. written += to_write;
  11703. if (!req.upload_progress(written, body_size)) {
  11704. error = Error::Canceled;
  11705. output_error_log(error, &req);
  11706. return false;
  11707. }
  11708. }
  11709. } else {
  11710. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11711. error = Error::Write;
  11712. output_error_log(error, &req);
  11713. return false;
  11714. }
  11715. }
  11716. return true;
  11717. }
  11718. inline std::unique_ptr<Response>
  11719. ClientImpl::send_with_content_provider_and_receiver(
  11720. Request &req, const char *body, size_t content_length,
  11721. ContentProvider content_provider,
  11722. ContentProviderWithoutLength content_provider_without_length,
  11723. const std::string &content_type, ContentReceiver content_receiver,
  11724. Error &error) {
  11725. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11726. auto enc = compress_
  11727. ? detail::create_compressor()
  11728. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11729. nullptr, nullptr);
  11730. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11731. if (enc.first && !content_provider_without_length) {
  11732. auto &compressor = enc.first;
  11733. if (content_provider) {
  11734. auto ok = true;
  11735. size_t offset = 0;
  11736. DataSink data_sink;
  11737. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11738. if (ok) {
  11739. auto last = offset + data_len == content_length;
  11740. auto ret = compressor->compress(
  11741. data, data_len, last,
  11742. [&](const char *compressed_data, size_t compressed_data_len) {
  11743. req.body.append(compressed_data, compressed_data_len);
  11744. return true;
  11745. });
  11746. if (ret) {
  11747. offset += data_len;
  11748. } else {
  11749. ok = false;
  11750. }
  11751. }
  11752. return ok;
  11753. };
  11754. while (ok && offset < content_length) {
  11755. if (!content_provider(offset, content_length - offset, data_sink)) {
  11756. error = Error::Canceled;
  11757. output_error_log(error, &req);
  11758. return nullptr;
  11759. }
  11760. }
  11761. } else {
  11762. if (!compressor->compress(body, content_length, true,
  11763. [&](const char *data, size_t data_len) {
  11764. req.body.append(data, data_len);
  11765. return true;
  11766. })) {
  11767. error = Error::Compression;
  11768. output_error_log(error, &req);
  11769. return nullptr;
  11770. }
  11771. }
  11772. } else {
  11773. if (content_provider) {
  11774. req.content_length_ = content_length;
  11775. req.content_provider_ = std::move(content_provider);
  11776. req.is_chunked_content_provider_ = false;
  11777. } else if (content_provider_without_length) {
  11778. req.content_length_ = 0;
  11779. req.content_provider_ = detail::ContentProviderAdapter(
  11780. std::move(content_provider_without_length));
  11781. req.is_chunked_content_provider_ = true;
  11782. req.set_header("Transfer-Encoding", "chunked");
  11783. } else {
  11784. req.body.assign(body, content_length);
  11785. }
  11786. }
  11787. if (content_receiver) {
  11788. req.content_receiver =
  11789. [content_receiver](const char *data, size_t data_length,
  11790. size_t /*offset*/, size_t /*total_length*/) {
  11791. return content_receiver(data, data_length);
  11792. };
  11793. }
  11794. auto res = detail::make_unique<Response>();
  11795. return send(req, *res, error) ? std::move(res) : nullptr;
  11796. }
  11797. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11798. const std::string &method, const std::string &path, const Headers &headers,
  11799. const char *body, size_t content_length, ContentProvider content_provider,
  11800. ContentProviderWithoutLength content_provider_without_length,
  11801. const std::string &content_type, ContentReceiver content_receiver,
  11802. UploadProgress progress) {
  11803. Request req;
  11804. req.method = method;
  11805. req.headers = headers;
  11806. req.path = path;
  11807. req.upload_progress = std::move(progress);
  11808. if (max_timeout_msec_ > 0) {
  11809. req.start_time_ = std::chrono::steady_clock::now();
  11810. }
  11811. auto error = Error::Success;
  11812. auto res = send_with_content_provider_and_receiver(
  11813. req, body, content_length, std::move(content_provider),
  11814. std::move(content_provider_without_length), content_type,
  11815. std::move(content_receiver), error);
  11816. #ifdef CPPHTTPLIB_SSL_ENABLED
  11817. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11818. last_backend_error_};
  11819. #else
  11820. return Result{std::move(res), error, std::move(req.headers)};
  11821. #endif
  11822. }
  11823. inline void ClientImpl::output_log(const Request &req,
  11824. const Response &res) const {
  11825. if (logger_) {
  11826. std::lock_guard<std::mutex> guard(logger_mutex_);
  11827. logger_(req, res);
  11828. }
  11829. }
  11830. inline void ClientImpl::output_error_log(const Error &err,
  11831. const Request *req) const {
  11832. if (error_logger_) {
  11833. std::lock_guard<std::mutex> guard(logger_mutex_);
  11834. error_logger_(err, req);
  11835. }
  11836. }
  11837. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11838. Response &res, bool close_connection,
  11839. Error &error) {
  11840. // Auto-add Expect: 100-continue for large bodies
  11841. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11842. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11843. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11844. req.set_header("Expect", "100-continue");
  11845. }
  11846. }
  11847. // Check for Expect: 100-continue
  11848. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11849. // Send request (skip body if using Expect: 100-continue)
  11850. auto write_request_success =
  11851. write_request(strm, req, close_connection, error, expect_100_continue);
  11852. #ifdef CPPHTTPLIB_SSL_ENABLED
  11853. if (is_ssl() && !expect_100_continue) {
  11854. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11855. if (!is_proxy_enabled) {
  11856. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11857. error = Error::SSLPeerCouldBeClosed_;
  11858. output_error_log(error, &req);
  11859. return false;
  11860. }
  11861. }
  11862. }
  11863. #endif
  11864. // Handle Expect: 100-continue.
  11865. //
  11866. // Wait for an interim/early response by attempting to read the status line
  11867. // under a short timeout, instead of trusting raw socket readability. Over
  11868. // TLS, post-handshake records (e.g. session tickets) make the socket
  11869. // readable without any HTTP response being available; relying on
  11870. // `select_read` there caused the body to be withheld forever and the
  11871. // request to fail with `Read` (#2458). If no status line arrives within the
  11872. // timeout, send the body anyway (matching curl's behavior).
  11873. auto status_line_read = false;
  11874. if (expect_100_continue && write_request_success) {
  11875. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11876. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11877. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11878. strm.set_read_timeout(sec, usec);
  11879. status_line_read = read_response_line(strm, req, res, false);
  11880. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11881. }
  11882. if (!status_line_read) {
  11883. // No interim response within the timeout: send the body and handle the
  11884. // response as usual.
  11885. if (!write_request_body(strm, req, error)) { return false; }
  11886. expect_100_continue = false; // Switch to normal response handling
  11887. }
  11888. }
  11889. // Receive response and headers
  11890. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11891. if ((!status_line_read &&
  11892. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11893. !detail::read_headers(strm, res.headers)) {
  11894. if (write_request_success) { error = Error::Read; }
  11895. output_error_log(error, &req);
  11896. return false;
  11897. }
  11898. if (!write_request_success) { return false; }
  11899. // Handle Expect: 100-continue response
  11900. if (expect_100_continue) {
  11901. if (res.status == StatusCode::Continue_100) {
  11902. // Server accepted, send the body
  11903. if (!write_request_body(strm, req, error)) { return false; }
  11904. // Read the actual response
  11905. res.headers.clear();
  11906. res.body.clear();
  11907. if (!read_response_line(strm, req, res) ||
  11908. !detail::read_headers(strm, res.headers)) {
  11909. error = Error::Read;
  11910. output_error_log(error, &req);
  11911. return false;
  11912. }
  11913. }
  11914. // If not 100 Continue, server returned an error; proceed with that response
  11915. }
  11916. // Body
  11917. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11918. req.method != "CONNECT") {
  11919. auto redirect = 300 < res.status && res.status < 400 &&
  11920. res.status != StatusCode::NotModified_304 &&
  11921. follow_location_;
  11922. if (req.response_handler && !redirect) {
  11923. if (!req.response_handler(res)) {
  11924. error = Error::Canceled;
  11925. output_error_log(error, &req);
  11926. return false;
  11927. }
  11928. }
  11929. auto out =
  11930. req.content_receiver
  11931. ? static_cast<ContentReceiverWithProgress>(
  11932. [&](const char *buf, size_t n, size_t off, size_t len) {
  11933. if (redirect) { return true; }
  11934. auto ret = req.content_receiver(buf, n, off, len);
  11935. if (!ret) {
  11936. error = Error::Canceled;
  11937. output_error_log(error, &req);
  11938. }
  11939. return ret;
  11940. })
  11941. : static_cast<ContentReceiverWithProgress>(
  11942. [&](const char *buf, size_t n, size_t /*off*/,
  11943. size_t /*len*/) {
  11944. assert(res.body.size() + n <= res.body.max_size());
  11945. if (payload_max_length_ > 0 &&
  11946. (res.body.size() >= payload_max_length_ ||
  11947. n > payload_max_length_ - res.body.size())) {
  11948. return false;
  11949. }
  11950. res.body.append(buf, n);
  11951. return true;
  11952. });
  11953. auto progress = [&](size_t current, size_t total) {
  11954. if (!req.download_progress || redirect) { return true; }
  11955. auto ret = req.download_progress(current, total);
  11956. if (!ret) {
  11957. error = Error::Canceled;
  11958. output_error_log(error, &req);
  11959. }
  11960. return ret;
  11961. };
  11962. if (res.has_header("Content-Length")) {
  11963. if (!req.content_receiver) {
  11964. auto len = res.get_header_value_u64("Content-Length");
  11965. if (len > res.body.max_size()) {
  11966. error = Error::Read;
  11967. output_error_log(error, &req);
  11968. return false;
  11969. }
  11970. // Cap the reservation by payload_max_length_ to avoid OOM when a
  11971. // hostile or malformed server sends an enormous Content-Length.
  11972. // The actual body read below is bounded by payload_max_length_,
  11973. // so reserving more than that is never useful.
  11974. auto reserve_len = static_cast<size_t>(len);
  11975. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  11976. reserve_len = payload_max_length_;
  11977. }
  11978. res.body.reserve(reserve_len);
  11979. }
  11980. }
  11981. if (res.status != StatusCode::NotModified_304) {
  11982. int dummy_status;
  11983. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11984. ? (std::numeric_limits<size_t>::max)()
  11985. : payload_max_length_;
  11986. if (!detail::read_content(strm, res, max_length, dummy_status,
  11987. std::move(progress), std::move(out),
  11988. decompress_)) {
  11989. if (error != Error::Canceled) { error = Error::Read; }
  11990. output_error_log(error, &req);
  11991. return false;
  11992. }
  11993. }
  11994. }
  11995. // Log
  11996. output_log(req, res);
  11997. return true;
  11998. }
  11999. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  12000. const std::string &boundary, const UploadFormDataItems &items,
  12001. const FormDataProviderItems &provider_items) const {
  12002. size_t cur_item = 0;
  12003. size_t cur_start = 0;
  12004. // cur_item and cur_start are copied to within the std::function and
  12005. // maintain state between successive calls
  12006. return [&, cur_item, cur_start](size_t offset,
  12007. DataSink &sink) mutable -> bool {
  12008. if (!offset && !items.empty()) {
  12009. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12010. return true;
  12011. } else if (cur_item < provider_items.size()) {
  12012. if (!cur_start) {
  12013. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12014. provider_items[cur_item], boundary);
  12015. offset += begin.size();
  12016. cur_start = offset;
  12017. sink.os << begin;
  12018. }
  12019. DataSink cur_sink;
  12020. auto has_data = true;
  12021. cur_sink.write = sink.write;
  12022. cur_sink.done = [&]() { has_data = false; };
  12023. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12024. return false;
  12025. }
  12026. if (!has_data) {
  12027. sink.os << detail::serialize_multipart_formdata_item_end();
  12028. cur_item++;
  12029. cur_start = 0;
  12030. }
  12031. return true;
  12032. } else {
  12033. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12034. sink.done();
  12035. return true;
  12036. }
  12037. };
  12038. }
  12039. inline bool ClientImpl::process_socket(
  12040. const Socket &socket,
  12041. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12042. std::function<bool(Stream &strm)> callback) {
  12043. return detail::process_client_socket(
  12044. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12045. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12046. }
  12047. inline bool ClientImpl::is_ssl() const { return false; }
  12048. inline Result ClientImpl::Get(const std::string &path,
  12049. DownloadProgress progress) {
  12050. return Get(path, Headers(), std::move(progress));
  12051. }
  12052. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12053. DownloadProgress progress) {
  12054. return Get(path, params, Headers(), std::move(progress));
  12055. }
  12056. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12057. const Headers &headers,
  12058. DownloadProgress progress) {
  12059. if (params.empty()) { return Get(path, headers); }
  12060. std::string path_with_query = append_query_params(path, params);
  12061. return Get(path_with_query, headers, std::move(progress));
  12062. }
  12063. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12064. DownloadProgress progress) {
  12065. Request req;
  12066. req.method = "GET";
  12067. req.path = path;
  12068. req.headers = headers;
  12069. req.download_progress = std::move(progress);
  12070. if (max_timeout_msec_ > 0) {
  12071. req.start_time_ = std::chrono::steady_clock::now();
  12072. }
  12073. return send_(std::move(req));
  12074. }
  12075. inline Result ClientImpl::Get(const std::string &path,
  12076. ContentReceiver content_receiver,
  12077. DownloadProgress progress) {
  12078. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12079. std::move(progress));
  12080. }
  12081. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12082. ContentReceiver content_receiver,
  12083. DownloadProgress progress) {
  12084. return Get(path, headers, nullptr, std::move(content_receiver),
  12085. std::move(progress));
  12086. }
  12087. inline Result ClientImpl::Get(const std::string &path,
  12088. ResponseHandler response_handler,
  12089. ContentReceiver content_receiver,
  12090. DownloadProgress progress) {
  12091. return Get(path, Headers(), std::move(response_handler),
  12092. std::move(content_receiver), std::move(progress));
  12093. }
  12094. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12095. ResponseHandler response_handler,
  12096. ContentReceiver content_receiver,
  12097. DownloadProgress progress) {
  12098. Request req;
  12099. req.method = "GET";
  12100. req.path = path;
  12101. req.headers = headers;
  12102. req.response_handler = std::move(response_handler);
  12103. req.content_receiver =
  12104. [content_receiver](const char *data, size_t data_length,
  12105. size_t /*offset*/, size_t /*total_length*/) {
  12106. return content_receiver(data, data_length);
  12107. };
  12108. req.download_progress = std::move(progress);
  12109. if (max_timeout_msec_ > 0) {
  12110. req.start_time_ = std::chrono::steady_clock::now();
  12111. }
  12112. return send_(std::move(req));
  12113. }
  12114. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12115. const Headers &headers,
  12116. ContentReceiver content_receiver,
  12117. DownloadProgress progress) {
  12118. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12119. std::move(progress));
  12120. }
  12121. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12122. const Headers &headers,
  12123. ResponseHandler response_handler,
  12124. ContentReceiver content_receiver,
  12125. DownloadProgress progress) {
  12126. if (params.empty()) {
  12127. return Get(path, headers, std::move(response_handler),
  12128. std::move(content_receiver), std::move(progress));
  12129. }
  12130. std::string path_with_query = append_query_params(path, params);
  12131. return Get(path_with_query, headers, std::move(response_handler),
  12132. std::move(content_receiver), std::move(progress));
  12133. }
  12134. inline Result ClientImpl::Head(const std::string &path) {
  12135. return Head(path, Headers());
  12136. }
  12137. inline Result ClientImpl::Head(const std::string &path,
  12138. const Headers &headers) {
  12139. Request req;
  12140. req.method = "HEAD";
  12141. req.headers = headers;
  12142. req.path = path;
  12143. if (max_timeout_msec_ > 0) {
  12144. req.start_time_ = std::chrono::steady_clock::now();
  12145. }
  12146. return send_(std::move(req));
  12147. }
  12148. inline Result ClientImpl::Post(const std::string &path) {
  12149. return Post(path, std::string(), std::string());
  12150. }
  12151. inline Result ClientImpl::Post(const std::string &path,
  12152. const Headers &headers) {
  12153. return Post(path, headers, nullptr, 0, std::string());
  12154. }
  12155. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12156. size_t content_length,
  12157. const std::string &content_type,
  12158. UploadProgress progress) {
  12159. return Post(path, Headers(), body, content_length, content_type, progress);
  12160. }
  12161. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12162. const std::string &content_type,
  12163. UploadProgress progress) {
  12164. return Post(path, Headers(), body, content_type, progress);
  12165. }
  12166. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12167. return Post(path, Headers(), params);
  12168. }
  12169. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12170. ContentProvider content_provider,
  12171. const std::string &content_type,
  12172. UploadProgress progress) {
  12173. return Post(path, Headers(), content_length, std::move(content_provider),
  12174. content_type, progress);
  12175. }
  12176. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12177. ContentProvider content_provider,
  12178. const std::string &content_type,
  12179. ContentReceiver content_receiver,
  12180. UploadProgress progress) {
  12181. return Post(path, Headers(), content_length, std::move(content_provider),
  12182. content_type, std::move(content_receiver), progress);
  12183. }
  12184. inline Result ClientImpl::Post(const std::string &path,
  12185. ContentProviderWithoutLength content_provider,
  12186. const std::string &content_type,
  12187. UploadProgress progress) {
  12188. return Post(path, Headers(), std::move(content_provider), content_type,
  12189. progress);
  12190. }
  12191. inline Result ClientImpl::Post(const std::string &path,
  12192. ContentProviderWithoutLength content_provider,
  12193. const std::string &content_type,
  12194. ContentReceiver content_receiver,
  12195. UploadProgress progress) {
  12196. return Post(path, Headers(), std::move(content_provider), content_type,
  12197. std::move(content_receiver), progress);
  12198. }
  12199. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12200. const Params &params) {
  12201. auto query = detail::params_to_query_str(params);
  12202. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12203. }
  12204. inline Result ClientImpl::Post(const std::string &path,
  12205. const UploadFormDataItems &items,
  12206. UploadProgress progress) {
  12207. return Post(path, Headers(), items, progress);
  12208. }
  12209. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12210. const UploadFormDataItems &items,
  12211. UploadProgress progress) {
  12212. const auto &boundary = detail::make_multipart_data_boundary();
  12213. const auto &content_type =
  12214. detail::serialize_multipart_formdata_get_content_type(boundary);
  12215. auto content_length = detail::get_multipart_content_length(items, boundary);
  12216. return Post(path, headers, content_length,
  12217. detail::make_multipart_content_provider(items, boundary),
  12218. content_type, progress);
  12219. }
  12220. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12221. const UploadFormDataItems &items,
  12222. const std::string &boundary,
  12223. UploadProgress progress) {
  12224. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12225. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12226. }
  12227. const auto &content_type =
  12228. detail::serialize_multipart_formdata_get_content_type(boundary);
  12229. auto content_length = detail::get_multipart_content_length(items, boundary);
  12230. return Post(path, headers, content_length,
  12231. detail::make_multipart_content_provider(items, boundary),
  12232. content_type, progress);
  12233. }
  12234. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12235. const char *body, size_t content_length,
  12236. const std::string &content_type,
  12237. UploadProgress progress) {
  12238. return send_with_content_provider_and_receiver(
  12239. "POST", path, headers, body, content_length, nullptr, nullptr,
  12240. content_type, nullptr, progress);
  12241. }
  12242. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12243. const std::string &body,
  12244. const std::string &content_type,
  12245. UploadProgress progress) {
  12246. return send_with_content_provider_and_receiver(
  12247. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12248. content_type, nullptr, progress);
  12249. }
  12250. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12251. size_t content_length,
  12252. ContentProvider content_provider,
  12253. const std::string &content_type,
  12254. UploadProgress progress) {
  12255. return send_with_content_provider_and_receiver(
  12256. "POST", path, headers, nullptr, content_length,
  12257. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12258. }
  12259. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12260. size_t content_length,
  12261. ContentProvider content_provider,
  12262. const std::string &content_type,
  12263. ContentReceiver content_receiver,
  12264. DownloadProgress progress) {
  12265. return send_with_content_provider_and_receiver(
  12266. "POST", path, headers, nullptr, content_length,
  12267. std::move(content_provider), nullptr, content_type,
  12268. std::move(content_receiver), std::move(progress));
  12269. }
  12270. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12271. ContentProviderWithoutLength content_provider,
  12272. const std::string &content_type,
  12273. UploadProgress progress) {
  12274. return send_with_content_provider_and_receiver(
  12275. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12276. content_type, nullptr, progress);
  12277. }
  12278. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12279. ContentProviderWithoutLength content_provider,
  12280. const std::string &content_type,
  12281. ContentReceiver content_receiver,
  12282. DownloadProgress progress) {
  12283. return send_with_content_provider_and_receiver(
  12284. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12285. content_type, std::move(content_receiver), std::move(progress));
  12286. }
  12287. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12288. const UploadFormDataItems &items,
  12289. const FormDataProviderItems &provider_items,
  12290. UploadProgress progress) {
  12291. const auto &boundary = detail::make_multipart_data_boundary();
  12292. const auto &content_type =
  12293. detail::serialize_multipart_formdata_get_content_type(boundary);
  12294. return send_with_content_provider_and_receiver(
  12295. "POST", path, headers, nullptr, 0, nullptr,
  12296. get_multipart_content_provider(boundary, items, provider_items),
  12297. content_type, nullptr, progress);
  12298. }
  12299. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12300. const std::string &body,
  12301. const std::string &content_type,
  12302. ContentReceiver content_receiver,
  12303. DownloadProgress progress) {
  12304. Request req;
  12305. req.method = "POST";
  12306. req.path = path;
  12307. req.headers = headers;
  12308. req.body = body;
  12309. req.content_receiver =
  12310. [content_receiver](const char *data, size_t data_length,
  12311. size_t /*offset*/, size_t /*total_length*/) {
  12312. return content_receiver(data, data_length);
  12313. };
  12314. req.download_progress = std::move(progress);
  12315. if (max_timeout_msec_ > 0) {
  12316. req.start_time_ = std::chrono::steady_clock::now();
  12317. }
  12318. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12319. return send_(std::move(req));
  12320. }
  12321. inline Result ClientImpl::Put(const std::string &path) {
  12322. return Put(path, std::string(), std::string());
  12323. }
  12324. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12325. return Put(path, headers, nullptr, 0, std::string());
  12326. }
  12327. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12328. size_t content_length,
  12329. const std::string &content_type,
  12330. UploadProgress progress) {
  12331. return Put(path, Headers(), body, content_length, content_type, progress);
  12332. }
  12333. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12334. const std::string &content_type,
  12335. UploadProgress progress) {
  12336. return Put(path, Headers(), body, content_type, progress);
  12337. }
  12338. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12339. return Put(path, Headers(), params);
  12340. }
  12341. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12342. ContentProvider content_provider,
  12343. const std::string &content_type,
  12344. UploadProgress progress) {
  12345. return Put(path, Headers(), content_length, std::move(content_provider),
  12346. content_type, progress);
  12347. }
  12348. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12349. ContentProvider content_provider,
  12350. const std::string &content_type,
  12351. ContentReceiver content_receiver,
  12352. UploadProgress progress) {
  12353. return Put(path, Headers(), content_length, std::move(content_provider),
  12354. content_type, std::move(content_receiver), progress);
  12355. }
  12356. inline Result ClientImpl::Put(const std::string &path,
  12357. ContentProviderWithoutLength content_provider,
  12358. const std::string &content_type,
  12359. UploadProgress progress) {
  12360. return Put(path, Headers(), std::move(content_provider), content_type,
  12361. progress);
  12362. }
  12363. inline Result ClientImpl::Put(const std::string &path,
  12364. ContentProviderWithoutLength content_provider,
  12365. const std::string &content_type,
  12366. ContentReceiver content_receiver,
  12367. UploadProgress progress) {
  12368. return Put(path, Headers(), std::move(content_provider), content_type,
  12369. std::move(content_receiver), progress);
  12370. }
  12371. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12372. const Params &params) {
  12373. auto query = detail::params_to_query_str(params);
  12374. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12375. }
  12376. inline Result ClientImpl::Put(const std::string &path,
  12377. const UploadFormDataItems &items,
  12378. UploadProgress progress) {
  12379. return Put(path, Headers(), items, progress);
  12380. }
  12381. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12382. const UploadFormDataItems &items,
  12383. UploadProgress progress) {
  12384. const auto &boundary = detail::make_multipart_data_boundary();
  12385. const auto &content_type =
  12386. detail::serialize_multipart_formdata_get_content_type(boundary);
  12387. auto content_length = detail::get_multipart_content_length(items, boundary);
  12388. return Put(path, headers, content_length,
  12389. detail::make_multipart_content_provider(items, boundary),
  12390. content_type, progress);
  12391. }
  12392. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12393. const UploadFormDataItems &items,
  12394. const std::string &boundary,
  12395. UploadProgress progress) {
  12396. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12397. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12398. }
  12399. const auto &content_type =
  12400. detail::serialize_multipart_formdata_get_content_type(boundary);
  12401. auto content_length = detail::get_multipart_content_length(items, boundary);
  12402. return Put(path, headers, content_length,
  12403. detail::make_multipart_content_provider(items, boundary),
  12404. content_type, progress);
  12405. }
  12406. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12407. const char *body, size_t content_length,
  12408. const std::string &content_type,
  12409. UploadProgress progress) {
  12410. return send_with_content_provider_and_receiver(
  12411. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12412. content_type, nullptr, progress);
  12413. }
  12414. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12415. const std::string &body,
  12416. const std::string &content_type,
  12417. UploadProgress progress) {
  12418. return send_with_content_provider_and_receiver(
  12419. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12420. content_type, nullptr, progress);
  12421. }
  12422. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12423. size_t content_length,
  12424. ContentProvider content_provider,
  12425. const std::string &content_type,
  12426. UploadProgress progress) {
  12427. return send_with_content_provider_and_receiver(
  12428. "PUT", path, headers, nullptr, content_length,
  12429. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12430. }
  12431. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12432. size_t content_length,
  12433. ContentProvider content_provider,
  12434. const std::string &content_type,
  12435. ContentReceiver content_receiver,
  12436. UploadProgress progress) {
  12437. return send_with_content_provider_and_receiver(
  12438. "PUT", path, headers, nullptr, content_length,
  12439. std::move(content_provider), nullptr, content_type,
  12440. std::move(content_receiver), progress);
  12441. }
  12442. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12443. ContentProviderWithoutLength content_provider,
  12444. const std::string &content_type,
  12445. UploadProgress progress) {
  12446. return send_with_content_provider_and_receiver(
  12447. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12448. content_type, nullptr, progress);
  12449. }
  12450. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12451. ContentProviderWithoutLength content_provider,
  12452. const std::string &content_type,
  12453. ContentReceiver content_receiver,
  12454. UploadProgress progress) {
  12455. return send_with_content_provider_and_receiver(
  12456. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12457. content_type, std::move(content_receiver), progress);
  12458. }
  12459. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12460. const UploadFormDataItems &items,
  12461. const FormDataProviderItems &provider_items,
  12462. UploadProgress progress) {
  12463. const auto &boundary = detail::make_multipart_data_boundary();
  12464. const auto &content_type =
  12465. detail::serialize_multipart_formdata_get_content_type(boundary);
  12466. return send_with_content_provider_and_receiver(
  12467. "PUT", path, headers, nullptr, 0, nullptr,
  12468. get_multipart_content_provider(boundary, items, provider_items),
  12469. content_type, nullptr, progress);
  12470. }
  12471. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12472. const std::string &body,
  12473. const std::string &content_type,
  12474. ContentReceiver content_receiver,
  12475. DownloadProgress progress) {
  12476. Request req;
  12477. req.method = "PUT";
  12478. req.path = path;
  12479. req.headers = headers;
  12480. req.body = body;
  12481. req.content_receiver =
  12482. [content_receiver](const char *data, size_t data_length,
  12483. size_t /*offset*/, size_t /*total_length*/) {
  12484. return content_receiver(data, data_length);
  12485. };
  12486. req.download_progress = std::move(progress);
  12487. if (max_timeout_msec_ > 0) {
  12488. req.start_time_ = std::chrono::steady_clock::now();
  12489. }
  12490. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12491. return send_(std::move(req));
  12492. }
  12493. inline Result ClientImpl::Patch(const std::string &path) {
  12494. return Patch(path, std::string(), std::string());
  12495. }
  12496. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12497. UploadProgress progress) {
  12498. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12499. }
  12500. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12501. size_t content_length,
  12502. const std::string &content_type,
  12503. UploadProgress progress) {
  12504. return Patch(path, Headers(), body, content_length, content_type, progress);
  12505. }
  12506. inline Result ClientImpl::Patch(const std::string &path,
  12507. const std::string &body,
  12508. const std::string &content_type,
  12509. UploadProgress progress) {
  12510. return Patch(path, Headers(), body, content_type, progress);
  12511. }
  12512. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12513. return Patch(path, Headers(), params);
  12514. }
  12515. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12516. ContentProvider content_provider,
  12517. const std::string &content_type,
  12518. UploadProgress progress) {
  12519. return Patch(path, Headers(), content_length, std::move(content_provider),
  12520. content_type, progress);
  12521. }
  12522. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12523. ContentProvider content_provider,
  12524. const std::string &content_type,
  12525. ContentReceiver content_receiver,
  12526. UploadProgress progress) {
  12527. return Patch(path, Headers(), content_length, std::move(content_provider),
  12528. content_type, std::move(content_receiver), progress);
  12529. }
  12530. inline Result ClientImpl::Patch(const std::string &path,
  12531. ContentProviderWithoutLength content_provider,
  12532. const std::string &content_type,
  12533. UploadProgress progress) {
  12534. return Patch(path, Headers(), std::move(content_provider), content_type,
  12535. progress);
  12536. }
  12537. inline Result ClientImpl::Patch(const std::string &path,
  12538. ContentProviderWithoutLength content_provider,
  12539. const std::string &content_type,
  12540. ContentReceiver content_receiver,
  12541. UploadProgress progress) {
  12542. return Patch(path, Headers(), std::move(content_provider), content_type,
  12543. std::move(content_receiver), progress);
  12544. }
  12545. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12546. const Params &params) {
  12547. auto query = detail::params_to_query_str(params);
  12548. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12549. }
  12550. inline Result ClientImpl::Patch(const std::string &path,
  12551. const UploadFormDataItems &items,
  12552. UploadProgress progress) {
  12553. return Patch(path, Headers(), items, progress);
  12554. }
  12555. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12556. const UploadFormDataItems &items,
  12557. UploadProgress progress) {
  12558. const auto &boundary = detail::make_multipart_data_boundary();
  12559. const auto &content_type =
  12560. detail::serialize_multipart_formdata_get_content_type(boundary);
  12561. auto content_length = detail::get_multipart_content_length(items, boundary);
  12562. return Patch(path, headers, content_length,
  12563. detail::make_multipart_content_provider(items, boundary),
  12564. content_type, progress);
  12565. }
  12566. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12567. const UploadFormDataItems &items,
  12568. const std::string &boundary,
  12569. UploadProgress progress) {
  12570. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12571. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12572. }
  12573. const auto &content_type =
  12574. detail::serialize_multipart_formdata_get_content_type(boundary);
  12575. auto content_length = detail::get_multipart_content_length(items, boundary);
  12576. return Patch(path, headers, content_length,
  12577. detail::make_multipart_content_provider(items, boundary),
  12578. content_type, progress);
  12579. }
  12580. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12581. const char *body, size_t content_length,
  12582. const std::string &content_type,
  12583. UploadProgress progress) {
  12584. return send_with_content_provider_and_receiver(
  12585. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12586. content_type, nullptr, progress);
  12587. }
  12588. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12589. const std::string &body,
  12590. const std::string &content_type,
  12591. UploadProgress progress) {
  12592. return send_with_content_provider_and_receiver(
  12593. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12594. content_type, nullptr, progress);
  12595. }
  12596. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12597. size_t content_length,
  12598. ContentProvider content_provider,
  12599. const std::string &content_type,
  12600. UploadProgress progress) {
  12601. return send_with_content_provider_and_receiver(
  12602. "PATCH", path, headers, nullptr, content_length,
  12603. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12604. }
  12605. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12606. size_t content_length,
  12607. ContentProvider content_provider,
  12608. const std::string &content_type,
  12609. ContentReceiver content_receiver,
  12610. UploadProgress progress) {
  12611. return send_with_content_provider_and_receiver(
  12612. "PATCH", path, headers, nullptr, content_length,
  12613. std::move(content_provider), nullptr, content_type,
  12614. std::move(content_receiver), progress);
  12615. }
  12616. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12617. ContentProviderWithoutLength content_provider,
  12618. const std::string &content_type,
  12619. UploadProgress progress) {
  12620. return send_with_content_provider_and_receiver(
  12621. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12622. content_type, nullptr, progress);
  12623. }
  12624. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12625. ContentProviderWithoutLength content_provider,
  12626. const std::string &content_type,
  12627. ContentReceiver content_receiver,
  12628. UploadProgress progress) {
  12629. return send_with_content_provider_and_receiver(
  12630. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12631. content_type, std::move(content_receiver), progress);
  12632. }
  12633. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12634. const UploadFormDataItems &items,
  12635. const FormDataProviderItems &provider_items,
  12636. UploadProgress progress) {
  12637. const auto &boundary = detail::make_multipart_data_boundary();
  12638. const auto &content_type =
  12639. detail::serialize_multipart_formdata_get_content_type(boundary);
  12640. return send_with_content_provider_and_receiver(
  12641. "PATCH", path, headers, nullptr, 0, nullptr,
  12642. get_multipart_content_provider(boundary, items, provider_items),
  12643. content_type, nullptr, progress);
  12644. }
  12645. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12646. const std::string &body,
  12647. const std::string &content_type,
  12648. ContentReceiver content_receiver,
  12649. DownloadProgress progress) {
  12650. Request req;
  12651. req.method = "PATCH";
  12652. req.path = path;
  12653. req.headers = headers;
  12654. req.body = body;
  12655. req.content_receiver =
  12656. [content_receiver](const char *data, size_t data_length,
  12657. size_t /*offset*/, size_t /*total_length*/) {
  12658. return content_receiver(data, data_length);
  12659. };
  12660. req.download_progress = std::move(progress);
  12661. if (max_timeout_msec_ > 0) {
  12662. req.start_time_ = std::chrono::steady_clock::now();
  12663. }
  12664. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12665. return send_(std::move(req));
  12666. }
  12667. inline Result ClientImpl::Delete(const std::string &path,
  12668. DownloadProgress progress) {
  12669. return Delete(path, Headers(), std::string(), std::string(), progress);
  12670. }
  12671. inline Result ClientImpl::Delete(const std::string &path,
  12672. const Headers &headers,
  12673. DownloadProgress progress) {
  12674. return Delete(path, headers, std::string(), std::string(), progress);
  12675. }
  12676. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12677. size_t content_length,
  12678. const std::string &content_type,
  12679. DownloadProgress progress) {
  12680. return Delete(path, Headers(), body, content_length, content_type, progress);
  12681. }
  12682. inline Result ClientImpl::Delete(const std::string &path,
  12683. const std::string &body,
  12684. const std::string &content_type,
  12685. DownloadProgress progress) {
  12686. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12687. progress);
  12688. }
  12689. inline Result ClientImpl::Delete(const std::string &path,
  12690. const Headers &headers,
  12691. const std::string &body,
  12692. const std::string &content_type,
  12693. DownloadProgress progress) {
  12694. return Delete(path, headers, body.data(), body.size(), content_type,
  12695. progress);
  12696. }
  12697. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12698. DownloadProgress progress) {
  12699. return Delete(path, Headers(), params, progress);
  12700. }
  12701. inline Result ClientImpl::Delete(const std::string &path,
  12702. const Headers &headers, const Params &params,
  12703. DownloadProgress progress) {
  12704. auto query = detail::params_to_query_str(params);
  12705. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12706. progress);
  12707. }
  12708. inline Result ClientImpl::Delete(const std::string &path,
  12709. const Headers &headers, const char *body,
  12710. size_t content_length,
  12711. const std::string &content_type,
  12712. DownloadProgress progress) {
  12713. Request req;
  12714. req.method = "DELETE";
  12715. req.headers = headers;
  12716. req.path = path;
  12717. req.download_progress = std::move(progress);
  12718. if (max_timeout_msec_ > 0) {
  12719. req.start_time_ = std::chrono::steady_clock::now();
  12720. }
  12721. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12722. req.body.assign(body, content_length);
  12723. return send_(std::move(req));
  12724. }
  12725. inline Result ClientImpl::Options(const std::string &path) {
  12726. return Options(path, Headers());
  12727. }
  12728. inline Result ClientImpl::Options(const std::string &path,
  12729. const Headers &headers) {
  12730. Request req;
  12731. req.method = "OPTIONS";
  12732. req.headers = headers;
  12733. req.path = path;
  12734. if (max_timeout_msec_ > 0) {
  12735. req.start_time_ = std::chrono::steady_clock::now();
  12736. }
  12737. return send_(std::move(req));
  12738. }
  12739. inline void ClientImpl::stop() {
  12740. std::lock_guard<std::mutex> guard(socket_mutex_);
  12741. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12742. // do is to shutdown_socket, so that threads using this socket suddenly
  12743. // discover they can't read/write any more and error out. Everything else
  12744. // (closing the socket, shutting ssl down) is unsafe because these actions
  12745. // are not thread-safe.
  12746. if (socket_requests_in_flight_ > 0) {
  12747. shutdown_socket(socket_);
  12748. // Aside from that, we set a flag for the socket to be closed when we're
  12749. // done.
  12750. socket_should_be_closed_when_request_is_done_ = true;
  12751. return;
  12752. }
  12753. disconnect(/*gracefully=*/true);
  12754. }
  12755. inline std::string ClientImpl::host() const { return host_; }
  12756. inline int ClientImpl::port() const { return port_; }
  12757. inline size_t ClientImpl::is_socket_open() const {
  12758. std::lock_guard<std::mutex> guard(socket_mutex_);
  12759. return socket_.is_open();
  12760. }
  12761. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12762. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12763. connection_timeout_sec_ = sec;
  12764. connection_timeout_usec_ = usec;
  12765. }
  12766. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12767. read_timeout_sec_ = sec;
  12768. read_timeout_usec_ = usec;
  12769. }
  12770. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12771. write_timeout_sec_ = sec;
  12772. write_timeout_usec_ = usec;
  12773. }
  12774. inline void ClientImpl::set_max_timeout(time_t msec) {
  12775. max_timeout_msec_ = msec;
  12776. }
  12777. inline void ClientImpl::set_basic_auth(const std::string &username,
  12778. const std::string &password) {
  12779. basic_auth_username_ = username;
  12780. basic_auth_password_ = password;
  12781. }
  12782. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12783. bearer_token_auth_token_ = token;
  12784. }
  12785. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12786. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12787. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12788. inline void
  12789. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12790. addr_map_ = std::move(addr_map);
  12791. }
  12792. inline void ClientImpl::set_default_headers(Headers headers) {
  12793. default_headers_ = std::move(headers);
  12794. }
  12795. inline void ClientImpl::set_header_writer(
  12796. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12797. header_writer_ = writer;
  12798. }
  12799. inline void ClientImpl::set_address_family(int family) {
  12800. address_family_ = family;
  12801. }
  12802. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12803. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12804. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12805. socket_options_ = std::move(socket_options);
  12806. }
  12807. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12808. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12809. inline void ClientImpl::set_payload_max_length(size_t length) {
  12810. payload_max_length_ = length;
  12811. has_payload_max_length_ = true;
  12812. }
  12813. inline void ClientImpl::set_interface(const std::string &intf) {
  12814. interface_ = intf;
  12815. }
  12816. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12817. proxy_host_ = host;
  12818. proxy_port_ = port;
  12819. std::lock_guard<std::mutex> guard(socket_mutex_);
  12820. disconnect(/*gracefully=*/true);
  12821. }
  12822. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12823. const std::string &password) {
  12824. proxy_basic_auth_username_ = username;
  12825. proxy_basic_auth_password_ = password;
  12826. }
  12827. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12828. proxy_bearer_token_auth_token_ = token;
  12829. }
  12830. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12831. std::vector<detail::NoProxyEntry> parsed;
  12832. parsed.reserve(patterns.size());
  12833. for (const auto &p : patterns) {
  12834. auto trimmed = detail::trim_copy(p);
  12835. if (trimmed.empty()) { continue; }
  12836. detail::NoProxyEntry entry;
  12837. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12838. parsed.push_back(std::move(entry));
  12839. }
  12840. }
  12841. no_proxy_entries_ = std::move(parsed);
  12842. std::lock_guard<std::mutex> guard(socket_mutex_);
  12843. disconnect(/*gracefully=*/true);
  12844. }
  12845. #ifdef CPPHTTPLIB_SSL_ENABLED
  12846. inline void ClientImpl::set_digest_auth(const std::string &username,
  12847. const std::string &password) {
  12848. digest_auth_username_ = username;
  12849. digest_auth_password_ = password;
  12850. }
  12851. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12852. const std::string &ca_cert_dir_path) {
  12853. ca_cert_file_path_ = ca_cert_file_path;
  12854. ca_cert_dir_path_ = ca_cert_dir_path;
  12855. }
  12856. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12857. const std::string &password) {
  12858. proxy_digest_auth_username_ = username;
  12859. proxy_digest_auth_password_ = password;
  12860. }
  12861. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12862. server_certificate_verification_ = enabled;
  12863. }
  12864. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12865. server_hostname_verification_ = enabled;
  12866. }
  12867. inline void ClientImpl::enable_system_ca(bool enabled) {
  12868. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12869. }
  12870. #endif
  12871. inline void ClientImpl::set_logger(Logger logger) {
  12872. logger_ = std::move(logger);
  12873. }
  12874. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12875. error_logger_ = std::move(error_logger);
  12876. }
  12877. /*
  12878. * SSL/TLS Common Implementation
  12879. */
  12880. inline ClientConnection::~ClientConnection() {
  12881. #ifdef CPPHTTPLIB_SSL_ENABLED
  12882. if (session) {
  12883. tls::shutdown(session, true);
  12884. tls::free_session(session);
  12885. session = nullptr;
  12886. }
  12887. #endif
  12888. if (sock != INVALID_SOCKET) {
  12889. detail::close_socket(sock);
  12890. sock = INVALID_SOCKET;
  12891. }
  12892. }
  12893. // Universal client implementation
  12894. inline Client::Client(const std::string &scheme_host_port)
  12895. : Client(scheme_host_port, std::string(), std::string()) {}
  12896. inline Client::Client(const std::string &scheme_host_port,
  12897. const std::string &client_cert_path,
  12898. const std::string &client_key_path) {
  12899. detail::UrlComponents uc;
  12900. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12901. auto &scheme = uc.scheme;
  12902. #ifdef CPPHTTPLIB_SSL_ENABLED
  12903. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12904. #else
  12905. if (!scheme.empty() && scheme != "http") {
  12906. #endif
  12907. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12908. std::string msg = "'" + scheme + "' scheme is not supported.";
  12909. throw std::invalid_argument(msg);
  12910. #endif
  12911. return;
  12912. }
  12913. auto is_ssl = scheme == "https";
  12914. auto host = std::move(uc.host);
  12915. auto port = is_ssl ? 443 : 80;
  12916. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12917. if (is_ssl) {
  12918. #ifdef CPPHTTPLIB_SSL_ENABLED
  12919. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12920. client_key_path);
  12921. is_ssl_ = is_ssl;
  12922. #endif
  12923. } else {
  12924. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12925. client_key_path);
  12926. }
  12927. } else {
  12928. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12929. // if port param below changes.
  12930. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12931. client_cert_path, client_key_path);
  12932. }
  12933. }
  12934. inline Client::Client(const std::string &host, int port)
  12935. : Client(host, port, std::string(), std::string()) {}
  12936. inline Client::Client(const std::string &host, int port,
  12937. const std::string &client_cert_path,
  12938. const std::string &client_key_path)
  12939. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12940. client_key_path)) {}
  12941. inline Client::~Client() = default;
  12942. inline bool Client::is_valid() const {
  12943. return cli_ != nullptr && cli_->is_valid();
  12944. }
  12945. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12946. return cli_->Get(path, std::move(progress));
  12947. }
  12948. inline Result Client::Get(const std::string &path, const Headers &headers,
  12949. DownloadProgress progress) {
  12950. return cli_->Get(path, headers, std::move(progress));
  12951. }
  12952. inline Result Client::Get(const std::string &path,
  12953. ContentReceiver content_receiver,
  12954. DownloadProgress progress) {
  12955. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12956. }
  12957. inline Result Client::Get(const std::string &path, const Headers &headers,
  12958. ContentReceiver content_receiver,
  12959. DownloadProgress progress) {
  12960. return cli_->Get(path, headers, std::move(content_receiver),
  12961. std::move(progress));
  12962. }
  12963. inline Result Client::Get(const std::string &path,
  12964. ResponseHandler response_handler,
  12965. ContentReceiver content_receiver,
  12966. DownloadProgress progress) {
  12967. return cli_->Get(path, std::move(response_handler),
  12968. std::move(content_receiver), std::move(progress));
  12969. }
  12970. inline Result Client::Get(const std::string &path, const Headers &headers,
  12971. ResponseHandler response_handler,
  12972. ContentReceiver content_receiver,
  12973. DownloadProgress progress) {
  12974. return cli_->Get(path, headers, std::move(response_handler),
  12975. std::move(content_receiver), std::move(progress));
  12976. }
  12977. inline Result Client::Get(const std::string &path, const Params &params,
  12978. DownloadProgress progress) {
  12979. return cli_->Get(path, params, std::move(progress));
  12980. }
  12981. inline Result Client::Get(const std::string &path, const Params &params,
  12982. const Headers &headers, DownloadProgress progress) {
  12983. return cli_->Get(path, params, headers, std::move(progress));
  12984. }
  12985. inline Result Client::Get(const std::string &path, const Params &params,
  12986. const Headers &headers,
  12987. ContentReceiver content_receiver,
  12988. DownloadProgress progress) {
  12989. return cli_->Get(path, params, headers, std::move(content_receiver),
  12990. std::move(progress));
  12991. }
  12992. inline Result Client::Get(const std::string &path, const Params &params,
  12993. const Headers &headers,
  12994. ResponseHandler response_handler,
  12995. ContentReceiver content_receiver,
  12996. DownloadProgress progress) {
  12997. return cli_->Get(path, params, headers, std::move(response_handler),
  12998. std::move(content_receiver), std::move(progress));
  12999. }
  13000. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  13001. inline Result Client::Head(const std::string &path, const Headers &headers) {
  13002. return cli_->Head(path, headers);
  13003. }
  13004. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  13005. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13006. return cli_->Post(path, headers);
  13007. }
  13008. inline Result Client::Post(const std::string &path, const char *body,
  13009. size_t content_length,
  13010. const std::string &content_type,
  13011. UploadProgress progress) {
  13012. return cli_->Post(path, body, content_length, content_type, progress);
  13013. }
  13014. inline Result Client::Post(const std::string &path, const Headers &headers,
  13015. const char *body, size_t content_length,
  13016. const std::string &content_type,
  13017. UploadProgress progress) {
  13018. return cli_->Post(path, headers, body, content_length, content_type,
  13019. progress);
  13020. }
  13021. inline Result Client::Post(const std::string &path, const std::string &body,
  13022. const std::string &content_type,
  13023. UploadProgress progress) {
  13024. return cli_->Post(path, body, content_type, progress);
  13025. }
  13026. inline Result Client::Post(const std::string &path, const Headers &headers,
  13027. const std::string &body,
  13028. const std::string &content_type,
  13029. UploadProgress progress) {
  13030. return cli_->Post(path, headers, body, content_type, progress);
  13031. }
  13032. inline Result Client::Post(const std::string &path, size_t content_length,
  13033. ContentProvider content_provider,
  13034. const std::string &content_type,
  13035. UploadProgress progress) {
  13036. return cli_->Post(path, content_length, std::move(content_provider),
  13037. content_type, progress);
  13038. }
  13039. inline Result Client::Post(const std::string &path, size_t content_length,
  13040. ContentProvider content_provider,
  13041. const std::string &content_type,
  13042. ContentReceiver content_receiver,
  13043. UploadProgress progress) {
  13044. return cli_->Post(path, content_length, std::move(content_provider),
  13045. content_type, std::move(content_receiver), progress);
  13046. }
  13047. inline Result Client::Post(const std::string &path,
  13048. ContentProviderWithoutLength content_provider,
  13049. const std::string &content_type,
  13050. UploadProgress progress) {
  13051. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13052. }
  13053. inline Result Client::Post(const std::string &path,
  13054. ContentProviderWithoutLength content_provider,
  13055. const std::string &content_type,
  13056. ContentReceiver content_receiver,
  13057. UploadProgress progress) {
  13058. return cli_->Post(path, std::move(content_provider), content_type,
  13059. std::move(content_receiver), progress);
  13060. }
  13061. inline Result Client::Post(const std::string &path, const Headers &headers,
  13062. size_t content_length,
  13063. ContentProvider content_provider,
  13064. const std::string &content_type,
  13065. UploadProgress progress) {
  13066. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13067. content_type, progress);
  13068. }
  13069. inline Result Client::Post(const std::string &path, const Headers &headers,
  13070. size_t content_length,
  13071. ContentProvider content_provider,
  13072. const std::string &content_type,
  13073. ContentReceiver content_receiver,
  13074. DownloadProgress progress) {
  13075. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13076. content_type, std::move(content_receiver), progress);
  13077. }
  13078. inline Result Client::Post(const std::string &path, const Headers &headers,
  13079. ContentProviderWithoutLength content_provider,
  13080. const std::string &content_type,
  13081. UploadProgress progress) {
  13082. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13083. progress);
  13084. }
  13085. inline Result Client::Post(const std::string &path, const Headers &headers,
  13086. ContentProviderWithoutLength content_provider,
  13087. const std::string &content_type,
  13088. ContentReceiver content_receiver,
  13089. DownloadProgress progress) {
  13090. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13091. std::move(content_receiver), progress);
  13092. }
  13093. inline Result Client::Post(const std::string &path, const Params &params) {
  13094. return cli_->Post(path, params);
  13095. }
  13096. inline Result Client::Post(const std::string &path, const Headers &headers,
  13097. const Params &params) {
  13098. return cli_->Post(path, headers, params);
  13099. }
  13100. inline Result Client::Post(const std::string &path,
  13101. const UploadFormDataItems &items,
  13102. UploadProgress progress) {
  13103. return cli_->Post(path, items, progress);
  13104. }
  13105. inline Result Client::Post(const std::string &path, const Headers &headers,
  13106. const UploadFormDataItems &items,
  13107. UploadProgress progress) {
  13108. return cli_->Post(path, headers, items, progress);
  13109. }
  13110. inline Result Client::Post(const std::string &path, const Headers &headers,
  13111. const UploadFormDataItems &items,
  13112. const std::string &boundary,
  13113. UploadProgress progress) {
  13114. return cli_->Post(path, headers, items, boundary, progress);
  13115. }
  13116. inline Result Client::Post(const std::string &path, const Headers &headers,
  13117. const UploadFormDataItems &items,
  13118. const FormDataProviderItems &provider_items,
  13119. UploadProgress progress) {
  13120. return cli_->Post(path, headers, items, provider_items, progress);
  13121. }
  13122. inline Result Client::Post(const std::string &path, const Headers &headers,
  13123. const std::string &body,
  13124. const std::string &content_type,
  13125. ContentReceiver content_receiver,
  13126. DownloadProgress progress) {
  13127. return cli_->Post(path, headers, body, content_type,
  13128. std::move(content_receiver), progress);
  13129. }
  13130. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13131. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13132. return cli_->Put(path, headers);
  13133. }
  13134. inline Result Client::Put(const std::string &path, const char *body,
  13135. size_t content_length,
  13136. const std::string &content_type,
  13137. UploadProgress progress) {
  13138. return cli_->Put(path, body, content_length, content_type, progress);
  13139. }
  13140. inline Result Client::Put(const std::string &path, const Headers &headers,
  13141. const char *body, size_t content_length,
  13142. const std::string &content_type,
  13143. UploadProgress progress) {
  13144. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13145. }
  13146. inline Result Client::Put(const std::string &path, const std::string &body,
  13147. const std::string &content_type,
  13148. UploadProgress progress) {
  13149. return cli_->Put(path, body, content_type, progress);
  13150. }
  13151. inline Result Client::Put(const std::string &path, const Headers &headers,
  13152. const std::string &body,
  13153. const std::string &content_type,
  13154. UploadProgress progress) {
  13155. return cli_->Put(path, headers, body, content_type, progress);
  13156. }
  13157. inline Result Client::Put(const std::string &path, size_t content_length,
  13158. ContentProvider content_provider,
  13159. const std::string &content_type,
  13160. UploadProgress progress) {
  13161. return cli_->Put(path, content_length, std::move(content_provider),
  13162. content_type, progress);
  13163. }
  13164. inline Result Client::Put(const std::string &path, size_t content_length,
  13165. ContentProvider content_provider,
  13166. const std::string &content_type,
  13167. ContentReceiver content_receiver,
  13168. UploadProgress progress) {
  13169. return cli_->Put(path, content_length, std::move(content_provider),
  13170. content_type, std::move(content_receiver), progress);
  13171. }
  13172. inline Result Client::Put(const std::string &path,
  13173. ContentProviderWithoutLength content_provider,
  13174. const std::string &content_type,
  13175. UploadProgress progress) {
  13176. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13177. }
  13178. inline Result Client::Put(const std::string &path,
  13179. ContentProviderWithoutLength content_provider,
  13180. const std::string &content_type,
  13181. ContentReceiver content_receiver,
  13182. UploadProgress progress) {
  13183. return cli_->Put(path, std::move(content_provider), content_type,
  13184. std::move(content_receiver), progress);
  13185. }
  13186. inline Result Client::Put(const std::string &path, const Headers &headers,
  13187. size_t content_length,
  13188. ContentProvider content_provider,
  13189. const std::string &content_type,
  13190. UploadProgress progress) {
  13191. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13192. content_type, progress);
  13193. }
  13194. inline Result Client::Put(const std::string &path, const Headers &headers,
  13195. size_t content_length,
  13196. ContentProvider content_provider,
  13197. const std::string &content_type,
  13198. ContentReceiver content_receiver,
  13199. UploadProgress progress) {
  13200. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13201. content_type, std::move(content_receiver), progress);
  13202. }
  13203. inline Result Client::Put(const std::string &path, const Headers &headers,
  13204. ContentProviderWithoutLength content_provider,
  13205. const std::string &content_type,
  13206. UploadProgress progress) {
  13207. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13208. progress);
  13209. }
  13210. inline Result Client::Put(const std::string &path, const Headers &headers,
  13211. ContentProviderWithoutLength content_provider,
  13212. const std::string &content_type,
  13213. ContentReceiver content_receiver,
  13214. UploadProgress progress) {
  13215. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13216. std::move(content_receiver), progress);
  13217. }
  13218. inline Result Client::Put(const std::string &path, const Params &params) {
  13219. return cli_->Put(path, params);
  13220. }
  13221. inline Result Client::Put(const std::string &path, const Headers &headers,
  13222. const Params &params) {
  13223. return cli_->Put(path, headers, params);
  13224. }
  13225. inline Result Client::Put(const std::string &path,
  13226. const UploadFormDataItems &items,
  13227. UploadProgress progress) {
  13228. return cli_->Put(path, items, progress);
  13229. }
  13230. inline Result Client::Put(const std::string &path, const Headers &headers,
  13231. const UploadFormDataItems &items,
  13232. UploadProgress progress) {
  13233. return cli_->Put(path, headers, items, progress);
  13234. }
  13235. inline Result Client::Put(const std::string &path, const Headers &headers,
  13236. const UploadFormDataItems &items,
  13237. const std::string &boundary,
  13238. UploadProgress progress) {
  13239. return cli_->Put(path, headers, items, boundary, progress);
  13240. }
  13241. inline Result Client::Put(const std::string &path, const Headers &headers,
  13242. const UploadFormDataItems &items,
  13243. const FormDataProviderItems &provider_items,
  13244. UploadProgress progress) {
  13245. return cli_->Put(path, headers, items, provider_items, progress);
  13246. }
  13247. inline Result Client::Put(const std::string &path, const Headers &headers,
  13248. const std::string &body,
  13249. const std::string &content_type,
  13250. ContentReceiver content_receiver,
  13251. DownloadProgress progress) {
  13252. return cli_->Put(path, headers, body, content_type, content_receiver,
  13253. progress);
  13254. }
  13255. inline Result Client::Patch(const std::string &path) {
  13256. return cli_->Patch(path);
  13257. }
  13258. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13259. return cli_->Patch(path, headers);
  13260. }
  13261. inline Result Client::Patch(const std::string &path, const char *body,
  13262. size_t content_length,
  13263. const std::string &content_type,
  13264. UploadProgress progress) {
  13265. return cli_->Patch(path, body, content_length, content_type, progress);
  13266. }
  13267. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13268. const char *body, size_t content_length,
  13269. const std::string &content_type,
  13270. UploadProgress progress) {
  13271. return cli_->Patch(path, headers, body, content_length, content_type,
  13272. progress);
  13273. }
  13274. inline Result Client::Patch(const std::string &path, const std::string &body,
  13275. const std::string &content_type,
  13276. UploadProgress progress) {
  13277. return cli_->Patch(path, body, content_type, progress);
  13278. }
  13279. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13280. const std::string &body,
  13281. const std::string &content_type,
  13282. UploadProgress progress) {
  13283. return cli_->Patch(path, headers, body, content_type, progress);
  13284. }
  13285. inline Result Client::Patch(const std::string &path, size_t content_length,
  13286. ContentProvider content_provider,
  13287. const std::string &content_type,
  13288. UploadProgress progress) {
  13289. return cli_->Patch(path, content_length, std::move(content_provider),
  13290. content_type, progress);
  13291. }
  13292. inline Result Client::Patch(const std::string &path, size_t content_length,
  13293. ContentProvider content_provider,
  13294. const std::string &content_type,
  13295. ContentReceiver content_receiver,
  13296. UploadProgress progress) {
  13297. return cli_->Patch(path, content_length, std::move(content_provider),
  13298. content_type, std::move(content_receiver), progress);
  13299. }
  13300. inline Result Client::Patch(const std::string &path,
  13301. ContentProviderWithoutLength content_provider,
  13302. const std::string &content_type,
  13303. UploadProgress progress) {
  13304. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13305. }
  13306. inline Result Client::Patch(const std::string &path,
  13307. ContentProviderWithoutLength content_provider,
  13308. const std::string &content_type,
  13309. ContentReceiver content_receiver,
  13310. UploadProgress progress) {
  13311. return cli_->Patch(path, std::move(content_provider), content_type,
  13312. std::move(content_receiver), progress);
  13313. }
  13314. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13315. size_t content_length,
  13316. ContentProvider content_provider,
  13317. const std::string &content_type,
  13318. UploadProgress progress) {
  13319. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13320. content_type, progress);
  13321. }
  13322. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13323. size_t content_length,
  13324. ContentProvider content_provider,
  13325. const std::string &content_type,
  13326. ContentReceiver content_receiver,
  13327. UploadProgress progress) {
  13328. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13329. content_type, std::move(content_receiver), progress);
  13330. }
  13331. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13332. ContentProviderWithoutLength content_provider,
  13333. const std::string &content_type,
  13334. UploadProgress progress) {
  13335. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13336. progress);
  13337. }
  13338. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13339. ContentProviderWithoutLength content_provider,
  13340. const std::string &content_type,
  13341. ContentReceiver content_receiver,
  13342. UploadProgress progress) {
  13343. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13344. std::move(content_receiver), progress);
  13345. }
  13346. inline Result Client::Patch(const std::string &path, const Params &params) {
  13347. return cli_->Patch(path, params);
  13348. }
  13349. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13350. const Params &params) {
  13351. return cli_->Patch(path, headers, params);
  13352. }
  13353. inline Result Client::Patch(const std::string &path,
  13354. const UploadFormDataItems &items,
  13355. UploadProgress progress) {
  13356. return cli_->Patch(path, items, progress);
  13357. }
  13358. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13359. const UploadFormDataItems &items,
  13360. UploadProgress progress) {
  13361. return cli_->Patch(path, headers, items, progress);
  13362. }
  13363. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13364. const UploadFormDataItems &items,
  13365. const std::string &boundary,
  13366. UploadProgress progress) {
  13367. return cli_->Patch(path, headers, items, boundary, progress);
  13368. }
  13369. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13370. const UploadFormDataItems &items,
  13371. const FormDataProviderItems &provider_items,
  13372. UploadProgress progress) {
  13373. return cli_->Patch(path, headers, items, provider_items, progress);
  13374. }
  13375. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13376. const std::string &body,
  13377. const std::string &content_type,
  13378. ContentReceiver content_receiver,
  13379. DownloadProgress progress) {
  13380. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13381. progress);
  13382. }
  13383. inline Result Client::Delete(const std::string &path,
  13384. DownloadProgress progress) {
  13385. return cli_->Delete(path, progress);
  13386. }
  13387. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13388. DownloadProgress progress) {
  13389. return cli_->Delete(path, headers, progress);
  13390. }
  13391. inline Result Client::Delete(const std::string &path, const char *body,
  13392. size_t content_length,
  13393. const std::string &content_type,
  13394. DownloadProgress progress) {
  13395. return cli_->Delete(path, body, content_length, content_type, progress);
  13396. }
  13397. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13398. const char *body, size_t content_length,
  13399. const std::string &content_type,
  13400. DownloadProgress progress) {
  13401. return cli_->Delete(path, headers, body, content_length, content_type,
  13402. progress);
  13403. }
  13404. inline Result Client::Delete(const std::string &path, const std::string &body,
  13405. const std::string &content_type,
  13406. DownloadProgress progress) {
  13407. return cli_->Delete(path, body, content_type, progress);
  13408. }
  13409. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13410. const std::string &body,
  13411. const std::string &content_type,
  13412. DownloadProgress progress) {
  13413. return cli_->Delete(path, headers, body, content_type, progress);
  13414. }
  13415. inline Result Client::Delete(const std::string &path, const Params &params,
  13416. DownloadProgress progress) {
  13417. return cli_->Delete(path, params, progress);
  13418. }
  13419. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13420. const Params &params, DownloadProgress progress) {
  13421. return cli_->Delete(path, headers, params, progress);
  13422. }
  13423. inline Result Client::Options(const std::string &path) {
  13424. return cli_->Options(path);
  13425. }
  13426. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13427. return cli_->Options(path, headers);
  13428. }
  13429. inline ClientImpl::StreamHandle
  13430. Client::open_stream(const std::string &method, const std::string &path,
  13431. const Params &params, const Headers &headers,
  13432. const std::string &body, const std::string &content_type) {
  13433. return cli_->open_stream(method, path, params, headers, body, content_type);
  13434. }
  13435. inline bool Client::send(Request &req, Response &res, Error &error) {
  13436. return cli_->send(req, res, error);
  13437. }
  13438. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13439. inline void Client::stop() { cli_->stop(); }
  13440. inline std::string Client::host() const { return cli_->host(); }
  13441. inline int Client::port() const { return cli_->port(); }
  13442. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13443. inline socket_t Client::socket() const { return cli_->socket(); }
  13444. inline void
  13445. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13446. cli_->set_hostname_addr_map(std::move(addr_map));
  13447. }
  13448. inline void Client::set_default_headers(Headers headers) {
  13449. cli_->set_default_headers(std::move(headers));
  13450. }
  13451. inline void Client::set_header_writer(
  13452. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13453. cli_->set_header_writer(writer);
  13454. }
  13455. inline void Client::set_address_family(int family) {
  13456. cli_->set_address_family(family);
  13457. }
  13458. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13459. inline void Client::set_socket_options(SocketOptions socket_options) {
  13460. cli_->set_socket_options(std::move(socket_options));
  13461. }
  13462. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13463. cli_->set_connection_timeout(sec, usec);
  13464. }
  13465. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13466. cli_->set_read_timeout(sec, usec);
  13467. }
  13468. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13469. cli_->set_write_timeout(sec, usec);
  13470. }
  13471. inline void Client::set_basic_auth(const std::string &username,
  13472. const std::string &password) {
  13473. cli_->set_basic_auth(username, password);
  13474. }
  13475. inline void Client::set_bearer_token_auth(const std::string &token) {
  13476. cli_->set_bearer_token_auth(token);
  13477. }
  13478. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13479. inline void Client::set_follow_location(bool on) {
  13480. cli_->set_follow_location(on);
  13481. }
  13482. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13483. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13484. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13485. inline void Client::set_payload_max_length(size_t length) {
  13486. cli_->set_payload_max_length(length);
  13487. }
  13488. inline void Client::set_interface(const std::string &intf) {
  13489. cli_->set_interface(intf);
  13490. }
  13491. inline void Client::set_proxy(const std::string &host, int port) {
  13492. cli_->set_proxy(host, port);
  13493. }
  13494. inline void Client::set_proxy_basic_auth(const std::string &username,
  13495. const std::string &password) {
  13496. cli_->set_proxy_basic_auth(username, password);
  13497. }
  13498. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13499. cli_->set_proxy_bearer_token_auth(token);
  13500. }
  13501. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13502. cli_->set_no_proxy(patterns);
  13503. }
  13504. inline void Client::set_logger(Logger logger) {
  13505. cli_->set_logger(std::move(logger));
  13506. }
  13507. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13508. cli_->set_error_logger(std::move(error_logger));
  13509. }
  13510. /*
  13511. * Group 6: SSL Server and Client implementation
  13512. */
  13513. #ifdef CPPHTTPLIB_SSL_ENABLED
  13514. // SSL HTTP server implementation
  13515. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13516. const char *client_ca_cert_file_path,
  13517. const char *client_ca_cert_dir_path,
  13518. const char *private_key_password) {
  13519. using namespace tls;
  13520. ctx_ = create_server_context();
  13521. if (!ctx_) { return; }
  13522. // Load server certificate and private key
  13523. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13524. private_key_password)) {
  13525. last_ssl_error_ = static_cast<int>(get_error());
  13526. free_context(ctx_);
  13527. ctx_ = nullptr;
  13528. return;
  13529. }
  13530. // Load client CA certificates for client authentication
  13531. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13532. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13533. client_ca_cert_dir_path)) {
  13534. last_ssl_error_ = static_cast<int>(get_error());
  13535. free_context(ctx_);
  13536. ctx_ = nullptr;
  13537. return;
  13538. }
  13539. // Enable client certificate verification
  13540. set_verify_client(ctx_, true);
  13541. }
  13542. }
  13543. inline SSLServer::SSLServer(const PemMemory &pem) {
  13544. using namespace tls;
  13545. ctx_ = create_server_context();
  13546. if (ctx_) {
  13547. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13548. pem.private_key_password)) {
  13549. last_ssl_error_ = static_cast<int>(get_error());
  13550. free_context(ctx_);
  13551. ctx_ = nullptr;
  13552. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13553. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13554. last_ssl_error_ = static_cast<int>(get_error());
  13555. free_context(ctx_);
  13556. ctx_ = nullptr;
  13557. } else {
  13558. set_verify_client(ctx_, true);
  13559. }
  13560. }
  13561. }
  13562. }
  13563. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13564. using namespace tls;
  13565. ctx_ = create_server_context();
  13566. if (ctx_) {
  13567. if (!setup_callback(ctx_)) {
  13568. free_context(ctx_);
  13569. ctx_ = nullptr;
  13570. }
  13571. }
  13572. }
  13573. inline SSLServer::~SSLServer() {
  13574. if (ctx_) { tls::free_context(ctx_); }
  13575. }
  13576. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13577. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13578. using namespace tls;
  13579. // Create TLS session with mutex protection
  13580. session_t session = nullptr;
  13581. {
  13582. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13583. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13584. }
  13585. if (!session) {
  13586. last_ssl_error_ = static_cast<int>(get_error());
  13587. detail::shutdown_socket(sock);
  13588. detail::close_socket(sock);
  13589. return false;
  13590. }
  13591. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13592. bool handshake_done = false;
  13593. bool ret = false;
  13594. bool websocket_upgraded = false;
  13595. auto cleanup = detail::scope_exit([&] {
  13596. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13597. free_session(session);
  13598. detail::shutdown_socket(sock);
  13599. detail::close_socket(sock);
  13600. });
  13601. // Perform TLS accept handshake with timeout
  13602. TlsError tls_err;
  13603. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13604. &tls_err)) {
  13605. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13606. // Map TlsError to legacy ssl_error for backward compatibility
  13607. if (tls_err.code == ErrorCode::WantRead) {
  13608. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13609. } else if (tls_err.code == ErrorCode::WantWrite) {
  13610. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13611. } else {
  13612. last_ssl_error_ = SSL_ERROR_SSL;
  13613. }
  13614. #else
  13615. last_ssl_error_ = static_cast<int>(get_error());
  13616. #endif
  13617. return false;
  13618. }
  13619. handshake_done = true;
  13620. std::string remote_addr;
  13621. int remote_port = 0;
  13622. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13623. std::string local_addr;
  13624. int local_port = 0;
  13625. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13626. ret = detail::process_server_socket_ssl(
  13627. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13628. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13629. write_timeout_usec_,
  13630. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13631. return process_request(
  13632. strm, remote_addr, remote_port, local_addr, local_port,
  13633. close_connection, connection_closed,
  13634. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13635. });
  13636. return ret;
  13637. }
  13638. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13639. const char *key_pem,
  13640. const char *client_ca_pem,
  13641. const char *password) {
  13642. if (!ctx_) { return false; }
  13643. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13644. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13645. return false;
  13646. }
  13647. if (client_ca_pem) {
  13648. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13649. }
  13650. return true;
  13651. }
  13652. // SSL HTTP client implementation
  13653. inline SSLClient::~SSLClient() {
  13654. if (ctx_) { tls::free_context(ctx_); }
  13655. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13656. // base function rather than the derived function once we get to the
  13657. // base class destructor, and won't free the SSL (causing a leak).
  13658. shutdown_ssl_impl(socket_, true);
  13659. }
  13660. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13661. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13662. shutdown_ssl_impl(socket, shutdown_gracefully);
  13663. }
  13664. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13665. bool shutdown_gracefully) {
  13666. if (socket.sock == INVALID_SOCKET) {
  13667. assert(socket.ssl == nullptr);
  13668. return;
  13669. }
  13670. if (socket.ssl) {
  13671. tls::shutdown(socket.ssl, shutdown_gracefully);
  13672. {
  13673. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13674. tls::free_session(socket.ssl);
  13675. }
  13676. socket.ssl = nullptr;
  13677. }
  13678. assert(socket.ssl == nullptr);
  13679. }
  13680. inline bool SSLClient::process_socket(
  13681. const Socket &socket,
  13682. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13683. std::function<bool(Stream &strm)> callback) {
  13684. assert(socket.ssl);
  13685. return detail::process_client_socket_ssl(
  13686. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13687. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13688. std::move(callback));
  13689. }
  13690. inline bool SSLClient::is_ssl() const { return true; }
  13691. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13692. if (!is_valid()) {
  13693. error = Error::SSLConnection;
  13694. return false;
  13695. }
  13696. return ClientImpl::create_and_connect_socket(socket, error);
  13697. }
  13698. inline bool SSLClient::setup_proxy_connection(
  13699. Socket &socket,
  13700. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13701. Response &res, bool &success, Error &error) {
  13702. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13703. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13704. return false;
  13705. }
  13706. if (!initialize_ssl(socket, error)) {
  13707. success = false;
  13708. return false;
  13709. }
  13710. return true;
  13711. }
  13712. // Assumes that socket_mutex_ is locked and that there are no requests in
  13713. // flight
  13714. inline bool SSLClient::connect_with_proxy(
  13715. Socket &socket,
  13716. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13717. Response &res, bool &success, Error &error) {
  13718. success = true;
  13719. Response proxy_res;
  13720. if (!detail::process_client_socket(
  13721. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13722. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13723. start_time, [&](Stream &strm) {
  13724. Request req2;
  13725. req2.method = "CONNECT";
  13726. req2.path =
  13727. detail::make_host_and_port_string_always_port(host_, port_);
  13728. if (max_timeout_msec_ > 0) {
  13729. req2.start_time_ = std::chrono::steady_clock::now();
  13730. }
  13731. return process_request(strm, req2, proxy_res, false, error);
  13732. })) {
  13733. // Thread-safe to close everything because we are assuming there are no
  13734. // requests in flight
  13735. shutdown_ssl(socket, true);
  13736. shutdown_socket(socket);
  13737. close_socket(socket);
  13738. success = false;
  13739. return false;
  13740. }
  13741. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13742. if (!proxy_digest_auth_username_.empty() &&
  13743. !proxy_digest_auth_password_.empty()) {
  13744. std::map<std::string, std::string> auth;
  13745. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13746. // Close the current socket and create a new one for the authenticated
  13747. // request
  13748. shutdown_ssl(socket, true);
  13749. shutdown_socket(socket);
  13750. close_socket(socket);
  13751. // Create a new socket for the authenticated CONNECT request
  13752. if (!ensure_socket_connection(socket, error)) {
  13753. success = false;
  13754. output_error_log(error, nullptr);
  13755. return false;
  13756. }
  13757. proxy_res = Response();
  13758. if (!detail::process_client_socket(
  13759. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13760. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13761. start_time, [&](Stream &strm) {
  13762. Request req3;
  13763. req3.method = "CONNECT";
  13764. req3.path = detail::make_host_and_port_string_always_port(
  13765. host_, port_);
  13766. req3.headers.insert(detail::make_digest_authentication_header(
  13767. req3, auth, 1, detail::random_string(10),
  13768. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13769. true));
  13770. if (max_timeout_msec_ > 0) {
  13771. req3.start_time_ = std::chrono::steady_clock::now();
  13772. }
  13773. return process_request(strm, req3, proxy_res, false, error);
  13774. })) {
  13775. // Thread-safe to close everything because we are assuming there are
  13776. // no requests in flight
  13777. shutdown_ssl(socket, true);
  13778. shutdown_socket(socket);
  13779. close_socket(socket);
  13780. success = false;
  13781. return false;
  13782. }
  13783. }
  13784. }
  13785. }
  13786. // If status code is not 200, proxy request is failed.
  13787. // Set error to ProxyConnection and return proxy response
  13788. // as the response of the request
  13789. if (proxy_res.status != StatusCode::OK_200) {
  13790. error = Error::ProxyConnection;
  13791. output_error_log(error, nullptr);
  13792. res = std::move(proxy_res);
  13793. // Thread-safe to close everything because we are assuming there are
  13794. // no requests in flight
  13795. shutdown_ssl(socket, true);
  13796. shutdown_socket(socket);
  13797. close_socket(socket);
  13798. return false;
  13799. }
  13800. return true;
  13801. }
  13802. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13803. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13804. if (is_proxy_enabled_for_host(host_)) { return true; }
  13805. if (!initialize_ssl(socket, error)) {
  13806. shutdown_socket(socket);
  13807. close_socket(socket);
  13808. return false;
  13809. }
  13810. return true;
  13811. }
  13812. // SSL HTTP client implementation
  13813. inline SSLClient::SSLClient(const std::string &host)
  13814. : SSLClient(host, 443, std::string(), std::string()) {}
  13815. inline SSLClient::SSLClient(const std::string &host, int port)
  13816. : SSLClient(host, port, std::string(), std::string()) {}
  13817. inline void SSLClient::init_ctx() {
  13818. ctx_ = tls::create_client_context();
  13819. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13820. }
  13821. inline void SSLClient::reset_ctx_on_error() {
  13822. last_backend_error_ = tls::get_error();
  13823. tls::free_context(ctx_);
  13824. ctx_ = nullptr;
  13825. }
  13826. inline SSLClient::SSLClient(const std::string &host, int port,
  13827. const std::string &client_cert_path,
  13828. const std::string &client_key_path,
  13829. const std::string &private_key_password)
  13830. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13831. init_ctx();
  13832. if (!ctx_) { return; }
  13833. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13834. const char *password =
  13835. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13836. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13837. client_key_path.c_str(), password)) {
  13838. reset_ctx_on_error();
  13839. }
  13840. }
  13841. }
  13842. inline SSLClient::SSLClient(const std::string &host, int port,
  13843. const PemMemory &pem)
  13844. : ClientImpl(host, port) {
  13845. init_ctx();
  13846. if (!ctx_) { return; }
  13847. if (pem.cert_pem && pem.key_pem) {
  13848. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13849. pem.private_key_password)) {
  13850. reset_ctx_on_error();
  13851. }
  13852. }
  13853. }
  13854. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13855. if (ca_cert_store && ctx_) {
  13856. // set_ca_store takes ownership of ca_cert_store
  13857. tls::set_ca_store(ctx_, ca_cert_store);
  13858. ca_cert_store_set_ = true;
  13859. } else if (ca_cert_store) {
  13860. tls::free_ca_store(ca_cert_store);
  13861. }
  13862. }
  13863. inline void
  13864. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13865. if (!ctx_) { return; }
  13866. tls::set_verify_callback(ctx_, verifier);
  13867. }
  13868. inline void SSLClient::set_session_verifier(
  13869. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13870. session_verifier_ = std::move(verifier);
  13871. }
  13872. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13873. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13874. enable_windows_cert_verification_ = enabled;
  13875. }
  13876. #endif
  13877. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13878. std::size_t size) {
  13879. if (ctx_ && ca_cert && size > 0) {
  13880. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13881. tls::load_ca_pem(ctx_, ca_cert, size);
  13882. }
  13883. }
  13884. inline bool SSLClient::load_certs() {
  13885. auto ret = true;
  13886. std::call_once(initialize_cert_, [&]() {
  13887. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13888. ret = detail::load_client_ca_config(
  13889. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13890. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13891. last_backend_error_);
  13892. });
  13893. return ret;
  13894. }
  13895. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13896. using namespace tls;
  13897. // Load CA certificates if server verification is enabled
  13898. if (server_certificate_verification_) {
  13899. if (!load_certs()) {
  13900. error = Error::SSLLoadingCerts;
  13901. output_error_log(error, nullptr);
  13902. return false;
  13903. }
  13904. }
  13905. bool is_ip = detail::is_ip_address(host_);
  13906. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13907. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13908. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13909. // Chain verification happens during the handshake even for IP hosts; the
  13910. // certificate identity is verified post-handshake via verify_hostname().
  13911. set_verify_client(ctx_, server_certificate_verification_);
  13912. #endif
  13913. // Create TLS session
  13914. session_t session = nullptr;
  13915. {
  13916. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13917. session = create_session(ctx_, socket.sock);
  13918. }
  13919. if (!session) {
  13920. error = Error::SSLConnection;
  13921. last_backend_error_ = get_error();
  13922. return false;
  13923. }
  13924. // Use scope_exit to ensure session is freed on error paths
  13925. bool success = false;
  13926. auto session_guard = detail::scope_exit([&] {
  13927. if (!success) { free_session(session); }
  13928. });
  13929. // Set SNI extension (skip for IP addresses per RFC 6066).
  13930. // On MbedTLS, set_sni also enables hostname verification internally.
  13931. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13932. if (!is_ip) {
  13933. if (!set_sni(session, host_.c_str())) {
  13934. error = Error::SSLConnection;
  13935. last_backend_error_ = get_error();
  13936. return false;
  13937. }
  13938. }
  13939. // Perform non-blocking TLS handshake with timeout
  13940. TlsError tls_err;
  13941. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13942. connection_timeout_usec_, &tls_err)) {
  13943. last_ssl_error_ = static_cast<int>(tls_err.code);
  13944. last_backend_error_ = tls_err.backend_code;
  13945. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13946. error = Error::SSLServerVerification;
  13947. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13948. error = Error::SSLServerHostnameVerification;
  13949. } else {
  13950. error = Error::SSLConnection;
  13951. }
  13952. output_error_log(error, nullptr);
  13953. return false;
  13954. }
  13955. // Post-handshake session verifier callback
  13956. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13957. if (session_verifier_) { verification_status = session_verifier_(session); }
  13958. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13959. last_backend_error_ = get_error();
  13960. error = Error::SSLServerVerification;
  13961. output_error_log(error, nullptr);
  13962. return false;
  13963. }
  13964. // Default server certificate verification
  13965. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13966. server_certificate_verification_) {
  13967. verify_result_ = tls::get_verify_result(session);
  13968. if (verify_result_ != 0) {
  13969. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13970. error = Error::SSLServerVerification;
  13971. output_error_log(error, nullptr);
  13972. return false;
  13973. }
  13974. auto server_cert = get_peer_cert(session);
  13975. if (!server_cert) {
  13976. last_backend_error_ = get_error();
  13977. error = Error::SSLServerVerification;
  13978. output_error_log(error, nullptr);
  13979. return false;
  13980. }
  13981. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13982. // Hostname verification (post-handshake for all cases).
  13983. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13984. // On MbedTLS, set_sni already enabled hostname verification during
  13985. // handshake for non-IP hosts, but this check is still needed for IP
  13986. // addresses where SNI is not set.
  13987. if (server_hostname_verification_) {
  13988. if (!verify_hostname(server_cert, host_.c_str())) {
  13989. last_backend_error_ = hostname_mismatch_code();
  13990. error = Error::SSLServerHostnameVerification;
  13991. output_error_log(error, nullptr);
  13992. return false;
  13993. }
  13994. }
  13995. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13996. // Additional Windows Schannel verification.
  13997. // This provides real-time certificate validation with Windows Update
  13998. // integration, working with both OpenSSL and MbedTLS backends.
  13999. // Skip when a custom CA cert is specified, as the Windows certificate
  14000. // store would not know about user-provided CA certificates. Also skip
  14001. // when system CA trust is explicitly disabled.
  14002. if (enable_windows_cert_verification_ &&
  14003. system_ca_mode_ != SystemCAMode::Disabled &&
  14004. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  14005. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  14006. std::vector<unsigned char> der;
  14007. if (get_cert_der(server_cert, der)) {
  14008. uint64_t wincrypt_error = 0;
  14009. if (!detail::verify_cert_with_windows_schannel(
  14010. der, host_, server_hostname_verification_, wincrypt_error)) {
  14011. last_backend_error_ = wincrypt_error;
  14012. error = Error::SSLServerVerification;
  14013. output_error_log(error, nullptr);
  14014. return false;
  14015. }
  14016. }
  14017. }
  14018. #endif
  14019. }
  14020. success = true;
  14021. socket.ssl = session;
  14022. return true;
  14023. }
  14024. inline void Client::set_digest_auth(const std::string &username,
  14025. const std::string &password) {
  14026. cli_->set_digest_auth(username, password);
  14027. }
  14028. inline void Client::set_proxy_digest_auth(const std::string &username,
  14029. const std::string &password) {
  14030. cli_->set_proxy_digest_auth(username, password);
  14031. }
  14032. inline void Client::enable_server_certificate_verification(bool enabled) {
  14033. cli_->enable_server_certificate_verification(enabled);
  14034. }
  14035. inline void Client::enable_server_hostname_verification(bool enabled) {
  14036. cli_->enable_server_hostname_verification(enabled);
  14037. }
  14038. inline void Client::enable_system_ca(bool enabled) {
  14039. cli_->enable_system_ca(enabled);
  14040. }
  14041. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14042. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14043. if (is_ssl_) {
  14044. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14045. enabled);
  14046. }
  14047. }
  14048. #endif
  14049. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14050. const std::string &ca_cert_dir_path) {
  14051. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14052. }
  14053. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14054. if (is_ssl_) {
  14055. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14056. } else if (ca_cert_store) {
  14057. tls::free_ca_store(ca_cert_store);
  14058. }
  14059. }
  14060. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14061. if (is_ssl_) {
  14062. // Use the PEM-based path so the CA data is retained for redirect transfer
  14063. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14064. }
  14065. }
  14066. inline void
  14067. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14068. if (is_ssl_) {
  14069. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14070. std::move(verifier));
  14071. }
  14072. }
  14073. inline void Client::set_session_verifier(
  14074. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14075. if (is_ssl_) {
  14076. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14077. }
  14078. }
  14079. inline tls::ctx_t Client::tls_context() const {
  14080. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14081. return nullptr;
  14082. }
  14083. #endif // CPPHTTPLIB_SSL_ENABLED
  14084. /*
  14085. * Group 7: TLS abstraction layer - Common API
  14086. */
  14087. #ifdef CPPHTTPLIB_SSL_ENABLED
  14088. namespace tls {
  14089. // Helper for PeerCert construction
  14090. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14091. return PeerCert(get_peer_cert(session));
  14092. }
  14093. namespace impl {
  14094. inline VerifyCallback &get_verify_callback() {
  14095. static thread_local VerifyCallback callback;
  14096. return callback;
  14097. }
  14098. inline VerifyCallback &get_mbedtls_verify_callback() {
  14099. static thread_local VerifyCallback callback;
  14100. return callback;
  14101. }
  14102. // Check if a string is an IPv4 address
  14103. inline bool is_ipv4_address(const std::string &str) {
  14104. int dots = 0;
  14105. for (char c : str) {
  14106. if (c == '.') {
  14107. dots++;
  14108. } else if (!detail::is_ascii_digit(c)) {
  14109. return false;
  14110. }
  14111. }
  14112. return dots == 3;
  14113. }
  14114. // Parse IPv4 address string to bytes
  14115. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14116. const char *p = str.c_str();
  14117. for (int i = 0; i < 4; i++) {
  14118. if (i > 0) {
  14119. if (*p != '.') { return false; }
  14120. p++;
  14121. }
  14122. int val = 0;
  14123. int digits = 0;
  14124. while (detail::is_ascii_digit(*p)) {
  14125. val = val * 10 + (*p - '0');
  14126. if (val > 255) { return false; }
  14127. p++;
  14128. digits++;
  14129. }
  14130. if (digits == 0) { return false; }
  14131. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14132. if (digits > 1 && *(p - digits) == '0') { return false; }
  14133. out[i] = static_cast<unsigned char>(val);
  14134. }
  14135. return *p == '\0';
  14136. }
  14137. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14138. // `out` must have room for at least 16 bytes. Returns the address length
  14139. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14140. // literal. Used to match a host against iPAddress SANs the same way the
  14141. // OpenSSL backend does via X509_check_ip.
  14142. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14143. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14144. struct in6_addr addr6 = {};
  14145. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14146. memcpy(out, &addr6, 16);
  14147. return 16;
  14148. }
  14149. return 0;
  14150. }
  14151. #ifdef _WIN32
  14152. // Enumerate Windows system certificates and call callback with DER data
  14153. template <typename Callback>
  14154. inline bool enumerate_windows_system_certs(Callback cb) {
  14155. bool loaded = false;
  14156. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14157. for (auto store_name : store_names) {
  14158. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14159. if (hStore) {
  14160. PCCERT_CONTEXT pContext = nullptr;
  14161. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14162. nullptr) {
  14163. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14164. loaded = true;
  14165. }
  14166. }
  14167. CertCloseStore(hStore, 0);
  14168. }
  14169. }
  14170. return loaded;
  14171. }
  14172. #endif
  14173. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14174. // Enumerate macOS Keychain certificates and call callback with DER data
  14175. template <typename Callback>
  14176. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14177. bool loaded = false;
  14178. const SecTrustSettingsDomain domains[] = {
  14179. kSecTrustSettingsDomainSystem,
  14180. kSecTrustSettingsDomainAdmin,
  14181. kSecTrustSettingsDomainUser,
  14182. };
  14183. for (auto domain : domains) {
  14184. CFArrayRef certs = nullptr;
  14185. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14186. if (status != errSecSuccess || !certs) {
  14187. if (certs) CFRelease(certs);
  14188. continue;
  14189. }
  14190. CFIndex count = CFArrayGetCount(certs);
  14191. for (CFIndex i = 0; i < count; i++) {
  14192. SecCertificateRef cert =
  14193. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14194. CFDataRef data = SecCertificateCopyData(cert);
  14195. if (data) {
  14196. if (cb(CFDataGetBytePtr(data),
  14197. static_cast<size_t>(CFDataGetLength(data)))) {
  14198. loaded = true;
  14199. }
  14200. CFRelease(data);
  14201. }
  14202. }
  14203. CFRelease(certs);
  14204. }
  14205. return loaded;
  14206. }
  14207. #endif
  14208. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14209. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14210. // Common CA certificate file paths on Linux/Unix
  14211. inline const char **system_ca_paths() {
  14212. static const char *paths[] = {
  14213. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14214. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14215. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14216. "/etc/pki/tls/cacert.pem", // OpenELEC
  14217. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14218. nullptr};
  14219. return paths;
  14220. }
  14221. // Common CA certificate directory paths on Linux/Unix
  14222. inline const char **system_ca_dirs() {
  14223. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14224. "/etc/pki/tls/certs", // RHEL/CentOS
  14225. "/usr/share/ca-certificates", // Other
  14226. nullptr};
  14227. return dirs;
  14228. }
  14229. #endif
  14230. } // namespace impl
  14231. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14232. const char *ca_dir) {
  14233. if (!ctx) { return false; }
  14234. bool success = true;
  14235. if (ca_file && *ca_file) {
  14236. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14237. }
  14238. if (ca_dir && *ca_dir) {
  14239. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14240. }
  14241. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14242. // Set CA list for client certificate request (CertificateRequest message)
  14243. if (ca_file && *ca_file) {
  14244. auto list = SSL_load_client_CA_file(ca_file);
  14245. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14246. }
  14247. #endif
  14248. return success;
  14249. }
  14250. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14251. const char *password) {
  14252. return set_client_cert_pem(ctx, cert, key, password);
  14253. }
  14254. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14255. const char *key_path, const char *password) {
  14256. return set_client_cert_file(ctx, cert_path, key_path, password);
  14257. }
  14258. // PeerCert implementation
  14259. inline PeerCert::PeerCert() = default;
  14260. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14261. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14262. other.cert_ = nullptr;
  14263. }
  14264. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14265. if (this != &other) {
  14266. if (cert_) { free_cert(cert_); }
  14267. cert_ = other.cert_;
  14268. other.cert_ = nullptr;
  14269. }
  14270. return *this;
  14271. }
  14272. inline PeerCert::~PeerCert() {
  14273. if (cert_) { free_cert(cert_); }
  14274. }
  14275. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14276. inline std::string PeerCert::subject_cn() const {
  14277. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14278. }
  14279. inline std::string PeerCert::issuer_name() const {
  14280. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14281. }
  14282. inline bool PeerCert::check_hostname(const char *hostname) const {
  14283. return cert_ ? verify_hostname(cert_, hostname) : false;
  14284. }
  14285. inline std::vector<SanEntry> PeerCert::sans() const {
  14286. std::vector<SanEntry> result;
  14287. if (cert_) { get_cert_sans(cert_, result); }
  14288. return result;
  14289. }
  14290. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14291. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14292. }
  14293. inline std::string PeerCert::serial() const {
  14294. return cert_ ? get_cert_serial(cert_) : std::string();
  14295. }
  14296. // VerifyContext method implementations
  14297. inline std::string VerifyContext::subject_cn() const {
  14298. return cert ? get_cert_subject_cn(cert) : std::string();
  14299. }
  14300. inline std::string VerifyContext::issuer_name() const {
  14301. return cert ? get_cert_issuer_name(cert) : std::string();
  14302. }
  14303. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14304. return cert ? verify_hostname(cert, hostname) : false;
  14305. }
  14306. inline std::vector<SanEntry> VerifyContext::sans() const {
  14307. std::vector<SanEntry> result;
  14308. if (cert) { get_cert_sans(cert, result); }
  14309. return result;
  14310. }
  14311. inline bool VerifyContext::validity(time_t &not_before,
  14312. time_t &not_after) const {
  14313. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14314. }
  14315. inline std::string VerifyContext::serial() const {
  14316. return cert ? get_cert_serial(cert) : std::string();
  14317. }
  14318. // TlsError static method implementation
  14319. inline std::string TlsError::verify_error_to_string(long error_code) {
  14320. return verify_error_string(error_code);
  14321. }
  14322. } // namespace tls
  14323. // Request::peer_cert() implementation
  14324. inline tls::PeerCert Request::peer_cert() const {
  14325. return tls::get_peer_cert_from_session(ssl);
  14326. }
  14327. // Request::sni() implementation
  14328. inline std::string Request::sni() const {
  14329. if (!ssl) { return std::string(); }
  14330. const char *s = tls::get_sni(ssl);
  14331. return s ? std::string(s) : std::string();
  14332. }
  14333. #endif // CPPHTTPLIB_SSL_ENABLED
  14334. /*
  14335. * Group 8: TLS abstraction layer - OpenSSL backend
  14336. */
  14337. /*
  14338. * OpenSSL Backend Implementation
  14339. */
  14340. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14341. namespace tls {
  14342. namespace impl {
  14343. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14344. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14345. switch (ssl_error) {
  14346. case SSL_ERROR_NONE: return ErrorCode::Success;
  14347. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14348. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14349. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14350. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14351. case SSL_ERROR_SSL:
  14352. default: return ErrorCode::Fatal;
  14353. }
  14354. }
  14355. // Helper: Create client CA list from PEM string
  14356. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14357. // Caller takes ownership of returned list
  14358. inline STACK_OF(X509_NAME) *
  14359. create_client_ca_list_from_pem(const char *ca_pem) {
  14360. if (!ca_pem) { return nullptr; }
  14361. auto ca_list = sk_X509_NAME_new_null();
  14362. if (!ca_list) { return nullptr; }
  14363. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14364. if (!bio) {
  14365. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14366. return nullptr;
  14367. }
  14368. X509 *cert = nullptr;
  14369. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14370. nullptr) {
  14371. const X509_NAME *name = X509_get_subject_name(cert);
  14372. if (name) {
  14373. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14374. }
  14375. X509_free(cert);
  14376. }
  14377. BIO_free(bio);
  14378. return ca_list;
  14379. }
  14380. // OpenSSL verify callback wrapper
  14381. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14382. auto &callback = get_verify_callback();
  14383. if (!callback) { return preverify_ok; }
  14384. // Get SSL object from X509_STORE_CTX
  14385. auto ssl = static_cast<SSL *>(
  14386. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14387. if (!ssl) { return preverify_ok; }
  14388. // Get current certificate and depth
  14389. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14390. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14391. int error = X509_STORE_CTX_get_error(ctx);
  14392. // Build context
  14393. VerifyContext verify_ctx;
  14394. verify_ctx.session = static_cast<session_t>(ssl);
  14395. verify_ctx.cert = static_cast<cert_t>(cert);
  14396. verify_ctx.depth = depth;
  14397. verify_ctx.preverify_ok = (preverify_ok != 0);
  14398. verify_ctx.error_code = error;
  14399. verify_ctx.error_string =
  14400. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14401. return callback(verify_ctx) ? 1 : 0;
  14402. }
  14403. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14404. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14405. // that must be released with release_store_objects
  14406. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14407. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14408. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14409. #endif
  14410. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14411. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14412. return X509_STORE_get1_objects(store);
  14413. #else
  14414. return X509_STORE_get0_objects(store);
  14415. #endif
  14416. }
  14417. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14418. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14419. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14420. #else
  14421. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14422. #endif
  14423. }
  14424. } // namespace impl
  14425. inline ctx_t create_client_context() {
  14426. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14427. if (ctx) {
  14428. // Disable auto-retry to properly handle non-blocking I/O
  14429. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14430. // Set minimum TLS version
  14431. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14432. }
  14433. return static_cast<ctx_t>(ctx);
  14434. }
  14435. inline void free_context(ctx_t ctx) {
  14436. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14437. }
  14438. inline bool set_min_version(ctx_t ctx, Version version) {
  14439. if (!ctx) return false;
  14440. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14441. static_cast<int>(version)) == 1;
  14442. }
  14443. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14444. if (!ctx || !pem || len == 0) return false;
  14445. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14446. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14447. if (!store) return false;
  14448. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14449. if (!bio) return false;
  14450. bool ok = true;
  14451. X509 *cert = nullptr;
  14452. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14453. nullptr) {
  14454. if (X509_STORE_add_cert(store, cert) != 1) {
  14455. // Ignore duplicate errors
  14456. auto err = ERR_peek_last_error();
  14457. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14458. ok = false;
  14459. }
  14460. }
  14461. X509_free(cert);
  14462. if (!ok) break;
  14463. }
  14464. BIO_free(bio);
  14465. // Clear any "no more certificates" errors
  14466. ERR_clear_error();
  14467. return ok;
  14468. }
  14469. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14470. if (!ctx || !file_path) return false;
  14471. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14472. nullptr) == 1;
  14473. }
  14474. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14475. if (!ctx || !dir_path) return false;
  14476. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14477. dir_path) == 1;
  14478. }
  14479. inline bool load_system_certs(ctx_t ctx) {
  14480. if (!ctx) return false;
  14481. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14482. #ifdef _WIN32
  14483. // Windows: Load from system certificate store (ROOT and CA)
  14484. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14485. if (!store) return false;
  14486. bool loaded_any = false;
  14487. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14488. for (auto store_name : store_names) {
  14489. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14490. if (!hStore) continue;
  14491. PCCERT_CONTEXT pContext = nullptr;
  14492. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14493. nullptr) {
  14494. const unsigned char *data = pContext->pbCertEncoded;
  14495. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14496. if (x509) {
  14497. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14498. X509_free(x509);
  14499. }
  14500. }
  14501. CertCloseStore(hStore, 0);
  14502. }
  14503. return loaded_any;
  14504. #elif defined(__APPLE__)
  14505. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14506. // macOS: Load from Keychain
  14507. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14508. if (!store) return false;
  14509. bool loaded_any = false;
  14510. const SecTrustSettingsDomain domains[] = {
  14511. kSecTrustSettingsDomainSystem,
  14512. kSecTrustSettingsDomainAdmin,
  14513. kSecTrustSettingsDomainUser,
  14514. };
  14515. for (auto domain : domains) {
  14516. CFArrayRef certs = nullptr;
  14517. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14518. !certs) {
  14519. if (certs) CFRelease(certs);
  14520. continue;
  14521. }
  14522. auto count = CFArrayGetCount(certs);
  14523. for (CFIndex i = 0; i < count; i++) {
  14524. auto cert = reinterpret_cast<SecCertificateRef>(
  14525. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14526. CFDataRef der = SecCertificateCopyData(cert);
  14527. if (der) {
  14528. const unsigned char *data = CFDataGetBytePtr(der);
  14529. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14530. if (x509) {
  14531. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14532. X509_free(x509);
  14533. }
  14534. CFRelease(der);
  14535. }
  14536. }
  14537. CFRelease(certs);
  14538. }
  14539. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14540. #else
  14541. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14542. #endif
  14543. #else
  14544. // Other Unix: use default verify paths
  14545. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14546. #endif
  14547. }
  14548. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14549. const char *password) {
  14550. if (!ctx || !cert || !key) return false;
  14551. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14552. // Load certificate
  14553. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14554. if (!cert_bio) return false;
  14555. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14556. BIO_free(cert_bio);
  14557. if (!x509) return false;
  14558. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14559. X509_free(x509);
  14560. if (!cert_ok) return false;
  14561. // Load private key
  14562. auto key_bio = BIO_new_mem_buf(key, -1);
  14563. if (!key_bio) return false;
  14564. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14565. password ? const_cast<char *>(password)
  14566. : nullptr);
  14567. BIO_free(key_bio);
  14568. if (!pkey) return false;
  14569. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14570. EVP_PKEY_free(pkey);
  14571. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14572. }
  14573. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14574. const char *key_path, const char *password) {
  14575. if (!ctx || !cert_path || !key_path) return false;
  14576. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14577. if (password && password[0] != '\0') {
  14578. SSL_CTX_set_default_passwd_cb_userdata(
  14579. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14580. }
  14581. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14582. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14583. }
  14584. inline ctx_t create_server_context() {
  14585. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14586. if (ctx) {
  14587. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14588. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14589. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14590. }
  14591. return static_cast<ctx_t>(ctx);
  14592. }
  14593. inline void set_verify_client(ctx_t ctx, bool require) {
  14594. if (!ctx) return;
  14595. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14596. require
  14597. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14598. : SSL_VERIFY_NONE,
  14599. nullptr);
  14600. }
  14601. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14602. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14603. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14604. SSL *ssl = SSL_new(ssl_ctx);
  14605. if (!ssl) return nullptr;
  14606. // Disable auto-retry for proper non-blocking I/O handling
  14607. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14608. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14609. if (!bio) {
  14610. SSL_free(ssl);
  14611. return nullptr;
  14612. }
  14613. SSL_set_bio(ssl, bio, bio);
  14614. return static_cast<session_t>(ssl);
  14615. }
  14616. inline void free_session(session_t session) {
  14617. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14618. }
  14619. inline bool set_sni(session_t session, const char *hostname) {
  14620. if (!session || !hostname) return false;
  14621. auto ssl = static_cast<SSL *>(session);
  14622. // Set SNI (Server Name Indication) only - does not enable verification
  14623. #if defined(OPENSSL_IS_BORINGSSL)
  14624. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14625. #else
  14626. // Direct call instead of macro to suppress -Wold-style-cast warning
  14627. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14628. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14629. #endif
  14630. }
  14631. inline bool set_hostname(session_t session, const char *hostname) {
  14632. if (!session || !hostname) return false;
  14633. auto ssl = static_cast<SSL *>(session);
  14634. // Enable hostname verification
  14635. auto param = SSL_get0_param(ssl);
  14636. if (!param) return false;
  14637. if (detail::is_ip_address(hostname)) {
  14638. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14639. // certificate's IP SANs instead of its DNS names
  14640. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14641. } else {
  14642. // Set SNI (Server Name Indication)
  14643. if (!set_sni(session, hostname)) { return false; }
  14644. X509_VERIFY_PARAM_set_hostflags(param,
  14645. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14646. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14647. }
  14648. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14649. return true;
  14650. }
  14651. inline TlsError connect(session_t session) {
  14652. if (!session) { return TlsError(); }
  14653. auto ssl = static_cast<SSL *>(session);
  14654. auto ret = SSL_connect(ssl);
  14655. TlsError err;
  14656. if (ret == 1) {
  14657. err.code = ErrorCode::Success;
  14658. } else {
  14659. auto ssl_err = SSL_get_error(ssl, ret);
  14660. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14661. err.backend_code = ERR_get_error();
  14662. }
  14663. return err;
  14664. }
  14665. inline TlsError accept(session_t session) {
  14666. if (!session) { return TlsError(); }
  14667. auto ssl = static_cast<SSL *>(session);
  14668. auto ret = SSL_accept(ssl);
  14669. TlsError err;
  14670. if (ret == 1) {
  14671. err.code = ErrorCode::Success;
  14672. } else {
  14673. auto ssl_err = SSL_get_error(ssl, ret);
  14674. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14675. err.backend_code = ERR_get_error();
  14676. }
  14677. return err;
  14678. }
  14679. inline bool connect_nonblocking(session_t session, socket_t sock,
  14680. time_t timeout_sec, time_t timeout_usec,
  14681. TlsError *err) {
  14682. if (!session) {
  14683. if (err) { err->code = ErrorCode::Fatal; }
  14684. return false;
  14685. }
  14686. auto ssl = static_cast<SSL *>(session);
  14687. auto bio = SSL_get_rbio(ssl);
  14688. // Set non-blocking mode for handshake
  14689. detail::set_nonblocking(sock, true);
  14690. if (bio) { BIO_set_nbio(bio, 1); }
  14691. auto cleanup = detail::scope_exit([&]() {
  14692. // Restore blocking mode after handshake
  14693. if (bio) { BIO_set_nbio(bio, 0); }
  14694. detail::set_nonblocking(sock, false);
  14695. });
  14696. auto res = 0;
  14697. while ((res = SSL_connect(ssl)) != 1) {
  14698. auto ssl_err = SSL_get_error(ssl, res);
  14699. switch (ssl_err) {
  14700. case SSL_ERROR_WANT_READ:
  14701. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14702. continue;
  14703. }
  14704. break;
  14705. case SSL_ERROR_WANT_WRITE:
  14706. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14707. continue;
  14708. }
  14709. break;
  14710. default: break;
  14711. }
  14712. if (err) {
  14713. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14714. err->backend_code = ERR_get_error();
  14715. }
  14716. return false;
  14717. }
  14718. if (err) { err->code = ErrorCode::Success; }
  14719. return true;
  14720. }
  14721. inline bool accept_nonblocking(session_t session, socket_t sock,
  14722. time_t timeout_sec, time_t timeout_usec,
  14723. TlsError *err) {
  14724. if (!session) {
  14725. if (err) { err->code = ErrorCode::Fatal; }
  14726. return false;
  14727. }
  14728. auto ssl = static_cast<SSL *>(session);
  14729. auto bio = SSL_get_rbio(ssl);
  14730. // Set non-blocking mode for handshake
  14731. detail::set_nonblocking(sock, true);
  14732. if (bio) { BIO_set_nbio(bio, 1); }
  14733. auto cleanup = detail::scope_exit([&]() {
  14734. // Restore blocking mode after handshake
  14735. if (bio) { BIO_set_nbio(bio, 0); }
  14736. detail::set_nonblocking(sock, false);
  14737. });
  14738. auto res = 0;
  14739. while ((res = SSL_accept(ssl)) != 1) {
  14740. auto ssl_err = SSL_get_error(ssl, res);
  14741. switch (ssl_err) {
  14742. case SSL_ERROR_WANT_READ:
  14743. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14744. continue;
  14745. }
  14746. break;
  14747. case SSL_ERROR_WANT_WRITE:
  14748. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14749. continue;
  14750. }
  14751. break;
  14752. default: break;
  14753. }
  14754. if (err) {
  14755. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14756. err->backend_code = ERR_get_error();
  14757. }
  14758. return false;
  14759. }
  14760. if (err) { err->code = ErrorCode::Success; }
  14761. return true;
  14762. }
  14763. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14764. if (!session || !buf) {
  14765. err.code = ErrorCode::Fatal;
  14766. return -1;
  14767. }
  14768. auto ssl = static_cast<SSL *>(session);
  14769. constexpr auto max_len =
  14770. static_cast<size_t>((std::numeric_limits<int>::max)());
  14771. if (len > max_len) { len = max_len; }
  14772. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14773. if (ret > 0) {
  14774. err.code = ErrorCode::Success;
  14775. return ret;
  14776. }
  14777. auto ssl_err = SSL_get_error(ssl, ret);
  14778. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14779. if (err.code == ErrorCode::PeerClosed) {
  14780. return 0;
  14781. } // Gracefully handle the peer closed state.
  14782. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14783. return -1;
  14784. }
  14785. inline ssize_t write(session_t session, const void *buf, size_t len,
  14786. TlsError &err) {
  14787. if (!session || !buf) {
  14788. err.code = ErrorCode::Fatal;
  14789. return -1;
  14790. }
  14791. auto ssl = static_cast<SSL *>(session);
  14792. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14793. if (ret > 0) {
  14794. err.code = ErrorCode::Success;
  14795. return ret;
  14796. }
  14797. auto ssl_err = SSL_get_error(ssl, ret);
  14798. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14799. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14800. return -1;
  14801. }
  14802. inline int pending(const_session_t session) {
  14803. if (!session) return 0;
  14804. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14805. }
  14806. inline void shutdown(session_t session, bool graceful) {
  14807. if (!session) return;
  14808. auto ssl = static_cast<SSL *>(session);
  14809. if (graceful) {
  14810. // First call sends close_notify
  14811. if (SSL_shutdown(ssl) == 0) {
  14812. // Second call waits for peer's close_notify
  14813. SSL_shutdown(ssl);
  14814. }
  14815. }
  14816. }
  14817. inline bool is_peer_closed(session_t session, socket_t sock) {
  14818. if (!session) return true;
  14819. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14820. detail::set_nonblocking(sock, true);
  14821. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14822. auto ssl = static_cast<SSL *>(session);
  14823. char buf;
  14824. auto ret = SSL_peek(ssl, &buf, 1);
  14825. if (ret > 0) return false;
  14826. auto err = SSL_get_error(ssl, ret);
  14827. return err == SSL_ERROR_ZERO_RETURN;
  14828. }
  14829. inline cert_t get_peer_cert(const_session_t session) {
  14830. if (!session) return nullptr;
  14831. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14832. static_cast<SSL *>(const_cast<void *>(session))));
  14833. }
  14834. inline void free_cert(cert_t cert) {
  14835. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14836. }
  14837. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14838. if (!cert || !hostname) return false;
  14839. auto x509 = static_cast<X509 *>(cert);
  14840. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14841. if (detail::is_ip_address(hostname)) {
  14842. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14843. }
  14844. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14845. }
  14846. inline uint64_t hostname_mismatch_code() {
  14847. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14848. }
  14849. inline long get_verify_result(const_session_t session) {
  14850. if (!session) return X509_V_ERR_UNSPECIFIED;
  14851. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14852. }
  14853. inline std::string get_cert_subject_cn(cert_t cert) {
  14854. if (!cert) return "";
  14855. auto x509 = static_cast<X509 *>(cert);
  14856. auto subject_name = X509_get_subject_name(x509);
  14857. if (!subject_name) return "";
  14858. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14859. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14860. if (idx < 0) return "";
  14861. auto entry = X509_NAME_get_entry(subject_name, idx);
  14862. if (!entry) return "";
  14863. auto data = X509_NAME_ENTRY_get_data(entry);
  14864. if (!data) return "";
  14865. return std::string(
  14866. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14867. static_cast<size_t>(ASN1_STRING_length(data)));
  14868. }
  14869. inline std::string get_cert_issuer_name(cert_t cert) {
  14870. if (!cert) return "";
  14871. auto x509 = static_cast<X509 *>(cert);
  14872. auto issuer_name = X509_get_issuer_name(x509);
  14873. if (!issuer_name) return "";
  14874. char buf[256];
  14875. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14876. return std::string(buf);
  14877. }
  14878. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14879. sans.clear();
  14880. if (!cert) return false;
  14881. auto x509 = static_cast<X509 *>(cert);
  14882. auto names = static_cast<GENERAL_NAMES *>(
  14883. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14884. if (!names) return true; // No SANs is valid
  14885. auto count = sk_GENERAL_NAME_num(names);
  14886. for (decltype(count) i = 0; i < count; i++) {
  14887. auto gen = sk_GENERAL_NAME_value(names, i);
  14888. if (!gen) continue;
  14889. SanEntry entry;
  14890. switch (gen->type) {
  14891. case GEN_DNS:
  14892. entry.type = SanType::DNS;
  14893. if (gen->d.dNSName) {
  14894. entry.value = std::string(
  14895. reinterpret_cast<const char *>(
  14896. ASN1_STRING_get0_data(gen->d.dNSName)),
  14897. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14898. }
  14899. break;
  14900. case GEN_IPADD:
  14901. entry.type = SanType::IP;
  14902. if (gen->d.iPAddress) {
  14903. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14904. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14905. if (len == 4) {
  14906. // IPv4
  14907. char buf[INET_ADDRSTRLEN];
  14908. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14909. entry.value = buf;
  14910. } else if (len == 16) {
  14911. // IPv6
  14912. char buf[INET6_ADDRSTRLEN];
  14913. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14914. entry.value = buf;
  14915. }
  14916. }
  14917. break;
  14918. case GEN_EMAIL:
  14919. entry.type = SanType::EMAIL;
  14920. if (gen->d.rfc822Name) {
  14921. entry.value = std::string(
  14922. reinterpret_cast<const char *>(
  14923. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14924. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14925. }
  14926. break;
  14927. case GEN_URI:
  14928. entry.type = SanType::URI;
  14929. if (gen->d.uniformResourceIdentifier) {
  14930. entry.value = std::string(
  14931. reinterpret_cast<const char *>(
  14932. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14933. static_cast<size_t>(
  14934. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14935. }
  14936. break;
  14937. default: entry.type = SanType::OTHER; break;
  14938. }
  14939. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14940. }
  14941. GENERAL_NAMES_free(names);
  14942. return true;
  14943. }
  14944. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14945. time_t &not_after) {
  14946. if (!cert) return false;
  14947. auto x509 = static_cast<X509 *>(cert);
  14948. auto nb = X509_get0_notBefore(x509);
  14949. auto na = X509_get0_notAfter(x509);
  14950. if (!nb || !na) return false;
  14951. ASN1_TIME *epoch = ASN1_TIME_new();
  14952. if (!epoch) return false;
  14953. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14954. if (!ASN1_TIME_set(epoch, 0)) return false;
  14955. int pday, psec;
  14956. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14957. not_before = 86400 * (time_t)pday + psec;
  14958. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14959. not_after = 86400 * (time_t)pday + psec;
  14960. return true;
  14961. }
  14962. inline std::string get_cert_serial(cert_t cert) {
  14963. if (!cert) return "";
  14964. auto x509 = static_cast<X509 *>(cert);
  14965. auto serial = X509_get_serialNumber(x509);
  14966. if (!serial) return "";
  14967. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14968. if (!bn) return "";
  14969. auto hex = BN_bn2hex(bn);
  14970. BN_free(bn);
  14971. if (!hex) return "";
  14972. std::string result(hex);
  14973. OPENSSL_free(hex);
  14974. return result;
  14975. }
  14976. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14977. if (!cert) return false;
  14978. auto x509 = static_cast<X509 *>(cert);
  14979. auto len = i2d_X509(x509, nullptr);
  14980. if (len < 0) return false;
  14981. der.resize(static_cast<size_t>(len));
  14982. auto p = der.data();
  14983. i2d_X509(x509, &p);
  14984. return true;
  14985. }
  14986. inline const char *get_sni(const_session_t session) {
  14987. if (!session) return nullptr;
  14988. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14989. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14990. }
  14991. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14992. inline uint64_t get_error() { return ERR_get_error(); }
  14993. inline std::string error_string(uint64_t code) {
  14994. char buf[256];
  14995. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14996. return std::string(buf);
  14997. }
  14998. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14999. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  15000. if (!mem) { return nullptr; }
  15001. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  15002. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  15003. if (!inf) { return nullptr; }
  15004. auto store = X509_STORE_new();
  15005. if (store) {
  15006. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  15007. auto itmp = sk_X509_INFO_value(inf, i);
  15008. if (!itmp) { continue; }
  15009. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  15010. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  15011. }
  15012. }
  15013. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  15014. return static_cast<ca_store_t>(store);
  15015. }
  15016. inline void free_ca_store(ca_store_t store) {
  15017. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15018. }
  15019. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15020. if (!ctx || !store) { return false; }
  15021. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15022. auto x509_store = static_cast<X509_STORE *>(store);
  15023. // Check if same store is already set
  15024. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15025. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15026. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15027. return true;
  15028. }
  15029. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15030. certs.clear();
  15031. if (!ctx) { return 0; }
  15032. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15033. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15034. if (!store) { return 0; }
  15035. auto objs = impl::get_store_objects(store);
  15036. if (!objs) { return 0; }
  15037. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15038. auto count = sk_X509_OBJECT_num(objs);
  15039. for (decltype(count) i = 0; i < count; i++) {
  15040. auto obj = sk_X509_OBJECT_value(objs, i);
  15041. if (!obj) { continue; }
  15042. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15043. auto x509 = X509_OBJECT_get0_X509(obj);
  15044. if (x509) {
  15045. // Increment reference count so caller can free it
  15046. X509_up_ref(x509);
  15047. certs.push_back(static_cast<cert_t>(x509));
  15048. }
  15049. }
  15050. }
  15051. return certs.size();
  15052. }
  15053. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15054. std::vector<std::string> names;
  15055. if (!ctx) { return names; }
  15056. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15057. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15058. if (!store) { return names; }
  15059. auto objs = impl::get_store_objects(store);
  15060. if (!objs) { return names; }
  15061. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15062. auto count = sk_X509_OBJECT_num(objs);
  15063. for (decltype(count) i = 0; i < count; i++) {
  15064. auto obj = sk_X509_OBJECT_value(objs, i);
  15065. if (!obj) { continue; }
  15066. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15067. auto x509 = X509_OBJECT_get0_X509(obj);
  15068. if (x509) {
  15069. auto subject = X509_get_subject_name(x509);
  15070. if (subject) {
  15071. char buf[512];
  15072. X509_NAME_oneline(subject, buf, sizeof(buf));
  15073. names.push_back(buf);
  15074. }
  15075. }
  15076. }
  15077. }
  15078. return names;
  15079. }
  15080. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15081. const char *key_pem, const char *password) {
  15082. if (!ctx || !cert_pem || !key_pem) { return false; }
  15083. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15084. // Load certificate from PEM
  15085. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15086. if (!cert_bio) { return false; }
  15087. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15088. BIO_free(cert_bio);
  15089. if (!cert) { return false; }
  15090. // Load private key from PEM
  15091. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15092. if (!key_bio) {
  15093. X509_free(cert);
  15094. return false;
  15095. }
  15096. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15097. password ? const_cast<char *>(password)
  15098. : nullptr);
  15099. BIO_free(key_bio);
  15100. if (!key) {
  15101. X509_free(cert);
  15102. return false;
  15103. }
  15104. // Update certificate and key
  15105. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15106. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15107. X509_free(cert);
  15108. EVP_PKEY_free(key);
  15109. return ret;
  15110. }
  15111. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15112. if (!ctx || !ca_pem) { return false; }
  15113. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15114. // Create new X509_STORE from PEM
  15115. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15116. if (!store) { return false; }
  15117. // SSL_CTX_set_cert_store takes ownership
  15118. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15119. // Set client CA list for client certificate request
  15120. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15121. if (ca_list) {
  15122. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15123. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15124. }
  15125. return true;
  15126. }
  15127. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15128. if (!ctx) { return false; }
  15129. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15130. impl::get_verify_callback() = std::move(callback);
  15131. if (impl::get_verify_callback()) {
  15132. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15133. } else {
  15134. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15135. }
  15136. return true;
  15137. }
  15138. inline long get_verify_error(const_session_t session) {
  15139. if (!session) { return -1; }
  15140. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15141. return SSL_get_verify_result(ssl);
  15142. }
  15143. inline std::string verify_error_string(long error_code) {
  15144. if (error_code == X509_V_OK) { return ""; }
  15145. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15146. return str ? str : "unknown error";
  15147. }
  15148. } // namespace tls
  15149. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15150. /*
  15151. * Group 9: TLS abstraction layer - Mbed TLS backend
  15152. */
  15153. /*
  15154. * Mbed TLS Backend Implementation
  15155. */
  15156. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15157. namespace tls {
  15158. namespace impl {
  15159. // Mbed TLS session wrapper
  15160. struct MbedTlsSession {
  15161. mbedtls_ssl_context ssl;
  15162. socket_t sock = INVALID_SOCKET;
  15163. std::string hostname; // For client: set via set_sni
  15164. std::string sni_hostname; // For server: received from client via SNI callback
  15165. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15166. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15167. MbedTlsSession(const MbedTlsSession &) = delete;
  15168. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15169. };
  15170. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15171. // queue)
  15172. inline int &mbedtls_last_error() {
  15173. static thread_local int err = 0;
  15174. return err;
  15175. }
  15176. // Helper to map Mbed TLS error to ErrorCode
  15177. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15178. if (ret == 0) { return ErrorCode::Success; }
  15179. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15180. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15181. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15182. return ErrorCode::PeerClosed;
  15183. }
  15184. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15185. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15186. out_errno = errno;
  15187. return ErrorCode::SyscallError;
  15188. }
  15189. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15190. return ErrorCode::CertVerifyFailed;
  15191. }
  15192. return ErrorCode::Fatal;
  15193. }
  15194. // BIO-like send callback for Mbed TLS
  15195. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15196. size_t len) {
  15197. auto sock = *static_cast<socket_t *>(ctx);
  15198. #ifdef _WIN32
  15199. auto ret =
  15200. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15201. if (ret == SOCKET_ERROR) {
  15202. int err = WSAGetLastError();
  15203. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15204. return MBEDTLS_ERR_NET_SEND_FAILED;
  15205. }
  15206. #else
  15207. auto ret = send(sock, buf, len, 0);
  15208. if (ret < 0) {
  15209. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15210. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15211. }
  15212. return MBEDTLS_ERR_NET_SEND_FAILED;
  15213. }
  15214. #endif
  15215. return static_cast<int>(ret);
  15216. }
  15217. // BIO-like recv callback for Mbed TLS
  15218. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15219. auto sock = *static_cast<socket_t *>(ctx);
  15220. #ifdef _WIN32
  15221. auto ret =
  15222. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15223. if (ret == SOCKET_ERROR) {
  15224. int err = WSAGetLastError();
  15225. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15226. return MBEDTLS_ERR_NET_RECV_FAILED;
  15227. }
  15228. #else
  15229. auto ret = recv(sock, buf, len, 0);
  15230. if (ret < 0) {
  15231. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15232. return MBEDTLS_ERR_SSL_WANT_READ;
  15233. }
  15234. return MBEDTLS_ERR_NET_RECV_FAILED;
  15235. }
  15236. #endif
  15237. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15238. return static_cast<int>(ret);
  15239. }
  15240. // MbedTlsContext constructor/destructor implementations
  15241. inline MbedTlsContext::MbedTlsContext() {
  15242. mbedtls_ssl_config_init(&conf);
  15243. mbedtls_entropy_init(&entropy);
  15244. mbedtls_ctr_drbg_init(&ctr_drbg);
  15245. mbedtls_x509_crt_init(&ca_chain);
  15246. mbedtls_x509_crt_init(&own_cert);
  15247. mbedtls_pk_init(&own_key);
  15248. }
  15249. inline MbedTlsContext::~MbedTlsContext() {
  15250. mbedtls_pk_free(&own_key);
  15251. mbedtls_x509_crt_free(&own_cert);
  15252. mbedtls_x509_crt_free(&ca_chain);
  15253. mbedtls_ctr_drbg_free(&ctr_drbg);
  15254. mbedtls_entropy_free(&entropy);
  15255. mbedtls_ssl_config_free(&conf);
  15256. }
  15257. // Thread-local storage for SNI captured during handshake
  15258. // This is needed because the SNI callback doesn't have a way to pass
  15259. // session-specific data before the session is fully set up
  15260. inline std::string &mbedpending_sni() {
  15261. static thread_local std::string sni;
  15262. return sni;
  15263. }
  15264. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15265. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15266. const unsigned char *name, size_t name_len) {
  15267. (void)p_ctx;
  15268. (void)ssl;
  15269. // Store SNI name in thread-local storage
  15270. // It will be retrieved and stored in the session after handshake
  15271. if (name && name_len > 0) {
  15272. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15273. } else {
  15274. mbedpending_sni().clear();
  15275. }
  15276. return 0; // Accept any SNI
  15277. }
  15278. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15279. int cert_depth, uint32_t *flags);
  15280. // MbedTLS verify callback wrapper
  15281. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15282. int cert_depth, uint32_t *flags) {
  15283. auto &callback = get_verify_callback();
  15284. if (!callback) { return 0; } // Continue with default verification
  15285. // data points to the MbedTlsSession
  15286. auto *session = static_cast<MbedTlsSession *>(data);
  15287. // Build context
  15288. VerifyContext verify_ctx;
  15289. verify_ctx.session = static_cast<session_t>(session);
  15290. verify_ctx.cert = static_cast<cert_t>(crt);
  15291. verify_ctx.depth = cert_depth;
  15292. verify_ctx.preverify_ok = (*flags == 0);
  15293. verify_ctx.error_code = static_cast<long>(*flags);
  15294. // Convert Mbed TLS flags to error string
  15295. static thread_local char error_buf[256];
  15296. if (*flags != 0) {
  15297. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15298. verify_ctx.error_string = error_buf;
  15299. } else {
  15300. verify_ctx.error_string = nullptr;
  15301. }
  15302. bool accepted = callback(verify_ctx);
  15303. if (accepted) {
  15304. *flags = 0; // Clear all error flags
  15305. return 0;
  15306. }
  15307. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15308. }
  15309. } // namespace impl
  15310. inline ctx_t create_client_context() {
  15311. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15312. if (!ctx) { return nullptr; }
  15313. ctx->is_server = false;
  15314. // Seed the random number generator
  15315. const char *pers = "httplib_client";
  15316. int ret = mbedtls_ctr_drbg_seed(
  15317. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15318. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15319. if (ret != 0) {
  15320. impl::mbedtls_last_error() = ret;
  15321. delete ctx;
  15322. return nullptr;
  15323. }
  15324. // Set up SSL config for client
  15325. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15326. MBEDTLS_SSL_TRANSPORT_STREAM,
  15327. MBEDTLS_SSL_PRESET_DEFAULT);
  15328. if (ret != 0) {
  15329. impl::mbedtls_last_error() = ret;
  15330. delete ctx;
  15331. return nullptr;
  15332. }
  15333. // Set random number generator
  15334. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15335. // Default: verify peer certificate
  15336. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15337. // Set minimum TLS version to 1.2
  15338. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15339. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15340. #else
  15341. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15342. MBEDTLS_SSL_MINOR_VERSION_3);
  15343. #endif
  15344. return static_cast<ctx_t>(ctx);
  15345. }
  15346. inline ctx_t create_server_context() {
  15347. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15348. if (!ctx) { return nullptr; }
  15349. ctx->is_server = true;
  15350. // Seed the random number generator
  15351. const char *pers = "httplib_server";
  15352. int ret = mbedtls_ctr_drbg_seed(
  15353. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15354. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15355. if (ret != 0) {
  15356. impl::mbedtls_last_error() = ret;
  15357. delete ctx;
  15358. return nullptr;
  15359. }
  15360. // Set up SSL config for server
  15361. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15362. MBEDTLS_SSL_TRANSPORT_STREAM,
  15363. MBEDTLS_SSL_PRESET_DEFAULT);
  15364. if (ret != 0) {
  15365. impl::mbedtls_last_error() = ret;
  15366. delete ctx;
  15367. return nullptr;
  15368. }
  15369. // Set random number generator
  15370. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15371. // Default: don't verify client
  15372. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15373. // Set minimum TLS version to 1.2
  15374. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15375. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15376. #else
  15377. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15378. MBEDTLS_SSL_MINOR_VERSION_3);
  15379. #endif
  15380. // Set SNI callback to capture client's SNI hostname
  15381. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15382. return static_cast<ctx_t>(ctx);
  15383. }
  15384. inline void free_context(ctx_t ctx) {
  15385. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15386. }
  15387. inline bool set_min_version(ctx_t ctx, Version version) {
  15388. if (!ctx) { return false; }
  15389. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15390. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15391. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15392. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15393. if (version >= Version::TLS1_3) {
  15394. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15395. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15396. #endif
  15397. }
  15398. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15399. #else
  15400. // Mbed TLS 2.x uses major/minor version numbers
  15401. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15402. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15403. if (version >= Version::TLS1_3) {
  15404. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15405. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15406. #else
  15407. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15408. #endif
  15409. }
  15410. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15411. #endif
  15412. return true;
  15413. }
  15414. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15415. if (!ctx || !pem) { return false; }
  15416. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15417. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15418. // Add null terminator if not present
  15419. std::string pem_str(pem, len);
  15420. int ret = mbedtls_x509_crt_parse(
  15421. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15422. pem_str.size() + 1);
  15423. if (ret != 0) {
  15424. impl::mbedtls_last_error() = ret;
  15425. return false;
  15426. }
  15427. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15428. return true;
  15429. }
  15430. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15431. if (!ctx || !file_path) { return false; }
  15432. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15433. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15434. if (ret != 0) {
  15435. impl::mbedtls_last_error() = ret;
  15436. return false;
  15437. }
  15438. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15439. return true;
  15440. }
  15441. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15442. if (!ctx || !dir_path) { return false; }
  15443. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15444. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15445. if (ret < 0) { // Returns number of certs on success, negative on error
  15446. impl::mbedtls_last_error() = ret;
  15447. return false;
  15448. }
  15449. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15450. return true;
  15451. }
  15452. inline bool load_system_certs(ctx_t ctx) {
  15453. if (!ctx) { return false; }
  15454. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15455. bool loaded = false;
  15456. #ifdef _WIN32
  15457. loaded = impl::enumerate_windows_system_certs(
  15458. [&](const unsigned char *data, size_t len) {
  15459. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15460. });
  15461. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15462. loaded = impl::enumerate_macos_keychain_certs(
  15463. [&](const unsigned char *data, size_t len) {
  15464. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15465. });
  15466. #else
  15467. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15468. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15469. loaded = true;
  15470. break;
  15471. }
  15472. }
  15473. if (!loaded) {
  15474. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15475. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15476. loaded = true;
  15477. break;
  15478. }
  15479. }
  15480. }
  15481. #endif
  15482. if (loaded) {
  15483. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15484. }
  15485. return loaded;
  15486. }
  15487. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15488. const char *password) {
  15489. if (!ctx || !cert || !key) { return false; }
  15490. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15491. // Parse certificate
  15492. std::string cert_str(cert);
  15493. int ret = mbedtls_x509_crt_parse(
  15494. &mctx->own_cert,
  15495. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15496. cert_str.size() + 1);
  15497. if (ret != 0) {
  15498. impl::mbedtls_last_error() = ret;
  15499. return false;
  15500. }
  15501. // Parse private key
  15502. std::string key_str(key);
  15503. const unsigned char *pwd =
  15504. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15505. size_t pwd_len = password ? strlen(password) : 0;
  15506. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15507. ret = mbedtls_pk_parse_key(
  15508. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15509. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15510. &mctx->ctr_drbg);
  15511. #else
  15512. ret = mbedtls_pk_parse_key(
  15513. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15514. key_str.size() + 1, pwd, pwd_len);
  15515. #endif
  15516. if (ret != 0) {
  15517. impl::mbedtls_last_error() = ret;
  15518. return false;
  15519. }
  15520. // Verify that the certificate and private key match
  15521. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15522. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15523. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15524. #else
  15525. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15526. #endif
  15527. if (ret != 0) {
  15528. impl::mbedtls_last_error() = ret;
  15529. return false;
  15530. }
  15531. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15532. if (ret != 0) {
  15533. impl::mbedtls_last_error() = ret;
  15534. return false;
  15535. }
  15536. return true;
  15537. }
  15538. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15539. const char *key_path, const char *password) {
  15540. if (!ctx || !cert_path || !key_path) { return false; }
  15541. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15542. // Parse certificate file
  15543. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15544. if (ret != 0) {
  15545. impl::mbedtls_last_error() = ret;
  15546. return false;
  15547. }
  15548. // Parse private key file
  15549. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15550. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15551. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15552. #else
  15553. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15554. #endif
  15555. if (ret != 0) {
  15556. impl::mbedtls_last_error() = ret;
  15557. return false;
  15558. }
  15559. // Verify that the certificate and private key match
  15560. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15561. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15562. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15563. #else
  15564. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15565. #endif
  15566. if (ret != 0) {
  15567. impl::mbedtls_last_error() = ret;
  15568. return false;
  15569. }
  15570. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15571. if (ret != 0) {
  15572. impl::mbedtls_last_error() = ret;
  15573. return false;
  15574. }
  15575. return true;
  15576. }
  15577. inline void set_verify_client(ctx_t ctx, bool require) {
  15578. if (!ctx) { return; }
  15579. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15580. mctx->verify_client = require;
  15581. if (require) {
  15582. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15583. } else {
  15584. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15585. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15586. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15587. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15588. : MBEDTLS_SSL_VERIFY_NONE);
  15589. }
  15590. }
  15591. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15592. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15593. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15594. auto session = new (std::nothrow) impl::MbedTlsSession();
  15595. if (!session) { return nullptr; }
  15596. session->sock = sock;
  15597. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15598. if (ret != 0) {
  15599. impl::mbedtls_last_error() = ret;
  15600. delete session;
  15601. return nullptr;
  15602. }
  15603. // Explicitly opt out of in-handshake hostname verification by default;
  15604. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15605. // fails outright when no hostname was set. set_sni() installs the real
  15606. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15607. // caller verifies the certificate identity post-handshake via
  15608. // verify_hostname().
  15609. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15610. // Set BIO callbacks
  15611. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15612. impl::mbedtls_net_recv_cb, nullptr);
  15613. // Set per-session verify callback with session pointer if callback is
  15614. // registered
  15615. if (mctx->has_verify_callback) {
  15616. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15617. session);
  15618. }
  15619. return static_cast<session_t>(session);
  15620. }
  15621. inline void free_session(session_t session) {
  15622. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15623. }
  15624. inline bool set_sni(session_t session, const char *hostname) {
  15625. if (!session || !hostname) { return false; }
  15626. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15627. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15628. if (ret != 0) {
  15629. impl::mbedtls_last_error() = ret;
  15630. return false;
  15631. }
  15632. msession->hostname = hostname;
  15633. return true;
  15634. }
  15635. inline bool set_hostname(session_t session, const char *hostname) {
  15636. // In Mbed TLS, set_hostname also sets up hostname verification
  15637. return set_sni(session, hostname);
  15638. }
  15639. inline TlsError connect(session_t session) {
  15640. TlsError err;
  15641. if (!session) {
  15642. err.code = ErrorCode::Fatal;
  15643. return err;
  15644. }
  15645. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15646. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15647. if (ret == 0) {
  15648. err.code = ErrorCode::Success;
  15649. } else {
  15650. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15651. err.backend_code = static_cast<uint64_t>(-ret);
  15652. impl::mbedtls_last_error() = ret;
  15653. }
  15654. return err;
  15655. }
  15656. inline TlsError accept(session_t session) {
  15657. // Same as connect for Mbed TLS - handshake works for both client and server
  15658. auto result = connect(session);
  15659. // After successful handshake, capture SNI from thread-local storage
  15660. if (result.code == ErrorCode::Success && session) {
  15661. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15662. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15663. impl::mbedpending_sni().clear();
  15664. }
  15665. return result;
  15666. }
  15667. inline bool connect_nonblocking(session_t session, socket_t sock,
  15668. time_t timeout_sec, time_t timeout_usec,
  15669. TlsError *err) {
  15670. if (!session) {
  15671. if (err) { err->code = ErrorCode::Fatal; }
  15672. return false;
  15673. }
  15674. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15675. // Set socket to non-blocking mode
  15676. detail::set_nonblocking(sock, true);
  15677. auto cleanup =
  15678. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15679. int ret;
  15680. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15681. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15682. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15683. continue;
  15684. }
  15685. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15686. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15687. continue;
  15688. }
  15689. }
  15690. // TlsError or timeout
  15691. if (err) {
  15692. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15693. err->backend_code = static_cast<uint64_t>(-ret);
  15694. }
  15695. impl::mbedtls_last_error() = ret;
  15696. return false;
  15697. }
  15698. if (err) { err->code = ErrorCode::Success; }
  15699. return true;
  15700. }
  15701. inline bool accept_nonblocking(session_t session, socket_t sock,
  15702. time_t timeout_sec, time_t timeout_usec,
  15703. TlsError *err) {
  15704. // Same implementation as connect for Mbed TLS
  15705. bool result =
  15706. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15707. // After successful handshake, capture SNI from thread-local storage
  15708. if (result && session) {
  15709. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15710. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15711. impl::mbedpending_sni().clear();
  15712. }
  15713. return result;
  15714. }
  15715. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15716. if (!session || !buf) {
  15717. err.code = ErrorCode::Fatal;
  15718. return -1;
  15719. }
  15720. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15721. int ret =
  15722. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15723. if (ret > 0) {
  15724. err.code = ErrorCode::Success;
  15725. return static_cast<ssize_t>(ret);
  15726. }
  15727. if (ret == 0) {
  15728. err.code = ErrorCode::PeerClosed;
  15729. return 0;
  15730. }
  15731. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15732. err.backend_code = static_cast<uint64_t>(-ret);
  15733. impl::mbedtls_last_error() = ret;
  15734. // mbedTLS signals a clean close_notify via a negative error code rather
  15735. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15736. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15737. return -1;
  15738. }
  15739. inline ssize_t write(session_t session, const void *buf, size_t len,
  15740. TlsError &err) {
  15741. if (!session || !buf) {
  15742. err.code = ErrorCode::Fatal;
  15743. return -1;
  15744. }
  15745. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15746. int ret = mbedtls_ssl_write(&msession->ssl,
  15747. static_cast<const unsigned char *>(buf), len);
  15748. if (ret > 0) {
  15749. err.code = ErrorCode::Success;
  15750. return static_cast<ssize_t>(ret);
  15751. }
  15752. if (ret == 0) {
  15753. err.code = ErrorCode::PeerClosed;
  15754. return 0;
  15755. }
  15756. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15757. err.backend_code = static_cast<uint64_t>(-ret);
  15758. impl::mbedtls_last_error() = ret;
  15759. return -1;
  15760. }
  15761. inline int pending(const_session_t session) {
  15762. if (!session) { return 0; }
  15763. auto msession =
  15764. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15765. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15766. }
  15767. inline void shutdown(session_t session, bool graceful) {
  15768. if (!session) { return; }
  15769. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15770. if (graceful) {
  15771. // Try to send close_notify, but don't block forever
  15772. int ret;
  15773. int attempts = 0;
  15774. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15775. attempts < 3) {
  15776. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15777. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15778. break;
  15779. }
  15780. attempts++;
  15781. }
  15782. }
  15783. }
  15784. inline bool is_peer_closed(session_t session, socket_t sock) {
  15785. if (!session || sock == INVALID_SOCKET) { return true; }
  15786. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15787. // Check if there's already decrypted data available in the TLS buffer
  15788. // If so, the connection is definitely alive
  15789. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15790. // Set socket to non-blocking to avoid blocking on read
  15791. detail::set_nonblocking(sock, true);
  15792. auto cleanup =
  15793. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15794. // Try a 1-byte read to check connection status
  15795. // Note: This will consume the byte if data is available, but for the
  15796. // purpose of checking if peer is closed, this should be acceptable
  15797. // since we're only called when we expect the connection might be closing
  15798. unsigned char buf;
  15799. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15800. // If we got data or WANT_READ (would block), connection is alive
  15801. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15802. // If we get a peer close notify or a connection reset, the peer is closed
  15803. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15804. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15805. }
  15806. inline cert_t get_peer_cert(const_session_t session) {
  15807. if (!session) { return nullptr; }
  15808. auto msession =
  15809. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15810. // Mbed TLS returns a pointer to the internal peer cert chain.
  15811. // WARNING: This pointer is only valid while the session is active.
  15812. // Do not use the certificate after calling free_session().
  15813. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15814. return const_cast<mbedtls_x509_crt *>(cert);
  15815. }
  15816. inline void free_cert(cert_t cert) {
  15817. // Mbed TLS: peer certificate is owned by the SSL context.
  15818. // No-op here, but callers should still call this for cross-backend
  15819. // portability.
  15820. (void)cert;
  15821. }
  15822. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15823. if (!cert || !hostname) { return false; }
  15824. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15825. std::string host_str(hostname);
  15826. // Check if hostname is an IP address (IPv4 or IPv6)
  15827. unsigned char ip_bytes[16];
  15828. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15829. auto is_ip = ip_len > 0;
  15830. // Check Subject Alternative Names (SAN)
  15831. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15832. // - DNS names: raw string bytes
  15833. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15834. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15835. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15836. const unsigned char *p = san->buf.p;
  15837. size_t len = san->buf.len;
  15838. if (is_ip) {
  15839. // For an IP host, only a matching iPAddress SAN of the same family
  15840. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15841. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15842. } else {
  15843. // Check if this SAN is a DNS name (printable ASCII string)
  15844. bool is_dns = len > 0;
  15845. for (size_t i = 0; i < len && is_dns; i++) {
  15846. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15847. }
  15848. if (is_dns) {
  15849. std::string san_name(reinterpret_cast<const char *>(p), len);
  15850. if (detail::match_hostname(san_name, host_str)) { return true; }
  15851. }
  15852. }
  15853. san = san->next;
  15854. }
  15855. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15856. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15857. // the OpenSSL backend's X509_check_ip behaves the same way).
  15858. if (!is_ip) {
  15859. char cn[256];
  15860. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15861. if (ret > 0) {
  15862. std::string cn_str(cn);
  15863. // Look for "CN=" in the DN string
  15864. size_t cn_pos = cn_str.find("CN=");
  15865. if (cn_pos != std::string::npos) {
  15866. size_t start = cn_pos + 3;
  15867. size_t end = cn_str.find(',', start);
  15868. std::string cn_value =
  15869. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15870. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15871. }
  15872. }
  15873. }
  15874. return false;
  15875. }
  15876. inline uint64_t hostname_mismatch_code() {
  15877. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15878. }
  15879. inline long get_verify_result(const_session_t session) {
  15880. if (!session) { return -1; }
  15881. auto msession =
  15882. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15883. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15884. // Return 0 (X509_V_OK equivalent) if verification passed
  15885. return flags == 0 ? 0 : static_cast<long>(flags);
  15886. }
  15887. inline std::string get_cert_subject_cn(cert_t cert) {
  15888. if (!cert) return "";
  15889. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15890. // Find the CN in the subject
  15891. const mbedtls_x509_name *name = &x509->subject;
  15892. while (name != nullptr) {
  15893. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15894. return std::string(reinterpret_cast<const char *>(name->val.p),
  15895. name->val.len);
  15896. }
  15897. name = name->next;
  15898. }
  15899. return "";
  15900. }
  15901. inline std::string get_cert_issuer_name(cert_t cert) {
  15902. if (!cert) return "";
  15903. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15904. // Build a human-readable issuer name string
  15905. char buf[512];
  15906. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15907. if (ret < 0) return "";
  15908. return std::string(buf);
  15909. }
  15910. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15911. sans.clear();
  15912. if (!cert) return false;
  15913. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15914. // Parse the Subject Alternative Name extension
  15915. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15916. while (cur != nullptr) {
  15917. if (cur->buf.len > 0) {
  15918. // Mbed TLS stores SAN as ASN.1 sequences
  15919. // The tag byte indicates the type
  15920. const unsigned char *p = cur->buf.p;
  15921. size_t len = cur->buf.len;
  15922. // First byte is the tag
  15923. unsigned char tag = *p;
  15924. p++;
  15925. len--;
  15926. // Parse length (simple single-byte length assumed)
  15927. if (len > 0 && *p < 0x80) {
  15928. size_t value_len = *p;
  15929. p++;
  15930. len--;
  15931. if (value_len <= len) {
  15932. SanEntry entry;
  15933. // ASN.1 context tags for GeneralName
  15934. switch (tag & 0x1F) {
  15935. case 2: // dNSName
  15936. entry.type = SanType::DNS;
  15937. entry.value =
  15938. std::string(reinterpret_cast<const char *>(p), value_len);
  15939. break;
  15940. case 7: // iPAddress
  15941. entry.type = SanType::IP;
  15942. if (value_len == 4) {
  15943. // IPv4
  15944. char buf[16];
  15945. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15946. entry.value = buf;
  15947. } else if (value_len == 16) {
  15948. // IPv6
  15949. char buf[64];
  15950. snprintf(buf, sizeof(buf),
  15951. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15952. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15953. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15954. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15955. entry.value = buf;
  15956. }
  15957. break;
  15958. case 1: // rfc822Name (email)
  15959. entry.type = SanType::EMAIL;
  15960. entry.value =
  15961. std::string(reinterpret_cast<const char *>(p), value_len);
  15962. break;
  15963. case 6: // uniformResourceIdentifier
  15964. entry.type = SanType::URI;
  15965. entry.value =
  15966. std::string(reinterpret_cast<const char *>(p), value_len);
  15967. break;
  15968. default: entry.type = SanType::OTHER; break;
  15969. }
  15970. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15971. }
  15972. }
  15973. }
  15974. cur = cur->next;
  15975. }
  15976. return true;
  15977. }
  15978. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15979. time_t &not_after) {
  15980. if (!cert) return false;
  15981. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15982. // Convert mbedtls_x509_time to time_t
  15983. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15984. struct tm tm_time = {};
  15985. tm_time.tm_year = t.year - 1900;
  15986. tm_time.tm_mon = t.mon - 1;
  15987. tm_time.tm_mday = t.day;
  15988. tm_time.tm_hour = t.hour;
  15989. tm_time.tm_min = t.min;
  15990. tm_time.tm_sec = t.sec;
  15991. #ifdef _WIN32
  15992. return _mkgmtime(&tm_time);
  15993. #else
  15994. return timegm(&tm_time);
  15995. #endif
  15996. };
  15997. not_before = to_time_t(x509->valid_from);
  15998. not_after = to_time_t(x509->valid_to);
  15999. return true;
  16000. }
  16001. inline std::string get_cert_serial(cert_t cert) {
  16002. if (!cert) return "";
  16003. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  16004. // Convert serial number to hex string
  16005. std::string result;
  16006. result.reserve(x509->serial.len * 2);
  16007. for (size_t i = 0; i < x509->serial.len; i++) {
  16008. char hex[3];
  16009. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  16010. result += hex;
  16011. }
  16012. return result;
  16013. }
  16014. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16015. if (!cert) return false;
  16016. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16017. if (!crt->raw.p || crt->raw.len == 0) return false;
  16018. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16019. return true;
  16020. }
  16021. inline const char *get_sni(const_session_t session) {
  16022. if (!session) return nullptr;
  16023. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16024. // For server: return SNI received from client during handshake
  16025. if (!msession->sni_hostname.empty()) {
  16026. return msession->sni_hostname.c_str();
  16027. }
  16028. // For client: return the hostname set via set_sni
  16029. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16030. return nullptr;
  16031. }
  16032. inline uint64_t peek_error() {
  16033. // Mbed TLS doesn't have an error queue, return the last error
  16034. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16035. }
  16036. inline uint64_t get_error() {
  16037. // Mbed TLS doesn't have an error queue, return and clear the last error
  16038. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16039. impl::mbedtls_last_error() = 0;
  16040. return err;
  16041. }
  16042. inline std::string error_string(uint64_t code) {
  16043. char buf[256];
  16044. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16045. return std::string(buf);
  16046. }
  16047. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16048. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16049. if (!ca_chain) { return nullptr; }
  16050. mbedtls_x509_crt_init(ca_chain);
  16051. // mbedtls_x509_crt_parse expects null-terminated PEM
  16052. int ret = mbedtls_x509_crt_parse(ca_chain,
  16053. reinterpret_cast<const unsigned char *>(pem),
  16054. len + 1); // +1 for null terminator
  16055. if (ret != 0) {
  16056. // Try without +1 in case PEM is already null-terminated
  16057. ret = mbedtls_x509_crt_parse(
  16058. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16059. if (ret != 0) {
  16060. mbedtls_x509_crt_free(ca_chain);
  16061. delete ca_chain;
  16062. return nullptr;
  16063. }
  16064. }
  16065. return static_cast<ca_store_t>(ca_chain);
  16066. }
  16067. inline void free_ca_store(ca_store_t store) {
  16068. if (store) {
  16069. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16070. mbedtls_x509_crt_free(ca_chain);
  16071. delete ca_chain;
  16072. }
  16073. }
  16074. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16075. if (!ctx || !store) { return false; }
  16076. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16077. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16078. // Free existing CA chain
  16079. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16080. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16081. // Copy the CA chain (deep copy)
  16082. // Parse from the raw data of the source cert
  16083. mbedtls_x509_crt *src = ca_chain;
  16084. while (src != nullptr) {
  16085. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16086. src->raw.len);
  16087. if (ret != 0) {
  16088. free_ca_store(store);
  16089. return false;
  16090. }
  16091. src = src->next;
  16092. }
  16093. // This function takes ownership of the store; the chain was deep-copied
  16094. // above, so release the source
  16095. free_ca_store(store);
  16096. // Update the SSL config to use the new CA chain
  16097. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16098. return true;
  16099. }
  16100. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16101. certs.clear();
  16102. if (!ctx) { return 0; }
  16103. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16104. // Iterate through the CA chain
  16105. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16106. while (cert != nullptr && cert->raw.len > 0) {
  16107. // Create a copy of the certificate for the caller
  16108. auto *copy = new mbedtls_x509_crt;
  16109. mbedtls_x509_crt_init(copy);
  16110. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16111. if (ret == 0) {
  16112. certs.push_back(static_cast<cert_t>(copy));
  16113. } else {
  16114. mbedtls_x509_crt_free(copy);
  16115. delete copy;
  16116. }
  16117. cert = cert->next;
  16118. }
  16119. return certs.size();
  16120. }
  16121. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16122. std::vector<std::string> names;
  16123. if (!ctx) { return names; }
  16124. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16125. // Iterate through the CA chain
  16126. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16127. while (cert != nullptr && cert->raw.len > 0) {
  16128. char buf[512];
  16129. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16130. if (ret > 0) { names.push_back(buf); }
  16131. cert = cert->next;
  16132. }
  16133. return names;
  16134. }
  16135. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16136. const char *key_pem, const char *password) {
  16137. if (!ctx || !cert_pem || !key_pem) { return false; }
  16138. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16139. // Free existing certificate and key
  16140. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16141. mbedtls_pk_free(&mbed_ctx->own_key);
  16142. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16143. mbedtls_pk_init(&mbed_ctx->own_key);
  16144. // Parse certificate PEM
  16145. int ret = mbedtls_x509_crt_parse(
  16146. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16147. strlen(cert_pem) + 1);
  16148. if (ret != 0) {
  16149. impl::mbedtls_last_error() = ret;
  16150. return false;
  16151. }
  16152. // Parse private key PEM
  16153. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16154. ret = mbedtls_pk_parse_key(
  16155. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16156. strlen(key_pem) + 1,
  16157. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16158. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16159. &mbed_ctx->ctr_drbg);
  16160. #else
  16161. ret = mbedtls_pk_parse_key(
  16162. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16163. strlen(key_pem) + 1,
  16164. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16165. password ? strlen(password) : 0);
  16166. #endif
  16167. if (ret != 0) {
  16168. impl::mbedtls_last_error() = ret;
  16169. return false;
  16170. }
  16171. // Configure SSL to use the new certificate and key
  16172. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16173. &mbed_ctx->own_key);
  16174. if (ret != 0) {
  16175. impl::mbedtls_last_error() = ret;
  16176. return false;
  16177. }
  16178. return true;
  16179. }
  16180. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16181. if (!ctx || !ca_pem) { return false; }
  16182. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16183. // Free existing CA chain
  16184. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16185. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16186. // Parse CA PEM
  16187. int ret = mbedtls_x509_crt_parse(
  16188. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16189. strlen(ca_pem) + 1);
  16190. if (ret != 0) {
  16191. impl::mbedtls_last_error() = ret;
  16192. return false;
  16193. }
  16194. // Update SSL config to use new CA chain
  16195. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16196. return true;
  16197. }
  16198. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16199. if (!ctx) { return false; }
  16200. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16201. impl::get_verify_callback() = std::move(callback);
  16202. mbed_ctx->has_verify_callback =
  16203. static_cast<bool>(impl::get_verify_callback());
  16204. if (mbed_ctx->has_verify_callback) {
  16205. // Set OPTIONAL mode to ensure callback is called even when verification
  16206. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16207. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16208. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16209. nullptr);
  16210. } else {
  16211. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16212. }
  16213. return true;
  16214. }
  16215. inline long get_verify_error(const_session_t session) {
  16216. if (!session) { return -1; }
  16217. auto *msession =
  16218. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16219. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16220. }
  16221. inline std::string verify_error_string(long error_code) {
  16222. if (error_code == 0) { return ""; }
  16223. char buf[256];
  16224. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16225. static_cast<uint32_t>(error_code));
  16226. // Remove trailing newline if present
  16227. std::string result(buf);
  16228. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16229. result.pop_back();
  16230. }
  16231. return result;
  16232. }
  16233. } // namespace tls
  16234. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16235. /*
  16236. * Group 10: TLS abstraction layer - wolfSSL backend
  16237. */
  16238. /*
  16239. * wolfSSL Backend Implementation
  16240. */
  16241. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16242. namespace tls {
  16243. namespace impl {
  16244. // wolfSSL session wrapper
  16245. struct WolfSSLSession {
  16246. WOLFSSL *ssl = nullptr;
  16247. socket_t sock = INVALID_SOCKET;
  16248. std::string hostname; // For client: set via set_sni
  16249. std::string sni_hostname; // For server: received from client via SNI callback
  16250. WolfSSLSession() = default;
  16251. ~WolfSSLSession() {
  16252. if (ssl) { wolfSSL_free(ssl); }
  16253. }
  16254. WolfSSLSession(const WolfSSLSession &) = delete;
  16255. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16256. };
  16257. // Thread-local error code accessor for wolfSSL
  16258. inline uint64_t &wolfssl_last_error() {
  16259. static thread_local uint64_t err = 0;
  16260. return err;
  16261. }
  16262. // Helper to map wolfSSL error to ErrorCode.
  16263. // ssl_error is the value from wolfSSL_get_error().
  16264. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16265. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16266. int &out_errno) {
  16267. switch (ssl_error) {
  16268. case SSL_ERROR_NONE: return ErrorCode::Success;
  16269. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16270. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16271. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16272. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16273. default:
  16274. if (ssl) {
  16275. // wolfSSL stores the low-level error code as a negative value.
  16276. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16277. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16278. if (low_err == DOMAIN_NAME_MISMATCH) {
  16279. return ErrorCode::HostnameMismatch;
  16280. }
  16281. // Check verify result to distinguish cert verification from generic SSL
  16282. // errors.
  16283. long vr = wolfSSL_get_verify_result(ssl);
  16284. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16285. }
  16286. return ErrorCode::Fatal;
  16287. }
  16288. }
  16289. // WolfSSLContext constructor/destructor implementations
  16290. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16291. inline WolfSSLContext::~WolfSSLContext() {
  16292. if (ctx) { wolfSSL_CTX_free(ctx); }
  16293. }
  16294. // Thread-local storage for SNI captured during handshake
  16295. inline std::string &wolfssl_pending_sni() {
  16296. static thread_local std::string sni;
  16297. return sni;
  16298. }
  16299. // SNI callback for wolfSSL server to capture client's SNI hostname
  16300. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16301. (void)ret;
  16302. (void)exArg;
  16303. void *name_data = nullptr;
  16304. unsigned short name_len =
  16305. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16306. if (name_data && name_len > 0) {
  16307. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16308. name_len);
  16309. } else {
  16310. wolfssl_pending_sni().clear();
  16311. }
  16312. return 0; // Continue regardless
  16313. }
  16314. // wolfSSL verify callback wrapper
  16315. inline int wolfssl_verify_callback(int preverify_ok,
  16316. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16317. auto &callback = get_verify_callback();
  16318. if (!callback) { return preverify_ok; }
  16319. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16320. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16321. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16322. // Get the WOLFSSL object from the X509_STORE_CTX
  16323. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16324. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16325. VerifyContext verify_ctx;
  16326. verify_ctx.session = static_cast<session_t>(ssl);
  16327. verify_ctx.cert = static_cast<cert_t>(cert);
  16328. verify_ctx.depth = depth;
  16329. verify_ctx.preverify_ok = (preverify_ok != 0);
  16330. verify_ctx.error_code = static_cast<long>(err);
  16331. if (err != 0) {
  16332. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16333. } else {
  16334. verify_ctx.error_string = nullptr;
  16335. }
  16336. bool accepted = callback(verify_ctx);
  16337. return accepted ? 1 : 0;
  16338. }
  16339. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16340. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16341. wolfSSL_CTX_set_default_passwd_cb(
  16342. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16343. auto *pwd = static_cast<const char *>(userdata);
  16344. if (!pwd) return 0;
  16345. auto len = static_cast<int>(strlen(pwd));
  16346. if (len > size) len = size;
  16347. memcpy(buf, pwd, static_cast<size_t>(len));
  16348. return len;
  16349. });
  16350. }
  16351. } // namespace impl
  16352. inline ctx_t create_client_context() {
  16353. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16354. if (!ctx) { return nullptr; }
  16355. ctx->is_server = false;
  16356. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16357. if (!method) {
  16358. delete ctx;
  16359. return nullptr;
  16360. }
  16361. ctx->ctx = wolfSSL_CTX_new(method);
  16362. if (!ctx->ctx) {
  16363. delete ctx;
  16364. return nullptr;
  16365. }
  16366. // Default: verify peer certificate
  16367. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16368. return static_cast<ctx_t>(ctx);
  16369. }
  16370. inline ctx_t create_server_context() {
  16371. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16372. if (!ctx) { return nullptr; }
  16373. ctx->is_server = true;
  16374. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16375. if (!method) {
  16376. delete ctx;
  16377. return nullptr;
  16378. }
  16379. ctx->ctx = wolfSSL_CTX_new(method);
  16380. if (!ctx->ctx) {
  16381. delete ctx;
  16382. return nullptr;
  16383. }
  16384. // Default: don't verify client
  16385. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16386. // Enable SNI on server
  16387. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16388. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16389. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16390. return static_cast<ctx_t>(ctx);
  16391. }
  16392. inline void free_context(ctx_t ctx) {
  16393. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16394. }
  16395. inline bool set_min_version(ctx_t ctx, Version version) {
  16396. if (!ctx) { return false; }
  16397. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16398. int min_ver = WOLFSSL_TLSV1_2;
  16399. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16400. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16401. }
  16402. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16403. if (!ctx || !pem) { return false; }
  16404. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16405. int ret = wolfSSL_CTX_load_verify_buffer(
  16406. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16407. static_cast<long>(len), SSL_FILETYPE_PEM);
  16408. if (ret != SSL_SUCCESS) {
  16409. impl::wolfssl_last_error() =
  16410. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16411. return false;
  16412. }
  16413. wctx->ca_pem_data_.append(pem, len);
  16414. return true;
  16415. }
  16416. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16417. if (!ctx || !file_path) { return false; }
  16418. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16419. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16420. if (ret != SSL_SUCCESS) {
  16421. impl::wolfssl_last_error() =
  16422. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16423. return false;
  16424. }
  16425. return true;
  16426. }
  16427. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16428. if (!ctx || !dir_path) { return false; }
  16429. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16430. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16431. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16432. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16433. // immediately. Return true even on failure since the CA file may have
  16434. // already been loaded, matching OpenSSL's lenient behavior.
  16435. (void)ret;
  16436. return true;
  16437. }
  16438. inline bool load_system_certs(ctx_t ctx) {
  16439. if (!ctx) { return false; }
  16440. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16441. bool loaded = false;
  16442. #ifdef _WIN32
  16443. loaded = impl::enumerate_windows_system_certs(
  16444. [&](const unsigned char *data, size_t len) {
  16445. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16446. static_cast<long>(len),
  16447. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16448. });
  16449. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16450. loaded = impl::enumerate_macos_keychain_certs(
  16451. [&](const unsigned char *data, size_t len) {
  16452. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16453. static_cast<long>(len),
  16454. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16455. });
  16456. #else
  16457. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16458. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16459. SSL_SUCCESS) {
  16460. loaded = true;
  16461. break;
  16462. }
  16463. }
  16464. if (!loaded) {
  16465. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16466. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16467. SSL_SUCCESS) {
  16468. loaded = true;
  16469. break;
  16470. }
  16471. }
  16472. }
  16473. #endif
  16474. return loaded;
  16475. }
  16476. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16477. const char *password) {
  16478. if (!ctx || !cert || !key) { return false; }
  16479. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16480. // Load certificate
  16481. int ret = wolfSSL_CTX_use_certificate_buffer(
  16482. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16483. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16484. if (ret != SSL_SUCCESS) {
  16485. impl::wolfssl_last_error() =
  16486. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16487. return false;
  16488. }
  16489. // Set password callback if password is provided
  16490. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16491. // Load private key
  16492. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16493. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16494. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16495. if (ret != SSL_SUCCESS) {
  16496. impl::wolfssl_last_error() =
  16497. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16498. return false;
  16499. }
  16500. // Verify that the certificate and private key match
  16501. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16502. }
  16503. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16504. const char *key_path, const char *password) {
  16505. if (!ctx || !cert_path || !key_path) { return false; }
  16506. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16507. // Load certificate file
  16508. int ret =
  16509. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16510. if (ret != SSL_SUCCESS) {
  16511. impl::wolfssl_last_error() =
  16512. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16513. return false;
  16514. }
  16515. // Set password callback if password is provided
  16516. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16517. // Load private key file
  16518. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16519. if (ret != SSL_SUCCESS) {
  16520. impl::wolfssl_last_error() =
  16521. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16522. return false;
  16523. }
  16524. // Verify that the certificate and private key match
  16525. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16526. }
  16527. inline void set_verify_client(ctx_t ctx, bool require) {
  16528. if (!ctx) { return; }
  16529. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16530. wctx->verify_client = require;
  16531. if (require) {
  16532. wolfSSL_CTX_set_verify(
  16533. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16534. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16535. } else {
  16536. if (wctx->has_verify_callback) {
  16537. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16538. impl::wolfssl_verify_callback);
  16539. } else {
  16540. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16541. }
  16542. }
  16543. }
  16544. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16545. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16546. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16547. auto session = new (std::nothrow) impl::WolfSSLSession();
  16548. if (!session) { return nullptr; }
  16549. session->sock = sock;
  16550. session->ssl = wolfSSL_new(wctx->ctx);
  16551. if (!session->ssl) {
  16552. impl::wolfssl_last_error() =
  16553. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16554. delete session;
  16555. return nullptr;
  16556. }
  16557. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16558. return static_cast<session_t>(session);
  16559. }
  16560. inline void free_session(session_t session) {
  16561. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16562. }
  16563. inline bool set_sni(session_t session, const char *hostname) {
  16564. if (!session || !hostname) { return false; }
  16565. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16566. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16567. static_cast<word16>(strlen(hostname)));
  16568. if (ret != WOLFSSL_SUCCESS) {
  16569. impl::wolfssl_last_error() =
  16570. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16571. return false;
  16572. }
  16573. // Also set hostname for verification
  16574. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16575. wsession->hostname = hostname;
  16576. return true;
  16577. }
  16578. inline bool set_hostname(session_t session, const char *hostname) {
  16579. // In wolfSSL, set_hostname also sets up hostname verification
  16580. return set_sni(session, hostname);
  16581. }
  16582. inline TlsError connect(session_t session) {
  16583. TlsError err;
  16584. if (!session) {
  16585. err.code = ErrorCode::Fatal;
  16586. return err;
  16587. }
  16588. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16589. int ret = wolfSSL_connect(wsession->ssl);
  16590. if (ret == SSL_SUCCESS) {
  16591. err.code = ErrorCode::Success;
  16592. } else {
  16593. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16594. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16595. err.backend_code = static_cast<uint64_t>(ssl_error);
  16596. impl::wolfssl_last_error() = err.backend_code;
  16597. }
  16598. return err;
  16599. }
  16600. inline TlsError accept(session_t session) {
  16601. TlsError err;
  16602. if (!session) {
  16603. err.code = ErrorCode::Fatal;
  16604. return err;
  16605. }
  16606. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16607. int ret = wolfSSL_accept(wsession->ssl);
  16608. if (ret == SSL_SUCCESS) {
  16609. err.code = ErrorCode::Success;
  16610. // Capture SNI from thread-local storage after successful handshake
  16611. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16612. impl::wolfssl_pending_sni().clear();
  16613. } else {
  16614. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16615. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16616. err.backend_code = static_cast<uint64_t>(ssl_error);
  16617. impl::wolfssl_last_error() = err.backend_code;
  16618. }
  16619. return err;
  16620. }
  16621. inline bool connect_nonblocking(session_t session, socket_t sock,
  16622. time_t timeout_sec, time_t timeout_usec,
  16623. TlsError *err) {
  16624. if (!session) {
  16625. if (err) { err->code = ErrorCode::Fatal; }
  16626. return false;
  16627. }
  16628. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16629. // Set socket to non-blocking mode
  16630. detail::set_nonblocking(sock, true);
  16631. auto cleanup =
  16632. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16633. int ret;
  16634. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16635. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16636. if (ssl_error == SSL_ERROR_WANT_READ) {
  16637. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16638. continue;
  16639. }
  16640. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16641. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16642. continue;
  16643. }
  16644. }
  16645. // Error or timeout
  16646. if (err) {
  16647. err->code =
  16648. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16649. err->backend_code = static_cast<uint64_t>(ssl_error);
  16650. }
  16651. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16652. return false;
  16653. }
  16654. if (err) { err->code = ErrorCode::Success; }
  16655. return true;
  16656. }
  16657. inline bool accept_nonblocking(session_t session, socket_t sock,
  16658. time_t timeout_sec, time_t timeout_usec,
  16659. TlsError *err) {
  16660. if (!session) {
  16661. if (err) { err->code = ErrorCode::Fatal; }
  16662. return false;
  16663. }
  16664. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16665. // Set socket to non-blocking mode
  16666. detail::set_nonblocking(sock, true);
  16667. auto cleanup =
  16668. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16669. int ret;
  16670. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16671. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16672. if (ssl_error == SSL_ERROR_WANT_READ) {
  16673. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16674. continue;
  16675. }
  16676. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16677. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16678. continue;
  16679. }
  16680. }
  16681. // Error or timeout
  16682. if (err) {
  16683. err->code =
  16684. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16685. err->backend_code = static_cast<uint64_t>(ssl_error);
  16686. }
  16687. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16688. return false;
  16689. }
  16690. if (err) { err->code = ErrorCode::Success; }
  16691. // Capture SNI from thread-local storage after successful handshake
  16692. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16693. impl::wolfssl_pending_sni().clear();
  16694. return true;
  16695. }
  16696. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16697. if (!session || !buf) {
  16698. err.code = ErrorCode::Fatal;
  16699. return -1;
  16700. }
  16701. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16702. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16703. if (ret > 0) {
  16704. err.code = ErrorCode::Success;
  16705. return static_cast<ssize_t>(ret);
  16706. }
  16707. if (ret == 0) {
  16708. err.code = ErrorCode::PeerClosed;
  16709. return 0;
  16710. }
  16711. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16712. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16713. err.backend_code = static_cast<uint64_t>(ssl_error);
  16714. impl::wolfssl_last_error() = err.backend_code;
  16715. return -1;
  16716. }
  16717. inline ssize_t write(session_t session, const void *buf, size_t len,
  16718. TlsError &err) {
  16719. if (!session || !buf) {
  16720. err.code = ErrorCode::Fatal;
  16721. return -1;
  16722. }
  16723. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16724. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16725. if (ret > 0) {
  16726. err.code = ErrorCode::Success;
  16727. return static_cast<ssize_t>(ret);
  16728. }
  16729. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16730. // Treat this as an error (return -1) so callers don't spin in a
  16731. // write loop adding zero to the offset.
  16732. if (ret == 0) {
  16733. err.code = ErrorCode::PeerClosed;
  16734. return -1;
  16735. }
  16736. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16737. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16738. err.backend_code = static_cast<uint64_t>(ssl_error);
  16739. impl::wolfssl_last_error() = err.backend_code;
  16740. return -1;
  16741. }
  16742. inline int pending(const_session_t session) {
  16743. if (!session) { return 0; }
  16744. auto wsession =
  16745. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16746. return wolfSSL_pending(wsession->ssl);
  16747. }
  16748. inline void shutdown(session_t session, bool graceful) {
  16749. if (!session) { return; }
  16750. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16751. if (graceful) {
  16752. int ret;
  16753. int attempts = 0;
  16754. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16755. attempts < 3) {
  16756. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16757. if (ssl_error != SSL_ERROR_WANT_READ &&
  16758. ssl_error != SSL_ERROR_WANT_WRITE) {
  16759. break;
  16760. }
  16761. attempts++;
  16762. }
  16763. } else {
  16764. wolfSSL_shutdown(wsession->ssl);
  16765. }
  16766. }
  16767. inline bool is_peer_closed(session_t session, socket_t sock) {
  16768. if (!session || sock == INVALID_SOCKET) { return true; }
  16769. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16770. // Check if there's already decrypted data available
  16771. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16772. // Set socket to non-blocking to avoid blocking on read
  16773. detail::set_nonblocking(sock, true);
  16774. auto cleanup =
  16775. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16776. // Peek 1 byte to check connection status without consuming data
  16777. unsigned char buf;
  16778. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16779. // If we got data or WANT_READ (would block), connection is alive
  16780. if (ret > 0) { return false; }
  16781. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16782. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16783. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16784. ret == 0;
  16785. }
  16786. inline cert_t get_peer_cert(const_session_t session) {
  16787. if (!session) { return nullptr; }
  16788. auto wsession =
  16789. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16790. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16791. return static_cast<cert_t>(cert);
  16792. }
  16793. inline void free_cert(cert_t cert) {
  16794. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16795. }
  16796. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16797. if (!cert || !hostname) { return false; }
  16798. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16799. std::string host_str(hostname);
  16800. // Check if hostname is an IP address (IPv4 or IPv6)
  16801. unsigned char ip_bytes[16];
  16802. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16803. auto is_ip = ip_len > 0;
  16804. // Check Subject Alternative Names
  16805. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16806. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16807. if (san_names) {
  16808. int san_count = wolfSSL_sk_num(san_names);
  16809. for (int i = 0; i < san_count; i++) {
  16810. auto *names =
  16811. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16812. if (!names) continue;
  16813. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16814. // DNS name
  16815. unsigned char *dns_name = nullptr;
  16816. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16817. if (dns_name && dns_len > 0) {
  16818. std::string san_name(reinterpret_cast<char *>(dns_name),
  16819. static_cast<size_t>(dns_len));
  16820. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16821. if (detail::match_hostname(san_name, host_str)) {
  16822. wolfSSL_sk_free(san_names);
  16823. return true;
  16824. }
  16825. }
  16826. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16827. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16828. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16829. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16830. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16831. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16832. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16833. wolfSSL_sk_free(san_names);
  16834. return true;
  16835. }
  16836. }
  16837. }
  16838. wolfSSL_sk_free(san_names);
  16839. }
  16840. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16841. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16842. // the OpenSSL backend's X509_check_ip behaves the same way).
  16843. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16844. if (subject) {
  16845. char cn[256] = {};
  16846. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16847. sizeof(cn));
  16848. if (cn_len > 0) {
  16849. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16850. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16851. }
  16852. }
  16853. return false;
  16854. }
  16855. inline uint64_t hostname_mismatch_code() {
  16856. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16857. }
  16858. inline long get_verify_result(const_session_t session) {
  16859. if (!session) { return -1; }
  16860. auto wsession =
  16861. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16862. long result = wolfSSL_get_verify_result(wsession->ssl);
  16863. return result;
  16864. }
  16865. inline std::string get_cert_subject_cn(cert_t cert) {
  16866. if (!cert) return "";
  16867. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16868. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16869. if (!subject) return "";
  16870. char cn[256] = {};
  16871. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16872. sizeof(cn));
  16873. if (cn_len <= 0) return "";
  16874. return std::string(cn, static_cast<size_t>(cn_len));
  16875. }
  16876. inline std::string get_cert_issuer_name(cert_t cert) {
  16877. if (!cert) return "";
  16878. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16879. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16880. if (!issuer) return "";
  16881. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16882. if (!name_str) return "";
  16883. std::string result(name_str);
  16884. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16885. return result;
  16886. }
  16887. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16888. sans.clear();
  16889. if (!cert) return false;
  16890. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16891. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16892. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16893. if (!san_names) return true; // No SANs is not an error
  16894. int count = wolfSSL_sk_num(san_names);
  16895. for (int i = 0; i < count; i++) {
  16896. auto *name =
  16897. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16898. if (!name) continue;
  16899. SanEntry entry;
  16900. switch (name->type) {
  16901. case WOLFSSL_GEN_DNS: {
  16902. entry.type = SanType::DNS;
  16903. unsigned char *dns_name = nullptr;
  16904. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16905. if (dns_name && dns_len > 0) {
  16906. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16907. static_cast<size_t>(dns_len));
  16908. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16909. }
  16910. break;
  16911. }
  16912. case WOLFSSL_GEN_IPADD: {
  16913. entry.type = SanType::IP;
  16914. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16915. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16916. if (ip_data && ip_len == 4) {
  16917. char buf[16];
  16918. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16919. ip_data[2], ip_data[3]);
  16920. entry.value = buf;
  16921. } else if (ip_data && ip_len == 16) {
  16922. char buf[64];
  16923. snprintf(buf, sizeof(buf),
  16924. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16925. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16926. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16927. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16928. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16929. ip_data[14], ip_data[15]);
  16930. entry.value = buf;
  16931. }
  16932. break;
  16933. }
  16934. case WOLFSSL_GEN_EMAIL:
  16935. entry.type = SanType::EMAIL;
  16936. {
  16937. unsigned char *email = nullptr;
  16938. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16939. if (email && email_len > 0) {
  16940. entry.value = std::string(reinterpret_cast<char *>(email),
  16941. static_cast<size_t>(email_len));
  16942. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16943. }
  16944. }
  16945. break;
  16946. case WOLFSSL_GEN_URI:
  16947. entry.type = SanType::URI;
  16948. {
  16949. unsigned char *uri = nullptr;
  16950. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16951. &uri, name->d.uniformResourceIdentifier);
  16952. if (uri && uri_len > 0) {
  16953. entry.value = std::string(reinterpret_cast<char *>(uri),
  16954. static_cast<size_t>(uri_len));
  16955. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16956. }
  16957. }
  16958. break;
  16959. default: entry.type = SanType::OTHER; break;
  16960. }
  16961. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16962. }
  16963. wolfSSL_sk_free(san_names);
  16964. return true;
  16965. }
  16966. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16967. time_t &not_after) {
  16968. if (!cert) return false;
  16969. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16970. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16971. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16972. if (!nb || !na) return false;
  16973. // wolfSSL_ASN1_TIME_to_tm is available
  16974. struct tm tm_nb = {}, tm_na = {};
  16975. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16976. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16977. #ifdef _WIN32
  16978. not_before = _mkgmtime(&tm_nb);
  16979. not_after = _mkgmtime(&tm_na);
  16980. #else
  16981. not_before = timegm(&tm_nb);
  16982. not_after = timegm(&tm_na);
  16983. #endif
  16984. return true;
  16985. }
  16986. inline std::string get_cert_serial(cert_t cert) {
  16987. if (!cert) return "";
  16988. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16989. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16990. if (!serial_asn1) return "";
  16991. // Get the serial number data
  16992. int len = serial_asn1->length;
  16993. unsigned char *data = serial_asn1->data;
  16994. if (!data || len <= 0) return "";
  16995. std::string result;
  16996. result.reserve(static_cast<size_t>(len) * 2);
  16997. for (int i = 0; i < len; i++) {
  16998. char hex[3];
  16999. snprintf(hex, sizeof(hex), "%02X", data[i]);
  17000. result += hex;
  17001. }
  17002. return result;
  17003. }
  17004. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  17005. if (!cert) return false;
  17006. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17007. int der_len = 0;
  17008. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  17009. if (!der_data || der_len <= 0) return false;
  17010. der.assign(der_data, der_data + der_len);
  17011. return true;
  17012. }
  17013. inline const char *get_sni(const_session_t session) {
  17014. if (!session) return nullptr;
  17015. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17016. // For server: return SNI received from client during handshake
  17017. if (!wsession->sni_hostname.empty()) {
  17018. return wsession->sni_hostname.c_str();
  17019. }
  17020. // For client: return the hostname set via set_sni
  17021. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17022. return nullptr;
  17023. }
  17024. inline uint64_t peek_error() {
  17025. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17026. }
  17027. inline uint64_t get_error() {
  17028. uint64_t err = impl::wolfssl_last_error();
  17029. impl::wolfssl_last_error() = 0;
  17030. return err;
  17031. }
  17032. inline std::string error_string(uint64_t code) {
  17033. char buf[256];
  17034. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17035. return std::string(buf);
  17036. }
  17037. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17038. if (!pem || len == 0) { return nullptr; }
  17039. // Validate by attempting to load into a temporary ctx
  17040. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17041. if (!tmp_ctx) { return nullptr; }
  17042. int ret = wolfSSL_CTX_load_verify_buffer(
  17043. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17044. static_cast<long>(len), SSL_FILETYPE_PEM);
  17045. wolfSSL_CTX_free(tmp_ctx);
  17046. if (ret != SSL_SUCCESS) { return nullptr; }
  17047. return static_cast<ca_store_t>(
  17048. new impl::WolfSSLCAStore{std::string(pem, len)});
  17049. }
  17050. inline void free_ca_store(ca_store_t store) {
  17051. delete static_cast<impl::WolfSSLCAStore *>(store);
  17052. }
  17053. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17054. if (!ctx || !store) { return false; }
  17055. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17056. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17057. int ret = wolfSSL_CTX_load_verify_buffer(
  17058. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17059. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17060. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17061. // This function takes ownership of the store; the PEM data was copied into
  17062. // the context, so release the source
  17063. free_ca_store(store);
  17064. return ret == SSL_SUCCESS;
  17065. }
  17066. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17067. certs.clear();
  17068. if (!ctx) { return 0; }
  17069. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17070. if (wctx->ca_pem_data_.empty()) { return 0; }
  17071. const std::string &pem = wctx->ca_pem_data_;
  17072. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17073. const std::string end_marker = "-----END CERTIFICATE-----";
  17074. size_t pos = 0;
  17075. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17076. size_t end_pos = pem.find(end_marker, pos);
  17077. if (end_pos == std::string::npos) { break; }
  17078. end_pos += end_marker.size();
  17079. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17080. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17081. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17082. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17083. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17084. pos = end_pos;
  17085. }
  17086. return certs.size();
  17087. }
  17088. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17089. std::vector<std::string> names;
  17090. if (!ctx) { return names; }
  17091. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17092. if (wctx->ca_pem_data_.empty()) { return names; }
  17093. const std::string &pem = wctx->ca_pem_data_;
  17094. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17095. const std::string end_marker = "-----END CERTIFICATE-----";
  17096. size_t pos = 0;
  17097. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17098. size_t end_pos = pem.find(end_marker, pos);
  17099. if (end_pos == std::string::npos) { break; }
  17100. end_pos += end_marker.size();
  17101. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17102. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17103. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17104. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17105. if (x509) {
  17106. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17107. if (subject) {
  17108. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17109. if (name_str) {
  17110. names.push_back(name_str);
  17111. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17112. }
  17113. }
  17114. wolfSSL_X509_free(x509);
  17115. }
  17116. pos = end_pos;
  17117. }
  17118. return names;
  17119. }
  17120. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17121. const char *key_pem, const char *password) {
  17122. if (!ctx || !cert_pem || !key_pem) { return false; }
  17123. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17124. // Load new certificate
  17125. int ret = wolfSSL_CTX_use_certificate_buffer(
  17126. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17127. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17128. if (ret != SSL_SUCCESS) {
  17129. impl::wolfssl_last_error() =
  17130. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17131. return false;
  17132. }
  17133. // Set password if provided
  17134. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17135. // Load new private key
  17136. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17137. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17138. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17139. if (ret != SSL_SUCCESS) {
  17140. impl::wolfssl_last_error() =
  17141. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17142. return false;
  17143. }
  17144. return true;
  17145. }
  17146. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17147. if (!ctx || !ca_pem) { return false; }
  17148. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17149. int ret = wolfSSL_CTX_load_verify_buffer(
  17150. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17151. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17152. if (ret != SSL_SUCCESS) {
  17153. impl::wolfssl_last_error() =
  17154. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17155. return false;
  17156. }
  17157. return true;
  17158. }
  17159. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17160. if (!ctx) { return false; }
  17161. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17162. impl::get_verify_callback() = std::move(callback);
  17163. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17164. if (wctx->has_verify_callback) {
  17165. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17166. impl::wolfssl_verify_callback);
  17167. } else {
  17168. wolfSSL_CTX_set_verify(
  17169. wctx->ctx,
  17170. wctx->verify_client
  17171. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17172. : SSL_VERIFY_NONE,
  17173. nullptr);
  17174. }
  17175. return true;
  17176. }
  17177. inline long get_verify_error(const_session_t session) {
  17178. if (!session) { return -1; }
  17179. auto *wsession =
  17180. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17181. return wolfSSL_get_verify_result(wsession->ssl);
  17182. }
  17183. inline std::string verify_error_string(long error_code) {
  17184. if (error_code == 0) { return ""; }
  17185. const char *str =
  17186. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17187. return str ? std::string(str) : std::string();
  17188. }
  17189. } // namespace tls
  17190. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17191. // WebSocket implementation
  17192. namespace ws {
  17193. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17194. bool fin) {
  17195. std::lock_guard<std::mutex> lock(write_mutex_);
  17196. if (closed_) { return false; }
  17197. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17198. }
  17199. inline ReadResult WebSocket::read(std::string &msg) {
  17200. while (!closed_) {
  17201. Opcode opcode;
  17202. std::string payload;
  17203. bool fin;
  17204. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17205. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17206. closed_ = true;
  17207. return Fail;
  17208. }
  17209. switch (opcode) {
  17210. case Opcode::Ping: {
  17211. std::lock_guard<std::mutex> lock(write_mutex_);
  17212. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17213. payload.size(), true, !is_server_);
  17214. continue;
  17215. }
  17216. case Opcode::Pong: {
  17217. std::lock_guard<std::mutex> lock(ping_mutex_);
  17218. unacked_pings_ = 0;
  17219. continue;
  17220. }
  17221. case Opcode::Close: {
  17222. if (!closed_.exchange(true)) {
  17223. // Echo close frame back
  17224. std::lock_guard<std::mutex> lock(write_mutex_);
  17225. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17226. payload.size(), true, !is_server_);
  17227. }
  17228. return Fail;
  17229. }
  17230. case Opcode::Text:
  17231. case Opcode::Binary: {
  17232. auto result = opcode == Opcode::Text ? Text : Binary;
  17233. msg = std::move(payload);
  17234. // Handle fragmentation
  17235. if (!fin) {
  17236. while (true) {
  17237. Opcode cont_opcode;
  17238. std::string cont_payload;
  17239. bool cont_fin;
  17240. if (!impl::read_websocket_frame(
  17241. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17242. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17243. closed_ = true;
  17244. return Fail;
  17245. }
  17246. if (cont_opcode == Opcode::Ping) {
  17247. std::lock_guard<std::mutex> lock(write_mutex_);
  17248. detail::write_websocket_frame(
  17249. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17250. true, !is_server_);
  17251. continue;
  17252. }
  17253. if (cont_opcode == Opcode::Pong) {
  17254. std::lock_guard<std::mutex> lock(ping_mutex_);
  17255. unacked_pings_ = 0;
  17256. continue;
  17257. }
  17258. if (cont_opcode == Opcode::Close) {
  17259. if (!closed_.exchange(true)) {
  17260. std::lock_guard<std::mutex> lock(write_mutex_);
  17261. detail::write_websocket_frame(
  17262. strm_, Opcode::Close, cont_payload.data(),
  17263. cont_payload.size(), true, !is_server_);
  17264. }
  17265. return Fail;
  17266. }
  17267. // RFC 6455: continuation frames must use opcode 0x0
  17268. if (cont_opcode != Opcode::Continuation) {
  17269. closed_ = true;
  17270. return Fail;
  17271. }
  17272. msg += cont_payload;
  17273. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17274. closed_ = true;
  17275. return Fail;
  17276. }
  17277. if (cont_fin) { break; }
  17278. }
  17279. }
  17280. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17281. if (result == Text && !impl::is_valid_utf8(msg)) {
  17282. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17283. return Fail;
  17284. }
  17285. return result;
  17286. }
  17287. default: closed_ = true; return Fail;
  17288. }
  17289. }
  17290. return Fail;
  17291. }
  17292. inline bool WebSocket::send(const std::string &data) {
  17293. return send_frame(Opcode::Text, data.data(), data.size());
  17294. }
  17295. inline bool WebSocket::send(const char *data, size_t len) {
  17296. return send_frame(Opcode::Binary, data, len);
  17297. }
  17298. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17299. if (closed_.exchange(true)) { return; }
  17300. ping_cv_.notify_all();
  17301. std::string payload;
  17302. auto code = static_cast<uint16_t>(status);
  17303. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17304. payload.push_back(static_cast<char>(code & 0xFF));
  17305. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17306. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17307. payload += reason.substr(0, 123);
  17308. {
  17309. std::lock_guard<std::mutex> lock(write_mutex_);
  17310. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17311. payload.size(), true, !is_server_);
  17312. }
  17313. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17314. // Close response before closing the TCP connection. Use a short timeout to
  17315. // avoid hanging if the peer doesn't respond.
  17316. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17317. Opcode op;
  17318. std::string resp;
  17319. bool fin;
  17320. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17321. if (op == Opcode::Close) { break; }
  17322. }
  17323. }
  17324. inline WebSocket::~WebSocket() {
  17325. {
  17326. std::lock_guard<std::mutex> lock(ping_mutex_);
  17327. closed_ = true;
  17328. }
  17329. ping_cv_.notify_all();
  17330. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17331. }
  17332. inline void WebSocket::start_heartbeat() {
  17333. if (ping_interval_sec_ == 0) { return; }
  17334. ping_thread_ = std::thread([this]() {
  17335. std::unique_lock<std::mutex> lock(ping_mutex_);
  17336. while (!closed_) {
  17337. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17338. if (closed_) { break; }
  17339. // If the peer has failed to respond to the previous pings, give up.
  17340. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17341. // opt-in liveness check controlled by max_missed_pongs_.
  17342. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17343. lock.unlock();
  17344. close(CloseStatus::GoingAway, "pong timeout");
  17345. return;
  17346. }
  17347. lock.unlock();
  17348. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17349. lock.lock();
  17350. closed_ = true;
  17351. break;
  17352. }
  17353. lock.lock();
  17354. unacked_pings_++;
  17355. }
  17356. });
  17357. }
  17358. inline const Request &WebSocket::request() const { return req_; }
  17359. inline bool WebSocket::is_open() const { return !closed_; }
  17360. // WebSocketClient implementation
  17361. inline WebSocketClient::WebSocketClient(
  17362. const std::string &scheme_host_port_path, const Headers &headers)
  17363. : headers_(headers) {
  17364. detail::UrlComponents uc;
  17365. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17366. !uc.host.empty() && !uc.path.empty()) {
  17367. auto &scheme = uc.scheme;
  17368. #ifdef CPPHTTPLIB_SSL_ENABLED
  17369. if (scheme != "ws" && scheme != "wss") {
  17370. #else
  17371. if (scheme != "ws") {
  17372. #endif
  17373. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17374. std::string msg = "'" + scheme + "' scheme is not supported.";
  17375. throw std::invalid_argument(msg);
  17376. #endif
  17377. return;
  17378. }
  17379. auto is_ssl = scheme == "wss";
  17380. host_ = std::move(uc.host);
  17381. port_ = is_ssl ? 443 : 80;
  17382. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17383. path_ = std::move(uc.path);
  17384. if (!uc.query.empty()) { path_ += uc.query; }
  17385. #ifdef CPPHTTPLIB_SSL_ENABLED
  17386. is_ssl_ = is_ssl;
  17387. if (is_ssl_) {
  17388. // The context lives as long as the client so that CA configuration
  17389. // survives reconnects; sessions are created per connection.
  17390. tls_ctx_ = tls::create_client_context();
  17391. if (!tls_ctx_) { return; }
  17392. }
  17393. #else
  17394. if (is_ssl) { return; }
  17395. #endif
  17396. is_valid_ = true;
  17397. }
  17398. }
  17399. inline WebSocketClient::~WebSocketClient() {
  17400. shutdown_and_close();
  17401. #ifdef CPPHTTPLIB_SSL_ENABLED
  17402. if (tls_ctx_) {
  17403. tls::free_context(tls_ctx_);
  17404. tls_ctx_ = nullptr;
  17405. }
  17406. #endif
  17407. }
  17408. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17409. inline void WebSocketClient::shutdown_and_close() {
  17410. #ifdef CPPHTTPLIB_SSL_ENABLED
  17411. if (is_ssl_) {
  17412. if (tls_session_) {
  17413. tls::shutdown(tls_session_, true);
  17414. tls::free_session(tls_session_);
  17415. tls_session_ = nullptr;
  17416. }
  17417. }
  17418. #endif
  17419. if (ws_ && ws_->is_open()) { ws_->close(); }
  17420. ws_.reset();
  17421. if (sock_ != INVALID_SOCKET) {
  17422. detail::shutdown_socket(sock_);
  17423. detail::close_socket(sock_);
  17424. sock_ = INVALID_SOCKET;
  17425. }
  17426. }
  17427. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17428. #ifdef CPPHTTPLIB_SSL_ENABLED
  17429. if (is_ssl_) {
  17430. if (server_certificate_verification_ && !certs_loaded_) {
  17431. uint64_t backend_error = 0;
  17432. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17433. custom_ca_loaded_, system_ca_mode_,
  17434. backend_error);
  17435. certs_loaded_ = true;
  17436. }
  17437. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17438. server_certificate_verification_,
  17439. read_timeout_sec_,
  17440. read_timeout_usec_)) {
  17441. return false;
  17442. }
  17443. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17444. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17445. write_timeout_sec_, write_timeout_usec_));
  17446. return true;
  17447. }
  17448. #endif
  17449. strm = std::unique_ptr<Stream>(
  17450. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17451. write_timeout_sec_, write_timeout_usec_));
  17452. return true;
  17453. }
  17454. inline bool WebSocketClient::connect() {
  17455. if (!is_valid_) { return false; }
  17456. shutdown_and_close();
  17457. // Check is custom IP specified for host_
  17458. std::string ip;
  17459. auto it = addr_map_.find(host_);
  17460. if (it != addr_map_.end()) { ip = it->second; }
  17461. Error error;
  17462. sock_ = detail::create_client_socket(
  17463. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17464. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17465. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17466. write_timeout_usec_, interface_, error);
  17467. if (sock_ == INVALID_SOCKET) { return false; }
  17468. std::unique_ptr<Stream> strm;
  17469. if (!create_stream(strm)) {
  17470. shutdown_and_close();
  17471. return false;
  17472. }
  17473. #ifdef CPPHTTPLIB_SSL_ENABLED
  17474. auto is_ssl = is_ssl_;
  17475. #else
  17476. auto is_ssl = false;
  17477. #endif
  17478. std::string selected_subprotocol;
  17479. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17480. headers_, selected_subprotocol)) {
  17481. shutdown_and_close();
  17482. return false;
  17483. }
  17484. subprotocol_ = std::move(selected_subprotocol);
  17485. Request req;
  17486. req.method = "GET";
  17487. req.path = path_;
  17488. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17489. websocket_ping_interval_sec_,
  17490. websocket_max_missed_pongs_));
  17491. return true;
  17492. }
  17493. inline ReadResult WebSocketClient::read(std::string &msg) {
  17494. if (!ws_) { return Fail; }
  17495. return ws_->read(msg);
  17496. }
  17497. inline bool WebSocketClient::send(const std::string &data) {
  17498. if (!ws_) { return false; }
  17499. return ws_->send(data);
  17500. }
  17501. inline bool WebSocketClient::send(const char *data, size_t len) {
  17502. if (!ws_) { return false; }
  17503. return ws_->send(data, len);
  17504. }
  17505. inline void WebSocketClient::close(CloseStatus status,
  17506. const std::string &reason) {
  17507. if (ws_) { ws_->close(status, reason); }
  17508. }
  17509. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17510. inline const std::string &WebSocketClient::subprotocol() const {
  17511. return subprotocol_;
  17512. }
  17513. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17514. read_timeout_sec_ = sec;
  17515. read_timeout_usec_ = usec;
  17516. }
  17517. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17518. write_timeout_sec_ = sec;
  17519. write_timeout_usec_ = usec;
  17520. }
  17521. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17522. websocket_ping_interval_sec_ = sec;
  17523. }
  17524. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17525. websocket_max_missed_pongs_ = count;
  17526. }
  17527. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17528. inline void WebSocketClient::set_address_family(int family) {
  17529. address_family_ = family;
  17530. }
  17531. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17532. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17533. socket_options_ = std::move(socket_options);
  17534. }
  17535. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17536. connection_timeout_sec_ = sec;
  17537. connection_timeout_usec_ = usec;
  17538. }
  17539. inline void WebSocketClient::set_interface(const std::string &intf) {
  17540. interface_ = intf;
  17541. }
  17542. inline void WebSocketClient::set_hostname_addr_map(
  17543. std::map<std::string, std::string> addr_map) {
  17544. addr_map_ = std::move(addr_map);
  17545. }
  17546. #ifdef CPPHTTPLIB_SSL_ENABLED
  17547. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17548. ca_cert_file_path_ = path;
  17549. }
  17550. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17551. if (store && tls_ctx_) {
  17552. // set_ca_store takes ownership of store
  17553. tls::set_ca_store(tls_ctx_, store);
  17554. custom_ca_loaded_ = true;
  17555. } else if (store) {
  17556. tls::free_ca_store(store);
  17557. }
  17558. }
  17559. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17560. std::size_t size) {
  17561. if (tls_ctx_ && ca_cert && size > 0) {
  17562. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17563. custom_ca_loaded_ = true;
  17564. }
  17565. }
  17566. inline void
  17567. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17568. server_certificate_verification_ = enabled;
  17569. }
  17570. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17571. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17572. }
  17573. #endif // CPPHTTPLIB_SSL_ENABLED
  17574. } // namespace ws
  17575. // ----------------------------------------------------------------------------
  17576. } // namespace httplib
  17577. #endif // CPPHTTPLIB_HTTPLIB_H